diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 2929169cf..71f3ac20e 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,8 +1,15 @@ * @sonnyp + +/src/langs/vala/ @lw64 *.vala @lw64 + +/src/langs/rust/ @lw64 *.rs @Hofer-Julian Cargo.toml @Hofer-Julian Cargo.lock @Hofer-Julian + +/src/langs/python/ @theCapypara +*.py @theCapypara + *.c @andyholmes *.h @andyholmes -*.py @theCapypara diff --git a/src/PanelStyle.js b/src/PanelStyle.js index a99f065f2..6442f41b9 100644 --- a/src/PanelStyle.js +++ b/src/PanelStyle.js @@ -1,9 +1,7 @@ import Gio from "gi://Gio"; import GObject from "gi://GObject"; -import { setup as setupCSS } from "./langs/css/css.js"; - -export default function PanelStyle({ builder, document_css, settings }) { +export default function PanelStyle({ builder, settings }) { const button_style = builder.get_object("button_style"); const panel_style = builder.get_object("panel_style"); settings.bind( @@ -18,5 +16,4 @@ export default function PanelStyle({ builder, document_css, settings }) { "visible", GObject.BindingFlags.SYNC_CREATE, ); - setupCSS({ document: document_css }); } diff --git a/src/langs/css/CssDocument.js b/src/langs/css/CssDocument.js index 139bc0c54..126de6c16 100644 --- a/src/langs/css/CssDocument.js +++ b/src/langs/css/CssDocument.js @@ -1,14 +1,33 @@ -import { format as prettier } from "../../lib/prettier.js"; -import prettier_postcss from "../../lib/prettier-postcss.js"; - import Document from "../../Document.js"; +import { applyTextEdits } from "../../lsp/sourceview.js"; +import { setup } from "./css.js"; export class CssDocument extends Document { + constructor(...args) { + super(...args); + + this.lspc = setup({ document: this }); + } + async format() { - const code = await prettier(this.buffer.text, { - parser: "css", - plugins: [prettier_postcss], + // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_formatting + const text_edits = await this.lspc.request("textDocument/formatting", { + textDocument: { + uri: this.file.get_uri(), + }, + options: { + tabSize: 2, + insertSpaces: true, + trimTrailingWhitespace: true, + insertFinalNewline: true, + trimFinalNewlines: true, + }, }); - this.code_view.replaceText(code, true); + + // Biome doesn't support diff - it just returns one edit + // we don't want to loose the cursor position so we use this + const state = this.code_view.saveState(); + applyTextEdits(text_edits, this.buffer); + await this.code_view.restoreState(state); } } diff --git a/src/langs/css/css.js b/src/langs/css/css.js index c4a714b88..e5bc3d4b5 100644 --- a/src/langs/css/css.js +++ b/src/langs/css/css.js @@ -13,6 +13,8 @@ export function setup({ document }) { if (!code_view.buffer.get_modified()) return; lspc.didChange().catch(console.error); }); + + return lspc; } function createLSPClient({ code_view, file }) { diff --git a/src/langs/css/meson.build b/src/langs/css/meson.build new file mode 100644 index 000000000..d4b75b7c8 --- /dev/null +++ b/src/langs/css/meson.build @@ -0,0 +1,15 @@ +gjspack = find_program(meson.project_source_root() / 'troll/gjspack/bin/gjspack') +custom_target('prettier', + input: ['prettier.js'], + output: ['prettier', 'prettier.src.gresource'], + command: [ + gjspack, + '--resource-root', meson.project_source_root() / 'src', + '@INPUT0@', + '@OUTDIR@', + ], + install: true, + install_dir: get_option('bindir'), + build_always_stale: true, +) + diff --git a/src/langs/css/prettier.js b/src/langs/css/prettier.js new file mode 100755 index 000000000..e8541a57f --- /dev/null +++ b/src/langs/css/prettier.js @@ -0,0 +1,29 @@ +#!/usr/bin/env -S gjs -m + +// Shim to Node.js prettier CLI for GTKCssLanguageServer +// ./src/langs/css/prettier.js --stdin-filepath src/style.css +// or +// ./troll/gjspack/bin/gjspack src/langs/css/prettier.js src/langs/css && ./src/langs/css/prettier --stdin-filepath src/style.css + +import { exit } from "system"; +import Gio from "gi://Gio"; + +import { format } from "../../lib/prettier.js"; +import prettier_postcss from "../../lib/prettier-postcss.js"; + +const idx = ARGV.indexOf("--stdin-filepath"); +if (idx < 0) exit(1); +const filename = ARGV[idx + 1]; +if (!filename) exit(1); + +const file = Gio.File.new_for_path(filename); +const [, contents] = file.load_contents(null); +const text = new TextDecoder().decode(contents); + +const formatted = await format(text, { + parser: "css", + plugins: [prettier_postcss], +}); + +// eslint-disable-next-line no-restricted-globals +print(formatted); diff --git a/src/lib/prettier-babel.js b/src/lib/prettier-babel.js deleted file mode 100644 index 85d3f3a66..000000000 --- a/src/lib/prettier-babel.js +++ /dev/null @@ -1,18 +0,0 @@ -var Ys=Object.create;var Ke=Object.defineProperty;var Qs=Object.getOwnPropertyDescriptor;var Zs=Object.getOwnPropertyNames;var ei=Object.getPrototypeOf,ti=Object.prototype.hasOwnProperty;var Bt=(a,t)=>()=>(t||a((t={exports:{}}).exports,t),t.exports),si=(a,t)=>{for(var e in t)Ke(a,e,{get:t[e],enumerable:!0});},ii=(a,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Zs(t))!ti.call(a,i)&&i!==e&&Ke(a,i,{get:()=>t[i],enumerable:!(s=Qs(t,i))||s.enumerable});return a};var qe=(a,t,e)=>(e=a!=null?Ys(ei(a)):{},ii(t||!a||!a.__esModule?Ke(e,"default",{value:a,enumerable:!0}):e,a));var kt=Bt(Re=>{function Le(a,t){if(a==null)return {};var e={},s=Object.keys(a),i,r;for(r=0;r=0)&&(e[i]=a[i]);return e}var F=class{constructor(t,e,s){this.line=void 0,this.column=void 0,this.index=void 0,this.line=t,this.column=e,this.index=s;}},ie=class{constructor(t,e){this.start=void 0,this.end=void 0,this.filename=void 0,this.identifierName=void 0,this.start=t,this.end=e;}};function L(a,t){let{line:e,column:s,index:i}=a;return new F(e,s+t,i+t)}var Ye={SyntaxError:"BABEL_PARSER_SYNTAX_ERROR",SourceTypeModuleError:"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"},ri=(a,t=a.length-1)=>({get(){return a.reduce((e,s)=>e[s],this)},set(e){a.reduce((s,i,r)=>r===t?s[i]=e:s[i],this);}}),ai=(a,t,e)=>Object.keys(e).map(s=>[s,e[s]]).filter(([,s])=>!!s).map(([s,i])=>[s,typeof i=="function"?{value:i,enumerable:!1}:typeof i.reflect=="string"?Object.assign({},i,ri(i.reflect.split("."))):i]).reduce((s,[i,r])=>Object.defineProperty(s,i,Object.assign({configurable:!0},r)),Object.assign(new a,t)),ni={ImportMetaOutsideModule:{message:`import.meta may appear only with 'sourceType: "module"'`,code:Ye.SourceTypeModuleError},ImportOutsideModule:{message:`'import' and 'export' may appear only with 'sourceType: "module"'`,code:Ye.SourceTypeModuleError}},Rt={ArrayPattern:"array destructuring pattern",AssignmentExpression:"assignment expression",AssignmentPattern:"assignment expression",ArrowFunctionExpression:"arrow function expression",ConditionalExpression:"conditional expression",CatchClause:"catch clause",ForOfStatement:"for-of statement",ForInStatement:"for-in statement",ForStatement:"for-loop",FormalParameters:"function parameter list",Identifier:"identifier",ImportSpecifier:"import specifier",ImportDefaultSpecifier:"import default specifier",ImportNamespaceSpecifier:"import namespace specifier",ObjectPattern:"object destructuring pattern",ParenthesizedExpression:"parenthesized expression",RestElement:"rest element",UpdateExpression:{true:"prefix operation",false:"postfix operation"},VariableDeclarator:"variable declaration",YieldExpression:"yield expression"},Qe=({type:a,prefix:t})=>a==="UpdateExpression"?Rt.UpdateExpression[String(t)]:Rt[a],oi={AccessorIsGenerator:({kind:a})=>`A ${a}ter 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.",AwaitBindingIdentifierInStaticBlock:"Can not use 'await' as identifier inside a static block.",AwaitExpressionFormalParameter:"'await' is not allowed in async function parameters.",AwaitUsingNotInAsyncContext:"'await using' is only allowed within async functions and at the top levels of modules.",AwaitNotInAsyncContext:"'await' is only allowed within async functions and at the top levels of modules.",AwaitNotInAsyncFunction:"'await' is only allowed within async functions.",BadGetterArity:"A 'get' accessor must not have any formal parameters.",BadSetterArity:"A 'set' accessor must have exactly one formal parameter.",BadSetterRestParameter:"A 'set' accessor 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:({kind:a})=>`Missing initializer in ${a} declaration.`,DecoratorArgumentsOutsideParentheses:"Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",DecoratorBeforeExport:"Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",DecoratorsBeforeAfterExport:"Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",DecoratorConstructor:"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",DecoratorExportClass:"Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",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:({exportName:a})=>`\`${a}\` has already been exported. Exported identifiers must be unique.`,DuplicateProto:"Redefinition of __proto__ property.",DuplicateRegExpFlags:"Duplicate regular expression flag.",ElementAfterRest:"Rest element must be last element.",EscapedCharNotAnIdentifier:"Invalid Unicode escape.",ExportBindingIsString:({localName:a,exportName:t})=>`A string literal cannot be used as an exported binding without \`from\`. -- Did you mean \`export { '${a}' as '${t}' } from 'some-module'\`?`,ExportDefaultFromAsIdentifier:"'from' is not allowed as an identifier after 'export default'.",ForInOfLoopInitializer:({type:a})=>`'${a==="ForInStatement"?"for-in":"for-of"}' loop variable declaration may not have an initializer.`,ForInUsing:"For-in loop may not start with 'using' declaration.",ForOfAsync:"The left-hand side of a for-of loop may not be 'async'.",ForOfLet:"The left-hand side of a for-of loop may not start with 'let'.",GeneratorInSingleStatementContext:"Generators can only be declared at the top level or inside a block.",IllegalBreakContinue:({type:a})=>`Unsyntactic ${a==="BreakStatement"?"break":"continue"}.`,IllegalLanguageModeDirective:"Illegal 'use strict' directive in function with non-simple parameter list.",IllegalReturn:"'return' outside of function.",ImportAttributesUseAssert:"The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedAssertSyntax: true` option in the import attributes plugin to suppress this error.",ImportBindingIsString:({importName:a})=>`A string literal cannot be used as an imported binding. -- Did you mean \`import { "${a}" as foo }\`?`,ImportCallArgumentTrailingComma:"Trailing comma is disallowed inside import(...) arguments.",ImportCallArity:({maxArgumentCount:a})=>`\`import()\` requires exactly ${a===1?"one argument":"one or two arguments"}.`,ImportCallNotNewExpression:"Cannot use new with import(...).",ImportCallSpreadArgument:"`...` is not allowed in `import()`.",ImportJSONBindingNotDefault:"A JSON module can only be imported with `default`.",ImportReflectionHasAssertion:"`import module x` cannot have assertions.",ImportReflectionNotBinding:'Only `import module x from "./module"` is valid.',IncompatibleRegExpUVFlags:"The 'u' and 'v' regular expression flags cannot be enabled at the same time.",InvalidBigIntLiteral:"Invalid BigIntLiteral.",InvalidCodePoint:"Code point out of bounds.",InvalidCoverInitializedName:"Invalid shorthand property initializer.",InvalidDecimal:"Invalid decimal.",InvalidDigit:({radix:a})=>`Expected number in radix ${a}.`,InvalidEscapeSequence:"Bad character escape sequence.",InvalidEscapeSequenceTemplate:"Invalid escape sequence in template.",InvalidEscapedReservedWord:({reservedWord:a})=>`Escape sequence in keyword ${a}.`,InvalidIdentifier:({identifierName:a})=>`Invalid identifier ${a}.`,InvalidLhs:({ancestor:a})=>`Invalid left-hand side in ${Qe(a)}.`,InvalidLhsBinding:({ancestor:a})=>`Binding invalid left-hand side in ${Qe(a)}.`,InvalidNumber:"Invalid number.",InvalidOrMissingExponent:"Floating-point numbers require a valid exponent after the 'e'.",InvalidOrUnexpectedToken:({unexpected:a})=>`Unexpected character '${a}'.`,InvalidParenthesizedAssignment:"Invalid parenthesized assignment pattern.",InvalidPrivateFieldResolution:({identifierName:a})=>`Private name #${a} 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:({labelName:a})=>`Label '${a}' 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.",MissingSemicolon:"Missing semicolon.",MissingPlugin:({missingPlugin:a})=>`This experimental syntax requires enabling the parser plugin: ${a.map(t=>JSON.stringify(t)).join(", ")}.`,MissingOneOfPlugins:({missingPlugin:a})=>`This experimental syntax requires enabling one of the following parser plugin(s): ${a.map(t=>JSON.stringify(t)).join(", ")}.`,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:({key:a})=>`Duplicate key "${a}" is not allowed in module attributes.`,ModuleExportNameHasLoneSurrogate:({surrogateCharCode:a})=>`An export name cannot include a lone surrogate, found '\\u${a.toString(16)}'.`,ModuleExportUndefined:({localName:a})=>`Export '${a}' 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.",OverrideOnConstructor:"'override' modifier cannot appear on a constructor declaration.",ParamDupe:"Argument name clash.",PatternHasAccessor:"Object pattern can't contain getter or setter.",PatternHasMethod:"Object pattern can't contain methods.",PrivateInExpectedIn:({identifierName:a})=>`Private names are only allowed in property accesses (\`obj.#${a}\`) or in \`in\` expressions (\`#${a} in obj\`).`,PrivateNameRedeclaration:({identifierName:a})=>`Duplicate private name #${a}.`,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 or inside a block.",SloppyFunctionAnnexB:"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.",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:({keyword:a})=>`Unexpected keyword '${a}'.`,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 or class properties.",UnexpectedNumericSeparator:"A numeric separator is only allowed between two digits.",UnexpectedPrivateField:"Unexpected private name.",UnexpectedReservedWord:({reservedWord:a})=>`Unexpected reserved word '${a}'.`,UnexpectedSuper:"'super' is only allowed in object methods and classes.",UnexpectedToken:({expected:a,unexpected:t})=>`Unexpected token${t?` '${t}'.`:""}${a?`, expected "${a}"`:""}`,UnexpectedTokenUnaryExponentiation:"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",UnexpectedUsingDeclaration:"Using declaration cannot appear in the top level when source type is `script`.",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:({target:a,onlyValidPropertyName:t})=>`The only valid meta property for ${a} is ${a}.${t}.`,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.",UsingDeclarationHasBindingPattern:"Using declaration cannot have destructuring patterns.",VarRedeclaration:({identifierName:a})=>`Identifier '${a}' 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."},hi={StrictDelete:"Deleting local variable in strict mode.",StrictEvalArguments:({referenceName:a})=>`Assigning to '${a}' in strict mode.`,StrictEvalArgumentsBinding:({bindingName:a})=>`Binding '${a}' 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."},li=new Set(["ArrowFunctionExpression","AssignmentExpression","ConditionalExpression","YieldExpression"]),ci={PipeBodyIsTighter:"Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",PipeTopicRequiresHackPipes:'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',PipeTopicUnbound:"Topic reference is unbound; it must be inside a pipe body.",PipeTopicUnconfiguredToken:({token:a})=>`Invalid topic token ${a}. In order to use ${a} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${a}" }.`,PipeTopicUnused:"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",PipeUnparenthesizedBody:({type:a})=>`Hack-style pipe body cannot be an unparenthesized ${Qe({type:a})}; please wrap it in parentheses.`,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:'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.'},pi=["toMessage"],ui=["message"];function di(a){let{toMessage:t}=a,e=Le(a,pi);return function s({loc:i,details:r}){return ai(SyntaxError,Object.assign({},e,{loc:i}),{clone(n={}){let o=n.loc||{};return s({loc:new F("line"in o?o.line:this.loc.line,"column"in o?o.column:this.loc.column,"index"in o?o.index:this.loc.index),details:Object.assign({},this.details,n.details)})},details:{value:r,enumerable:!1},message:{get(){return `${t(this.details)} (${this.loc.line}:${this.loc.column})`},set(n){Object.defineProperty(this,"message",{value:n});}},pos:{reflect:"loc.index",enumerable:!0},missingPlugin:"missingPlugin"in r&&{reflect:"details.missingPlugin",enumerable:!0}})}}function $(a,t){if(Array.isArray(a))return s=>$(s,a[0]);let e={};for(let s of Object.keys(a)){let i=a[s],r=typeof i=="string"?{message:()=>i}:typeof i=="function"?{message:i}:i,{message:n}=r,o=Le(r,ui),h=typeof n=="string"?()=>n:n;e[s]=di(Object.assign({code:Ye.SyntaxError,reasonCode:s,toMessage:h},t?{syntaxPlugin:t}:{},o));}return e}var p=Object.assign({},$(ni),$(oi),$(hi),$`pipelineOperator`(ci)),{defineProperty:fi}=Object,_t=(a,t)=>fi(a,t,{enumerable:!1,value:a[t]});function pe(a){return a.loc.start&&_t(a.loc.start,"index"),a.loc.end&&_t(a.loc.end,"index"),a}var mi=a=>class extends a{parse(){let e=pe(super.parse());return this.options.tokens&&(e.tokens=e.tokens.map(pe)),e}parseRegExpLiteral({pattern:e,flags:s}){let i=null;try{i=new RegExp(e,s);}catch{}let r=this.estreeParseLiteral(i);return r.regex={pattern:e,flags:s},r}parseBigIntLiteral(e){let s;try{s=BigInt(e);}catch{s=null;}let i=this.estreeParseLiteral(s);return i.bigint=String(i.value||e),i}parseDecimalLiteral(e){let i=this.estreeParseLiteral(null);return i.decimal=String(i.value||e),i}estreeParseLiteral(e){return this.parseLiteral(e,"Literal")}parseStringLiteral(e){return this.estreeParseLiteral(e)}parseNumericLiteral(e){return this.estreeParseLiteral(e)}parseNullLiteral(){return this.estreeParseLiteral(null)}parseBooleanLiteral(e){return this.estreeParseLiteral(e)}directiveToStmt(e){let s=e.value;delete e.value,s.type="Literal",s.raw=s.extra.raw,s.value=s.extra.expressionValue;let i=e;return i.type="ExpressionStatement",i.expression=s,i.directive=s.extra.rawValue,delete s.extra,i}initFunction(e,s){super.initFunction(e,s),e.expression=!1;}checkDeclaration(e){e!=null&&this.isObjectProperty(e)?this.checkDeclaration(e.value):super.checkDeclaration(e);}getObjectOrClassMethodParams(e){return e.value.params}isValidDirective(e){var s;return e.type==="ExpressionStatement"&&e.expression.type==="Literal"&&typeof e.expression.value=="string"&&!((s=e.expression.extra)!=null&&s.parenthesized)}parseBlockBody(e,s,i,r,n){super.parseBlockBody(e,s,i,r,n);let o=e.directives.map(h=>this.directiveToStmt(h));e.body=o.concat(e.body),delete e.directives;}pushClassMethod(e,s,i,r,n,o){this.parseMethod(s,i,r,n,o,"ClassMethod",!0),s.typeParameters&&(s.value.typeParameters=s.typeParameters,delete s.typeParameters),e.body.push(s);}parsePrivateName(){let e=super.parsePrivateName();return this.getPluginOption("estree","classFeatures")?this.convertPrivateNameToPrivateIdentifier(e):e}convertPrivateNameToPrivateIdentifier(e){let s=super.getPrivateNameSV(e);return e=e,delete e.id,e.name=s,e.type="PrivateIdentifier",e}isPrivateName(e){return this.getPluginOption("estree","classFeatures")?e.type==="PrivateIdentifier":super.isPrivateName(e)}getPrivateNameSV(e){return this.getPluginOption("estree","classFeatures")?e.name:super.getPrivateNameSV(e)}parseLiteral(e,s){let i=super.parseLiteral(e,s);return i.raw=i.extra.raw,delete i.extra,i}parseFunctionBody(e,s,i=!1){super.parseFunctionBody(e,s,i),e.expression=e.body.type!=="BlockStatement";}parseMethod(e,s,i,r,n,o,h=!1){let l=this.startNode();return l.kind=e.kind,l=super.parseMethod(l,s,i,r,n,o,h),l.type="FunctionExpression",delete l.kind,e.value=l,o==="ClassPrivateMethod"&&(e.computed=!1),this.finishNode(e,"MethodDefinition")}parseClassProperty(...e){let s=super.parseClassProperty(...e);return this.getPluginOption("estree","classFeatures")&&(s.type="PropertyDefinition"),s}parseClassPrivateProperty(...e){let s=super.parseClassPrivateProperty(...e);return this.getPluginOption("estree","classFeatures")&&(s.type="PropertyDefinition",s.computed=!1),s}parseObjectMethod(e,s,i,r,n){let o=super.parseObjectMethod(e,s,i,r,n);return o&&(o.type="Property",o.kind==="method"&&(o.kind="init"),o.shorthand=!1),o}parseObjectProperty(e,s,i,r){let n=super.parseObjectProperty(e,s,i,r);return n&&(n.kind="init",n.type="Property"),n}isValidLVal(e,s,i){return e==="Property"?"value":super.isValidLVal(e,s,i)}isAssignable(e,s){return e!=null&&this.isObjectProperty(e)?this.isAssignable(e.value,s):super.isAssignable(e,s)}toAssignable(e,s=!1){if(e!=null&&this.isObjectProperty(e)){let{key:i,value:r}=e;this.isPrivateName(i)&&this.classScope.usePrivateName(this.getPrivateNameSV(i),i.loc.start),this.toAssignable(r,s);}else super.toAssignable(e,s);}toAssignableObjectExpressionProp(e,s,i){e.kind==="get"||e.kind==="set"?this.raise(p.PatternHasAccessor,{at:e.key}):e.method?this.raise(p.PatternHasMethod,{at:e.key}):super.toAssignableObjectExpressionProp(e,s,i);}finishCallExpression(e,s){let i=super.finishCallExpression(e,s);if(i.callee.type==="Import"){if(i.type="ImportExpression",i.source=i.arguments[0],this.hasPlugin("importAttributes")||this.hasPlugin("importAssertions")){var r;i.attributes=(r=i.arguments[1])!=null?r:null;}delete i.arguments,delete i.callee;}return i}toReferencedArguments(e){e.type!=="ImportExpression"&&super.toReferencedArguments(e);}parseExport(e,s){let i=this.state.lastTokStartLoc,r=super.parseExport(e,s);switch(r.type){case"ExportAllDeclaration":r.exported=null;break;case"ExportNamedDeclaration":r.specifiers.length===1&&r.specifiers[0].type==="ExportNamespaceSpecifier"&&(r.type="ExportAllDeclaration",r.exported=r.specifiers[0].exported,delete r.specifiers);case"ExportDefaultDeclaration":{var n;let{declaration:o}=r;(o==null?void 0:o.type)==="ClassDeclaration"&&((n=o.decorators)==null?void 0:n.length)>0&&o.start===r.start&&this.resetStartLocation(r,i);}break}return r}parseSubscript(e,s,i,r){let n=super.parseSubscript(e,s,i,r);if(r.optionalChainMember){if((n.type==="OptionalMemberExpression"||n.type==="OptionalCallExpression")&&(n.type=n.type.substring(8)),r.stop){let o=this.startNodeAtNode(n);return o.expression=n,this.finishNode(o,"ChainExpression")}}else (n.type==="MemberExpression"||n.type==="CallExpression")&&(n.optional=!1);return n}hasPropertyAsPrivateName(e){return e.type==="ChainExpression"&&(e=e.expression),super.hasPropertyAsPrivateName(e)}isObjectProperty(e){return e.type==="Property"&&e.kind==="init"&&!e.method}isObjectMethod(e){return e.method||e.kind==="get"||e.kind==="set"}finishNodeAt(e,s,i){return pe(super.finishNodeAt(e,s,i))}resetStartLocation(e,s){super.resetStartLocation(e,s),pe(e);}resetEndLocation(e,s=this.state.lastTokEndLoc){super.resetEndLocation(e,s),pe(e);}},X=class{constructor(t,e){this.token=void 0,this.preserveSpace=void 0,this.token=t,this.preserveSpace=!!e;}},w={brace:new X("{"),j_oTag:new X("...",!0)};w.template=new X("`",!0);var T=!0,m=!0,He=!0,ue=!0,z=!0,yi=!0,De=class{constructor(t,e={}){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.label=t,this.keyword=e.keyword,this.beforeExpr=!!e.beforeExpr,this.startsExpr=!!e.startsExpr,this.rightAssociative=!!e.rightAssociative,this.isLoop=!!e.isLoop,this.isAssign=!!e.isAssign,this.prefix=!!e.prefix,this.postfix=!!e.postfix,this.binop=e.binop!=null?e.binop:null,this.updateContext=null;}},gt=new Map;function A(a,t={}){t.keyword=a;let e=P(a,t);return gt.set(a,e),e}function v(a,t){return P(a,{beforeExpr:T,binop:t})}var ye=-1,U=[],Tt=[],bt=[],At=[],St=[],wt=[];function P(a,t={}){var e,s,i,r;return ++ye,Tt.push(a),bt.push((e=t.binop)!=null?e:-1),At.push((s=t.beforeExpr)!=null?s:!1),St.push((i=t.startsExpr)!=null?i:!1),wt.push((r=t.prefix)!=null?r:!1),U.push(new De(a,t)),ye}function b(a,t={}){var e,s,i,r;return ++ye,gt.set(a,ye),Tt.push(a),bt.push((e=t.binop)!=null?e:-1),At.push((s=t.beforeExpr)!=null?s:!1),St.push((i=t.startsExpr)!=null?i:!1),wt.push((r=t.prefix)!=null?r:!1),U.push(new De("name",t)),ye}var xi={bracketL:P("[",{beforeExpr:T,startsExpr:m}),bracketHashL:P("#[",{beforeExpr:T,startsExpr:m}),bracketBarL:P("[|",{beforeExpr:T,startsExpr:m}),bracketR:P("]"),bracketBarR:P("|]"),braceL:P("{",{beforeExpr:T,startsExpr:m}),braceBarL:P("{|",{beforeExpr:T,startsExpr:m}),braceHashL:P("#{",{beforeExpr:T,startsExpr:m}),braceR:P("}"),braceBarR:P("|}"),parenL:P("(",{beforeExpr:T,startsExpr:m}),parenR:P(")"),comma:P(",",{beforeExpr:T}),semi:P(";",{beforeExpr:T}),colon:P(":",{beforeExpr:T}),doubleColon:P("::",{beforeExpr:T}),dot:P("."),question:P("?",{beforeExpr:T}),questionDot:P("?."),arrow:P("=>",{beforeExpr:T}),template:P("template"),ellipsis:P("...",{beforeExpr:T}),backQuote:P("`",{startsExpr:m}),dollarBraceL:P("${",{beforeExpr:T,startsExpr:m}),templateTail:P("...`",{startsExpr:m}),templateNonTail:P("...${",{beforeExpr:T,startsExpr:m}),at:P("@"),hash:P("#",{startsExpr:m}),interpreterDirective:P("#!..."),eq:P("=",{beforeExpr:T,isAssign:ue}),assign:P("_=",{beforeExpr:T,isAssign:ue}),slashAssign:P("_=",{beforeExpr:T,isAssign:ue}),xorAssign:P("_=",{beforeExpr:T,isAssign:ue}),moduloAssign:P("_=",{beforeExpr:T,isAssign:ue}),incDec:P("++/--",{prefix:z,postfix:yi,startsExpr:m}),bang:P("!",{beforeExpr:T,prefix:z,startsExpr:m}),tilde:P("~",{beforeExpr:T,prefix:z,startsExpr:m}),doubleCaret:P("^^",{startsExpr:m}),doubleAt:P("@@",{startsExpr:m}),pipeline:v("|>",0),nullishCoalescing:v("??",1),logicalOR:v("||",1),logicalAND:v("&&",2),bitwiseOR:v("|",3),bitwiseXOR:v("^",4),bitwiseAND:v("&",5),equality:v("==/!=/===/!==",6),lt:v("/<=/>=",7),gt:v("/<=/>=",7),relational:v("/<=/>=",7),bitShift:v("<>/>>>",8),bitShiftL:v("<>/>>>",8),bitShiftR:v("<>/>>>",8),plusMin:P("+/-",{beforeExpr:T,binop:9,prefix:z,startsExpr:m}),modulo:P("%",{binop:10,startsExpr:m}),star:P("*",{binop:10}),slash:v("/",10),exponent:P("**",{beforeExpr:T,binop:11,rightAssociative:!0}),_in:A("in",{beforeExpr:T,binop:7}),_instanceof:A("instanceof",{beforeExpr:T,binop:7}),_break:A("break"),_case:A("case",{beforeExpr:T}),_catch:A("catch"),_continue:A("continue"),_debugger:A("debugger"),_default:A("default",{beforeExpr:T}),_else:A("else",{beforeExpr:T}),_finally:A("finally"),_function:A("function",{startsExpr:m}),_if:A("if"),_return:A("return",{beforeExpr:T}),_switch:A("switch"),_throw:A("throw",{beforeExpr:T,prefix:z,startsExpr:m}),_try:A("try"),_var:A("var"),_const:A("const"),_with:A("with"),_new:A("new",{beforeExpr:T,startsExpr:m}),_this:A("this",{startsExpr:m}),_super:A("super",{startsExpr:m}),_class:A("class",{startsExpr:m}),_extends:A("extends",{beforeExpr:T}),_export:A("export"),_import:A("import",{startsExpr:m}),_null:A("null",{startsExpr:m}),_true:A("true",{startsExpr:m}),_false:A("false",{startsExpr:m}),_typeof:A("typeof",{beforeExpr:T,prefix:z,startsExpr:m}),_void:A("void",{beforeExpr:T,prefix:z,startsExpr:m}),_delete:A("delete",{beforeExpr:T,prefix:z,startsExpr:m}),_do:A("do",{isLoop:He,beforeExpr:T}),_for:A("for",{isLoop:He}),_while:A("while",{isLoop:He}),_as:b("as",{startsExpr:m}),_assert:b("assert",{startsExpr:m}),_async:b("async",{startsExpr:m}),_await:b("await",{startsExpr:m}),_from:b("from",{startsExpr:m}),_get:b("get",{startsExpr:m}),_let:b("let",{startsExpr:m}),_meta:b("meta",{startsExpr:m}),_of:b("of",{startsExpr:m}),_sent:b("sent",{startsExpr:m}),_set:b("set",{startsExpr:m}),_static:b("static",{startsExpr:m}),_using:b("using",{startsExpr:m}),_yield:b("yield",{startsExpr:m}),_asserts:b("asserts",{startsExpr:m}),_checks:b("checks",{startsExpr:m}),_exports:b("exports",{startsExpr:m}),_global:b("global",{startsExpr:m}),_implements:b("implements",{startsExpr:m}),_intrinsic:b("intrinsic",{startsExpr:m}),_infer:b("infer",{startsExpr:m}),_is:b("is",{startsExpr:m}),_mixins:b("mixins",{startsExpr:m}),_proto:b("proto",{startsExpr:m}),_require:b("require",{startsExpr:m}),_satisfies:b("satisfies",{startsExpr:m}),_keyof:b("keyof",{startsExpr:m}),_readonly:b("readonly",{startsExpr:m}),_unique:b("unique",{startsExpr:m}),_abstract:b("abstract",{startsExpr:m}),_declare:b("declare",{startsExpr:m}),_enum:b("enum",{startsExpr:m}),_module:b("module",{startsExpr:m}),_namespace:b("namespace",{startsExpr:m}),_interface:b("interface",{startsExpr:m}),_type:b("type",{startsExpr:m}),_opaque:b("opaque",{startsExpr:m}),name:P("name",{startsExpr:m}),string:P("string",{startsExpr:m}),num:P("num",{startsExpr:m}),bigint:P("bigint",{startsExpr:m}),decimal:P("decimal",{startsExpr:m}),regexp:P("regexp",{startsExpr:m}),privateName:P("#name",{startsExpr:m}),eof:P("eof"),jsxName:P("jsxName"),jsxText:P("jsxText",{beforeExpr:!0}),jsxTagStart:P("jsxTagStart",{startsExpr:!0}),jsxTagEnd:P("jsxTagEnd"),placeholder:P("%%",{startsExpr:!0})};function S(a){return a>=93&&a<=130}function Pi(a){return a<=92}function M(a){return a>=58&&a<=130}function Yt(a){return a>=58&&a<=134}function gi(a){return At[a]}function Ze(a){return St[a]}function Ti(a){return a>=29&&a<=33}function Ut(a){return a>=127&&a<=129}function bi(a){return a>=90&&a<=92}function Ct(a){return a>=58&&a<=92}function Ai(a){return a>=39&&a<=59}function Si(a){return a===34}function wi(a){return wt[a]}function Ci(a){return a>=119&&a<=121}function Ei(a){return a>=122&&a<=128}function q(a){return Tt[a]}function Ne(a){return bt[a]}function Ii(a){return a===57}function Me(a){return a>=24&&a<=25}function _(a){return U[a]}U[8].updateContext=a=>{a.pop();},U[5].updateContext=U[7].updateContext=U[23].updateContext=a=>{a.push(w.brace);},U[22].updateContext=a=>{a[a.length-1]===w.template?a.pop():a.push(w.template);},U[140].updateContext=a=>{a.push(w.j_expr,w.j_oTag);};var Et="\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\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\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\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\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-\u1711\u171F-\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-\u1B4C\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-\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-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\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",Qt="\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\u0898-\u089F\u08CA-\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\u0C3C\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\u0CF3\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-\u0ECE\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-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ACE\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-\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",Ni=new RegExp("["+Et+"]"),ki=new RegExp("["+Et+Qt+"]");Et=Qt=null;var Zt=[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,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,68,310,10,21,11,7,25,5,2,41,2,8,70,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,43,17,47,20,28,22,13,52,58,1,3,0,14,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,20,1,64,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,38,6,186,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,19,72,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,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,4026,582,8634,568,8,30,18,78,18,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,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,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,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,757,6,2,3,2,1,2,14,2,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,42719,33,4153,7,221,3,5761,15,7472,3104,541,1507,4938,6,4191],vi=[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,81,2,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,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,10,1,2,0,49,6,4,4,14,9,5351,0,7,14,13835,9,87,9,39,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,4706,45,3,22,543,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,101,0,161,6,10,9,357,0,62,13,499,13,983,6,110,6,6,9,4759,9,787719,239];function et(a,t){let e=65536;for(let s=0,i=t.length;sa)return !1;if(e+=t[s+1],e>=a)return !0}return !1}function j(a){return a<65?a===36:a<=90?!0:a<97?a===95:a<=122?!0:a<=65535?a>=170&&Ni.test(String.fromCharCode(a)):et(a,Zt)}function ee(a){return a<48?a===36:a<58?!0:a<65?!1:a<=90?!0:a<97?a===95:a<=122?!0:a<=65535?a>=170&&ki.test(String.fromCharCode(a)):et(a,Zt)||et(a,vi)}var It={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"]},Li=new Set(It.keyword),Di=new Set(It.strict),Mi=new Set(It.strictBind);function es(a,t){return t&&a==="await"||a==="enum"}function ts(a,t){return es(a,t)||Di.has(a)}function ss(a){return Mi.has(a)}function is(a,t){return ts(a,t)||ss(a)}function Oi(a){return Li.has(a)}function Fi(a,t,e){return a===64&&t===64&&j(e)}var Bi=new Set(["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","implements","interface","let","package","private","protected","public","static","yield","eval","arguments","enum","await"]);function Ri(a){return Bi.has(a)}var Pe=class{constructor(t){this.var=new Set,this.lexical=new Set,this.functions=new Set,this.flags=t;}},ge=class{constructor(t,e){this.parser=void 0,this.scopeStack=[],this.inModule=void 0,this.undefinedExports=new Map,this.parser=t,this.inModule=e;}get inTopLevel(){return (this.currentScope().flags&1)>0}get inFunction(){return (this.currentVarScopeFlags()&2)>0}get allowSuper(){return (this.currentThisScopeFlags()&16)>0}get allowDirectSuper(){return (this.currentThisScopeFlags()&32)>0}get inClass(){return (this.currentThisScopeFlags()&64)>0}get inClassAndNotInNonArrowFunction(){let t=this.currentThisScopeFlags();return (t&64)>0&&(t&2)===0}get inStaticBlock(){for(let t=this.scopeStack.length-1;;t--){let{flags:e}=this.scopeStack[t];if(e&128)return !0;if(e&451)return !1}}get inNonArrowFunction(){return (this.currentThisScopeFlags()&2)>0}get treatFunctionsAsVar(){return this.treatFunctionsAsVarInScope(this.currentScope())}createScope(t){return new Pe(t)}enter(t){this.scopeStack.push(this.createScope(t));}exit(){return this.scopeStack.pop().flags}treatFunctionsAsVarInScope(t){return !!(t.flags&130||!this.parser.inModule&&t.flags&1)}declareName(t,e,s){let i=this.currentScope();if(e&8||e&16)this.checkRedeclarationInScope(i,t,e,s),e&16?i.functions.add(t):i.lexical.add(t),e&8&&this.maybeExportDefined(i,t);else if(e&4)for(let r=this.scopeStack.length-1;r>=0&&(i=this.scopeStack[r],this.checkRedeclarationInScope(i,t,e,s),i.var.add(t),this.maybeExportDefined(i,t),!(i.flags&387));--r);this.parser.inModule&&i.flags&1&&this.undefinedExports.delete(t);}maybeExportDefined(t,e){this.parser.inModule&&t.flags&1&&this.undefinedExports.delete(e);}checkRedeclarationInScope(t,e,s,i){this.isRedeclaredInScope(t,e,s)&&this.parser.raise(p.VarRedeclaration,{at:i,identifierName:e});}isRedeclaredInScope(t,e,s){return s&1?s&8?t.lexical.has(e)||t.functions.has(e)||t.var.has(e):s&16?t.lexical.has(e)||!this.treatFunctionsAsVarInScope(t)&&t.var.has(e):t.lexical.has(e)&&!(t.flags&8&&t.lexical.values().next().value===e)||!this.treatFunctionsAsVarInScope(t)&&t.functions.has(e):!1}checkLocalExport(t){let{name:e}=t,s=this.scopeStack[0];!s.lexical.has(e)&&!s.var.has(e)&&!s.functions.has(e)&&this.undefinedExports.set(e,t.loc.start);}currentScope(){return this.scopeStack[this.scopeStack.length-1]}currentVarScopeFlags(){for(let t=this.scopeStack.length-1;;t--){let{flags:e}=this.scopeStack[t];if(e&387)return e}}currentThisScopeFlags(){for(let t=this.scopeStack.length-1;;t--){let{flags:e}=this.scopeStack[t];if(e&451&&!(e&4))return e}}},tt=class extends Pe{constructor(...t){super(...t),this.declareFunctions=new Set;}},st=class extends ge{createScope(t){return new tt(t)}declareName(t,e,s){let i=this.currentScope();if(e&2048){this.checkRedeclarationInScope(i,t,e,s),this.maybeExportDefined(i,t),i.declareFunctions.add(t);return}super.declareName(t,e,s);}isRedeclaredInScope(t,e,s){return super.isRedeclaredInScope(t,e,s)?!0:s&2048?!t.declareFunctions.has(e)&&(t.lexical.has(e)||t.functions.has(e)):!1}checkLocalExport(t){this.scopeStack[0].declareFunctions.has(t.name)||super.checkLocalExport(t);}},it=class{constructor(){this.sawUnambiguousESM=!1,this.ambiguousScriptDifferentAst=!1;}hasPlugin(t){if(typeof t=="string")return this.plugins.has(t);{let[e,s]=t;if(!this.hasPlugin(e))return !1;let i=this.plugins.get(e);for(let r of Object.keys(s))if((i==null?void 0:i[r])!==s[r])return !1;return !0}}getPluginOption(t,e){var s;return (s=this.plugins.get(t))==null?void 0:s[e]}};function rs(a,t){a.trailingComments===void 0?a.trailingComments=t:a.trailingComments.unshift(...t);}function _i(a,t){a.leadingComments===void 0?a.leadingComments=t:a.leadingComments.unshift(...t);}function Te(a,t){a.innerComments===void 0?a.innerComments=t:a.innerComments.unshift(...t);}function de(a,t,e){let s=null,i=t.length;for(;s===null&&i>0;)s=t[--i];s===null||s.start>e.start?Te(a,e.comments):rs(s,e.comments);}var rt=class extends it{addComment(t){this.filename&&(t.loc.filename=this.filename),this.state.comments.push(t);}processComment(t){let{commentStack:e}=this.state,s=e.length;if(s===0)return;let i=s-1,r=e[i];r.start===t.end&&(r.leadingNode=t,i--);let{start:n}=t;for(;i>=0;i--){let o=e[i],h=o.end;if(h>n)o.containingNode=t,this.finalizeComment(o),e.splice(i,1);else {h===n&&(o.trailingNode=t);break}}}finalizeComment(t){let{comments:e}=t;if(t.leadingNode!==null||t.trailingNode!==null)t.leadingNode!==null&&rs(t.leadingNode,e),t.trailingNode!==null&&_i(t.trailingNode,e);else {let{containingNode:s,start:i}=t;if(this.input.charCodeAt(i-1)===44)switch(s.type){case"ObjectExpression":case"ObjectPattern":case"RecordExpression":de(s,s.properties,t);break;case"CallExpression":case"OptionalCallExpression":de(s,s.arguments,t);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":case"ObjectMethod":case"ClassMethod":case"ClassPrivateMethod":de(s,s.params,t);break;case"ArrayExpression":case"ArrayPattern":case"TupleExpression":de(s,s.elements,t);break;case"ExportNamedDeclaration":case"ImportDeclaration":de(s,s.specifiers,t);break;default:Te(s,e);}else Te(s,e);}}finalizeRemainingComments(){let{commentStack:t}=this.state;for(let e=t.length-1;e>=0;e--)this.finalizeComment(t[e]);this.state.commentStack=[];}resetPreviousNodeTrailingComments(t){let{commentStack:e}=this.state,{length:s}=e;if(s===0)return;let i=e[s-1];i.leadingNode===t&&(i.leadingNode=null);}resetPreviousIdentifierLeadingComments(t){let{commentStack:e}=this.state,{length:s}=e;s!==0&&(e[s-1].trailingNode===t?e[s-1].trailingNode=null:s>=2&&e[s-2].trailingNode===t&&(e[s-2].trailingNode=null));}takeSurroundingComments(t,e,s){let{commentStack:i}=this.state,r=i.length;if(r===0)return;let n=r-1;for(;n>=0;n--){let o=i[n],h=o.end;if(o.start===s)o.leadingNode=t;else if(h===e)o.trailingNode=t;else if(h=48&&t<=57},$t={decBinOct:new Set([46,66,69,79,95,98,101,111]),hex:new Set([46,88,95,120])},Ie={bin:a=>a===48||a===49,oct:a=>a>=48&&a<=55,dec:a=>a>=48&&a<=57,hex:a=>a>=48&&a<=57||a>=65&&a<=70||a>=97&&a<=102};function Vt(a,t,e,s,i,r){let n=e,o=s,h=i,l="",c=null,u=e,{length:f}=t;for(;;){if(e>=f){r.unterminated(n,o,h),l+=t.slice(u,e);break}let d=t.charCodeAt(e);if($i(a,d,t,e)){l+=t.slice(u,e);break}if(d===92){l+=t.slice(u,e);let x=Vi(t,e,s,i,a==="template",r);x.ch===null&&!c?c={pos:e,lineStart:s,curLine:i}:l+=x.ch,{pos:e,lineStart:s,curLine:i}=x,u=e;}else d===8232||d===8233?(++e,++i,s=e):d===10||d===13?a==="template"?(l+=t.slice(u,e)+` -`,++e,d===13&&t.charCodeAt(e)===10&&++e,++i,u=s=e):r.unterminated(n,o,h):++e;}return {pos:e,str:l,firstInvalidLoc:c,lineStart:s,curLine:i,containsInvalid:!!c}}function $i(a,t,e,s){return a==="template"?t===96||t===36&&e.charCodeAt(s+1)===123:t===(a==="double"?34:39)}function Vi(a,t,e,s,i,r){let n=!i;t++;let o=l=>({pos:t,ch:l,lineStart:e,curLine:s}),h=a.charCodeAt(t++);switch(h){case 110:return o(` -`);case 114:return o("\r");case 120:{let l;return {code:l,pos:t}=nt(a,t,e,s,2,!1,n,r),o(l===null?null:String.fromCharCode(l))}case 117:{let l;return {code:l,pos:t}=os(a,t,e,s,n,r),o(l===null?null:String.fromCodePoint(l))}case 116:return o(" ");case 98:return o("\b");case 118:return o("\v");case 102:return o("\f");case 13:a.charCodeAt(t)===10&&++t;case 10:e=t,++s;case 8232:case 8233:return o("");case 56:case 57:if(i)return o(null);r.strictNumericEscape(t-1,e,s);default:if(h>=48&&h<=55){let l=t-1,u=a.slice(l,t+2).match(/^[0-7]+/)[0],f=parseInt(u,8);f>255&&(u=u.slice(0,-1),f=parseInt(u,8)),t+=u.length-1;let d=a.charCodeAt(t);if(u!=="0"||d===56||d===57){if(i)return o(null);r.strictNumericEscape(l,e,s);}return o(String.fromCharCode(f))}return o(String.fromCharCode(h))}}function nt(a,t,e,s,i,r,n,o){let h=t,l;return {n:l,pos:t}=ns(a,t,e,s,16,i,r,!1,o,!n),l===null&&(n?o.invalidEscapeSequence(h,e,s):t=h-1),{code:l,pos:t}}function ns(a,t,e,s,i,r,n,o,h,l){let c=t,u=i===16?$t.hex:$t.decBinOct,f=i===16?Ie.hex:i===10?Ie.dec:i===8?Ie.oct:Ie.bin,d=!1,x=0;for(let I=0,C=r??1/0;I=97?N=E-97+10:E>=65?N=E-65+10:ji(E)?N=E-48:N=1/0,N>=i){if(N<=9&&l)return {n:null,pos:t};if(N<=9&&h.invalidDigit(t,e,s,i))N=0;else if(n)N=0,d=!0;else break}++t,x=x*i+N;}return t===c||r!=null&&t-c!==r||d?{n:null,pos:t}:{n:x,pos:t}}function os(a,t,e,s,i,r){let n=a.charCodeAt(t),o;if(n===123){if(++t,{code:o,pos:t}=nt(a,t,e,s,a.indexOf("}",t)-t,!0,i,r),++t,o!==null&&o>1114111)if(i)r.invalidCodePoint(t,e,s);else return {code:null,pos:t}}else ({code:o,pos:t}=nt(a,t,e,s,4,!1,i,r));return {code:o,pos:t}}var zi=["at"],Ki=["at"];function fe(a,t,e){return new F(e,a-t,a)}var qi=new Set([103,109,115,105,121,117,100,118]),O=class{constructor(t){this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,this.loc=new ie(t.startLoc,t.endLoc);}},ot=class extends rt{constructor(t,e){super(),this.isLookahead=void 0,this.tokens=[],this.errorHandlers_readInt={invalidDigit:(s,i,r,n)=>this.options.errorRecovery?(this.raise(p.InvalidDigit,{at:fe(s,i,r),radix:n}),!0):!1,numericSeparatorInEscapeSequence:this.errorBuilder(p.NumericSeparatorInEscapeSequence),unexpectedNumericSeparator:this.errorBuilder(p.UnexpectedNumericSeparator)},this.errorHandlers_readCodePoint=Object.assign({},this.errorHandlers_readInt,{invalidEscapeSequence:this.errorBuilder(p.InvalidEscapeSequence),invalidCodePoint:this.errorBuilder(p.InvalidCodePoint)}),this.errorHandlers_readStringContents_string=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:(s,i,r)=>{this.recordStrictModeErrors(p.StrictNumericEscape,{at:fe(s,i,r)});},unterminated:(s,i,r)=>{throw this.raise(p.UnterminatedString,{at:fe(s-1,i,r)})}}),this.errorHandlers_readStringContents_template=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:this.errorBuilder(p.StrictNumericEscape),unterminated:(s,i,r)=>{throw this.raise(p.UnterminatedTemplate,{at:fe(s,i,r)})}}),this.state=new at,this.state.init(t),this.input=e,this.length=e.length,this.isLookahead=!1;}pushToken(t){this.tokens.length=this.state.tokensLength,this.tokens.push(t),++this.state.tokensLength;}next(){this.checkKeywordEscapes(),this.options.tokens&&this.pushToken(new O(this.state)),this.state.lastTokStart=this.state.start,this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken();}eat(t){return this.match(t)?(this.next(),!0):!1}match(t){return this.state.type===t}createLookaheadState(t){return {pos:t.pos,value:null,type:t.type,start:t.start,end:t.end,context:[this.curContext()],inType:t.inType,startLoc:t.startLoc,lastTokEndLoc:t.lastTokEndLoc,curLine:t.curLine,lineStart:t.lineStart,curPosition:t.curPosition}}lookahead(){let t=this.state;this.state=this.createLookaheadState(t),this.isLookahead=!0,this.nextToken(),this.isLookahead=!1;let e=this.state;return this.state=t,e}nextTokenStart(){return this.nextTokenStartSince(this.state.pos)}nextTokenStartSince(t){return We.lastIndex=t,We.test(this.input)?We.lastIndex:t}lookaheadCharCode(){return this.input.charCodeAt(this.nextTokenStart())}nextTokenInLineStart(){return this.nextTokenInLineStartSince(this.state.pos)}nextTokenInLineStartSince(t){return ke.lastIndex=t,ke.test(this.input)?ke.lastIndex:t}lookaheadInLineCharCode(){return this.input.charCodeAt(this.nextTokenInLineStart())}codePointAtPos(t){let e=this.input.charCodeAt(t);if((e&64512)===55296&&++tthis.raise(e,{at:s})),this.state.strictErrors.clear());}curContext(){return this.state.context[this.state.context.length-1]}nextToken(){if(this.skipSpace(),this.state.start=this.state.pos,this.isLookahead||(this.state.startLoc=this.state.curPosition()),this.state.pos>=this.length){this.finishToken(137);return}this.getTokenFromCode(this.codePointAtPos(this.state.pos));}skipBlockComment(t){let e;this.isLookahead||(e=this.state.curPosition());let s=this.state.pos,i=this.input.indexOf(t,s+2);if(i===-1)throw this.raise(p.UnterminatedComment,{at:this.state.curPosition()});for(this.state.pos=i+t.length,Ee.lastIndex=s+2;Ee.test(this.input)&&Ee.lastIndex<=i;)++this.state.curLine,this.state.lineStart=Ee.lastIndex;if(this.isLookahead)return;let r={type:"CommentBlock",value:this.input.slice(s+2,i),start:s,end:i+t.length,loc:new ie(e,this.state.curPosition())};return this.options.tokens&&this.pushToken(r),r}skipLineComment(t){let e=this.state.pos,s;this.isLookahead||(s=this.state.curPosition());let i=this.input.charCodeAt(this.state.pos+=t);if(this.state.post)){let r=this.skipLineComment(3);r!==void 0&&(this.addComment(r),this.options.attachComment&&e.push(r));}else break e}else if(s===60&&!this.inModule&&this.options.annexB){let i=this.state.pos;if(this.input.charCodeAt(i+1)===33&&this.input.charCodeAt(i+2)===45&&this.input.charCodeAt(i+3)===45){let r=this.skipLineComment(4);r!==void 0&&(this.addComment(r),this.options.attachComment&&e.push(r));}else break e}else break e}}if(e.length>0){let s=this.state.pos,i={start:t,end:s,comments:e,leadingNode:null,trailingNode:null,containingNode:null};this.state.commentStack.push(i);}}finishToken(t,e){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();let s=this.state.type;this.state.type=t,this.state.value=e,this.isLookahead||this.updateContext(s);}replaceToken(t){this.state.type=t,this.updateContext();}readToken_numberSign(){if(this.state.pos===0&&this.readToken_interpreter())return;let t=this.state.pos+1,e=this.codePointAtPos(t);if(e>=48&&e<=57)throw this.raise(p.UnexpectedDigitAfterHash,{at:this.state.curPosition()});if(e===123||e===91&&this.hasPlugin("recordAndTuple")){if(this.expectPlugin("recordAndTuple"),this.getPluginOption("recordAndTuple","syntaxType")==="bar")throw this.raise(e===123?p.RecordExpressionHashIncorrectStartSyntaxType:p.TupleExpressionHashIncorrectStartSyntaxType,{at:this.state.curPosition()});this.state.pos+=2,e===123?this.finishToken(7):this.finishToken(1);}else j(e)?(++this.state.pos,this.finishToken(136,this.readWord1(e))):e===92?(++this.state.pos,this.finishToken(136,this.readWord1())):this.finishOp(27,1);}readToken_dot(){let t=this.input.charCodeAt(this.state.pos+1);if(t>=48&&t<=57){this.readNumber(!0);return}t===46&&this.input.charCodeAt(this.state.pos+2)===46?(this.state.pos+=3,this.finishToken(21)):(++this.state.pos,this.finishToken(16));}readToken_slash(){this.input.charCodeAt(this.state.pos+1)===61?this.finishOp(31,2):this.finishOp(56,1);}readToken_interpreter(){if(this.state.pos!==0||this.length<2)return !1;let t=this.input.charCodeAt(this.state.pos+1);if(t!==33)return !1;let e=this.state.pos;for(this.state.pos+=1;!xe(t)&&++this.state.pos=48&&e<=57)?(this.state.pos+=2,this.finishToken(18)):(++this.state.pos,this.finishToken(17));}getTokenFromCode(t){switch(t){case 46:this.readToken_dot();return;case 40:++this.state.pos,this.finishToken(10);return;case 41:++this.state.pos,this.finishToken(11);return;case 59:++this.state.pos,this.finishToken(13);return;case 44:++this.state.pos,this.finishToken(12);return;case 91:if(this.hasPlugin("recordAndTuple")&&this.input.charCodeAt(this.state.pos+1)===124){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(p.TupleExpressionBarIncorrectStartSyntaxType,{at:this.state.curPosition()});this.state.pos+=2,this.finishToken(2);}else ++this.state.pos,this.finishToken(0);return;case 93:++this.state.pos,this.finishToken(3);return;case 123:if(this.hasPlugin("recordAndTuple")&&this.input.charCodeAt(this.state.pos+1)===124){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(p.RecordExpressionBarIncorrectStartSyntaxType,{at:this.state.curPosition()});this.state.pos+=2,this.finishToken(6);}else ++this.state.pos,this.finishToken(5);return;case 125:++this.state.pos,this.finishToken(8);return;case 58:this.hasPlugin("functionBind")&&this.input.charCodeAt(this.state.pos+1)===58?this.finishOp(15,2):(++this.state.pos,this.finishToken(14));return;case 63:this.readToken_question();return;case 96:this.readTemplateToken();return;case 48:{let e=this.input.charCodeAt(this.state.pos+1);if(e===120||e===88){this.readRadixNumber(16);return}if(e===111||e===79){this.readRadixNumber(8);return}if(e===98||e===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(!1);return;case 34:case 39:this.readString(t);return;case 47:this.readToken_slash();return;case 37:case 42:this.readToken_mult_modulo(t);return;case 124:case 38:this.readToken_pipe_amp(t);return;case 94:this.readToken_caret();return;case 43:case 45:this.readToken_plus_min(t);return;case 60:this.readToken_lt();return;case 62:this.readToken_gt();return;case 61:case 33:this.readToken_eq_excl(t);return;case 126:this.finishOp(36,1);return;case 64:this.readToken_atSign();return;case 35:this.readToken_numberSign();return;case 92:this.readWord();return;default:if(j(t)){this.readWord(t);return}}throw this.raise(p.InvalidOrUnexpectedToken,{at:this.state.curPosition(),unexpected:String.fromCodePoint(t)})}finishOp(t,e){let s=this.input.slice(this.state.pos,this.state.pos+e);this.state.pos+=e,this.finishToken(t,s);}readRegexp(){let t=this.state.startLoc,e=this.state.start+1,s,i,{pos:r}=this.state;for(;;++r){if(r>=this.length)throw this.raise(p.UnterminatedRegExp,{at:L(t,1)});let l=this.input.charCodeAt(r);if(xe(l))throw this.raise(p.UnterminatedRegExp,{at:L(t,1)});if(s)s=!1;else {if(l===91)i=!0;else if(l===93&&i)i=!1;else if(l===47&&!i)break;s=l===92;}}let n=this.input.slice(e,r);++r;let o="",h=()=>L(t,r+2-e);for(;r=2&&this.input.charCodeAt(e)===48;if(l){let d=this.input.slice(e,this.state.pos);if(this.recordStrictModeErrors(p.StrictOctalLiteral,{at:s}),!this.state.strict){let x=d.indexOf("_");x>0&&this.raise(p.ZeroDigitNumericSeparator,{at:L(s,x)});}h=l&&!/[89]/.test(d);}let c=this.input.charCodeAt(this.state.pos);if(c===46&&!h&&(++this.state.pos,this.readInt(10),i=!0,c=this.input.charCodeAt(this.state.pos)),(c===69||c===101)&&!h&&(c=this.input.charCodeAt(++this.state.pos),(c===43||c===45)&&++this.state.pos,this.readInt(10)===null&&this.raise(p.InvalidOrMissingExponent,{at:s}),i=!0,o=!0,c=this.input.charCodeAt(this.state.pos)),c===110&&((i||l)&&this.raise(p.InvalidBigIntLiteral,{at:s}),++this.state.pos,r=!0),c===109&&(this.expectPlugin("decimal",this.state.curPosition()),(o||l)&&this.raise(p.InvalidDecimal,{at:s}),++this.state.pos,n=!0),j(this.codePointAtPos(this.state.pos)))throw this.raise(p.NumberIdentifier,{at:this.state.curPosition()});let u=this.input.slice(e,this.state.pos).replace(/[_mn]/g,"");if(r){this.finishToken(133,u);return}if(n){this.finishToken(134,u);return}let f=h?parseInt(u,8):parseFloat(u);this.finishToken(132,f);}readCodePoint(t){let{code:e,pos:s}=os(this.input,this.state.pos,this.state.lineStart,this.state.curLine,t,this.errorHandlers_readCodePoint);return this.state.pos=s,e}readString(t){let{str:e,pos:s,curLine:i,lineStart:r}=Vt(t===34?"double":"single",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_string);this.state.pos=s+1,this.state.lineStart=r,this.state.curLine=i,this.finishToken(131,e);}readTemplateContinuation(){this.match(8)||this.unexpected(null,8),this.state.pos--,this.readTemplateToken();}readTemplateToken(){let t=this.input[this.state.pos],{str:e,firstInvalidLoc:s,pos:i,curLine:r,lineStart:n}=Vt("template",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_template);this.state.pos=i+1,this.state.lineStart=n,this.state.curLine=r,s&&(this.state.firstInvalidTemplateEscapePos=new F(s.curLine,s.pos-s.lineStart,s.pos)),this.input.codePointAt(i)===96?this.finishToken(24,s?null:t+e+"`"):(this.state.pos++,this.finishToken(25,s?null:t+e+"${"));}recordStrictModeErrors(t,{at:e}){let s=e.index;this.state.strict&&!this.state.strictErrors.has(s)?this.raise(t,{at:e}):this.state.strictErrors.set(s,[t,e]);}readWord1(t){this.state.containsEsc=!1;let e="",s=this.state.pos,i=this.state.pos;for(t!==void 0&&(this.state.pos+=t<=65535?1:2);this.state.pos=0;h--){let l=o[h];if(l.loc.index===n)return o[h]=t({loc:r,details:i});if(l.loc.indexthis.hasPlugin(e)))throw this.raise(p.MissingOneOfPlugins,{at:this.state.startLoc,missingPlugin:t})}errorBuilder(t){return (e,s,i)=>{this.raise(t,{at:fe(e,s,i)});}}},ht=class{constructor(){this.privateNames=new Set,this.loneAccessors=new Map,this.undefinedPrivateNames=new Map;}},lt=class{constructor(t){this.parser=void 0,this.stack=[],this.undefinedPrivateNames=new Map,this.parser=t;}current(){return this.stack[this.stack.length-1]}enter(){this.stack.push(new ht);}exit(){let t=this.stack.pop(),e=this.current();for(let[s,i]of Array.from(t.undefinedPrivateNames))e?e.undefinedPrivateNames.has(s)||e.undefinedPrivateNames.set(s,i):this.parser.raise(p.InvalidPrivateFieldResolution,{at:i,identifierName:s});}declarePrivateName(t,e,s){let{privateNames:i,loneAccessors:r,undefinedPrivateNames:n}=this.current(),o=i.has(t);if(e&3){let h=o&&r.get(t);if(h){let l=h&4,c=e&4,u=h&3,f=e&3;o=u===f||l!==c,o||r.delete(t);}else o||r.set(t,e);}o&&this.parser.raise(p.PrivateNameRedeclaration,{at:s,identifierName:t}),i.add(t),n.delete(t);}usePrivateName(t,e){let s;for(s of this.stack)if(s.privateNames.has(t))return;s?s.undefinedPrivateNames.set(t,e):this.parser.raise(p.InvalidPrivateFieldResolution,{at:e,identifierName:t});}},re=class{constructor(t=0){this.type=t;}canBeArrowParameterDeclaration(){return this.type===2||this.type===1}isCertainlyParameterDeclaration(){return this.type===3}},Oe=class extends re{constructor(t){super(t),this.declarationErrors=new Map;}recordDeclarationError(t,{at:e}){let s=e.index;this.declarationErrors.set(s,[t,e]);}clearDeclarationError(t){this.declarationErrors.delete(t);}iterateErrors(t){this.declarationErrors.forEach(t);}},ct=class{constructor(t){this.parser=void 0,this.stack=[new re],this.parser=t;}enter(t){this.stack.push(t);}exit(){this.stack.pop();}recordParameterInitializerError(t,{at:e}){let s={at:e.loc.start},{stack:i}=this,r=i.length-1,n=i[r];for(;!n.isCertainlyParameterDeclaration();){if(n.canBeArrowParameterDeclaration())n.recordDeclarationError(t,s);else return;n=i[--r];}this.parser.raise(t,s);}recordArrowParameterBindingError(t,{at:e}){let{stack:s}=this,i=s[s.length-1],r={at:e.loc.start};if(i.isCertainlyParameterDeclaration())this.parser.raise(t,r);else if(i.canBeArrowParameterDeclaration())i.recordDeclarationError(t,r);else return}recordAsyncArrowParametersError({at:t}){let{stack:e}=this,s=e.length-1,i=e[s];for(;i.canBeArrowParameterDeclaration();)i.type===2&&i.recordDeclarationError(p.AwaitBindingIdentifier,{at:t}),i=e[--s];}validateAsPattern(){let{stack:t}=this,e=t[t.length-1];e.canBeArrowParameterDeclaration()&&e.iterateErrors(([s,i])=>{this.parser.raise(s,{at:i});let r=t.length-2,n=t[r];for(;n.canBeArrowParameterDeclaration();)n.clearDeclarationError(i.index),n=t[--r];});}};function Hi(){return new re(3)}function Wi(){return new Oe(1)}function Ji(){return new Oe(2)}function hs(){return new re}var te=0,ls=1,Be=2,cs=4,Q=8,pt=class{constructor(){this.stacks=[];}enter(t){this.stacks.push(t);}exit(){this.stacks.pop();}currentFlags(){return this.stacks[this.stacks.length-1]}get hasAwait(){return (this.currentFlags()&Be)>0}get hasYield(){return (this.currentFlags()&ls)>0}get hasReturn(){return (this.currentFlags()&cs)>0}get hasIn(){return (this.currentFlags()&Q)>0}};function ve(a,t){return (a?Be:0)|(t?ls:0)}var ut=class extends ot{addExtra(t,e,s,i=!0){if(!t)return;let r=t.extra=t.extra||{};i?r[e]=s:Object.defineProperty(r,e,{enumerable:i,value:s});}isContextual(t){return this.state.type===t&&!this.state.containsEsc}isUnparsedContextual(t,e){let s=t+e.length;if(this.input.slice(t,s)===e){let i=this.input.charCodeAt(s);return !(ee(i)||(i&64512)===55296)}return !1}isLookaheadContextual(t){let e=this.nextTokenStart();return this.isUnparsedContextual(e,t)}eatContextual(t){return this.isContextual(t)?(this.next(),!0):!1}expectContextual(t,e){if(!this.eatContextual(t)){if(e!=null)throw this.raise(e,{at:this.state.startLoc});this.unexpected(null,t);}}canInsertSemicolon(){return this.match(137)||this.match(8)||this.hasPrecedingLineBreak()}hasPrecedingLineBreak(){return as.test(this.input.slice(this.state.lastTokEndLoc.index,this.state.start))}hasFollowingLineBreak(){return jt.lastIndex=this.state.end,jt.test(this.input)}isLineTerminator(){return this.eat(13)||this.canInsertSemicolon()}semicolon(t=!0){(t?this.isLineTerminator():this.eat(13))||this.raise(p.MissingSemicolon,{at:this.state.lastTokEndLoc});}expect(t,e){this.eat(t)||this.unexpected(e,t);}tryParse(t,e=this.state.clone()){let s={node:null};try{let i=t((r=null)=>{throw s.node=r,s});if(this.state.errors.length>e.errors.length){let r=this.state;return this.state=e,this.state.tokensLength=r.tokensLength,{node:i,error:r.errors[e.errors.length],thrown:!1,aborted:!1,failState:r}}return {node:i,error:null,thrown:!1,aborted:!1,failState:null}}catch(i){let r=this.state;if(this.state=e,i instanceof SyntaxError)return {node:null,error:i,thrown:!0,aborted:!1,failState:r};if(i===s)return {node:s.node,error:null,thrown:!1,aborted:!0,failState:r};throw i}}checkExpressionErrors(t,e){if(!t)return !1;let{shorthandAssignLoc:s,doubleProtoLoc:i,privateKeyLoc:r,optionalParametersLoc:n}=t,o=!!s||!!i||!!n||!!r;if(!e)return o;s!=null&&this.raise(p.InvalidCoverInitializedName,{at:s}),i!=null&&this.raise(p.DuplicateProto,{at:i}),r!=null&&this.raise(p.UnexpectedPrivateField,{at:r}),n!=null&&this.unexpected(n);}isLiteralPropertyName(){return Yt(this.state.type)}isPrivateName(t){return t.type==="PrivateName"}getPrivateNameSV(t){return t.id.name}hasPropertyAsPrivateName(t){return (t.type==="MemberExpression"||t.type==="OptionalMemberExpression")&&this.isPrivateName(t.property)}isObjectProperty(t){return t.type==="ObjectProperty"}isObjectMethod(t){return t.type==="ObjectMethod"}initializeScopes(t=this.options.sourceType==="module"){let e=this.state.labels;this.state.labels=[];let s=this.exportedIdentifiers;this.exportedIdentifiers=new Set;let i=this.inModule;this.inModule=t;let r=this.scope,n=this.getScopeHandler();this.scope=new n(this,t);let o=this.prodParam;this.prodParam=new pt;let h=this.classScope;this.classScope=new lt(this);let l=this.expressionScope;return this.expressionScope=new ct(this),()=>{this.state.labels=e,this.exportedIdentifiers=s,this.inModule=i,this.scope=r,this.prodParam=o,this.classScope=h,this.expressionScope=l;}}enterInitialScopes(){let t=te;this.inModule&&(t|=Be),this.scope.enter(1),this.prodParam.enter(t);}checkDestructuringPrivate(t){let{privateKeyLoc:e}=t;e!==null&&this.expectPlugin("destructuringPrivate",e);}},se=class{constructor(){this.shorthandAssignLoc=null,this.doubleProtoLoc=null,this.privateKeyLoc=null,this.optionalParametersLoc=null;}},ae=class{constructor(t,e,s){this.type="",this.start=e,this.end=0,this.loc=new ie(s),t!=null&&t.options.ranges&&(this.range=[e,0]),t!=null&&t.filename&&(this.loc.filename=t.filename);}},Nt=ae.prototype;Nt.__clone=function(){let a=new ae(void 0,this.start,this.loc.start),t=Object.keys(this);for(let e=0,s=t.length;e`Cannot overwrite reserved type ${a}.`,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:({memberName:a,enumName:t})=>`Boolean enum members need to be initialized. Use either \`${a} = true,\` or \`${a} = false,\` in enum \`${t}\`.`,EnumDuplicateMemberName:({memberName:a,enumName:t})=>`Enum member names need to be unique, but the name \`${a}\` has already been used before in enum \`${t}\`.`,EnumInconsistentMemberValues:({enumName:a})=>`Enum \`${a}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,EnumInvalidExplicitType:({invalidEnumType:a,enumName:t})=>`Enum type \`${a}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${t}\`.`,EnumInvalidExplicitTypeUnknownSupplied:({enumName:a})=>`Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${a}\`.`,EnumInvalidMemberInitializerPrimaryType:({enumName:a,memberName:t,explicitType:e})=>`Enum \`${a}\` has type \`${e}\`, so the initializer of \`${t}\` needs to be a ${e} literal.`,EnumInvalidMemberInitializerSymbolType:({enumName:a,memberName:t})=>`Symbol enum members cannot be initialized. Use \`${t},\` in enum \`${a}\`.`,EnumInvalidMemberInitializerUnknownType:({enumName:a,memberName:t})=>`The enum member initializer for \`${t}\` needs to be a literal (either a boolean, number, or string) in enum \`${a}\`.`,EnumInvalidMemberName:({enumName:a,memberName:t,suggestion:e})=>`Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${t}\`, consider using \`${e}\`, in enum \`${a}\`.`,EnumNumberMemberNotInitialized:({enumName:a,memberName:t})=>`Number enum members need to be initialized, e.g. \`${t} = 1\` in enum \`${a}\`.`,EnumStringMemberInconsistentlyInitialized:({enumName:a})=>`String enum members need to consistently either all use initializers, or use no initializers, in enum \`${a}\`.`,GetterMayNotHaveThisParam:"A getter cannot have a `this` parameter.",ImportReflectionHasImportType:"An `import module` declaration can not use `type` or `typeof` keyword.",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.",PatternIsOptional:Object.assign({message:"A binding pattern parameter cannot be optional in an implementation signature."},{reasonCode:"OptionalBindingPattern"}),SetterMayNotHaveThisParam:"A setter cannot have a `this` parameter.",SpreadVariance:"Spread properties cannot have variance.",ThisParamAnnotationRequired:"A type annotation is required for the `this` parameter.",ThisParamBannedInConstructor:"Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",ThisParamMayNotBeOptional:"The `this` parameter cannot be optional.",ThisParamMustBeFirst:"The `this` parameter must be the first function parameter.",ThisParamNoDefault:"The `this` parameter may not have a default value.",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:({reservedType:a})=>`Unexpected reserved type ${a}.`,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 ` async () => {}`, use `async () => {}`.",UnsupportedDeclareExportKind:({unsupportedExportKind:a,suggestion:t})=>`\`declare export ${a}\` is not supported. Use \`${t}\` instead.`,UnsupportedStatementInDeclareModule:"Only declares and type imports are allowed inside declare module.",UnterminatedFlowComment:"Unterminated flow-comment."});function Qi(a){return a.type==="DeclareExportAllDeclaration"||a.type==="DeclareExportDeclaration"&&(!a.declaration||a.declaration.type!=="TypeAlias"&&a.declaration.type!=="InterfaceDeclaration")}function zt(a){return a.importKind==="type"||a.importKind==="typeof"}var Zi={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"};function er(a,t){let e=[],s=[];for(let i=0;iclass extends a{constructor(...e){super(...e),this.flowPragma=void 0;}getScopeHandler(){return st}shouldParseTypes(){return this.getPluginOption("flow","all")||this.flowPragma==="flow"}shouldParseEnums(){return !!this.getPluginOption("flow","enums")}finishToken(e,s){e!==131&&e!==13&&e!==28&&this.flowPragma===void 0&&(this.flowPragma=null),super.finishToken(e,s);}addComment(e){if(this.flowPragma===void 0){let s=tr.exec(e.value);if(s)if(s[1]==="flow")this.flowPragma="flow";else if(s[1]==="noflow")this.flowPragma="noflow";else throw new Error("Unexpected flow pragma")}super.addComment(e);}flowParseTypeInitialiser(e){let s=this.state.inType;this.state.inType=!0,this.expect(e||14);let i=this.flowParseType();return this.state.inType=s,i}flowParsePredicate(){let e=this.startNode(),s=this.state.startLoc;return this.next(),this.expectContextual(108),this.state.lastTokStart>s.index+1&&this.raise(g.UnexpectedSpaceBetweenModuloChecks,{at:s}),this.eat(10)?(e.value=super.parseExpression(),this.expect(11),this.finishNode(e,"DeclaredPredicate")):this.finishNode(e,"InferredPredicate")}flowParseTypeAndPredicateInitialiser(){let e=this.state.inType;this.state.inType=!0,this.expect(14);let s=null,i=null;return this.match(54)?(this.state.inType=e,i=this.flowParsePredicate()):(s=this.flowParseType(),this.state.inType=e,this.match(54)&&(i=this.flowParsePredicate())),[s,i]}flowParseDeclareClass(e){return this.next(),this.flowParseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")}flowParseDeclareFunction(e){this.next();let s=e.id=this.parseIdentifier(),i=this.startNode(),r=this.startNode();this.match(47)?i.typeParameters=this.flowParseTypeParameterDeclaration():i.typeParameters=null,this.expect(10);let n=this.flowParseFunctionTypeParams();return i.params=n.params,i.rest=n.rest,i.this=n._this,this.expect(11),[i.returnType,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),r.typeAnnotation=this.finishNode(i,"FunctionTypeAnnotation"),s.typeAnnotation=this.finishNode(r,"TypeAnnotation"),this.resetEndLocation(s),this.semicolon(),this.scope.declareName(e.id.name,2048,e.id.loc.start),this.finishNode(e,"DeclareFunction")}flowParseDeclare(e,s){if(this.match(80))return this.flowParseDeclareClass(e);if(this.match(68))return this.flowParseDeclareFunction(e);if(this.match(74))return this.flowParseDeclareVariable(e);if(this.eatContextual(125))return this.match(16)?this.flowParseDeclareModuleExports(e):(s&&this.raise(g.NestedDeclareModule,{at:this.state.lastTokStartLoc}),this.flowParseDeclareModule(e));if(this.isContextual(128))return this.flowParseDeclareTypeAlias(e);if(this.isContextual(129))return this.flowParseDeclareOpaqueType(e);if(this.isContextual(127))return this.flowParseDeclareInterface(e);if(this.match(82))return this.flowParseDeclareExportDeclaration(e,s);this.unexpected();}flowParseDeclareVariable(e){return this.next(),e.id=this.flowParseTypeAnnotatableIdentifier(!0),this.scope.declareName(e.id.name,5,e.id.loc.start),this.semicolon(),this.finishNode(e,"DeclareVariable")}flowParseDeclareModule(e){this.scope.enter(0),this.match(131)?e.id=super.parseExprAtom():e.id=this.parseIdentifier();let s=e.body=this.startNode(),i=s.body=[];for(this.expect(5);!this.match(8);){let o=this.startNode();this.match(83)?(this.next(),!this.isContextual(128)&&!this.match(87)&&this.raise(g.InvalidNonTypeImportInDeclareModule,{at:this.state.lastTokStartLoc}),super.parseImport(o)):(this.expectContextual(123,g.UnsupportedStatementInDeclareModule),o=this.flowParseDeclare(o,!0)),i.push(o);}this.scope.exit(),this.expect(8),this.finishNode(s,"BlockStatement");let r=null,n=!1;return i.forEach(o=>{Qi(o)?(r==="CommonJS"&&this.raise(g.AmbiguousDeclareModuleKind,{at:o}),r="ES"):o.type==="DeclareModuleExports"&&(n&&this.raise(g.DuplicateDeclareModuleExports,{at:o}),r==="ES"&&this.raise(g.AmbiguousDeclareModuleKind,{at:o}),r="CommonJS",n=!0);}),e.kind=r||"CommonJS",this.finishNode(e,"DeclareModule")}flowParseDeclareExportDeclaration(e,s){if(this.expect(82),this.eat(65))return this.match(68)||this.match(80)?e.declaration=this.flowParseDeclare(this.startNode()):(e.declaration=this.flowParseType(),this.semicolon()),e.default=!0,this.finishNode(e,"DeclareExportDeclaration");if(this.match(75)||this.isLet()||(this.isContextual(128)||this.isContextual(127))&&!s){let i=this.state.value;throw this.raise(g.UnsupportedDeclareExportKind,{at:this.state.startLoc,unsupportedExportKind:i,suggestion:Zi[i]})}if(this.match(74)||this.match(68)||this.match(80)||this.isContextual(129))return e.declaration=this.flowParseDeclare(this.startNode()),e.default=!1,this.finishNode(e,"DeclareExportDeclaration");if(this.match(55)||this.match(5)||this.isContextual(127)||this.isContextual(128)||this.isContextual(129))return e=this.parseExport(e,null),e.type==="ExportNamedDeclaration"&&(e.type="ExportDeclaration",e.default=!1,delete e.exportKind),e.type="Declare"+e.type,e;this.unexpected();}flowParseDeclareModuleExports(e){return this.next(),this.expectContextual(109),e.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(e,"DeclareModuleExports")}flowParseDeclareTypeAlias(e){this.next();let s=this.flowParseTypeAlias(e);return s.type="DeclareTypeAlias",s}flowParseDeclareOpaqueType(e){this.next();let s=this.flowParseOpaqueType(e,!0);return s.type="DeclareOpaqueType",s}flowParseDeclareInterface(e){return this.next(),this.flowParseInterfaceish(e,!1),this.finishNode(e,"DeclareInterface")}flowParseInterfaceish(e,s){if(e.id=this.flowParseRestrictedIdentifier(!s,!0),this.scope.declareName(e.id.name,s?17:8201,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.extends=[],this.eat(81))do e.extends.push(this.flowParseInterfaceExtends());while(!s&&this.eat(12));if(s){if(e.implements=[],e.mixins=[],this.eatContextual(115))do e.mixins.push(this.flowParseInterfaceExtends());while(this.eat(12));if(this.eatContextual(111))do e.implements.push(this.flowParseInterfaceExtends());while(this.eat(12))}e.body=this.flowParseObjectType({allowStatic:s,allowExact:!1,allowSpread:!1,allowProto:s,allowInexact:!1});}flowParseInterfaceExtends(){let e=this.startNode();return e.id=this.flowParseQualifiedTypeIdentifier(),this.match(47)?e.typeParameters=this.flowParseTypeParameterInstantiation():e.typeParameters=null,this.finishNode(e,"InterfaceExtends")}flowParseInterface(e){return this.flowParseInterfaceish(e,!1),this.finishNode(e,"InterfaceDeclaration")}checkNotUnderscore(e){e==="_"&&this.raise(g.UnexpectedReservedUnderscore,{at:this.state.startLoc});}checkReservedType(e,s,i){Yi.has(e)&&this.raise(i?g.AssignReservedType:g.UnexpectedReservedType,{at:s,reservedType:e});}flowParseRestrictedIdentifier(e,s){return this.checkReservedType(this.state.value,this.state.startLoc,s),this.parseIdentifier(e)}flowParseTypeAlias(e){return e.id=this.flowParseRestrictedIdentifier(!1,!0),this.scope.declareName(e.id.name,8201,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.right=this.flowParseTypeInitialiser(29),this.semicolon(),this.finishNode(e,"TypeAlias")}flowParseOpaqueType(e,s){return this.expectContextual(128),e.id=this.flowParseRestrictedIdentifier(!0,!0),this.scope.declareName(e.id.name,8201,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.supertype=null,this.match(14)&&(e.supertype=this.flowParseTypeInitialiser(14)),e.impltype=null,s||(e.impltype=this.flowParseTypeInitialiser(29)),this.semicolon(),this.finishNode(e,"OpaqueType")}flowParseTypeParameter(e=!1){let s=this.state.startLoc,i=this.startNode(),r=this.flowParseVariance(),n=this.flowParseTypeAnnotatableIdentifier();return i.name=n.name,i.variance=r,i.bound=n.typeAnnotation,this.match(29)?(this.eat(29),i.default=this.flowParseType()):e&&this.raise(g.MissingTypeParamDefault,{at:s}),this.finishNode(i,"TypeParameter")}flowParseTypeParameterDeclaration(){let e=this.state.inType,s=this.startNode();s.params=[],this.state.inType=!0,this.match(47)||this.match(140)?this.next():this.unexpected();let i=!1;do{let r=this.flowParseTypeParameter(i);s.params.push(r),r.default&&(i=!0),this.match(48)||this.expect(12);}while(!this.match(48));return this.expect(48),this.state.inType=e,this.finishNode(s,"TypeParameterDeclaration")}flowParseTypeParameterInstantiation(){let e=this.startNode(),s=this.state.inType;e.params=[],this.state.inType=!0,this.expect(47);let i=this.state.noAnonFunctionType;for(this.state.noAnonFunctionType=!1;!this.match(48);)e.params.push(this.flowParseType()),this.match(48)||this.expect(12);return this.state.noAnonFunctionType=i,this.expect(48),this.state.inType=s,this.finishNode(e,"TypeParameterInstantiation")}flowParseTypeParameterInstantiationCallOrNew(){let e=this.startNode(),s=this.state.inType;for(e.params=[],this.state.inType=!0,this.expect(47);!this.match(48);)e.params.push(this.flowParseTypeOrImplicitInstantiation()),this.match(48)||this.expect(12);return this.expect(48),this.state.inType=s,this.finishNode(e,"TypeParameterInstantiation")}flowParseInterfaceType(){let e=this.startNode();if(this.expectContextual(127),e.extends=[],this.eat(81))do e.extends.push(this.flowParseInterfaceExtends());while(this.eat(12));return e.body=this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!1,allowProto:!1,allowInexact:!1}),this.finishNode(e,"InterfaceTypeAnnotation")}flowParseObjectPropertyKey(){return this.match(132)||this.match(131)?super.parseExprAtom():this.parseIdentifier(!0)}flowParseObjectTypeIndexer(e,s,i){return e.static=s,this.lookahead().type===14?(e.id=this.flowParseObjectPropertyKey(),e.key=this.flowParseTypeInitialiser()):(e.id=null,e.key=this.flowParseType()),this.expect(3),e.value=this.flowParseTypeInitialiser(),e.variance=i,this.finishNode(e,"ObjectTypeIndexer")}flowParseObjectTypeInternalSlot(e,s){return e.static=s,e.id=this.flowParseObjectPropertyKey(),this.expect(3),this.expect(3),this.match(47)||this.match(10)?(e.method=!0,e.optional=!1,e.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e.loc.start))):(e.method=!1,this.eat(17)&&(e.optional=!0),e.value=this.flowParseTypeInitialiser()),this.finishNode(e,"ObjectTypeInternalSlot")}flowParseObjectTypeMethodish(e){for(e.params=[],e.rest=null,e.typeParameters=null,e.this=null,this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(10),this.match(78)&&(e.this=this.flowParseFunctionTypeParam(!0),e.this.name=null,this.match(11)||this.expect(12));!this.match(11)&&!this.match(21);)e.params.push(this.flowParseFunctionTypeParam(!1)),this.match(11)||this.expect(12);return this.eat(21)&&(e.rest=this.flowParseFunctionTypeParam(!1)),this.expect(11),e.returnType=this.flowParseTypeInitialiser(),this.finishNode(e,"FunctionTypeAnnotation")}flowParseObjectTypeCallProperty(e,s){let i=this.startNode();return e.static=s,e.value=this.flowParseObjectTypeMethodish(i),this.finishNode(e,"ObjectTypeCallProperty")}flowParseObjectType({allowStatic:e,allowExact:s,allowSpread:i,allowProto:r,allowInexact:n}){let o=this.state.inType;this.state.inType=!0;let h=this.startNode();h.callProperties=[],h.properties=[],h.indexers=[],h.internalSlots=[];let l,c,u=!1;for(s&&this.match(6)?(this.expect(6),l=9,c=!0):(this.expect(5),l=8,c=!1),h.exact=c;!this.match(l);){let d=!1,x=null,I=null,C=this.startNode();if(r&&this.isContextual(116)){let N=this.lookahead();N.type!==14&&N.type!==17&&(this.next(),x=this.state.startLoc,e=!1);}if(e&&this.isContextual(104)){let N=this.lookahead();N.type!==14&&N.type!==17&&(this.next(),d=!0);}let E=this.flowParseVariance();if(this.eat(0))x!=null&&this.unexpected(x),this.eat(0)?(E&&this.unexpected(E.loc.start),h.internalSlots.push(this.flowParseObjectTypeInternalSlot(C,d))):h.indexers.push(this.flowParseObjectTypeIndexer(C,d,E));else if(this.match(10)||this.match(47))x!=null&&this.unexpected(x),E&&this.unexpected(E.loc.start),h.callProperties.push(this.flowParseObjectTypeCallProperty(C,d));else {let N="init";if(this.isContextual(98)||this.isContextual(103)){let ce=this.lookahead();Yt(ce.type)&&(N=this.state.value,this.next());}let Ce=this.flowParseObjectTypeProperty(C,d,x,E,N,i,n??!c);Ce===null?(u=!0,I=this.state.lastTokStartLoc):h.properties.push(Ce);}this.flowObjectTypeSemicolon(),I&&!this.match(8)&&!this.match(9)&&this.raise(g.UnexpectedExplicitInexactInObject,{at:I});}this.expect(l),i&&(h.inexact=u);let f=this.finishNode(h,"ObjectTypeAnnotation");return this.state.inType=o,f}flowParseObjectTypeProperty(e,s,i,r,n,o,h){if(this.eat(21))return this.match(12)||this.match(13)||this.match(8)||this.match(9)?(o?h||this.raise(g.InexactInsideExact,{at:this.state.lastTokStartLoc}):this.raise(g.InexactInsideNonObject,{at:this.state.lastTokStartLoc}),r&&this.raise(g.InexactVariance,{at:r}),null):(o||this.raise(g.UnexpectedSpreadType,{at:this.state.lastTokStartLoc}),i!=null&&this.unexpected(i),r&&this.raise(g.SpreadVariance,{at:r}),e.argument=this.flowParseType(),this.finishNode(e,"ObjectTypeSpreadProperty"));{e.key=this.flowParseObjectPropertyKey(),e.static=s,e.proto=i!=null,e.kind=n;let l=!1;return this.match(47)||this.match(10)?(e.method=!0,i!=null&&this.unexpected(i),r&&this.unexpected(r.loc.start),e.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e.loc.start)),(n==="get"||n==="set")&&this.flowCheckGetterSetterParams(e),!o&&e.key.name==="constructor"&&e.value.this&&this.raise(g.ThisParamBannedInConstructor,{at:e.value.this})):(n!=="init"&&this.unexpected(),e.method=!1,this.eat(17)&&(l=!0),e.value=this.flowParseTypeInitialiser(),e.variance=r),e.optional=l,this.finishNode(e,"ObjectTypeProperty")}}flowCheckGetterSetterParams(e){let s=e.kind==="get"?0:1,i=e.value.params.length+(e.value.rest?1:0);e.value.this&&this.raise(e.kind==="get"?g.GetterMayNotHaveThisParam:g.SetterMayNotHaveThisParam,{at:e.value.this}),i!==s&&this.raise(e.kind==="get"?p.BadGetterArity:p.BadSetterArity,{at:e}),e.kind==="set"&&e.value.rest&&this.raise(p.BadSetterRestParameter,{at:e});}flowObjectTypeSemicolon(){!this.eat(13)&&!this.eat(12)&&!this.match(8)&&!this.match(9)&&this.unexpected();}flowParseQualifiedTypeIdentifier(e,s){(e)!=null||(e=this.state.startLoc);let r=s||this.flowParseRestrictedIdentifier(!0);for(;this.eat(16);){let n=this.startNodeAt(e);n.qualification=r,n.id=this.flowParseRestrictedIdentifier(!0),r=this.finishNode(n,"QualifiedTypeIdentifier");}return r}flowParseGenericType(e,s){let i=this.startNodeAt(e);return i.typeParameters=null,i.id=this.flowParseQualifiedTypeIdentifier(e,s),this.match(47)&&(i.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(i,"GenericTypeAnnotation")}flowParseTypeofType(){let e=this.startNode();return this.expect(87),e.argument=this.flowParsePrimaryType(),this.finishNode(e,"TypeofTypeAnnotation")}flowParseTupleType(){let e=this.startNode();for(e.types=[],this.expect(0);this.state.possuper.parseFunctionBody(e,!0,i));return}super.parseFunctionBody(e,!1,i);}parseFunctionBodyAndFinish(e,s,i=!1){if(this.match(14)){let r=this.startNode();[r.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),e.returnType=r.typeAnnotation?this.finishNode(r,"TypeAnnotation"):null;}return super.parseFunctionBodyAndFinish(e,s,i)}parseStatementLike(e){if(this.state.strict&&this.isContextual(127)){let i=this.lookahead();if(M(i.type)){let r=this.startNode();return this.next(),this.flowParseInterface(r)}}else if(this.shouldParseEnums()&&this.isContextual(124)){let i=this.startNode();return this.next(),this.flowParseEnumDeclaration(i)}let s=super.parseStatementLike(e);return this.flowPragma===void 0&&!this.isValidDirective(s)&&(this.flowPragma=null),s}parseExpressionStatement(e,s,i){if(s.type==="Identifier"){if(s.name==="declare"){if(this.match(80)||S(this.state.type)||this.match(68)||this.match(74)||this.match(82))return this.flowParseDeclare(e)}else if(S(this.state.type)){if(s.name==="interface")return this.flowParseInterface(e);if(s.name==="type")return this.flowParseTypeAlias(e);if(s.name==="opaque")return this.flowParseOpaqueType(e,!1)}}return super.parseExpressionStatement(e,s,i)}shouldParseExportDeclaration(){let{type:e}=this.state;return Ut(e)||this.shouldParseEnums()&&e===124?!this.state.containsEsc:super.shouldParseExportDeclaration()}isExportDefaultSpecifier(){let{type:e}=this.state;return Ut(e)||this.shouldParseEnums()&&e===124?this.state.containsEsc:super.isExportDefaultSpecifier()}parseExportDefaultExpression(){if(this.shouldParseEnums()&&this.isContextual(124)){let e=this.startNode();return this.next(),this.flowParseEnumDeclaration(e)}return super.parseExportDefaultExpression()}parseConditional(e,s,i){if(!this.match(17))return e;if(this.state.maybeInArrowParameters){let f=this.lookaheadCharCode();if(f===44||f===61||f===58||f===41)return this.setOptionalParametersError(i),e}this.expect(17);let r=this.state.clone(),n=this.state.noArrowAt,o=this.startNodeAt(s),{consequent:h,failed:l}=this.tryParseConditionalConsequent(),[c,u]=this.getArrowLikeExpressions(h);if(l||u.length>0){let f=[...n];if(u.length>0){this.state=r,this.state.noArrowAt=f;for(let d=0;d1&&this.raise(g.AmbiguousConditionalArrow,{at:r.startLoc}),l&&c.length===1&&(this.state=r,f.push(c[0].start),this.state.noArrowAt=f,{consequent:h,failed:l}=this.tryParseConditionalConsequent());}return this.getArrowLikeExpressions(h,!0),this.state.noArrowAt=n,this.expect(14),o.test=e,o.consequent=h,o.alternate=this.forwardNoArrowParamsConversionAt(o,()=>this.parseMaybeAssign(void 0,void 0)),this.finishNode(o,"ConditionalExpression")}tryParseConditionalConsequent(){this.state.noArrowParamsConversionAt.push(this.state.start);let e=this.parseMaybeAssignAllowIn(),s=!this.match(14);return this.state.noArrowParamsConversionAt.pop(),{consequent:e,failed:s}}getArrowLikeExpressions(e,s){let i=[e],r=[];for(;i.length!==0;){let n=i.pop();n.type==="ArrowFunctionExpression"?(n.typeParameters||!n.returnType?this.finishArrowValidation(n):r.push(n),i.push(n.body)):n.type==="ConditionalExpression"&&(i.push(n.consequent),i.push(n.alternate));}return s?(r.forEach(n=>this.finishArrowValidation(n)),[r,[]]):er(r,n=>n.params.every(o=>this.isAssignable(o,!0)))}finishArrowValidation(e){var s;this.toAssignableList(e.params,(s=e.extra)==null?void 0:s.trailingCommaLoc,!1),this.scope.enter(6),super.checkParams(e,!1,!0),this.scope.exit();}forwardNoArrowParamsConversionAt(e,s){let i;return this.state.noArrowParamsConversionAt.indexOf(e.start)!==-1?(this.state.noArrowParamsConversionAt.push(this.state.start),i=s(),this.state.noArrowParamsConversionAt.pop()):i=s(),i}parseParenItem(e,s){if(e=super.parseParenItem(e,s),this.eat(17)&&(e.optional=!0,this.resetEndLocation(e)),this.match(14)){let i=this.startNodeAt(s);return i.expression=e,i.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(i,"TypeCastExpression")}return e}assertModuleNodeAllowed(e){e.type==="ImportDeclaration"&&(e.importKind==="type"||e.importKind==="typeof")||e.type==="ExportNamedDeclaration"&&e.exportKind==="type"||e.type==="ExportAllDeclaration"&&e.exportKind==="type"||super.assertModuleNodeAllowed(e);}parseExportDeclaration(e){if(this.isContextual(128)){e.exportKind="type";let s=this.startNode();return this.next(),this.match(5)?(e.specifiers=this.parseExportSpecifiers(!0),super.parseExportFrom(e),null):this.flowParseTypeAlias(s)}else if(this.isContextual(129)){e.exportKind="type";let s=this.startNode();return this.next(),this.flowParseOpaqueType(s,!1)}else if(this.isContextual(127)){e.exportKind="type";let s=this.startNode();return this.next(),this.flowParseInterface(s)}else if(this.shouldParseEnums()&&this.isContextual(124)){e.exportKind="value";let s=this.startNode();return this.next(),this.flowParseEnumDeclaration(s)}else return super.parseExportDeclaration(e)}eatExportStar(e){return super.eatExportStar(e)?!0:this.isContextual(128)&&this.lookahead().type===55?(e.exportKind="type",this.next(),this.next(),!0):!1}maybeParseExportNamespaceSpecifier(e){let{startLoc:s}=this.state,i=super.maybeParseExportNamespaceSpecifier(e);return i&&e.exportKind==="type"&&this.unexpected(s),i}parseClassId(e,s,i){super.parseClassId(e,s,i),this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration());}parseClassMember(e,s,i){let{startLoc:r}=this.state;if(this.isContextual(123)){if(super.parseClassMemberFromModifier(e,s))return;s.declare=!0;}super.parseClassMember(e,s,i),s.declare&&(s.type!=="ClassProperty"&&s.type!=="ClassPrivateProperty"&&s.type!=="PropertyDefinition"?this.raise(g.DeclareClassElement,{at:r}):s.value&&this.raise(g.DeclareClassFieldInitializer,{at:s.value}));}isIterator(e){return e==="iterator"||e==="asyncIterator"}readIterator(){let e=super.readWord1(),s="@@"+e;(!this.isIterator(e)||!this.state.inType)&&this.raise(p.InvalidIdentifier,{at:this.state.curPosition(),identifierName:s}),this.finishToken(130,s);}getTokenFromCode(e){let s=this.input.charCodeAt(this.state.pos+1);e===123&&s===124?this.finishOp(6,2):this.state.inType&&(e===62||e===60)?this.finishOp(e===62?48:47,1):this.state.inType&&e===63?s===46?this.finishOp(18,2):this.finishOp(17,1):Fi(e,s,this.input.charCodeAt(this.state.pos+2))?(this.state.pos+=2,this.readIterator()):super.getTokenFromCode(e);}isAssignable(e,s){return e.type==="TypeCastExpression"?this.isAssignable(e.expression,s):super.isAssignable(e,s)}toAssignable(e,s=!1){!s&&e.type==="AssignmentExpression"&&e.left.type==="TypeCastExpression"&&(e.left=this.typeCastToParameter(e.left)),super.toAssignable(e,s);}toAssignableList(e,s,i){for(let r=0;r1||!s)&&this.raise(g.TypeCastInPattern,{at:n.typeAnnotation});}return e}parseArrayLike(e,s,i,r){let n=super.parseArrayLike(e,s,i,r);return s&&!this.state.maybeInArrowParameters&&this.toReferencedList(n.elements),n}isValidLVal(e,s,i){return e==="TypeCastExpression"||super.isValidLVal(e,s,i)}parseClassProperty(e){return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassProperty(e)}parseClassPrivateProperty(e){return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassPrivateProperty(e)}isClassMethod(){return this.match(47)||super.isClassMethod()}isClassProperty(){return this.match(14)||super.isClassProperty()}isNonstaticConstructor(e){return !this.match(14)&&super.isNonstaticConstructor(e)}pushClassMethod(e,s,i,r,n,o){if(s.variance&&this.unexpected(s.variance.loc.start),delete s.variance,this.match(47)&&(s.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassMethod(e,s,i,r,n,o),s.params&&n){let h=s.params;h.length>0&&this.isThisParam(h[0])&&this.raise(g.ThisParamBannedInConstructor,{at:s});}else if(s.type==="MethodDefinition"&&n&&s.value.params){let h=s.value.params;h.length>0&&this.isThisParam(h[0])&&this.raise(g.ThisParamBannedInConstructor,{at:s});}}pushClassPrivateMethod(e,s,i,r){s.variance&&this.unexpected(s.variance.loc.start),delete s.variance,this.match(47)&&(s.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassPrivateMethod(e,s,i,r);}parseClassSuper(e){if(super.parseClassSuper(e),e.superClass&&this.match(47)&&(e.superTypeParameters=this.flowParseTypeParameterInstantiation()),this.isContextual(111)){this.next();let s=e.implements=[];do{let i=this.startNode();i.id=this.flowParseRestrictedIdentifier(!0),this.match(47)?i.typeParameters=this.flowParseTypeParameterInstantiation():i.typeParameters=null,s.push(this.finishNode(i,"ClassImplements"));}while(this.eat(12))}}checkGetterSetterParams(e){super.checkGetterSetterParams(e);let s=this.getObjectOrClassMethodParams(e);if(s.length>0){let i=s[0];this.isThisParam(i)&&e.kind==="get"?this.raise(g.GetterMayNotHaveThisParam,{at:i}):this.isThisParam(i)&&this.raise(g.SetterMayNotHaveThisParam,{at:i});}}parsePropertyNamePrefixOperator(e){e.variance=this.flowParseVariance();}parseObjPropValue(e,s,i,r,n,o,h){e.variance&&this.unexpected(e.variance.loc.start),delete e.variance;let l;this.match(47)&&!o&&(l=this.flowParseTypeParameterDeclaration(),this.match(10)||this.unexpected());let c=super.parseObjPropValue(e,s,i,r,n,o,h);return l&&((c.value||c).typeParameters=l),c}parseAssignableListItemTypes(e){return this.eat(17)&&(e.type!=="Identifier"&&this.raise(g.PatternIsOptional,{at:e}),this.isThisParam(e)&&this.raise(g.ThisParamMayNotBeOptional,{at:e}),e.optional=!0),this.match(14)?e.typeAnnotation=this.flowParseTypeAnnotation():this.isThisParam(e)&&this.raise(g.ThisParamAnnotationRequired,{at:e}),this.match(29)&&this.isThisParam(e)&&this.raise(g.ThisParamNoDefault,{at:e}),this.resetEndLocation(e),e}parseMaybeDefault(e,s){let i=super.parseMaybeDefault(e,s);return i.type==="AssignmentPattern"&&i.typeAnnotation&&i.right.startsuper.parseMaybeAssign(e,s),r),!n.error)return n.node;let{context:l}=this.state,c=l[l.length-1];(c===w.j_oTag||c===w.j_expr)&&l.pop();}if((i=n)!=null&&i.error||this.match(47)){var o,h;r=r||this.state.clone();let l,c=this.tryParse(f=>{var d;l=this.flowParseTypeParameterDeclaration();let x=this.forwardNoArrowParamsConversionAt(l,()=>{let C=super.parseMaybeAssign(e,s);return this.resetStartLocationFromNode(C,l),C});(d=x.extra)!=null&&d.parenthesized&&f();let I=this.maybeUnwrapTypeCastExpression(x);return I.type!=="ArrowFunctionExpression"&&f(),I.typeParameters=l,this.resetStartLocationFromNode(I,l),x},r),u=null;if(c.node&&this.maybeUnwrapTypeCastExpression(c.node).type==="ArrowFunctionExpression"){if(!c.error&&!c.aborted)return c.node.async&&this.raise(g.UnexpectedTypeParameterBeforeAsyncArrowFunction,{at:l}),c.node;u=c.node;}if((o=n)!=null&&o.node)return this.state=n.failState,n.node;if(u)return this.state=c.failState,u;throw (h=n)!=null&&h.thrown?n.error:c.thrown?c.error:this.raise(g.UnexpectedTokenAfterTypeParameter,{at:l})}return super.parseMaybeAssign(e,s)}parseArrow(e){if(this.match(14)){let s=this.tryParse(()=>{let i=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0;let r=this.startNode();return [r.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),this.state.noAnonFunctionType=i,this.canInsertSemicolon()&&this.unexpected(),this.match(19)||this.unexpected(),r});if(s.thrown)return null;s.error&&(this.state=s.failState),e.returnType=s.node.typeAnnotation?this.finishNode(s.node,"TypeAnnotation"):null;}return super.parseArrow(e)}shouldParseArrow(e){return this.match(14)||super.shouldParseArrow(e)}setArrowFunctionParameters(e,s){this.state.noArrowParamsConversionAt.indexOf(e.start)!==-1?e.params=s:super.setArrowFunctionParameters(e,s);}checkParams(e,s,i,r=!0){if(!(i&&this.state.noArrowParamsConversionAt.indexOf(e.start)!==-1)){for(let n=0;n0&&this.raise(g.ThisParamMustBeFirst,{at:e.params[n]});super.checkParams(e,s,i,r);}}parseParenAndDistinguishExpression(e){return super.parseParenAndDistinguishExpression(e&&this.state.noArrowAt.indexOf(this.state.start)===-1)}parseSubscripts(e,s,i){if(e.type==="Identifier"&&e.name==="async"&&this.state.noArrowAt.indexOf(s.index)!==-1){this.next();let r=this.startNodeAt(s);r.callee=e,r.arguments=super.parseCallExpressionArguments(11,!1),e=this.finishNode(r,"CallExpression");}else if(e.type==="Identifier"&&e.name==="async"&&this.match(47)){let r=this.state.clone(),n=this.tryParse(h=>this.parseAsyncArrowWithTypeParameters(s)||h(),r);if(!n.error&&!n.aborted)return n.node;let o=this.tryParse(()=>super.parseSubscripts(e,s,i),r);if(o.node&&!o.error)return o.node;if(n.node)return this.state=n.failState,n.node;if(o.node)return this.state=o.failState,o.node;throw n.error||o.error}return super.parseSubscripts(e,s,i)}parseSubscript(e,s,i,r){if(this.match(18)&&this.isLookaheadToken_lt()){if(r.optionalChainMember=!0,i)return r.stop=!0,e;this.next();let n=this.startNodeAt(s);return n.callee=e,n.typeArguments=this.flowParseTypeParameterInstantiation(),this.expect(10),n.arguments=this.parseCallExpressionArguments(11,!1),n.optional=!0,this.finishCallExpression(n,!0)}else if(!i&&this.shouldParseTypes()&&this.match(47)){let n=this.startNodeAt(s);n.callee=e;let o=this.tryParse(()=>(n.typeArguments=this.flowParseTypeParameterInstantiationCallOrNew(),this.expect(10),n.arguments=super.parseCallExpressionArguments(11,!1),r.optionalChainMember&&(n.optional=!1),this.finishCallExpression(n,r.optionalChainMember)));if(o.node)return o.error&&(this.state=o.failState),o.node}return super.parseSubscript(e,s,i,r)}parseNewCallee(e){super.parseNewCallee(e);let s=null;this.shouldParseTypes()&&this.match(47)&&(s=this.tryParse(()=>this.flowParseTypeParameterInstantiationCallOrNew()).node),e.typeArguments=s;}parseAsyncArrowWithTypeParameters(e){let s=this.startNodeAt(e);if(this.parseFunctionParams(s,!1),!!this.parseArrow(s))return super.parseArrowExpression(s,void 0,!0)}readToken_mult_modulo(e){let s=this.input.charCodeAt(this.state.pos+1);if(e===42&&s===47&&this.state.hasFlowComment){this.state.hasFlowComment=!1,this.state.pos+=2,this.nextToken();return}super.readToken_mult_modulo(e);}readToken_pipe_amp(e){let s=this.input.charCodeAt(this.state.pos+1);if(e===124&&s===125){this.finishOp(9,2);return}super.readToken_pipe_amp(e);}parseTopLevel(e,s){let i=super.parseTopLevel(e,s);return this.state.hasFlowComment&&this.raise(g.UnterminatedFlowComment,{at:this.state.curPosition()}),i}skipBlockComment(){if(this.hasPlugin("flowComments")&&this.skipFlowComment()){if(this.state.hasFlowComment)throw this.raise(g.NestedFlowComment,{at:this.state.startLoc});this.hasFlowCommentCompletion();let e=this.skipFlowComment();e&&(this.state.pos+=e,this.state.hasFlowComment=!0);return}return super.skipBlockComment(this.state.hasFlowComment?"*-/":"*/")}skipFlowComment(){let{pos:e}=this.state,s=2;for(;[32,9].includes(this.input.charCodeAt(e+s));)s++;let i=this.input.charCodeAt(s+e),r=this.input.charCodeAt(s+e+1);return i===58&&r===58?s+2:this.input.slice(s+e,s+e+12)==="flow-include"?s+12:i===58&&r!==58?s:!1}hasFlowCommentCompletion(){if(this.input.indexOf("*/",this.state.pos)===-1)throw this.raise(p.UnterminatedComment,{at:this.state.curPosition()})}flowEnumErrorBooleanMemberNotInitialized(e,{enumName:s,memberName:i}){this.raise(g.EnumBooleanMemberNotInitialized,{at:e,memberName:i,enumName:s});}flowEnumErrorInvalidMemberInitializer(e,s){return this.raise(s.explicitType?s.explicitType==="symbol"?g.EnumInvalidMemberInitializerSymbolType:g.EnumInvalidMemberInitializerPrimaryType:g.EnumInvalidMemberInitializerUnknownType,Object.assign({at:e},s))}flowEnumErrorNumberMemberNotInitialized(e,{enumName:s,memberName:i}){this.raise(g.EnumNumberMemberNotInitialized,{at:e,enumName:s,memberName:i});}flowEnumErrorStringMemberInconsistentlyInitialized(e,{enumName:s}){this.raise(g.EnumStringMemberInconsistentlyInitialized,{at:e,enumName:s});}flowEnumMemberInit(){let e=this.state.startLoc,s=()=>this.match(12)||this.match(8);switch(this.state.type){case 132:{let i=this.parseNumericLiteral(this.state.value);return s()?{type:"number",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}case 131:{let i=this.parseStringLiteral(this.state.value);return s()?{type:"string",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}case 85:case 86:{let i=this.parseBooleanLiteral(this.match(85));return s()?{type:"boolean",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}default:return {type:"invalid",loc:e}}}flowEnumMemberRaw(){let e=this.state.startLoc,s=this.parseIdentifier(!0),i=this.eat(29)?this.flowEnumMemberInit():{type:"none",loc:e};return {id:s,init:i}}flowEnumCheckExplicitTypeMismatch(e,s,i){let{explicitType:r}=s;r!==null&&r!==i&&this.flowEnumErrorInvalidMemberInitializer(e,s);}flowEnumMembers({enumName:e,explicitType:s}){let i=new Set,r={booleanMembers:[],numberMembers:[],stringMembers:[],defaultedMembers:[]},n=!1;for(;!this.match(8);){if(this.eat(21)){n=!0;break}let o=this.startNode(),{id:h,init:l}=this.flowEnumMemberRaw(),c=h.name;if(c==="")continue;/^[a-z]/.test(c)&&this.raise(g.EnumInvalidMemberName,{at:h,memberName:c,suggestion:c[0].toUpperCase()+c.slice(1),enumName:e}),i.has(c)&&this.raise(g.EnumDuplicateMemberName,{at:h,memberName:c,enumName:e}),i.add(c);let u={enumName:e,explicitType:s,memberName:c};switch(o.id=h,l.type){case"boolean":{this.flowEnumCheckExplicitTypeMismatch(l.loc,u,"boolean"),o.init=l.value,r.booleanMembers.push(this.finishNode(o,"EnumBooleanMember"));break}case"number":{this.flowEnumCheckExplicitTypeMismatch(l.loc,u,"number"),o.init=l.value,r.numberMembers.push(this.finishNode(o,"EnumNumberMember"));break}case"string":{this.flowEnumCheckExplicitTypeMismatch(l.loc,u,"string"),o.init=l.value,r.stringMembers.push(this.finishNode(o,"EnumStringMember"));break}case"invalid":throw this.flowEnumErrorInvalidMemberInitializer(l.loc,u);case"none":switch(s){case"boolean":this.flowEnumErrorBooleanMemberNotInitialized(l.loc,u);break;case"number":this.flowEnumErrorNumberMemberNotInitialized(l.loc,u);break;default:r.defaultedMembers.push(this.finishNode(o,"EnumDefaultedMember"));}}this.match(8)||this.expect(12);}return {members:r,hasUnknownMembers:n}}flowEnumStringMembers(e,s,{enumName:i}){if(e.length===0)return s;if(s.length===0)return e;if(s.length>e.length){for(let r of e)this.flowEnumErrorStringMemberInconsistentlyInitialized(r,{enumName:i});return s}else {for(let r of s)this.flowEnumErrorStringMemberInconsistentlyInitialized(r,{enumName:i});return e}}flowEnumParseExplicitType({enumName:e}){if(!this.eatContextual(101))return null;if(!S(this.state.type))throw this.raise(g.EnumInvalidExplicitTypeUnknownSupplied,{at:this.state.startLoc,enumName:e});let{value:s}=this.state;return this.next(),s!=="boolean"&&s!=="number"&&s!=="string"&&s!=="symbol"&&this.raise(g.EnumInvalidExplicitType,{at:this.state.startLoc,enumName:e,invalidEnumType:s}),s}flowEnumBody(e,s){let i=s.name,r=s.loc.start,n=this.flowEnumParseExplicitType({enumName:i});this.expect(5);let{members:o,hasUnknownMembers:h}=this.flowEnumMembers({enumName:i,explicitType:n});switch(e.hasUnknownMembers=h,n){case"boolean":return e.explicitType=!0,e.members=o.booleanMembers,this.expect(8),this.finishNode(e,"EnumBooleanBody");case"number":return e.explicitType=!0,e.members=o.numberMembers,this.expect(8),this.finishNode(e,"EnumNumberBody");case"string":return e.explicitType=!0,e.members=this.flowEnumStringMembers(o.stringMembers,o.defaultedMembers,{enumName:i}),this.expect(8),this.finishNode(e,"EnumStringBody");case"symbol":return e.members=o.defaultedMembers,this.expect(8),this.finishNode(e,"EnumSymbolBody");default:{let l=()=>(e.members=[],this.expect(8),this.finishNode(e,"EnumStringBody"));e.explicitType=!1;let c=o.booleanMembers.length,u=o.numberMembers.length,f=o.stringMembers.length,d=o.defaultedMembers.length;if(!c&&!u&&!f&&!d)return l();if(!c&&!u)return e.members=this.flowEnumStringMembers(o.stringMembers,o.defaultedMembers,{enumName:i}),this.expect(8),this.finishNode(e,"EnumStringBody");if(!u&&!f&&c>=d){for(let x of o.defaultedMembers)this.flowEnumErrorBooleanMemberNotInitialized(x.loc.start,{enumName:i,memberName:x.id.name});return e.members=o.booleanMembers,this.expect(8),this.finishNode(e,"EnumBooleanBody")}else if(!c&&!f&&u>=d){for(let x of o.defaultedMembers)this.flowEnumErrorNumberMemberNotInitialized(x.loc.start,{enumName:i,memberName:x.id.name});return e.members=o.numberMembers,this.expect(8),this.finishNode(e,"EnumNumberBody")}else return this.raise(g.EnumInconsistentMemberValues,{at:r,enumName:i}),l()}}}flowParseEnumDeclaration(e){let s=this.parseIdentifier();return e.id=s,e.body=this.flowEnumBody(this.startNode(),s),this.finishNode(e,"EnumDeclaration")}isLookaheadToken_lt(){let e=this.nextTokenStart();if(this.input.charCodeAt(e)===60){let s=this.input.charCodeAt(e+1);return s!==60&&s!==61}return !1}maybeUnwrapTypeCastExpression(e){return e.type==="TypeCastExpression"?e.expression:e}},W=$`jsx`({AttributeIsEmpty:"JSX attributes must only be assigned a non-empty expression.",MissingClosingTagElement:({openingTagName:a})=>`Expected corresponding JSX closing tag for <${a}>.`,MissingClosingTagFragment:"Expected corresponding JSX closing tag for <>.",UnexpectedSequenceExpression:"Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",UnexpectedToken:({unexpected:a,HTMLEntity:t})=>`Unexpected token \`${a}\`. Did you mean \`${t}\` or \`{'${a}'}\`?`,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 <>...?"});function K(a){return a?a.type==="JSXOpeningFragment"||a.type==="JSXClosingFragment":!1}function Z(a){if(a.type==="JSXIdentifier")return a.name;if(a.type==="JSXNamespacedName")return a.namespace.name+":"+a.name.name;if(a.type==="JSXMemberExpression")return Z(a.object)+"."+Z(a.property);throw new Error("Node had unexpected type: "+a.type)}var ir=a=>class extends a{jsxReadToken(){let e="",s=this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(W.UnterminatedJsxContent,{at:this.state.startLoc});let i=this.input.charCodeAt(this.state.pos);switch(i){case 60:case 123:if(this.state.pos===this.state.start){i===60&&this.state.canStartJSXElement?(++this.state.pos,this.finishToken(140)):super.getTokenFromCode(i);return}e+=this.input.slice(s,this.state.pos),this.finishToken(139,e);return;case 38:e+=this.input.slice(s,this.state.pos),e+=this.jsxReadEntity(),s=this.state.pos;break;case 62:case 125:default:xe(i)?(e+=this.input.slice(s,this.state.pos),e+=this.jsxReadNewLine(!0),s=this.state.pos):++this.state.pos;}}}jsxReadNewLine(e){let s=this.input.charCodeAt(this.state.pos),i;return ++this.state.pos,s===13&&this.input.charCodeAt(this.state.pos)===10?(++this.state.pos,i=e?` -`:`\r -`):i=String.fromCharCode(s),++this.state.curLine,this.state.lineStart=this.state.pos,i}jsxReadString(e){let s="",i=++this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(p.UnterminatedString,{at:this.state.startLoc});let r=this.input.charCodeAt(this.state.pos);if(r===e)break;r===38?(s+=this.input.slice(i,this.state.pos),s+=this.jsxReadEntity(),i=this.state.pos):xe(r)?(s+=this.input.slice(i,this.state.pos),s+=this.jsxReadNewLine(!1),i=this.state.pos):++this.state.pos;}s+=this.input.slice(i,this.state.pos++),this.finishToken(131,s);}jsxReadEntity(){let e=++this.state.pos;if(this.codePointAtPos(this.state.pos)===35){++this.state.pos;let s=10;this.codePointAtPos(this.state.pos)===120&&(s=16,++this.state.pos);let i=this.readInt(s,void 0,!1,"bail");if(i!==null&&this.codePointAtPos(this.state.pos)===59)return ++this.state.pos,String.fromCodePoint(i)}else {let s=0,i=!1;for(;s++<10&&this.state.pos1){for(let i=0;i=0;i--){let r=this.scopeStack[i];if(r.types.has(e)||r.exportOnlyBindings.has(e))return}super.checkLocalExport(t);}},rr=(a,t)=>Object.hasOwnProperty.call(a,t)&&a[t],ps=a=>a.type==="ParenthesizedExpression"?ps(a.expression):a,yt=class extends dt{toAssignable(t,e=!1){var s,i;let r;switch((t.type==="ParenthesizedExpression"||(s=t.extra)!=null&&s.parenthesized)&&(r=ps(t),e?r.type==="Identifier"?this.expressionScope.recordArrowParameterBindingError(p.InvalidParenthesizedAssignment,{at:t}):r.type!=="MemberExpression"&&this.raise(p.InvalidParenthesizedAssignment,{at:t}):this.raise(p.InvalidParenthesizedAssignment,{at:t})),t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":t.type="ObjectPattern";for(let o=0,h=t.properties.length,l=h-1;oi.type!=="ObjectMethod"&&(r===s||i.type!=="SpreadElement")&&this.isAssignable(i))}case"ObjectProperty":return this.isAssignable(t.value);case"SpreadElement":return this.isAssignable(t.argument);case"ArrayExpression":return t.elements.every(s=>s===null||this.isAssignable(s));case"AssignmentExpression":return t.operator==="=";case"ParenthesizedExpression":return this.isAssignable(t.expression);case"MemberExpression":case"OptionalMemberExpression":return !e;default:return !1}}toReferencedList(t,e){return t}toReferencedListDeep(t,e){this.toReferencedList(t,e);for(let s of t)(s==null?void 0:s.type)==="ArrayExpression"&&this.toReferencedListDeep(s.elements);}parseSpread(t){let e=this.startNode();return this.next(),e.argument=this.parseMaybeAssignAllowIn(t,void 0),this.finishNode(e,"SpreadElement")}parseRestBinding(){let t=this.startNode();return this.next(),t.argument=this.parseBindingAtom(),this.finishNode(t,"RestElement")}parseBindingAtom(){switch(this.state.type){case 0:{let t=this.startNode();return this.next(),t.elements=this.parseBindingList(3,93,1),this.finishNode(t,"ArrayPattern")}case 5:return this.parseObjectLike(8,!0)}return this.parseIdentifier()}parseBindingList(t,e,s){let i=s&1,r=[],n=!0;for(;!this.eat(t);)if(n?n=!1:this.expect(12),i&&this.match(12))r.push(null);else {if(this.eat(t))break;if(this.match(21)){if(r.push(this.parseAssignableListItemTypes(this.parseRestBinding(),s)),!this.checkCommaAfterRest(e)){this.expect(t);break}}else {let o=[];for(this.match(26)&&this.hasPlugin("decorators")&&this.raise(p.UnsupportedParameterDecorator,{at:this.state.startLoc});this.match(26);)o.push(this.parseDecorator());r.push(this.parseAssignableListItem(s,o));}}return r}parseBindingRestProperty(t){return this.next(),t.argument=this.parseIdentifier(),this.checkCommaAfterRest(125),this.finishNode(t,"RestElement")}parseBindingProperty(){let t=this.startNode(),{type:e,startLoc:s}=this.state;return e===21?this.parseBindingRestProperty(t):(e===136?(this.expectPlugin("destructuringPrivate",s),this.classScope.usePrivateName(this.state.value,s),t.key=this.parsePrivateName()):this.parsePropertyName(t),t.method=!1,this.parseObjPropValue(t,s,!1,!1,!0,!1))}parseAssignableListItem(t,e){let s=this.parseMaybeDefault();this.parseAssignableListItemTypes(s,t);let i=this.parseMaybeDefault(s.loc.start,s);return e.length&&(s.decorators=e),i}parseAssignableListItemTypes(t,e){return t}parseMaybeDefault(t,e){var i;if((t)!=null||(t=this.state.startLoc),e=(i=e)!=null?i:this.parseBindingAtom(),!this.eat(29))return e;let r=this.startNodeAt(t);return r.left=e,r.right=this.parseMaybeAssignAllowIn(),this.finishNode(r,"AssignmentPattern")}isValidLVal(t,e,s){return rr({AssignmentPattern:"left",RestElement:"argument",ObjectProperty:"value",ParenthesizedExpression:"expression",ArrayPattern:"elements",ObjectPattern:"properties"},t)}checkLVal(t,{in:e,binding:s=64,checkClashes:i=!1,strictModeChanged:r=!1,hasParenthesizedAncestor:n=!1}){var o;let h=t.type;if(this.isObjectMethod(t))return;if(h==="MemberExpression"){s!==64&&this.raise(p.InvalidPropertyBindingPattern,{at:t});return}if(h==="Identifier"){this.checkIdentifier(t,s,r);let{name:d}=t;i&&(i.has(d)?this.raise(p.ParamDupe,{at:t}):i.add(d));return}let l=this.isValidLVal(h,!(n||(o=t.extra)!=null&&o.parenthesized)&&e.type==="AssignmentExpression",s);if(l===!0)return;if(l===!1){let d=s===64?p.InvalidLhs:p.InvalidLhsBinding;this.raise(d,{at:t,ancestor:e});return}let[c,u]=Array.isArray(l)?l:[l,h==="ParenthesizedExpression"],f=h==="ArrayPattern"||h==="ObjectPattern"||h==="ParenthesizedExpression"?{type:h}:e;for(let d of [].concat(t[c]))d&&this.checkLVal(d,{in:f,binding:s,checkClashes:i,strictModeChanged:r,hasParenthesizedAncestor:u});}checkIdentifier(t,e,s=!1){this.state.strict&&(s?is(t.name,this.inModule):ss(t.name))&&(e===64?this.raise(p.StrictEvalArguments,{at:t,referenceName:t.name}):this.raise(p.StrictEvalArgumentsBinding,{at:t,bindingName:t.name})),e&8192&&t.name==="let"&&this.raise(p.LetInLexicalBinding,{at:t}),e&64||this.declareNameFromIdentifier(t,e);}declareNameFromIdentifier(t,e){this.scope.declareName(t.name,e,t.loc.start);}checkToRestConversion(t,e){switch(t.type){case"ParenthesizedExpression":this.checkToRestConversion(t.expression,e);break;case"Identifier":case"MemberExpression":break;case"ArrayExpression":case"ObjectExpression":if(e)break;default:this.raise(p.InvalidRestAssignmentPattern,{at:t});}}checkCommaAfterRest(t){return this.match(12)?(this.raise(this.lookaheadCharCode()===t?p.RestTrailingComma:p.ElementAfterRest,{at:this.state.startLoc}),!0):!1}},ar=(a,t)=>Object.hasOwnProperty.call(a,t)&&a[t];function nr(a){if(a==null)throw new Error(`Unexpected ${a} value.`);return a}function Kt(a){if(!a)throw new Error("Assert fail")}var y=$`typescript`({AbstractMethodHasImplementation:({methodName:a})=>`Method '${a}' cannot have an implementation because it is marked abstract.`,AbstractPropertyHasInitializer:({propertyName:a})=>`Property '${a}' cannot have an initializer because it is marked abstract.`,AccesorCannotDeclareThisParameter:"'get' and 'set' accessors cannot declare 'this' parameters.",AccesorCannotHaveTypeParameters:"An accessor cannot have type parameters.",AccessorCannotBeOptional:"An 'accessor' property cannot be declared optional.",ClassMethodHasDeclare:"Class methods cannot have the 'declare' modifier.",ClassMethodHasReadonly:"Class methods cannot have the 'readonly' modifier.",ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference:"A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",ConstructorHasTypeParameters:"Type parameters cannot appear on a constructor declaration.",DeclareAccessor:({kind:a})=>`'declare' is not allowed in ${a}ters.`,DeclareClassFieldHasInitializer:"Initializers are not allowed in ambient contexts.",DeclareFunctionHasImplementation:"An implementation cannot be declared in ambient contexts.",DuplicateAccessibilityModifier:({modifier:a})=>"Accessibility modifier already seen.",DuplicateModifier:({modifier:a})=>`Duplicate modifier: '${a}'.`,EmptyHeritageClauseType:({token:a})=>`'${a}' list cannot be empty.`,EmptyTypeArguments:"Type argument list cannot be empty.",EmptyTypeParameters:"Type parameter list cannot be empty.",ExpectedAmbientAfterExportDeclare:"'export declare' must be followed by an ambient declaration.",ImportAliasHasImportType:"An import alias can not use 'import type'.",ImportReflectionHasImportType:"An `import module` declaration can not use `type` modifier",IncompatibleModifiers:({modifiers:a})=>`'${a[0]}' modifier cannot be used with '${a[1]}' modifier.`,IndexSignatureHasAbstract:"Index signatures cannot have the 'abstract' modifier.",IndexSignatureHasAccessibility:({modifier:a})=>`Index signatures cannot have an accessibility modifier ('${a}').`,IndexSignatureHasDeclare:"Index signatures cannot have the 'declare' modifier.",IndexSignatureHasOverride:"'override' modifier cannot appear on an index signature.",IndexSignatureHasStatic:"Index signatures cannot have the 'static' modifier.",InitializerNotAllowedInAmbientContext:"Initializers are not allowed in ambient contexts.",InvalidModifierOnTypeMember:({modifier:a})=>`'${a}' modifier cannot appear on a type member.`,InvalidModifierOnTypeParameter:({modifier:a})=>`'${a}' modifier cannot appear on a type parameter.`,InvalidModifierOnTypeParameterPositions:({modifier:a})=>`'${a}' modifier can only appear on a type parameter of a class, interface or type alias.`,InvalidModifiersOrder:({orderedModifiers:a})=>`'${a[0]}' modifier must precede '${a[1]}' modifier.`,InvalidPropertyAccessAfterInstantiationExpression:"Invalid property access after an instantiation expression. You can either wrap the instantiation expression in parentheses, or delete the type arguments.",InvalidTupleMemberLabel:"Tuple members must be labeled with a simple identifier.",MissingInterfaceName:"'interface' declarations must be followed by an identifier.",MixedLabeledAndUnlabeledElements:"Tuple members must all have names or all not have names.",NonAbstractClassHasAbstractMethod:"Abstract methods can only appear within an abstract class.",NonClassMethodPropertyHasAbstractModifer:"'abstract' modifier can only appear on a class, method, or property declaration.",OptionalTypeBeforeRequired:"A required element cannot follow an optional element.",OverrideNotInSubClass:"This member cannot have an 'override' modifier because its containing class does not extend another class.",PatternIsOptional:"A binding pattern parameter cannot be optional in an implementation signature.",PrivateElementHasAbstract:"Private elements cannot have the 'abstract' modifier.",PrivateElementHasAccessibility:({modifier:a})=>`Private elements cannot have an accessibility modifier ('${a}').`,ReadonlyForMethodSignature:"'readonly' modifier can only appear on a property declaration or index signature.",ReservedArrowTypeParam:"This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `() => ...`.",ReservedTypeAssertion:"This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",SetAccesorCannotHaveOptionalParameter:"A 'set' accessor cannot have an optional parameter.",SetAccesorCannotHaveRestParameter:"A 'set' accessor cannot have rest parameter.",SetAccesorCannotHaveReturnType:"A 'set' accessor cannot have a return type annotation.",SingleTypeParameterWithoutTrailingComma:({typeParameterName:a})=>`Single type parameter ${a} should have a trailing comma. Example usage: <${a},>.`,StaticBlockCannotHaveModifier:"Static class blocks cannot have any modifier.",TupleOptionalAfterType:"A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).",TypeAnnotationAfterAssign:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeImportCannotSpecifyDefaultAndNamed:"A type-only import can specify a default import or named bindings, but not both.",TypeModifierIsUsedInTypeExports:"The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",TypeModifierIsUsedInTypeImports:"The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",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:({type:a})=>`Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${a}.`});function or(a){switch(a){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}}function qt(a){return a==="private"||a==="public"||a==="protected"}function hr(a){return a==="in"||a==="out"}var lr=a=>class extends a{constructor(...e){super(...e),this.tsParseInOutModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out"],disallowedModifiers:["const","public","private","protected","readonly","declare","abstract","override"],errorTemplate:y.InvalidModifierOnTypeParameter}),this.tsParseConstModifier=this.tsParseModifiers.bind(this,{allowedModifiers:["const"],disallowedModifiers:["in","out"],errorTemplate:y.InvalidModifierOnTypeParameterPositions}),this.tsParseInOutConstModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out","const"],disallowedModifiers:["public","private","protected","readonly","declare","abstract","override"],errorTemplate:y.InvalidModifierOnTypeParameter});}getScopeHandler(){return mt}tsIsIdentifier(){return S(this.state.type)}tsTokenCanFollowModifier(){return (this.match(0)||this.match(5)||this.match(55)||this.match(21)||this.match(136)||this.isLiteralPropertyName())&&!this.hasPrecedingLineBreak()}tsNextTokenCanFollowModifier(){return this.next(),this.tsTokenCanFollowModifier()}tsParseModifier(e,s){if(!S(this.state.type)&&this.state.type!==58&&this.state.type!==75)return;let i=this.state.value;if(e.indexOf(i)!==-1){if(s&&this.tsIsStartOfStaticBlocks())return;if(this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this)))return i}}tsParseModifiers({allowedModifiers:e,disallowedModifiers:s,stopOnStartOfClassStaticBlock:i,errorTemplate:r=y.InvalidModifierOnTypeMember},n){let o=(l,c,u,f)=>{c===u&&n[f]&&this.raise(y.InvalidModifiersOrder,{at:l,orderedModifiers:[u,f]});},h=(l,c,u,f)=>{(n[u]&&c===f||n[f]&&c===u)&&this.raise(y.IncompatibleModifiers,{at:l,modifiers:[u,f]});};for(;;){let{startLoc:l}=this.state,c=this.tsParseModifier(e.concat(s??[]),i);if(!c)break;qt(c)?n.accessibility?this.raise(y.DuplicateAccessibilityModifier,{at:l,modifier:c}):(o(l,c,c,"override"),o(l,c,c,"static"),o(l,c,c,"readonly"),n.accessibility=c):hr(c)?(n[c]&&this.raise(y.DuplicateModifier,{at:l,modifier:c}),n[c]=!0,o(l,c,"in","out")):(Object.hasOwnProperty.call(n,c)?this.raise(y.DuplicateModifier,{at:l,modifier:c}):(o(l,c,"static","readonly"),o(l,c,"static","override"),o(l,c,"override","readonly"),o(l,c,"abstract","override"),h(l,c,"declare","override"),h(l,c,"static","abstract")),n[c]=!0),s!=null&&s.includes(c)&&this.raise(r,{at:l,modifier:c});}}tsIsListTerminator(e){switch(e){case"EnumMembers":case"TypeMembers":return this.match(8);case"HeritageClauseElement":return this.match(5);case"TupleElementTypes":return this.match(3);case"TypeParametersOrArguments":return this.match(48)}}tsParseList(e,s){let i=[];for(;!this.tsIsListTerminator(e);)i.push(s());return i}tsParseDelimitedList(e,s,i){return nr(this.tsParseDelimitedListWorker(e,s,!0,i))}tsParseDelimitedListWorker(e,s,i,r){let n=[],o=-1;for(;!this.tsIsListTerminator(e);){o=-1;let h=s();if(h==null)return;if(n.push(h),this.eat(12)){o=this.state.lastTokStart;continue}if(this.tsIsListTerminator(e))break;i&&this.expect(12);return}return r&&(r.value=o),n}tsParseBracketedList(e,s,i,r,n){r||(i?this.expect(0):this.expect(47));let o=this.tsParseDelimitedList(e,s,n);return i?this.expect(3):this.expect(48),o}tsParseImportType(){let e=this.startNode();return this.expect(83),this.expect(10),this.match(131)||this.raise(y.UnsupportedImportTypeArgument,{at:this.state.startLoc}),e.argument=super.parseExprAtom(),this.expect(11),this.eat(16)&&(e.qualifier=this.tsParseEntityName()),this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSImportType")}tsParseEntityName(e=!0){let s=this.parseIdentifier(e);for(;this.eat(16);){let i=this.startNodeAtNode(s);i.left=s,i.right=this.parseIdentifier(e),s=this.finishNode(i,"TSQualifiedName");}return s}tsParseTypeReference(){let e=this.startNode();return e.typeName=this.tsParseEntityName(),!this.hasPrecedingLineBreak()&&this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSTypeReference")}tsParseThisTypePredicate(e){this.next();let s=this.startNodeAtNode(e);return s.parameterName=e,s.typeAnnotation=this.tsParseTypeAnnotation(!1),s.asserts=!1,this.finishNode(s,"TSTypePredicate")}tsParseThisTypeNode(){let e=this.startNode();return this.next(),this.finishNode(e,"TSThisType")}tsParseTypeQuery(){let e=this.startNode();return this.expect(87),this.match(83)?e.exprName=this.tsParseImportType():e.exprName=this.tsParseEntityName(),!this.hasPrecedingLineBreak()&&this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSTypeQuery")}tsParseTypeParameter(e){let s=this.startNode();return e(s),s.name=this.tsParseTypeParameterName(),s.constraint=this.tsEatThenParseType(81),s.default=this.tsEatThenParseType(29),this.finishNode(s,"TSTypeParameter")}tsTryParseTypeParameters(e){if(this.match(47))return this.tsParseTypeParameters(e)}tsParseTypeParameters(e){let s=this.startNode();this.match(47)||this.match(140)?this.next():this.unexpected();let i={value:-1};return s.params=this.tsParseBracketedList("TypeParametersOrArguments",this.tsParseTypeParameter.bind(this,e),!1,!0,i),s.params.length===0&&this.raise(y.EmptyTypeParameters,{at:s}),i.value!==-1&&this.addExtra(s,"trailingComma",i.value),this.finishNode(s,"TSTypeParameterDeclaration")}tsFillSignature(e,s){let i=e===19,r="parameters",n="typeAnnotation";s.typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier),this.expect(10),s[r]=this.tsParseBindingListForSignature(),i?s[n]=this.tsParseTypeOrTypePredicateAnnotation(e):this.match(e)&&(s[n]=this.tsParseTypeOrTypePredicateAnnotation(e));}tsParseBindingListForSignature(){let e=super.parseBindingList(11,41,2);for(let s of e){let{type:i}=s;(i==="AssignmentPattern"||i==="TSParameterProperty")&&this.raise(y.UnsupportedSignatureParameterKind,{at:s,type:i});}return e}tsParseTypeMemberSemicolon(){!this.eat(12)&&!this.isLineTerminator()&&this.expect(13);}tsParseSignatureMember(e,s){return this.tsFillSignature(14,s),this.tsParseTypeMemberSemicolon(),this.finishNode(s,e)}tsIsUnambiguouslyIndexSignature(){return this.next(),S(this.state.type)?(this.next(),this.match(14)):!1}tsTryParseIndexSignature(e){if(!(this.match(0)&&this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this))))return;this.expect(0);let s=this.parseIdentifier();s.typeAnnotation=this.tsParseTypeAnnotation(),this.resetEndLocation(s),this.expect(3),e.parameters=[s];let i=this.tsTryParseTypeAnnotation();return i&&(e.typeAnnotation=i),this.tsParseTypeMemberSemicolon(),this.finishNode(e,"TSIndexSignature")}tsParsePropertyOrMethodSignature(e,s){this.eat(17)&&(e.optional=!0);let i=e;if(this.match(10)||this.match(47)){s&&this.raise(y.ReadonlyForMethodSignature,{at:e});let r=i;r.kind&&this.match(47)&&this.raise(y.AccesorCannotHaveTypeParameters,{at:this.state.curPosition()}),this.tsFillSignature(14,r),this.tsParseTypeMemberSemicolon();let n="parameters",o="typeAnnotation";if(r.kind==="get")r[n].length>0&&(this.raise(p.BadGetterArity,{at:this.state.curPosition()}),this.isThisParam(r[n][0])&&this.raise(y.AccesorCannotDeclareThisParameter,{at:this.state.curPosition()}));else if(r.kind==="set"){if(r[n].length!==1)this.raise(p.BadSetterArity,{at:this.state.curPosition()});else {let h=r[n][0];this.isThisParam(h)&&this.raise(y.AccesorCannotDeclareThisParameter,{at:this.state.curPosition()}),h.type==="Identifier"&&h.optional&&this.raise(y.SetAccesorCannotHaveOptionalParameter,{at:this.state.curPosition()}),h.type==="RestElement"&&this.raise(y.SetAccesorCannotHaveRestParameter,{at:this.state.curPosition()});}r[o]&&this.raise(y.SetAccesorCannotHaveReturnType,{at:r[o]});}else r.kind="method";return this.finishNode(r,"TSMethodSignature")}else {let r=i;s&&(r.readonly=!0);let n=this.tsTryParseTypeAnnotation();return n&&(r.typeAnnotation=n),this.tsParseTypeMemberSemicolon(),this.finishNode(r,"TSPropertySignature")}}tsParseTypeMember(){let e=this.startNode();if(this.match(10)||this.match(47))return this.tsParseSignatureMember("TSCallSignatureDeclaration",e);if(this.match(77)){let i=this.startNode();return this.next(),this.match(10)||this.match(47)?this.tsParseSignatureMember("TSConstructSignatureDeclaration",e):(e.key=this.createIdentifier(i,"new"),this.tsParsePropertyOrMethodSignature(e,!1))}this.tsParseModifiers({allowedModifiers:["readonly"],disallowedModifiers:["declare","abstract","private","protected","public","static","override"]},e);let s=this.tsTryParseIndexSignature(e);return s||(super.parsePropertyName(e),!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&this.tsTokenCanFollowModifier()&&(e.kind=e.key.name,super.parsePropertyName(e)),this.tsParsePropertyOrMethodSignature(e,!!e.readonly))}tsParseTypeLiteral(){let e=this.startNode();return e.members=this.tsParseObjectTypeMembers(),this.finishNode(e,"TSTypeLiteral")}tsParseObjectTypeMembers(){this.expect(5);let e=this.tsParseList("TypeMembers",this.tsParseTypeMember.bind(this));return this.expect(8),e}tsIsStartOfMappedType(){return this.next(),this.eat(53)?this.isContextual(120):(this.isContextual(120)&&this.next(),!this.match(0)||(this.next(),!this.tsIsIdentifier())?!1:(this.next(),this.match(58)))}tsParseMappedTypeParameter(){let e=this.startNode();return e.name=this.tsParseTypeParameterName(),e.constraint=this.tsExpectThenParseType(58),this.finishNode(e,"TSTypeParameter")}tsParseMappedType(){let e=this.startNode();return this.expect(5),this.match(53)?(e.readonly=this.state.value,this.next(),this.expectContextual(120)):this.eatContextual(120)&&(e.readonly=!0),this.expect(0),e.typeParameter=this.tsParseMappedTypeParameter(),e.nameType=this.eatContextual(93)?this.tsParseType():null,this.expect(3),this.match(53)?(e.optional=this.state.value,this.next(),this.expect(17)):this.eat(17)&&(e.optional=!0),e.typeAnnotation=this.tsTryParseType(),this.semicolon(),this.expect(8),this.finishNode(e,"TSMappedType")}tsParseTupleType(){let e=this.startNode();e.elementTypes=this.tsParseBracketedList("TupleElementTypes",this.tsParseTupleElementType.bind(this),!0,!1);let s=!1,i=null;return e.elementTypes.forEach(r=>{let{type:o}=r;s&&o!=="TSRestType"&&o!=="TSOptionalType"&&!(o==="TSNamedTupleMember"&&r.optional)&&this.raise(y.OptionalTypeBeforeRequired,{at:r}),s||(s=o==="TSNamedTupleMember"&&r.optional||o==="TSOptionalType");let h=o;o==="TSRestType"&&(r=r.typeAnnotation,h=r.type);let l=h==="TSNamedTupleMember";(i)!=null||(i=l),i!==l&&this.raise(y.MixedLabeledAndUnlabeledElements,{at:r});}),this.finishNode(e,"TSTupleType")}tsParseTupleElementType(){let{startLoc:e}=this.state,s=this.eat(21),i,r,n,o,l=M(this.state.type)?this.lookaheadCharCode():null;if(l===58)i=!0,n=!1,r=this.parseIdentifier(!0),this.expect(14),o=this.tsParseType();else if(l===63){n=!0;let c=this.state.startLoc,u=this.state.value,f=this.tsParseNonArrayType();this.lookaheadCharCode()===58?(i=!0,r=this.createIdentifier(this.startNodeAt(c),u),this.expect(17),this.expect(14),o=this.tsParseType()):(i=!1,o=f,this.expect(17));}else o=this.tsParseType(),n=this.eat(17),i=this.eat(14);if(i){let c;r?(c=this.startNodeAtNode(r),c.optional=n,c.label=r,c.elementType=o,this.eat(17)&&(c.optional=!0,this.raise(y.TupleOptionalAfterType,{at:this.state.lastTokStartLoc}))):(c=this.startNodeAtNode(o),c.optional=n,this.raise(y.InvalidTupleMemberLabel,{at:o}),c.label=o,c.elementType=this.tsParseType()),o=this.finishNode(c,"TSNamedTupleMember");}else if(n){let c=this.startNodeAtNode(o);c.typeAnnotation=o,o=this.finishNode(c,"TSOptionalType");}if(s){let c=this.startNodeAt(e);c.typeAnnotation=o,o=this.finishNode(c,"TSRestType");}return o}tsParseParenthesizedType(){let e=this.startNode();return this.expect(10),e.typeAnnotation=this.tsParseType(),this.expect(11),this.finishNode(e,"TSParenthesizedType")}tsParseFunctionOrConstructorType(e,s){let i=this.startNode();return e==="TSConstructorType"&&(i.abstract=!!s,s&&this.next(),this.next()),this.tsInAllowConditionalTypesContext(()=>this.tsFillSignature(19,i)),this.finishNode(i,e)}tsParseLiteralTypeNode(){let e=this.startNode();switch(this.state.type){case 132:case 133:case 131:case 85:case 86:e.literal=super.parseExprAtom();break;default:this.unexpected();}return this.finishNode(e,"TSLiteralType")}tsParseTemplateLiteralType(){let e=this.startNode();return e.literal=super.parseTemplate(!1),this.finishNode(e,"TSLiteralType")}parseTemplateSubstitution(){return this.state.inType?this.tsParseType():super.parseTemplateSubstitution()}tsParseThisTypeOrThisTypePredicate(){let e=this.tsParseThisTypeNode();return this.isContextual(114)&&!this.hasPrecedingLineBreak()?this.tsParseThisTypePredicate(e):e}tsParseNonArrayType(){switch(this.state.type){case 131:case 132:case 133:case 85:case 86:return this.tsParseLiteralTypeNode();case 53:if(this.state.value==="-"){let e=this.startNode(),s=this.lookahead();return s.type!==132&&s.type!==133&&this.unexpected(),e.literal=this.parseMaybeUnary(),this.finishNode(e,"TSLiteralType")}break;case 78:return this.tsParseThisTypeOrThisTypePredicate();case 87:return this.tsParseTypeQuery();case 83:return this.tsParseImportType();case 5:return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this))?this.tsParseMappedType():this.tsParseTypeLiteral();case 0:return this.tsParseTupleType();case 10:return this.tsParseParenthesizedType();case 25:case 24:return this.tsParseTemplateLiteralType();default:{let{type:e}=this.state;if(S(e)||e===88||e===84){let s=e===88?"TSVoidKeyword":e===84?"TSNullKeyword":or(this.state.value);if(s!==void 0&&this.lookaheadCharCode()!==46){let i=this.startNode();return this.next(),this.finishNode(i,s)}return this.tsParseTypeReference()}}}this.unexpected();}tsParseArrayTypeOrHigher(){let e=this.tsParseNonArrayType();for(;!this.hasPrecedingLineBreak()&&this.eat(0);)if(this.match(3)){let s=this.startNodeAtNode(e);s.elementType=e,this.expect(3),e=this.finishNode(s,"TSArrayType");}else {let s=this.startNodeAtNode(e);s.objectType=e,s.indexType=this.tsParseType(),this.expect(3),e=this.finishNode(s,"TSIndexedAccessType");}return e}tsParseTypeOperator(){let e=this.startNode(),s=this.state.value;return this.next(),e.operator=s,e.typeAnnotation=this.tsParseTypeOperatorOrHigher(),s==="readonly"&&this.tsCheckTypeAnnotationForReadOnly(e),this.finishNode(e,"TSTypeOperator")}tsCheckTypeAnnotationForReadOnly(e){switch(e.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(y.UnexpectedReadonly,{at:e});}}tsParseInferType(){let e=this.startNode();this.expectContextual(113);let s=this.startNode();return s.name=this.tsParseTypeParameterName(),s.constraint=this.tsTryParse(()=>this.tsParseConstraintForInferType()),e.typeParameter=this.finishNode(s,"TSTypeParameter"),this.finishNode(e,"TSInferType")}tsParseConstraintForInferType(){if(this.eat(81)){let e=this.tsInDisallowConditionalTypesContext(()=>this.tsParseType());if(this.state.inDisallowConditionalTypesContext||!this.match(17))return e}}tsParseTypeOperatorOrHigher(){return Ci(this.state.type)&&!this.state.containsEsc?this.tsParseTypeOperator():this.isContextual(113)?this.tsParseInferType():this.tsInAllowConditionalTypesContext(()=>this.tsParseArrayTypeOrHigher())}tsParseUnionOrIntersectionType(e,s,i){let r=this.startNode(),n=this.eat(i),o=[];do o.push(s());while(this.eat(i));return o.length===1&&!n?o[0]:(r.types=o,this.finishNode(r,e))}tsParseIntersectionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSIntersectionType",this.tsParseTypeOperatorOrHigher.bind(this),45)}tsParseUnionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSUnionType",this.tsParseIntersectionTypeOrHigher.bind(this),43)}tsIsStartOfFunctionType(){return this.match(47)?!0:this.match(10)&&this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this))}tsSkipParameterStart(){if(S(this.state.type)||this.match(78))return this.next(),!0;if(this.match(5)){let{errors:e}=this.state,s=e.length;try{return this.parseObjectLike(8,!0),e.length===s}catch{return !1}}if(this.match(0)){this.next();let{errors:e}=this.state,s=e.length;try{return super.parseBindingList(3,93,1),e.length===s}catch{return !1}}return !1}tsIsUnambiguouslyStartOfFunctionType(){return this.next(),!!(this.match(11)||this.match(21)||this.tsSkipParameterStart()&&(this.match(14)||this.match(12)||this.match(17)||this.match(29)||this.match(11)&&(this.next(),this.match(19))))}tsParseTypeOrTypePredicateAnnotation(e){return this.tsInType(()=>{let s=this.startNode();this.expect(e);let i=this.startNode(),r=!!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));if(r&&this.match(78)){let h=this.tsParseThisTypeOrThisTypePredicate();return h.type==="TSThisType"?(i.parameterName=h,i.asserts=!0,i.typeAnnotation=null,h=this.finishNode(i,"TSTypePredicate")):(this.resetStartLocationFromNode(h,i),h.asserts=!0),s.typeAnnotation=h,this.finishNode(s,"TSTypeAnnotation")}let n=this.tsIsIdentifier()&&this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));if(!n)return r?(i.parameterName=this.parseIdentifier(),i.asserts=r,i.typeAnnotation=null,s.typeAnnotation=this.finishNode(i,"TSTypePredicate"),this.finishNode(s,"TSTypeAnnotation")):this.tsParseTypeAnnotation(!1,s);let o=this.tsParseTypeAnnotation(!1);return i.parameterName=n,i.typeAnnotation=o,i.asserts=r,s.typeAnnotation=this.finishNode(i,"TSTypePredicate"),this.finishNode(s,"TSTypeAnnotation")})}tsTryParseTypeOrTypePredicateAnnotation(){if(this.match(14))return this.tsParseTypeOrTypePredicateAnnotation(14)}tsTryParseTypeAnnotation(){if(this.match(14))return this.tsParseTypeAnnotation()}tsTryParseType(){return this.tsEatThenParseType(14)}tsParseTypePredicatePrefix(){let e=this.parseIdentifier();if(this.isContextual(114)&&!this.hasPrecedingLineBreak())return this.next(),e}tsParseTypePredicateAsserts(){if(this.state.type!==107)return !1;let e=this.state.containsEsc;return this.next(),!S(this.state.type)&&!this.match(78)?!1:(e&&this.raise(p.InvalidEscapedReservedWord,{at:this.state.lastTokStartLoc,reservedWord:"asserts"}),!0)}tsParseTypeAnnotation(e=!0,s=this.startNode()){return this.tsInType(()=>{e&&this.expect(14),s.typeAnnotation=this.tsParseType();}),this.finishNode(s,"TSTypeAnnotation")}tsParseType(){Kt(this.state.inType);let e=this.tsParseNonConditionalType();if(this.state.inDisallowConditionalTypesContext||this.hasPrecedingLineBreak()||!this.eat(81))return e;let s=this.startNodeAtNode(e);return s.checkType=e,s.extendsType=this.tsInDisallowConditionalTypesContext(()=>this.tsParseNonConditionalType()),this.expect(17),s.trueType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.expect(14),s.falseType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.finishNode(s,"TSConditionalType")}isAbstractConstructorSignature(){return this.isContextual(122)&&this.lookahead().type===77}tsParseNonConditionalType(){return this.tsIsStartOfFunctionType()?this.tsParseFunctionOrConstructorType("TSFunctionType"):this.match(77)?this.tsParseFunctionOrConstructorType("TSConstructorType"):this.isAbstractConstructorSignature()?this.tsParseFunctionOrConstructorType("TSConstructorType",!0):this.tsParseUnionTypeOrHigher()}tsParseTypeAssertion(){this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(y.ReservedTypeAssertion,{at:this.state.startLoc});let e=this.startNode();return e.typeAnnotation=this.tsInType(()=>(this.next(),this.match(75)?this.tsParseTypeReference():this.tsParseType())),this.expect(48),e.expression=this.parseMaybeUnary(),this.finishNode(e,"TSTypeAssertion")}tsParseHeritageClause(e){let s=this.state.startLoc,i=this.tsParseDelimitedList("HeritageClauseElement",()=>{let r=this.startNode();return r.expression=this.tsParseEntityName(),this.match(47)&&(r.typeParameters=this.tsParseTypeArguments()),this.finishNode(r,"TSExpressionWithTypeArguments")});return i.length||this.raise(y.EmptyHeritageClauseType,{at:s,token:e}),i}tsParseInterfaceDeclaration(e,s={}){if(this.hasFollowingLineBreak())return null;this.expectContextual(127),s.declare&&(e.declare=!0),S(this.state.type)?(e.id=this.parseIdentifier(),this.checkIdentifier(e.id,130)):(e.id=null,this.raise(y.MissingInterfaceName,{at:this.state.startLoc})),e.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers),this.eat(81)&&(e.extends=this.tsParseHeritageClause("extends"));let i=this.startNode();return i.body=this.tsInType(this.tsParseObjectTypeMembers.bind(this)),e.body=this.finishNode(i,"TSInterfaceBody"),this.finishNode(e,"TSInterfaceDeclaration")}tsParseTypeAliasDeclaration(e){return e.id=this.parseIdentifier(),this.checkIdentifier(e.id,2),e.typeAnnotation=this.tsInType(()=>{if(e.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutModifiers),this.expect(29),this.isContextual(112)&&this.lookahead().type!==16){let s=this.startNode();return this.next(),this.finishNode(s,"TSIntrinsicKeyword")}return this.tsParseType()}),this.semicolon(),this.finishNode(e,"TSTypeAliasDeclaration")}tsInNoContext(e){let s=this.state.context;this.state.context=[s[0]];try{return e()}finally{this.state.context=s;}}tsInType(e){let s=this.state.inType;this.state.inType=!0;try{return e()}finally{this.state.inType=s;}}tsInDisallowConditionalTypesContext(e){let s=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!0;try{return e()}finally{this.state.inDisallowConditionalTypesContext=s;}}tsInAllowConditionalTypesContext(e){let s=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!1;try{return e()}finally{this.state.inDisallowConditionalTypesContext=s;}}tsEatThenParseType(e){if(this.match(e))return this.tsNextThenParseType()}tsExpectThenParseType(e){return this.tsInType(()=>(this.expect(e),this.tsParseType()))}tsNextThenParseType(){return this.tsInType(()=>(this.next(),this.tsParseType()))}tsParseEnumMember(){let e=this.startNode();return e.id=this.match(131)?super.parseStringLiteral(this.state.value):this.parseIdentifier(!0),this.eat(29)&&(e.initializer=super.parseMaybeAssignAllowIn()),this.finishNode(e,"TSEnumMember")}tsParseEnumDeclaration(e,s={}){return s.const&&(e.const=!0),s.declare&&(e.declare=!0),this.expectContextual(124),e.id=this.parseIdentifier(),this.checkIdentifier(e.id,e.const?8971:8459),this.expect(5),e.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(8),this.finishNode(e,"TSEnumDeclaration")}tsParseModuleBlock(){let e=this.startNode();return this.scope.enter(0),this.expect(5),super.parseBlockOrModuleBlockBody(e.body=[],void 0,!0,8),this.scope.exit(),this.finishNode(e,"TSModuleBlock")}tsParseModuleOrNamespaceDeclaration(e,s=!1){if(e.id=this.parseIdentifier(),s||this.checkIdentifier(e.id,1024),this.eat(16)){let i=this.startNode();this.tsParseModuleOrNamespaceDeclaration(i,!0),e.body=i;}else this.scope.enter(256),this.prodParam.enter(te),e.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit();return this.finishNode(e,"TSModuleDeclaration")}tsParseAmbientExternalModuleDeclaration(e){return this.isContextual(110)?(e.global=!0,e.id=this.parseIdentifier()):this.match(131)?e.id=super.parseStringLiteral(this.state.value):this.unexpected(),this.match(5)?(this.scope.enter(256),this.prodParam.enter(te),e.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit()):this.semicolon(),this.finishNode(e,"TSModuleDeclaration")}tsParseImportEqualsDeclaration(e,s,i){e.isExport=i||!1,e.id=s||this.parseIdentifier(),this.checkIdentifier(e.id,4096),this.expect(29);let r=this.tsParseModuleReference();return e.importKind==="type"&&r.type!=="TSExternalModuleReference"&&this.raise(y.ImportAliasHasImportType,{at:r}),e.moduleReference=r,this.semicolon(),this.finishNode(e,"TSImportEqualsDeclaration")}tsIsExternalModuleReference(){return this.isContextual(117)&&this.lookaheadCharCode()===40}tsParseModuleReference(){return this.tsIsExternalModuleReference()?this.tsParseExternalModuleReference():this.tsParseEntityName(!1)}tsParseExternalModuleReference(){let e=this.startNode();return this.expectContextual(117),this.expect(10),this.match(131)||this.unexpected(),e.expression=super.parseExprAtom(),this.expect(11),this.sawUnambiguousESM=!0,this.finishNode(e,"TSExternalModuleReference")}tsLookAhead(e){let s=this.state.clone(),i=e();return this.state=s,i}tsTryParseAndCatch(e){let s=this.tryParse(i=>e()||i());if(!(s.aborted||!s.node))return s.error&&(this.state=s.failState),s.node}tsTryParse(e){let s=this.state.clone(),i=e();if(i!==void 0&&i!==!1)return i;this.state=s;}tsTryParseDeclare(e){if(this.isLineTerminator())return;let s=this.state.type,i;return this.isContextual(99)&&(s=74,i="let"),this.tsInAmbientContext(()=>{switch(s){case 68:return e.declare=!0,super.parseFunctionStatement(e,!1,!1);case 80:return e.declare=!0,this.parseClass(e,!0,!1);case 124:return this.tsParseEnumDeclaration(e,{declare:!0});case 110:return this.tsParseAmbientExternalModuleDeclaration(e);case 75:case 74:return !this.match(75)||!this.isLookaheadContextual("enum")?(e.declare=!0,this.parseVarStatement(e,i||this.state.value,!0)):(this.expect(75),this.tsParseEnumDeclaration(e,{const:!0,declare:!0}));case 127:{let r=this.tsParseInterfaceDeclaration(e,{declare:!0});if(r)return r}default:if(S(s))return this.tsParseDeclaration(e,this.state.value,!0,null)}})}tsTryParseExportDeclaration(){return this.tsParseDeclaration(this.startNode(),this.state.value,!0,null)}tsParseExpressionStatement(e,s,i){switch(s.name){case"declare":{let r=this.tsTryParseDeclare(e);return r&&(r.declare=!0),r}case"global":if(this.match(5)){this.scope.enter(256),this.prodParam.enter(te);let r=e;return r.global=!0,r.id=s,r.body=this.tsParseModuleBlock(),this.scope.exit(),this.prodParam.exit(),this.finishNode(r,"TSModuleDeclaration")}break;default:return this.tsParseDeclaration(e,s.name,!1,i)}}tsParseDeclaration(e,s,i,r){switch(s){case"abstract":if(this.tsCheckLineTerminator(i)&&(this.match(80)||S(this.state.type)))return this.tsParseAbstractDeclaration(e,r);break;case"module":if(this.tsCheckLineTerminator(i)){if(this.match(131))return this.tsParseAmbientExternalModuleDeclaration(e);if(S(this.state.type))return this.tsParseModuleOrNamespaceDeclaration(e)}break;case"namespace":if(this.tsCheckLineTerminator(i)&&S(this.state.type))return this.tsParseModuleOrNamespaceDeclaration(e);break;case"type":if(this.tsCheckLineTerminator(i)&&S(this.state.type))return this.tsParseTypeAliasDeclaration(e);break}}tsCheckLineTerminator(e){return e?this.hasFollowingLineBreak()?!1:(this.next(),!0):!this.isLineTerminator()}tsTryParseGenericAsyncArrowFunction(e){if(!this.match(47))return;let s=this.state.maybeInArrowParameters;this.state.maybeInArrowParameters=!0;let i=this.tsTryParseAndCatch(()=>{let r=this.startNodeAt(e);return r.typeParameters=this.tsParseTypeParameters(this.tsParseConstModifier),super.parseFunctionParams(r),r.returnType=this.tsTryParseTypeOrTypePredicateAnnotation(),this.expect(19),r});if(this.state.maybeInArrowParameters=s,!!i)return super.parseArrowExpression(i,null,!0)}tsParseTypeArgumentsInExpression(){if(this.reScan_lt()===47)return this.tsParseTypeArguments()}tsParseTypeArguments(){let e=this.startNode();return e.params=this.tsInType(()=>this.tsInNoContext(()=>(this.expect(47),this.tsParseDelimitedList("TypeParametersOrArguments",this.tsParseType.bind(this))))),e.params.length===0?this.raise(y.EmptyTypeArguments,{at:e}):!this.state.inType&&this.curContext()===w.brace&&this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TSTypeParameterInstantiation")}tsIsDeclarationStart(){return Ei(this.state.type)}isExportDefaultSpecifier(){return this.tsIsDeclarationStart()?!1:super.isExportDefaultSpecifier()}parseAssignableListItem(e,s){let i=this.state.startLoc,r={};this.tsParseModifiers({allowedModifiers:["public","private","protected","override","readonly"]},r);let n=r.accessibility,o=r.override,h=r.readonly;!(e&4)&&(n||h||o)&&this.raise(y.UnexpectedParameterModifier,{at:i});let l=this.parseMaybeDefault();this.parseAssignableListItemTypes(l,e);let c=this.parseMaybeDefault(l.loc.start,l);if(n||h||o){let u=this.startNodeAt(i);return s.length&&(u.decorators=s),n&&(u.accessibility=n),h&&(u.readonly=h),o&&(u.override=o),c.type!=="Identifier"&&c.type!=="AssignmentPattern"&&this.raise(y.UnsupportedParameterPropertyKind,{at:u}),u.parameter=c,this.finishNode(u,"TSParameterProperty")}return s.length&&(l.decorators=s),c}isSimpleParameter(e){return e.type==="TSParameterProperty"&&super.isSimpleParameter(e.parameter)||super.isSimpleParameter(e)}tsDisallowOptionalPattern(e){for(let s of e.params)s.type!=="Identifier"&&s.optional&&!this.state.isAmbientContext&&this.raise(y.PatternIsOptional,{at:s});}setArrowFunctionParameters(e,s,i){super.setArrowFunctionParameters(e,s,i),this.tsDisallowOptionalPattern(e);}parseFunctionBodyAndFinish(e,s,i=!1){this.match(14)&&(e.returnType=this.tsParseTypeOrTypePredicateAnnotation(14));let r=s==="FunctionDeclaration"?"TSDeclareFunction":s==="ClassMethod"||s==="ClassPrivateMethod"?"TSDeclareMethod":void 0;return r&&!this.match(5)&&this.isLineTerminator()?this.finishNode(e,r):r==="TSDeclareFunction"&&this.state.isAmbientContext&&(this.raise(y.DeclareFunctionHasImplementation,{at:e}),e.declare)?super.parseFunctionBodyAndFinish(e,r,i):(this.tsDisallowOptionalPattern(e),super.parseFunctionBodyAndFinish(e,s,i))}registerFunctionStatementId(e){!e.body&&e.id?this.checkIdentifier(e.id,1024):super.registerFunctionStatementId(e);}tsCheckForInvalidTypeCasts(e){e.forEach(s=>{(s==null?void 0:s.type)==="TSTypeCastExpression"&&this.raise(y.UnexpectedTypeAnnotation,{at:s.typeAnnotation});});}toReferencedList(e,s){return this.tsCheckForInvalidTypeCasts(e),e}parseArrayLike(e,s,i,r){let n=super.parseArrayLike(e,s,i,r);return n.type==="ArrayExpression"&&this.tsCheckForInvalidTypeCasts(n.elements),n}parseSubscript(e,s,i,r){if(!this.hasPrecedingLineBreak()&&this.match(35)){this.state.canStartJSXElement=!1,this.next();let o=this.startNodeAt(s);return o.expression=e,this.finishNode(o,"TSNonNullExpression")}let n=!1;if(this.match(18)&&this.lookaheadCharCode()===60){if(i)return r.stop=!0,e;r.optionalChainMember=n=!0,this.next();}if(this.match(47)||this.match(51)){let o,h=this.tsTryParseAndCatch(()=>{if(!i&&this.atPossibleAsyncArrow(e)){let f=this.tsTryParseGenericAsyncArrowFunction(s);if(f)return f}let l=this.tsParseTypeArgumentsInExpression();if(!l)return;if(n&&!this.match(10)){o=this.state.curPosition();return}if(Me(this.state.type)){let f=super.parseTaggedTemplateExpression(e,s,r);return f.typeParameters=l,f}if(!i&&this.eat(10)){let f=this.startNodeAt(s);return f.callee=e,f.arguments=this.parseCallExpressionArguments(11,!1),this.tsCheckForInvalidTypeCasts(f.arguments),f.typeParameters=l,r.optionalChainMember&&(f.optional=n),this.finishCallExpression(f,r.optionalChainMember)}let c=this.state.type;if(c===48||c===52||c!==10&&Ze(c)&&!this.hasPrecedingLineBreak())return;let u=this.startNodeAt(s);return u.expression=e,u.typeParameters=l,this.finishNode(u,"TSInstantiationExpression")});if(o&&this.unexpected(o,10),h)return h.type==="TSInstantiationExpression"&&(this.match(16)||this.match(18)&&this.lookaheadCharCode()!==40)&&this.raise(y.InvalidPropertyAccessAfterInstantiationExpression,{at:this.state.startLoc}),h}return super.parseSubscript(e,s,i,r)}parseNewCallee(e){var s;super.parseNewCallee(e);let{callee:i}=e;i.type==="TSInstantiationExpression"&&!((s=i.extra)!=null&&s.parenthesized)&&(e.typeParameters=i.typeParameters,e.callee=i.expression);}parseExprOp(e,s,i){let r;if(Ne(58)>i&&!this.hasPrecedingLineBreak()&&(this.isContextual(93)||(r=this.isContextual(118)))){let n=this.startNodeAt(s);return n.expression=e,n.typeAnnotation=this.tsInType(()=>(this.next(),this.match(75)?(r&&this.raise(p.UnexpectedKeyword,{at:this.state.startLoc,keyword:"const"}),this.tsParseTypeReference()):this.tsParseType())),this.finishNode(n,r?"TSSatisfiesExpression":"TSAsExpression"),this.reScan_lt_gt(),this.parseExprOp(n,s,i)}return super.parseExprOp(e,s,i)}checkReservedWord(e,s,i,r){this.state.isAmbientContext||super.checkReservedWord(e,s,i,r);}checkImportReflection(e){super.checkImportReflection(e),e.module&&e.importKind!=="value"&&this.raise(y.ImportReflectionHasImportType,{at:e.specifiers[0].loc.start});}checkDuplicateExports(){}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return !0;if(this.isContextual(128)){let s=this.lookaheadCharCode();return e?s===123||s===42:s!==61}return !e&&this.isContextual(87)}applyImportPhase(e,s,i,r){super.applyImportPhase(e,s,i,r),s?e.exportKind=i==="type"?"type":"value":e.importKind=i==="type"||i==="typeof"?i:"value";}parseImport(e){if(this.match(131))return e.importKind="value",super.parseImport(e);let s;if(S(this.state.type)&&this.lookaheadCharCode()===61)return e.importKind="value",this.tsParseImportEqualsDeclaration(e);if(this.isContextual(128)){let i=this.parseMaybeImportPhase(e,!1);if(this.lookaheadCharCode()===61)return this.tsParseImportEqualsDeclaration(e,i);s=super.parseImportSpecifiersAndAfter(e,i);}else s=super.parseImport(e);return s.importKind==="type"&&s.specifiers.length>1&&s.specifiers[0].type==="ImportDefaultSpecifier"&&this.raise(y.TypeImportCannotSpecifyDefaultAndNamed,{at:s}),s}parseExport(e,s){if(this.match(83)){this.next();let i=null;return this.isContextual(128)&&this.isPotentialImportPhase(!1)?i=this.parseMaybeImportPhase(e,!1):e.importKind="value",this.tsParseImportEqualsDeclaration(e,i,!0)}else if(this.eat(29)){let i=e;return i.expression=super.parseExpression(),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(i,"TSExportAssignment")}else if(this.eatContextual(93)){let i=e;return this.expectContextual(126),i.id=this.parseIdentifier(),this.semicolon(),this.finishNode(i,"TSNamespaceExportDeclaration")}else return super.parseExport(e,s)}isAbstractClass(){return this.isContextual(122)&&this.lookahead().type===80}parseExportDefaultExpression(){if(this.isAbstractClass()){let e=this.startNode();return this.next(),e.abstract=!0,this.parseClass(e,!0,!0)}if(this.match(127)){let e=this.tsParseInterfaceDeclaration(this.startNode());if(e)return e}return super.parseExportDefaultExpression()}parseVarStatement(e,s,i=!1){let{isAmbientContext:r}=this.state,n=super.parseVarStatement(e,s,i||r);if(!r)return n;for(let{id:o,init:h}of n.declarations)h&&(s!=="const"||o.typeAnnotation?this.raise(y.InitializerNotAllowedInAmbientContext,{at:h}):pr(h,this.hasPlugin("estree"))||this.raise(y.ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference,{at:h}));return n}parseStatementContent(e,s){if(this.match(75)&&this.isLookaheadContextual("enum")){let i=this.startNode();return this.expect(75),this.tsParseEnumDeclaration(i,{const:!0})}if(this.isContextual(124))return this.tsParseEnumDeclaration(this.startNode());if(this.isContextual(127)){let i=this.tsParseInterfaceDeclaration(this.startNode());if(i)return i}return super.parseStatementContent(e,s)}parseAccessModifier(){return this.tsParseModifier(["public","protected","private"])}tsHasSomeModifiers(e,s){return s.some(i=>qt(i)?e.accessibility===i:!!e[i])}tsIsStartOfStaticBlocks(){return this.isContextual(104)&&this.lookaheadCharCode()===123}parseClassMember(e,s,i){let r=["declare","private","public","protected","override","abstract","readonly","static"];this.tsParseModifiers({allowedModifiers:r,disallowedModifiers:["in","out"],stopOnStartOfClassStaticBlock:!0,errorTemplate:y.InvalidModifierOnTypeParameterPositions},s);let n=()=>{this.tsIsStartOfStaticBlocks()?(this.next(),this.next(),this.tsHasSomeModifiers(s,r)&&this.raise(y.StaticBlockCannotHaveModifier,{at:this.state.curPosition()}),super.parseClassStaticBlock(e,s)):this.parseClassMemberWithIsStatic(e,s,i,!!s.static);};s.declare?this.tsInAmbientContext(n):n();}parseClassMemberWithIsStatic(e,s,i,r){let n=this.tsTryParseIndexSignature(s);if(n){e.body.push(n),s.abstract&&this.raise(y.IndexSignatureHasAbstract,{at:s}),s.accessibility&&this.raise(y.IndexSignatureHasAccessibility,{at:s,modifier:s.accessibility}),s.declare&&this.raise(y.IndexSignatureHasDeclare,{at:s}),s.override&&this.raise(y.IndexSignatureHasOverride,{at:s});return}!this.state.inAbstractClass&&s.abstract&&this.raise(y.NonAbstractClassHasAbstractMethod,{at:s}),s.override&&(i.hadSuperClass||this.raise(y.OverrideNotInSubClass,{at:s})),super.parseClassMemberWithIsStatic(e,s,i,r);}parsePostMemberNameModifiers(e){this.eat(17)&&(e.optional=!0),e.readonly&&this.match(10)&&this.raise(y.ClassMethodHasReadonly,{at:e}),e.declare&&this.match(10)&&this.raise(y.ClassMethodHasDeclare,{at:e});}parseExpressionStatement(e,s,i){return (s.type==="Identifier"?this.tsParseExpressionStatement(e,s,i):void 0)||super.parseExpressionStatement(e,s,i)}shouldParseExportDeclaration(){return this.tsIsDeclarationStart()?!0:super.shouldParseExportDeclaration()}parseConditional(e,s,i){if(!this.state.maybeInArrowParameters||!this.match(17))return super.parseConditional(e,s,i);let r=this.tryParse(()=>super.parseConditional(e,s));return r.node?(r.error&&(this.state=r.failState),r.node):(r.error&&super.setOptionalParametersError(i,r.error),e)}parseParenItem(e,s){if(e=super.parseParenItem(e,s),this.eat(17)&&(e.optional=!0,this.resetEndLocation(e)),this.match(14)){let i=this.startNodeAt(s);return i.expression=e,i.typeAnnotation=this.tsParseTypeAnnotation(),this.finishNode(i,"TSTypeCastExpression")}return e}parseExportDeclaration(e){if(!this.state.isAmbientContext&&this.isContextual(123))return this.tsInAmbientContext(()=>this.parseExportDeclaration(e));let s=this.state.startLoc,i=this.eatContextual(123);if(i&&(this.isContextual(123)||!this.shouldParseExportDeclaration()))throw this.raise(y.ExpectedAmbientAfterExportDeclare,{at:this.state.startLoc});let n=S(this.state.type)&&this.tsTryParseExportDeclaration()||super.parseExportDeclaration(e);return n?((n.type==="TSInterfaceDeclaration"||n.type==="TSTypeAliasDeclaration"||i)&&(e.exportKind="type"),i&&(this.resetStartLocation(n,s),n.declare=!0),n):null}parseClassId(e,s,i,r){if((!s||i)&&this.isContextual(111))return;super.parseClassId(e,s,i,e.declare?1024:8331);let n=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);n&&(e.typeParameters=n);}parseClassPropertyAnnotation(e){e.optional||(this.eat(35)?e.definite=!0:this.eat(17)&&(e.optional=!0));let s=this.tsTryParseTypeAnnotation();s&&(e.typeAnnotation=s);}parseClassProperty(e){if(this.parseClassPropertyAnnotation(e),this.state.isAmbientContext&&!(e.readonly&&!e.typeAnnotation)&&this.match(29)&&this.raise(y.DeclareClassFieldHasInitializer,{at:this.state.startLoc}),e.abstract&&this.match(29)){let{key:s}=e;this.raise(y.AbstractPropertyHasInitializer,{at:this.state.startLoc,propertyName:s.type==="Identifier"&&!e.computed?s.name:`[${this.input.slice(s.start,s.end)}]`});}return super.parseClassProperty(e)}parseClassPrivateProperty(e){return e.abstract&&this.raise(y.PrivateElementHasAbstract,{at:e}),e.accessibility&&this.raise(y.PrivateElementHasAccessibility,{at:e,modifier:e.accessibility}),this.parseClassPropertyAnnotation(e),super.parseClassPrivateProperty(e)}parseClassAccessorProperty(e){return this.parseClassPropertyAnnotation(e),e.optional&&this.raise(y.AccessorCannotBeOptional,{at:e}),super.parseClassAccessorProperty(e)}pushClassMethod(e,s,i,r,n,o){let h=this.tsTryParseTypeParameters(this.tsParseConstModifier);h&&n&&this.raise(y.ConstructorHasTypeParameters,{at:h});let{declare:l=!1,kind:c}=s;l&&(c==="get"||c==="set")&&this.raise(y.DeclareAccessor,{at:s,kind:c}),h&&(s.typeParameters=h),super.pushClassMethod(e,s,i,r,n,o);}pushClassPrivateMethod(e,s,i,r){let n=this.tsTryParseTypeParameters(this.tsParseConstModifier);n&&(s.typeParameters=n),super.pushClassPrivateMethod(e,s,i,r);}declareClassPrivateMethodInScope(e,s){e.type!=="TSDeclareMethod"&&(e.type==="MethodDefinition"&&!e.value.body||super.declareClassPrivateMethodInScope(e,s));}parseClassSuper(e){super.parseClassSuper(e),e.superClass&&(this.match(47)||this.match(51))&&(e.superTypeParameters=this.tsParseTypeArgumentsInExpression()),this.eatContextual(111)&&(e.implements=this.tsParseHeritageClause("implements"));}parseObjPropValue(e,s,i,r,n,o,h){let l=this.tsTryParseTypeParameters(this.tsParseConstModifier);return l&&(e.typeParameters=l),super.parseObjPropValue(e,s,i,r,n,o,h)}parseFunctionParams(e,s){let i=this.tsTryParseTypeParameters(this.tsParseConstModifier);i&&(e.typeParameters=i),super.parseFunctionParams(e,s);}parseVarId(e,s){super.parseVarId(e,s),e.id.type==="Identifier"&&!this.hasPrecedingLineBreak()&&this.eat(35)&&(e.definite=!0);let i=this.tsTryParseTypeAnnotation();i&&(e.id.typeAnnotation=i,this.resetEndLocation(e.id));}parseAsyncArrowFromCallExpression(e,s){return this.match(14)&&(e.returnType=this.tsParseTypeAnnotation()),super.parseAsyncArrowFromCallExpression(e,s)}parseMaybeAssign(e,s){var i,r,n,o,h;let l,c,u;if(this.hasPlugin("jsx")&&(this.match(140)||this.match(47))){if(l=this.state.clone(),c=this.tryParse(()=>super.parseMaybeAssign(e,s),l),!c.error)return c.node;let{context:x}=this.state,I=x[x.length-1];(I===w.j_oTag||I===w.j_expr)&&x.pop();}if(!((i=c)!=null&&i.error)&&!this.match(47))return super.parseMaybeAssign(e,s);(!l||l===this.state)&&(l=this.state.clone());let f,d=this.tryParse(x=>{var I,C;f=this.tsParseTypeParameters(this.tsParseConstModifier);let E=super.parseMaybeAssign(e,s);return (E.type!=="ArrowFunctionExpression"||(I=E.extra)!=null&&I.parenthesized)&&x(),((C=f)==null?void 0:C.params.length)!==0&&this.resetStartLocationFromNode(E,f),E.typeParameters=f,E},l);if(!d.error&&!d.aborted)return f&&this.reportReservedArrowTypeParam(f),d.node;if(!c&&(Kt(!this.hasPlugin("jsx")),u=this.tryParse(()=>super.parseMaybeAssign(e,s),l),!u.error))return u.node;if((r=c)!=null&&r.node)return this.state=c.failState,c.node;if(d.node)return this.state=d.failState,f&&this.reportReservedArrowTypeParam(f),d.node;if((n=u)!=null&&n.node)return this.state=u.failState,u.node;throw ((o=c)==null?void 0:o.error)||d.error||((h=u)==null?void 0:h.error)}reportReservedArrowTypeParam(e){var s;e.params.length===1&&!e.params[0].constraint&&!((s=e.extra)!=null&&s.trailingComma)&&this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(y.ReservedArrowTypeParam,{at:e});}parseMaybeUnary(e,s){return !this.hasPlugin("jsx")&&this.match(47)?this.tsParseTypeAssertion():super.parseMaybeUnary(e,s)}parseArrow(e){if(this.match(14)){let s=this.tryParse(i=>{let r=this.tsParseTypeOrTypePredicateAnnotation(14);return (this.canInsertSemicolon()||!this.match(19))&&i(),r});if(s.aborted)return;s.thrown||(s.error&&(this.state=s.failState),e.returnType=s.node);}return super.parseArrow(e)}parseAssignableListItemTypes(e,s){if(!(s&2))return e;this.eat(17)&&(e.optional=!0);let i=this.tsTryParseTypeAnnotation();return i&&(e.typeAnnotation=i),this.resetEndLocation(e),e}isAssignable(e,s){switch(e.type){case"TSTypeCastExpression":return this.isAssignable(e.expression,s);case"TSParameterProperty":return !0;default:return super.isAssignable(e,s)}}toAssignable(e,s=!1){switch(e.type){case"ParenthesizedExpression":this.toAssignableParenthesizedExpression(e,s);break;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":s?this.expressionScope.recordArrowParameterBindingError(y.UnexpectedTypeCastInParameter,{at:e}):this.raise(y.UnexpectedTypeCastInParameter,{at:e}),this.toAssignable(e.expression,s);break;case"AssignmentExpression":!s&&e.left.type==="TSTypeCastExpression"&&(e.left=this.typeCastToParameter(e.left));default:super.toAssignable(e,s);}}toAssignableParenthesizedExpression(e,s){switch(e.expression.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":case"ParenthesizedExpression":this.toAssignable(e.expression,s);break;default:super.toAssignable(e,s);}}checkToRestConversion(e,s){switch(e.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":this.checkToRestConversion(e.expression,!1);break;default:super.checkToRestConversion(e,s);}}isValidLVal(e,s,i){return ar({TSTypeCastExpression:!0,TSParameterProperty:"parameter",TSNonNullExpression:"expression",TSAsExpression:(i!==64||!s)&&["expression",!0],TSSatisfiesExpression:(i!==64||!s)&&["expression",!0],TSTypeAssertion:(i!==64||!s)&&["expression",!0]},e)||super.isValidLVal(e,s,i)}parseBindingAtom(){return this.state.type===78?this.parseIdentifier(!0):super.parseBindingAtom()}parseMaybeDecoratorArguments(e){if(this.match(47)||this.match(51)){let s=this.tsParseTypeArgumentsInExpression();if(this.match(10)){let i=super.parseMaybeDecoratorArguments(e);return i.typeParameters=s,i}this.unexpected(null,10);}return super.parseMaybeDecoratorArguments(e)}checkCommaAfterRest(e){return this.state.isAmbientContext&&this.match(12)&&this.lookaheadCharCode()===e?(this.next(),!1):super.checkCommaAfterRest(e)}isClassMethod(){return this.match(47)||super.isClassMethod()}isClassProperty(){return this.match(35)||this.match(14)||super.isClassProperty()}parseMaybeDefault(e,s){let i=super.parseMaybeDefault(e,s);return i.type==="AssignmentPattern"&&i.typeAnnotation&&i.right.startthis.isAssignable(s,!0)):super.shouldParseArrow(e)}shouldParseAsyncArrow(){return this.match(14)||super.shouldParseAsyncArrow()}canHaveLeadingDecorator(){return super.canHaveLeadingDecorator()||this.isAbstractClass()}jsxParseOpeningElementAfterName(e){if(this.match(47)||this.match(51)){let s=this.tsTryParseAndCatch(()=>this.tsParseTypeArgumentsInExpression());s&&(e.typeParameters=s);}return super.jsxParseOpeningElementAfterName(e)}getGetterSetterExpectedParamCount(e){let s=super.getGetterSetterExpectedParamCount(e),r=this.getObjectOrClassMethodParams(e)[0];return r&&this.isThisParam(r)?s+1:s}parseCatchClauseParam(){let e=super.parseCatchClauseParam(),s=this.tsTryParseTypeAnnotation();return s&&(e.typeAnnotation=s,this.resetEndLocation(e)),e}tsInAmbientContext(e){let s=this.state.isAmbientContext;this.state.isAmbientContext=!0;try{return e()}finally{this.state.isAmbientContext=s;}}parseClass(e,s,i){let r=this.state.inAbstractClass;this.state.inAbstractClass=!!e.abstract;try{return super.parseClass(e,s,i)}finally{this.state.inAbstractClass=r;}}tsParseAbstractDeclaration(e,s){if(this.match(80))return e.abstract=!0,this.maybeTakeDecorators(s,this.parseClass(e,!0,!1));if(this.isContextual(127)){if(!this.hasFollowingLineBreak())return e.abstract=!0,this.raise(y.NonClassMethodPropertyHasAbstractModifer,{at:e}),this.tsParseInterfaceDeclaration(e)}else this.unexpected(null,80);}parseMethod(e,s,i,r,n,o,h){let l=super.parseMethod(e,s,i,r,n,o,h);if(l.abstract&&(this.hasPlugin("estree")?!!l.value.body:!!l.body)){let{key:u}=l;this.raise(y.AbstractMethodHasImplementation,{at:l,methodName:u.type==="Identifier"&&!l.computed?u.name:`[${this.input.slice(u.start,u.end)}]`});}return l}tsParseTypeParameterName(){return this.parseIdentifier().name}shouldParseAsAmbientContext(){return !!this.getPluginOption("typescript","dts")}parse(){return this.shouldParseAsAmbientContext()&&(this.state.isAmbientContext=!0),super.parse()}getExpression(){return this.shouldParseAsAmbientContext()&&(this.state.isAmbientContext=!0),super.getExpression()}parseExportSpecifier(e,s,i,r){return !s&&r?(this.parseTypeOnlyImportExportSpecifier(e,!1,i),this.finishNode(e,"ExportSpecifier")):(e.exportKind="value",super.parseExportSpecifier(e,s,i,r))}parseImportSpecifier(e,s,i,r,n){return !s&&r?(this.parseTypeOnlyImportExportSpecifier(e,!0,i),this.finishNode(e,"ImportSpecifier")):(e.importKind="value",super.parseImportSpecifier(e,s,i,r,i?4098:4096))}parseTypeOnlyImportExportSpecifier(e,s,i){let r=s?"imported":"local",n=s?"local":"exported",o=e[r],h,l=!1,c=!0,u=o.loc.start;if(this.isContextual(93)){let d=this.parseIdentifier();if(this.isContextual(93)){let x=this.parseIdentifier();M(this.state.type)?(l=!0,o=d,h=s?this.parseIdentifier():this.parseModuleExportName(),c=!1):(h=x,c=!1);}else M(this.state.type)?(c=!1,h=s?this.parseIdentifier():this.parseModuleExportName()):(l=!0,o=d);}else M(this.state.type)&&(l=!0,s?(o=this.parseIdentifier(!0),this.isContextual(93)||this.checkReservedWord(o.name,o.loc.start,!0,!0)):o=this.parseModuleExportName());l&&i&&this.raise(s?y.TypeModifierIsUsedInTypeImports:y.TypeModifierIsUsedInTypeExports,{at:u}),e[r]=o,e[n]=h;let f=s?"importKind":"exportKind";e[f]=l?"type":"value",c&&this.eatContextual(93)&&(e[n]=s?this.parseIdentifier():this.parseModuleExportName()),e[n]||(e[n]=V(e[r])),s&&this.checkIdentifier(e[n],l?4098:4096);}};function cr(a){if(a.type!=="MemberExpression")return !1;let{computed:t,property:e}=a;return t&&e.type!=="StringLiteral"&&(e.type!=="TemplateLiteral"||e.expressions.length>0)?!1:ds(a.object)}function pr(a,t){var e;let{type:s}=a;if((e=a.extra)!=null&&e.parenthesized)return !1;if(t){if(s==="Literal"){let{value:i}=a;if(typeof i=="string"||typeof i=="boolean")return !0}}else if(s==="StringLiteral"||s==="BooleanLiteral")return !0;return !!(us(a,t)||ur(a,t)||s==="TemplateLiteral"&&a.expressions.length===0||cr(a))}function us(a,t){return t?a.type==="Literal"&&(typeof a.value=="number"||"bigint"in a):a.type==="NumericLiteral"||a.type==="BigIntLiteral"}function ur(a,t){if(a.type==="UnaryExpression"){let{operator:e,argument:s}=a;if(e==="-"&&us(s,t))return !0}return !1}function ds(a){return a.type==="Identifier"?!0:a.type!=="MemberExpression"||a.computed?!1:ds(a.object)}var Ht=$`placeholders`({ClassNameIsRequired:"A class name is required.",UnexpectedSpace:"Unexpected space in placeholder."}),dr=a=>class extends a{parsePlaceholder(e){if(this.match(142)){let s=this.startNode();return this.next(),this.assertNoSpace(),s.name=super.parseIdentifier(!0),this.assertNoSpace(),this.expect(142),this.finishPlaceholder(s,e)}}finishPlaceholder(e,s){let i=!!(e.expectedNode&&e.type==="Placeholder");return e.expectedNode=s,i?e:this.finishNode(e,"Placeholder")}getTokenFromCode(e){e===37&&this.input.charCodeAt(this.state.pos+1)===37?this.finishOp(142,2):super.getTokenFromCode(e);}parseExprAtom(e){return this.parsePlaceholder("Expression")||super.parseExprAtom(e)}parseIdentifier(e){return this.parsePlaceholder("Identifier")||super.parseIdentifier(e)}checkReservedWord(e,s,i,r){e!==void 0&&super.checkReservedWord(e,s,i,r);}parseBindingAtom(){return this.parsePlaceholder("Pattern")||super.parseBindingAtom()}isValidLVal(e,s,i){return e==="Placeholder"||super.isValidLVal(e,s,i)}toAssignable(e,s){e&&e.type==="Placeholder"&&e.expectedNode==="Expression"?e.expectedNode="Pattern":super.toAssignable(e,s);}chStartsBindingIdentifier(e,s){return !!(super.chStartsBindingIdentifier(e,s)||this.lookahead().type===142)}verifyBreakContinue(e,s){e.label&&e.label.type==="Placeholder"||super.verifyBreakContinue(e,s);}parseExpressionStatement(e,s){var i;if(s.type!=="Placeholder"||(i=s.extra)!=null&&i.parenthesized)return super.parseExpressionStatement(e,s);if(this.match(14)){let r=e;return r.label=this.finishPlaceholder(s,"Identifier"),this.next(),r.body=super.parseStatementOrSloppyAnnexBFunctionDeclaration(),this.finishNode(r,"LabeledStatement")}return this.semicolon(),e.name=s.name,this.finishPlaceholder(e,"Statement")}parseBlock(e,s,i){return this.parsePlaceholder("BlockStatement")||super.parseBlock(e,s,i)}parseFunctionId(e){return this.parsePlaceholder("Identifier")||super.parseFunctionId(e)}parseClass(e,s,i){let r=s?"ClassDeclaration":"ClassExpression";this.next();let n=this.state.strict,o=this.parsePlaceholder("Identifier");if(o)if(this.match(81)||this.match(142)||this.match(5))e.id=o;else {if(i||!s)return e.id=null,e.body=this.finishPlaceholder(o,"ClassBody"),this.finishNode(e,r);throw this.raise(Ht.ClassNameIsRequired,{at:this.state.startLoc})}else this.parseClassId(e,s,i);return super.parseClassSuper(e),e.body=this.parsePlaceholder("ClassBody")||super.parseClassBody(!!e.superClass,n),this.finishNode(e,r)}parseExport(e,s){let i=this.parsePlaceholder("Identifier");if(!i)return super.parseExport(e,s);if(!this.isContextual(97)&&!this.match(12))return e.specifiers=[],e.source=null,e.declaration=this.finishPlaceholder(i,"Declaration"),this.finishNode(e,"ExportNamedDeclaration");this.expectPlugin("exportDefaultFrom");let r=this.startNode();return r.exported=i,e.specifiers=[this.finishNode(r,"ExportDefaultSpecifier")],super.parseExport(e,s)}isExportDefaultSpecifier(){if(this.match(65)){let e=this.nextTokenStart();if(this.isUnparsedContextual(e,"from")&&this.input.startsWith(q(142),this.nextTokenStartSince(e+4)))return !0}return super.isExportDefaultSpecifier()}maybeParseExportDefaultSpecifier(e,s){var i;return (i=e.specifiers)!=null&&i.length?!0:super.maybeParseExportDefaultSpecifier(e,s)}checkExport(e){let{specifiers:s}=e;s!=null&&s.length&&(e.specifiers=s.filter(i=>i.exported.type==="Placeholder")),super.checkExport(e),e.specifiers=s;}parseImport(e){let s=this.parsePlaceholder("Identifier");if(!s)return super.parseImport(e);if(e.specifiers=[],!this.isContextual(97)&&!this.match(12))return e.source=this.finishPlaceholder(s,"StringLiteral"),this.semicolon(),this.finishNode(e,"ImportDeclaration");let i=this.startNodeAtNode(s);return i.local=s,e.specifiers.push(this.finishNode(i,"ImportDefaultSpecifier")),this.eat(12)&&(this.maybeParseStarImportSpecifier(e)||this.parseNamedImportSpecifiers(e)),this.expectContextual(97),e.source=this.parseImportSource(),this.semicolon(),this.finishNode(e,"ImportDeclaration")}parseImportSource(){return this.parsePlaceholder("StringLiteral")||super.parseImportSource()}assertNoSpace(){this.state.start>this.state.lastTokEndLoc.index&&this.raise(Ht.UnexpectedSpace,{at:this.state.lastTokEndLoc});}},fr=a=>class extends a{parseV8Intrinsic(){if(this.match(54)){let e=this.state.startLoc,s=this.startNode();if(this.next(),S(this.state.type)){let i=this.parseIdentifierName(),r=this.createIdentifier(s,i);if(r.type="V8IntrinsicIdentifier",this.match(10))return r}this.unexpected(e);}}parseExprAtom(e){return this.parseV8Intrinsic()||super.parseExprAtom(e)}};function k(a,t){let[e,s]=typeof t=="string"?[t,{}]:t,i=Object.keys(s),r=i.length===0;return a.some(n=>{if(typeof n=="string")return r&&n===e;{let[o,h]=n;if(o!==e)return !1;for(let l of i)if(h[l]!==s[l])return !1;return !0}})}function J(a,t,e){let s=a.find(i=>Array.isArray(i)?i[0]===t:i===t);return s&&Array.isArray(s)&&s.length>1?s[1][e]:null}var Wt=["minimal","fsharp","hack","smart"],Jt=["^^","@@","^","%","#"],Xt=["hash","bar"];function mr(a){if(k(a,"decorators")){if(k(a,"decorators-legacy"))throw new Error("Cannot use the decorators and decorators-legacy plugin together");let t=J(a,"decorators","decoratorsBeforeExport");if(t!=null&&typeof t!="boolean")throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");let e=J(a,"decorators","allowCallParenthesized");if(e!=null&&typeof e!="boolean")throw new Error("'allowCallParenthesized' must be a boolean.")}if(k(a,"flow")&&k(a,"typescript"))throw new Error("Cannot combine flow and typescript plugins.");if(k(a,"placeholders")&&k(a,"v8intrinsic"))throw new Error("Cannot combine placeholders and v8intrinsic plugins.");if(k(a,"pipelineOperator")){let t=J(a,"pipelineOperator","proposal");if(!Wt.includes(t)){let s=Wt.map(i=>`"${i}"`).join(", ");throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${s}.`)}let e=k(a,["recordAndTuple",{syntaxType:"hash"}]);if(t==="hack"){if(k(a,"placeholders"))throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");if(k(a,"v8intrinsic"))throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");let s=J(a,"pipelineOperator","topicToken");if(!Jt.includes(s)){let i=Jt.map(r=>`"${r}"`).join(", ");throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${i}.`)}if(s==="#"&&e)throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "hack", topicToken: "#" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.')}else if(t==="smart"&&e)throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "smart" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.')}if(k(a,"moduleAttributes")){if(k(a,"importAssertions")||k(a,"importAttributes"))throw new Error("Cannot combine importAssertions, importAttributes and moduleAttributes plugins.");if(J(a,"moduleAttributes","version")!=="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(k(a,"importAssertions")&&k(a,"importAttributes"))throw new Error("Cannot combine importAssertions and importAttributes plugins.");if(k(a,"recordAndTuple")&&J(a,"recordAndTuple","syntaxType")!=null&&!Xt.includes(J(a,"recordAndTuple","syntaxType")))throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: "+Xt.map(t=>`'${t}'`).join(", "));if(k(a,"asyncDoExpressions")&&!k(a,"doExpressions")){let t=new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");throw t.missingPlugins="doExpressions",t}}var fs={estree:mi,jsx:ir,flow:sr,typescript:lr,v8intrinsic:fr,placeholders:dr},yr=Object.keys(fs),Je={sourceType:"script",sourceFilename:void 0,startColumn:0,startLine:1,allowAwaitOutsideFunction:!1,allowReturnOutsideFunction:!1,allowNewTargetOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,allowUndeclaredExports:!1,plugins:[],strictMode:null,ranges:!1,tokens:!1,createParenthesizedExpressions:!1,errorRecovery:!1,attachComment:!0,annexB:!0};function xr(a){if(a==null)return Object.assign({},Je);if(a.annexB!=null&&a.annexB!==!1)throw new Error("The `annexB` option can only be set to `false`.");let t={};for(let s of Object.keys(Je)){var e;t[s]=(e=a[s])!=null?e:Je[s];}return t}var xt=class extends yt{checkProto(t,e,s,i){if(t.type==="SpreadElement"||this.isObjectMethod(t)||t.computed||t.shorthand)return;let r=t.key;if((r.type==="Identifier"?r.name:r.value)==="__proto__"){if(e){this.raise(p.RecordNoProto,{at:r});return}s.used&&(i?i.doubleProtoLoc===null&&(i.doubleProtoLoc=r.loc.start):this.raise(p.DuplicateProto,{at:r})),s.used=!0;}}shouldExitDescending(t,e){return t.type==="ArrowFunctionExpression"&&t.start===e}getExpression(){this.enterInitialScopes(),this.nextToken();let t=this.parseExpression();return this.match(137)||this.unexpected(),this.finalizeRemainingComments(),t.comments=this.state.comments,t.errors=this.state.errors,this.options.tokens&&(t.tokens=this.tokens),t}parseExpression(t,e){return t?this.disallowInAnd(()=>this.parseExpressionBase(e)):this.allowInAnd(()=>this.parseExpressionBase(e))}parseExpressionBase(t){let e=this.state.startLoc,s=this.parseMaybeAssign(t);if(this.match(12)){let i=this.startNodeAt(e);for(i.expressions=[s];this.eat(12);)i.expressions.push(this.parseMaybeAssign(t));return this.toReferencedList(i.expressions),this.finishNode(i,"SequenceExpression")}return s}parseMaybeAssignDisallowIn(t,e){return this.disallowInAnd(()=>this.parseMaybeAssign(t,e))}parseMaybeAssignAllowIn(t,e){return this.allowInAnd(()=>this.parseMaybeAssign(t,e))}setOptionalParametersError(t,e){var s;t.optionalParametersLoc=(s=e==null?void 0:e.loc)!=null?s:this.state.startLoc;}parseMaybeAssign(t,e){let s=this.state.startLoc;if(this.isContextual(106)&&this.prodParam.hasYield){let o=this.parseYield();return e&&(o=e.call(this,o,s)),o}let i;t?i=!1:(t=new se,i=!0);let{type:r}=this.state;(r===10||S(r))&&(this.state.potentialArrowAt=this.state.start);let n=this.parseMaybeConditional(t);if(e&&(n=e.call(this,n,s)),Ti(this.state.type)){let o=this.startNodeAt(s),h=this.state.value;if(o.operator=h,this.match(29)){this.toAssignable(n,!0),o.left=n;let l=s.index;t.doubleProtoLoc!=null&&t.doubleProtoLoc.index>=l&&(t.doubleProtoLoc=null),t.shorthandAssignLoc!=null&&t.shorthandAssignLoc.index>=l&&(t.shorthandAssignLoc=null),t.privateKeyLoc!=null&&t.privateKeyLoc.index>=l&&(this.checkDestructuringPrivate(t),t.privateKeyLoc=null);}else o.left=n;return this.next(),o.right=this.parseMaybeAssign(),this.checkLVal(n,{in:this.finishNode(o,"AssignmentExpression")}),o}else i&&this.checkExpressionErrors(t,!0);return n}parseMaybeConditional(t){let e=this.state.startLoc,s=this.state.potentialArrowAt,i=this.parseExprOps(t);return this.shouldExitDescending(i,s)?i:this.parseConditional(i,e,t)}parseConditional(t,e,s){if(this.eat(17)){let i=this.startNodeAt(e);return i.test=t,i.consequent=this.parseMaybeAssignAllowIn(),this.expect(14),i.alternate=this.parseMaybeAssign(),this.finishNode(i,"ConditionalExpression")}return t}parseMaybeUnaryOrPrivate(t){return this.match(136)?this.parsePrivateName():this.parseMaybeUnary(t)}parseExprOps(t){let e=this.state.startLoc,s=this.state.potentialArrowAt,i=this.parseMaybeUnaryOrPrivate(t);return this.shouldExitDescending(i,s)?i:this.parseExprOp(i,e,-1)}parseExprOp(t,e,s){if(this.isPrivateName(t)){let r=this.getPrivateNameSV(t);(s>=Ne(58)||!this.prodParam.hasIn||!this.match(58))&&this.raise(p.PrivateInExpectedIn,{at:t,identifierName:r}),this.classScope.usePrivateName(r,t.loc.start);}let i=this.state.type;if(Ai(i)&&(this.prodParam.hasIn||!this.match(58))){let r=Ne(i);if(r>s){if(i===39){if(this.expectPlugin("pipelineOperator"),this.state.inFSharpPipelineDirectBody)return t;this.checkPipelineAtInfixOperator(t,e);}let n=this.startNodeAt(e);n.left=t,n.operator=this.state.value;let o=i===41||i===42,h=i===40;if(h&&(r=Ne(42)),this.next(),i===39&&this.hasPlugin(["pipelineOperator",{proposal:"minimal"}])&&this.state.type===96&&this.prodParam.hasAwait)throw this.raise(p.UnexpectedAwaitAfterPipelineBody,{at:this.state.startLoc});n.right=this.parseExprOpRightExpr(i,r);let l=this.finishNode(n,o||h?"LogicalExpression":"BinaryExpression"),c=this.state.type;if(h&&(c===41||c===42)||o&&c===40)throw this.raise(p.MixingCoalesceWithLogical,{at:this.state.startLoc});return this.parseExprOp(l,e,s)}}return t}parseExprOpRightExpr(t,e){let s=this.state.startLoc;switch(t){case 39:switch(this.getPluginOption("pipelineOperator","proposal")){case"hack":return this.withTopicBindingContext(()=>this.parseHackPipeBody());case"smart":return this.withTopicBindingContext(()=>{if(this.prodParam.hasYield&&this.isContextual(106))throw this.raise(p.PipeBodyIsTighter,{at:this.state.startLoc});return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(t,e),s)});case"fsharp":return this.withSoloAwaitPermittingContext(()=>this.parseFSharpPipelineBody(e))}default:return this.parseExprOpBaseRightExpr(t,e)}}parseExprOpBaseRightExpr(t,e){let s=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnaryOrPrivate(),s,Ii(t)?e-1:e)}parseHackPipeBody(){var t;let{startLoc:e}=this.state,s=this.parseMaybeAssign();return li.has(s.type)&&!((t=s.extra)!=null&&t.parenthesized)&&this.raise(p.PipeUnparenthesizedBody,{at:e,type:s.type}),this.topicReferenceWasUsedInCurrentContext()||this.raise(p.PipeTopicUnused,{at:e}),s}checkExponentialAfterUnary(t){this.match(57)&&this.raise(p.UnexpectedTokenUnaryExponentiation,{at:t.argument});}parseMaybeUnary(t,e){let s=this.state.startLoc,i=this.isContextual(96);if(i&&this.isAwaitAllowed()){this.next();let h=this.parseAwait(s);return e||this.checkExponentialAfterUnary(h),h}let r=this.match(34),n=this.startNode();if(wi(this.state.type)){n.operator=this.state.value,n.prefix=!0,this.match(72)&&this.expectPlugin("throwExpressions");let h=this.match(89);if(this.next(),n.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(t,!0),this.state.strict&&h){let l=n.argument;l.type==="Identifier"?this.raise(p.StrictDelete,{at:n}):this.hasPropertyAsPrivateName(l)&&this.raise(p.DeletePrivateField,{at:n});}if(!r)return e||this.checkExponentialAfterUnary(n),this.finishNode(n,"UnaryExpression")}let o=this.parseUpdate(n,r,t);if(i){let{type:h}=this.state;if((this.hasPlugin("v8intrinsic")?Ze(h):Ze(h)&&!this.match(54))&&!this.isAmbiguousAwait())return this.raiseOverwrite(p.AwaitNotInAsyncContext,{at:s}),this.parseAwait(s)}return o}parseUpdate(t,e,s){if(e){let n=t;return this.checkLVal(n.argument,{in:this.finishNode(n,"UpdateExpression")}),t}let i=this.state.startLoc,r=this.parseExprSubscripts(s);if(this.checkExpressionErrors(s,!1))return r;for(;Si(this.state.type)&&!this.canInsertSemicolon();){let n=this.startNodeAt(i);n.operator=this.state.value,n.prefix=!1,n.argument=r,this.next(),this.checkLVal(r,{in:r=this.finishNode(n,"UpdateExpression")});}return r}parseExprSubscripts(t){let e=this.state.startLoc,s=this.state.potentialArrowAt,i=this.parseExprAtom(t);return this.shouldExitDescending(i,s)?i:this.parseSubscripts(i,e)}parseSubscripts(t,e,s){let i={optionalChainMember:!1,maybeAsyncArrow:this.atPossibleAsyncArrow(t),stop:!1};do t=this.parseSubscript(t,e,s,i),i.maybeAsyncArrow=!1;while(!i.stop);return t}parseSubscript(t,e,s,i){let{type:r}=this.state;if(!s&&r===15)return this.parseBind(t,e,s,i);if(Me(r))return this.parseTaggedTemplateExpression(t,e,i);let n=!1;if(r===18){if(s&&(this.raise(p.OptionalChainingNoNew,{at:this.state.startLoc}),this.lookaheadCharCode()===40))return i.stop=!0,t;i.optionalChainMember=n=!0,this.next();}if(!s&&this.match(10))return this.parseCoverCallAndAsyncArrowHead(t,e,i,n);{let o=this.eat(0);return o||n||this.eat(16)?this.parseMember(t,e,i,o,n):(i.stop=!0,t)}}parseMember(t,e,s,i,r){let n=this.startNodeAt(e);return n.object=t,n.computed=i,i?(n.property=this.parseExpression(),this.expect(3)):this.match(136)?(t.type==="Super"&&this.raise(p.SuperPrivateField,{at:e}),this.classScope.usePrivateName(this.state.value,this.state.startLoc),n.property=this.parsePrivateName()):n.property=this.parseIdentifier(!0),s.optionalChainMember?(n.optional=r,this.finishNode(n,"OptionalMemberExpression")):this.finishNode(n,"MemberExpression")}parseBind(t,e,s,i){let r=this.startNodeAt(e);return r.object=t,this.next(),r.callee=this.parseNoCallExpr(),i.stop=!0,this.parseSubscripts(this.finishNode(r,"BindExpression"),e,s)}parseCoverCallAndAsyncArrowHead(t,e,s,i){let r=this.state.maybeInArrowParameters,n=null;this.state.maybeInArrowParameters=!0,this.next();let o=this.startNodeAt(e);o.callee=t;let{maybeAsyncArrow:h,optionalChainMember:l}=s;h&&(this.expressionScope.enter(Ji()),n=new se),l&&(o.optional=i),i?o.arguments=this.parseCallExpressionArguments(11):o.arguments=this.parseCallExpressionArguments(11,t.type==="Import",t.type!=="Super",h?o:null,n);let c=this.finishCallExpression(o,l);return h&&this.shouldParseAsyncArrow()&&!i?(s.stop=!0,this.checkDestructuringPrivate(n),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),c=this.parseAsyncArrowFromCallExpression(this.startNodeAt(e),c)):(h&&(this.checkExpressionErrors(n,!0),this.expressionScope.exit()),this.toReferencedArguments(c)),this.state.maybeInArrowParameters=r,c}toReferencedArguments(t,e){this.toReferencedListDeep(t.arguments,e);}parseTaggedTemplateExpression(t,e,s){let i=this.startNodeAt(e);return i.tag=t,i.quasi=this.parseTemplate(!0),s.optionalChainMember&&this.raise(p.OptionalChainingNoTemplate,{at:e}),this.finishNode(i,"TaggedTemplateExpression")}atPossibleAsyncArrow(t){return t.type==="Identifier"&&t.name==="async"&&this.state.lastTokEndLoc.index===t.end&&!this.canInsertSemicolon()&&t.end-t.start===5&&t.start===this.state.potentialArrowAt}expectImportAttributesPlugin(){this.hasPlugin("importAssertions")||this.expectPlugin("importAttributes");}finishCallExpression(t,e){if(t.callee.type==="Import")if(t.arguments.length===2&&(this.hasPlugin("moduleAttributes")||this.expectImportAttributesPlugin()),t.arguments.length===0||t.arguments.length>2)this.raise(p.ImportCallArity,{at:t,maxArgumentCount:this.hasPlugin("importAttributes")||this.hasPlugin("importAssertions")||this.hasPlugin("moduleAttributes")?2:1});else for(let s of t.arguments)s.type==="SpreadElement"&&this.raise(p.ImportCallSpreadArgument,{at:s});return this.finishNode(t,e?"OptionalCallExpression":"CallExpression")}parseCallExpressionArguments(t,e,s,i,r){let n=[],o=!0,h=this.state.inFSharpPipelineDirectBody;for(this.state.inFSharpPipelineDirectBody=!1;!this.eat(t);){if(o)o=!1;else if(this.expect(12),this.match(t)){e&&!this.hasPlugin("importAttributes")&&!this.hasPlugin("importAssertions")&&!this.hasPlugin("moduleAttributes")&&this.raise(p.ImportCallArgumentTrailingComma,{at:this.state.lastTokStartLoc}),i&&this.addTrailingCommaExtraToNode(i),this.next();break}n.push(this.parseExprListItem(!1,r,s));}return this.state.inFSharpPipelineDirectBody=h,n}shouldParseAsyncArrow(){return this.match(19)&&!this.canInsertSemicolon()}parseAsyncArrowFromCallExpression(t,e){var s;return this.resetPreviousNodeTrailingComments(e),this.expect(19),this.parseArrowExpression(t,e.arguments,!0,(s=e.extra)==null?void 0:s.trailingCommaLoc),e.innerComments&&Te(t,e.innerComments),e.callee.trailingComments&&Te(t,e.callee.trailingComments),t}parseNoCallExpr(){let t=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),t,!0)}parseExprAtom(t){let e,s=null,{type:i}=this.state;switch(i){case 79:return this.parseSuper();case 83:return e=this.startNode(),this.next(),this.match(16)?this.parseImportMetaProperty(e):(this.match(10)||this.raise(p.UnsupportedImport,{at:this.state.lastTokStartLoc}),this.finishNode(e,"Import"));case 78:return e=this.startNode(),this.next(),this.finishNode(e,"ThisExpression");case 90:return this.parseDo(this.startNode(),!1);case 56:case 31:return this.readRegexp(),this.parseRegExpLiteral(this.state.value);case 132:return this.parseNumericLiteral(this.state.value);case 133:return this.parseBigIntLiteral(this.state.value);case 134:return this.parseDecimalLiteral(this.state.value);case 131:return this.parseStringLiteral(this.state.value);case 84:return this.parseNullLiteral();case 85:return this.parseBooleanLiteral(!0);case 86:return this.parseBooleanLiteral(!1);case 10:{let r=this.state.potentialArrowAt===this.state.start;return this.parseParenAndDistinguishExpression(r)}case 2:case 1:return this.parseArrayLike(this.state.type===2?4:3,!1,!0);case 0:return this.parseArrayLike(3,!0,!1,t);case 6:case 7:return this.parseObjectLike(this.state.type===6?9:8,!1,!0);case 5:return this.parseObjectLike(8,!1,!1,t);case 68:return this.parseFunctionOrFunctionSent();case 26:s=this.parseDecorators();case 80:return this.parseClass(this.maybeTakeDecorators(s,this.startNode()),!1);case 77:return this.parseNewOrNewTarget();case 25:case 24:return this.parseTemplate(!1);case 15:{e=this.startNode(),this.next(),e.object=null;let r=e.callee=this.parseNoCallExpr();if(r.type==="MemberExpression")return this.finishNode(e,"BindExpression");throw this.raise(p.UnsupportedBind,{at:r})}case 136:return this.raise(p.PrivateInExpectedIn,{at:this.state.startLoc,identifierName:this.state.value}),this.parsePrivateName();case 33:return this.parseTopicReferenceThenEqualsSign(54,"%");case 32:return this.parseTopicReferenceThenEqualsSign(44,"^");case 37:case 38:return this.parseTopicReference("hack");case 44:case 54:case 27:{let r=this.getPluginOption("pipelineOperator","proposal");if(r)return this.parseTopicReference(r);this.unexpected();break}case 47:{let r=this.input.codePointAt(this.nextTokenStart());j(r)||r===62?this.expectOnePlugin(["jsx","flow","typescript"]):this.unexpected();break}default:if(S(i)){if(this.isContextual(125)&&this.lookaheadInLineCharCode()===123)return this.parseModuleExpression();let r=this.state.potentialArrowAt===this.state.start,n=this.state.containsEsc,o=this.parseIdentifier();if(!n&&o.name==="async"&&!this.canInsertSemicolon()){let{type:h}=this.state;if(h===68)return this.resetPreviousNodeTrailingComments(o),this.next(),this.parseAsyncFunctionExpression(this.startNodeAtNode(o));if(S(h))return this.lookaheadCharCode()===61?this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(o)):o;if(h===90)return this.resetPreviousNodeTrailingComments(o),this.parseDo(this.startNodeAtNode(o),!0)}return r&&this.match(19)&&!this.canInsertSemicolon()?(this.next(),this.parseArrowExpression(this.startNodeAtNode(o),[o],!1)):o}else this.unexpected();}}parseTopicReferenceThenEqualsSign(t,e){let s=this.getPluginOption("pipelineOperator","proposal");if(s)return this.state.type=t,this.state.value=e,this.state.pos--,this.state.end--,this.state.endLoc=L(this.state.endLoc,-1),this.parseTopicReference(s);this.unexpected();}parseTopicReference(t){let e=this.startNode(),s=this.state.startLoc,i=this.state.type;return this.next(),this.finishTopicReference(e,s,t,i)}finishTopicReference(t,e,s,i){if(this.testTopicReferenceConfiguration(s,e,i)){let r=s==="smart"?"PipelinePrimaryTopicReference":"TopicReference";return this.topicReferenceIsAllowedInCurrentContext()||this.raise(s==="smart"?p.PrimaryTopicNotAllowed:p.PipeTopicUnbound,{at:e}),this.registerTopicReference(),this.finishNode(t,r)}else throw this.raise(p.PipeTopicUnconfiguredToken,{at:e,token:q(i)})}testTopicReferenceConfiguration(t,e,s){switch(t){case"hack":return this.hasPlugin(["pipelineOperator",{topicToken:q(s)}]);case"smart":return s===27;default:throw this.raise(p.PipeTopicRequiresHackPipes,{at:e})}}parseAsyncArrowUnaryFunction(t){this.prodParam.enter(ve(!0,this.prodParam.hasYield));let e=[this.parseIdentifier()];return this.prodParam.exit(),this.hasPrecedingLineBreak()&&this.raise(p.LineTerminatorBeforeArrow,{at:this.state.curPosition()}),this.expect(19),this.parseArrowExpression(t,e,!0)}parseDo(t,e){this.expectPlugin("doExpressions"),e&&this.expectPlugin("asyncDoExpressions"),t.async=e,this.next();let s=this.state.labels;return this.state.labels=[],e?(this.prodParam.enter(Be),t.body=this.parseBlock(),this.prodParam.exit()):t.body=this.parseBlock(),this.state.labels=s,this.finishNode(t,"DoExpression")}parseSuper(){let t=this.startNode();return this.next(),this.match(10)&&!this.scope.allowDirectSuper&&!this.options.allowSuperOutsideMethod?this.raise(p.SuperNotAllowed,{at:t}):!this.scope.allowSuper&&!this.options.allowSuperOutsideMethod&&this.raise(p.UnexpectedSuper,{at:t}),!this.match(10)&&!this.match(0)&&!this.match(16)&&this.raise(p.UnsupportedSuper,{at:t}),this.finishNode(t,"Super")}parsePrivateName(){let t=this.startNode(),e=this.startNodeAt(L(this.state.startLoc,1)),s=this.state.value;return this.next(),t.id=this.createIdentifier(e,s),this.finishNode(t,"PrivateName")}parseFunctionOrFunctionSent(){let t=this.startNode();if(this.next(),this.prodParam.hasYield&&this.match(16)){let e=this.createIdentifier(this.startNodeAtNode(t),"function");return this.next(),this.match(102)?this.expectPlugin("functionSent"):this.hasPlugin("functionSent")||this.unexpected(),this.parseMetaProperty(t,e,"sent")}return this.parseFunction(t)}parseMetaProperty(t,e,s){t.meta=e;let i=this.state.containsEsc;return t.property=this.parseIdentifier(!0),(t.property.name!==s||i)&&this.raise(p.UnsupportedMetaProperty,{at:t.property,target:e.name,onlyValidPropertyName:s}),this.finishNode(t,"MetaProperty")}parseImportMetaProperty(t){let e=this.createIdentifier(this.startNodeAtNode(t),"import");return this.next(),this.isContextual(100)&&(this.inModule||this.raise(p.ImportMetaOutsideModule,{at:e}),this.sawUnambiguousESM=!0),this.parseMetaProperty(t,e,"meta")}parseLiteralAtNode(t,e,s){return this.addExtra(s,"rawValue",t),this.addExtra(s,"raw",this.input.slice(s.start,this.state.end)),s.value=t,this.next(),this.finishNode(s,e)}parseLiteral(t,e){let s=this.startNode();return this.parseLiteralAtNode(t,e,s)}parseStringLiteral(t){return this.parseLiteral(t,"StringLiteral")}parseNumericLiteral(t){return this.parseLiteral(t,"NumericLiteral")}parseBigIntLiteral(t){return this.parseLiteral(t,"BigIntLiteral")}parseDecimalLiteral(t){return this.parseLiteral(t,"DecimalLiteral")}parseRegExpLiteral(t){let e=this.parseLiteral(t.value,"RegExpLiteral");return e.pattern=t.pattern,e.flags=t.flags,e}parseBooleanLiteral(t){let e=this.startNode();return e.value=t,this.next(),this.finishNode(e,"BooleanLiteral")}parseNullLiteral(){let t=this.startNode();return this.next(),this.finishNode(t,"NullLiteral")}parseParenAndDistinguishExpression(t){let e=this.state.startLoc,s;this.next(),this.expressionScope.enter(Wi());let i=this.state.maybeInArrowParameters,r=this.state.inFSharpPipelineDirectBody;this.state.maybeInArrowParameters=!0,this.state.inFSharpPipelineDirectBody=!1;let n=this.state.startLoc,o=[],h=new se,l=!0,c,u;for(;!this.match(11);){if(l)l=!1;else if(this.expect(12,h.optionalParametersLoc===null?null:h.optionalParametersLoc),this.match(11)){u=this.state.startLoc;break}if(this.match(21)){let x=this.state.startLoc;if(c=this.state.startLoc,o.push(this.parseParenItem(this.parseRestBinding(),x)),!this.checkCommaAfterRest(41))break}else o.push(this.parseMaybeAssignAllowIn(h,this.parseParenItem));}let f=this.state.lastTokEndLoc;this.expect(11),this.state.maybeInArrowParameters=i,this.state.inFSharpPipelineDirectBody=r;let d=this.startNodeAt(e);return t&&this.shouldParseArrow(o)&&(d=this.parseArrow(d))?(this.checkDestructuringPrivate(h),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),this.parseArrowExpression(d,o,!1),d):(this.expressionScope.exit(),o.length||this.unexpected(this.state.lastTokStartLoc),u&&this.unexpected(u),c&&this.unexpected(c),this.checkExpressionErrors(h,!0),this.toReferencedListDeep(o,!0),o.length>1?(s=this.startNodeAt(n),s.expressions=o,this.finishNode(s,"SequenceExpression"),this.resetEndLocation(s,f)):s=o[0],this.wrapParenthesis(e,s))}wrapParenthesis(t,e){if(!this.options.createParenthesizedExpressions)return this.addExtra(e,"parenthesized",!0),this.addExtra(e,"parenStart",t.index),this.takeSurroundingComments(e,t.index,this.state.lastTokEndLoc.index),e;let s=this.startNodeAt(t);return s.expression=e,this.finishNode(s,"ParenthesizedExpression")}shouldParseArrow(t){return !this.canInsertSemicolon()}parseArrow(t){if(this.eat(19))return t}parseParenItem(t,e){return t}parseNewOrNewTarget(){let t=this.startNode();if(this.next(),this.match(16)){let e=this.createIdentifier(this.startNodeAtNode(t),"new");this.next();let s=this.parseMetaProperty(t,e,"target");return !this.scope.inNonArrowFunction&&!this.scope.inClass&&!this.options.allowNewTargetOutsideFunction&&this.raise(p.UnexpectedNewTarget,{at:s}),s}return this.parseNew(t)}parseNew(t){if(this.parseNewCallee(t),this.eat(10)){let e=this.parseExprList(11);this.toReferencedList(e),t.arguments=e;}else t.arguments=[];return this.finishNode(t,"NewExpression")}parseNewCallee(t){t.callee=this.parseNoCallExpr(),t.callee.type==="Import"&&this.raise(p.ImportCallNotNewExpression,{at:t.callee});}parseTemplateElement(t){let{start:e,startLoc:s,end:i,value:r}=this.state,n=e+1,o=this.startNodeAt(L(s,1));r===null&&(t||this.raise(p.InvalidEscapeSequenceTemplate,{at:L(this.state.firstInvalidTemplateEscapePos,1)}));let h=this.match(24),l=h?-1:-2,c=i+l;o.value={raw:this.input.slice(n,c).replace(/\r\n?/g,` -`),cooked:r===null?null:r.slice(1,l)},o.tail=h,this.next();let u=this.finishNode(o,"TemplateElement");return this.resetEndLocation(u,L(this.state.lastTokEndLoc,l)),u}parseTemplate(t){let e=this.startNode();e.expressions=[];let s=this.parseTemplateElement(t);for(e.quasis=[s];!s.tail;)e.expressions.push(this.parseTemplateSubstitution()),this.readTemplateContinuation(),e.quasis.push(s=this.parseTemplateElement(t));return this.finishNode(e,"TemplateLiteral")}parseTemplateSubstitution(){return this.parseExpression()}parseObjectLike(t,e,s,i){s&&this.expectPlugin("recordAndTuple");let r=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let n=Object.create(null),o=!0,h=this.startNode();for(h.properties=[],this.next();!this.match(t);){if(o)o=!1;else if(this.expect(12),this.match(t)){this.addTrailingCommaExtraToNode(h);break}let c;e?c=this.parseBindingProperty():(c=this.parsePropertyDefinition(i),this.checkProto(c,s,n,i)),s&&!this.isObjectProperty(c)&&c.type!=="SpreadElement"&&this.raise(p.InvalidRecordProperty,{at:c}),c.shorthand&&this.addExtra(c,"shorthand",!0),h.properties.push(c);}this.next(),this.state.inFSharpPipelineDirectBody=r;let l="ObjectExpression";return e?l="ObjectPattern":s&&(l="RecordExpression"),this.finishNode(h,l)}addTrailingCommaExtraToNode(t){this.addExtra(t,"trailingComma",this.state.lastTokStart),this.addExtra(t,"trailingCommaLoc",this.state.lastTokStartLoc,!1);}maybeAsyncOrAccessorProp(t){return !t.computed&&t.key.type==="Identifier"&&(this.isLiteralPropertyName()||this.match(0)||this.match(55))}parsePropertyDefinition(t){let e=[];if(this.match(26))for(this.hasPlugin("decorators")&&this.raise(p.UnsupportedPropertyDecorator,{at:this.state.startLoc});this.match(26);)e.push(this.parseDecorator());let s=this.startNode(),i=!1,r=!1,n;if(this.match(21))return e.length&&this.unexpected(),this.parseSpread();e.length&&(s.decorators=e,e=[]),s.method=!1,t&&(n=this.state.startLoc);let o=this.eat(55);this.parsePropertyNamePrefixOperator(s);let h=this.state.containsEsc,l=this.parsePropertyName(s,t);if(!o&&!h&&this.maybeAsyncOrAccessorProp(s)){let c=l.name;c==="async"&&!this.hasPrecedingLineBreak()&&(i=!0,this.resetPreviousNodeTrailingComments(l),o=this.eat(55),this.parsePropertyName(s)),(c==="get"||c==="set")&&(r=!0,this.resetPreviousNodeTrailingComments(l),s.kind=c,this.match(55)&&(o=!0,this.raise(p.AccessorIsGenerator,{at:this.state.curPosition(),kind:c}),this.next()),this.parsePropertyName(s));}return this.parseObjPropValue(s,n,o,i,!1,r,t)}getGetterSetterExpectedParamCount(t){return t.kind==="get"?0:1}getObjectOrClassMethodParams(t){return t.params}checkGetterSetterParams(t){var e;let s=this.getGetterSetterExpectedParamCount(t),i=this.getObjectOrClassMethodParams(t);i.length!==s&&this.raise(t.kind==="get"?p.BadGetterArity:p.BadSetterArity,{at:t}),t.kind==="set"&&((e=i[i.length-1])==null?void 0:e.type)==="RestElement"&&this.raise(p.BadSetterRestParameter,{at:t});}parseObjectMethod(t,e,s,i,r){if(r){let n=this.parseMethod(t,e,!1,!1,!1,"ObjectMethod");return this.checkGetterSetterParams(n),n}if(s||e||this.match(10))return i&&this.unexpected(),t.kind="method",t.method=!0,this.parseMethod(t,e,s,!1,!1,"ObjectMethod")}parseObjectProperty(t,e,s,i){if(t.shorthand=!1,this.eat(14))return t.value=s?this.parseMaybeDefault(this.state.startLoc):this.parseMaybeAssignAllowIn(i),this.finishNode(t,"ObjectProperty");if(!t.computed&&t.key.type==="Identifier"){if(this.checkReservedWord(t.key.name,t.key.loc.start,!0,!1),s)t.value=this.parseMaybeDefault(e,V(t.key));else if(this.match(29)){let r=this.state.startLoc;i!=null?i.shorthandAssignLoc===null&&(i.shorthandAssignLoc=r):this.raise(p.InvalidCoverInitializedName,{at:r}),t.value=this.parseMaybeDefault(e,V(t.key));}else t.value=V(t.key);return t.shorthand=!0,this.finishNode(t,"ObjectProperty")}}parseObjPropValue(t,e,s,i,r,n,o){let h=this.parseObjectMethod(t,s,i,r,n)||this.parseObjectProperty(t,e,r,o);return h||this.unexpected(),h}parsePropertyName(t,e){if(this.eat(0))t.computed=!0,t.key=this.parseMaybeAssignAllowIn(),this.expect(3);else {let{type:s,value:i}=this.state,r;if(M(s))r=this.parseIdentifier(!0);else switch(s){case 132:r=this.parseNumericLiteral(i);break;case 131:r=this.parseStringLiteral(i);break;case 133:r=this.parseBigIntLiteral(i);break;case 134:r=this.parseDecimalLiteral(i);break;case 136:{let n=this.state.startLoc;e!=null?e.privateKeyLoc===null&&(e.privateKeyLoc=n):this.raise(p.UnexpectedPrivateField,{at:n}),r=this.parsePrivateName();break}default:this.unexpected();}t.key=r,s!==136&&(t.computed=!1);}return t.key}initFunction(t,e){t.id=null,t.generator=!1,t.async=e;}parseMethod(t,e,s,i,r,n,o=!1){this.initFunction(t,s),t.generator=e,this.scope.enter(18|(o?64:0)|(r?32:0)),this.prodParam.enter(ve(s,t.generator)),this.parseFunctionParams(t,i);let h=this.parseFunctionBodyAndFinish(t,n,!0);return this.prodParam.exit(),this.scope.exit(),h}parseArrayLike(t,e,s,i){s&&this.expectPlugin("recordAndTuple");let r=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let n=this.startNode();return this.next(),n.elements=this.parseExprList(t,!s,i,n),this.state.inFSharpPipelineDirectBody=r,this.finishNode(n,s?"TupleExpression":"ArrayExpression")}parseArrowExpression(t,e,s,i){this.scope.enter(6);let r=ve(s,!1);!this.match(5)&&this.prodParam.hasIn&&(r|=Q),this.prodParam.enter(r),this.initFunction(t,s);let n=this.state.maybeInArrowParameters;return e&&(this.state.maybeInArrowParameters=!0,this.setArrowFunctionParameters(t,e,i)),this.state.maybeInArrowParameters=!1,this.parseFunctionBody(t,!0),this.prodParam.exit(),this.scope.exit(),this.state.maybeInArrowParameters=n,this.finishNode(t,"ArrowFunctionExpression")}setArrowFunctionParameters(t,e,s){this.toAssignableList(e,s,!1),t.params=e;}parseFunctionBodyAndFinish(t,e,s=!1){return this.parseFunctionBody(t,!1,s),this.finishNode(t,e)}parseFunctionBody(t,e,s=!1){let i=e&&!this.match(5);if(this.expressionScope.enter(hs()),i)t.body=this.parseMaybeAssign(),this.checkParams(t,!1,e,!1);else {let r=this.state.strict,n=this.state.labels;this.state.labels=[],this.prodParam.enter(this.prodParam.currentFlags()|cs),t.body=this.parseBlock(!0,!1,o=>{let h=!this.isSimpleParamList(t.params);o&&h&&this.raise(p.IllegalLanguageModeDirective,{at:(t.kind==="method"||t.kind==="constructor")&&t.key?t.key.loc.end:t});let l=!r&&this.state.strict;this.checkParams(t,!this.state.strict&&!e&&!s&&!h,e,l),this.state.strict&&t.id&&this.checkIdentifier(t.id,65,l);}),this.prodParam.exit(),this.state.labels=n;}this.expressionScope.exit();}isSimpleParameter(t){return t.type==="Identifier"}isSimpleParamList(t){for(let e=0,s=t.length;e10||!Ri(t))return;if(s&&Oi(t)){this.raise(p.UnexpectedKeyword,{at:e,keyword:t});return}if((this.state.strict?i?is:ts:es)(t,this.inModule)){this.raise(p.UnexpectedReservedWord,{at:e,reservedWord:t});return}else if(t==="yield"){if(this.prodParam.hasYield){this.raise(p.YieldBindingIdentifier,{at:e});return}}else if(t==="await"){if(this.prodParam.hasAwait){this.raise(p.AwaitBindingIdentifier,{at:e});return}if(this.scope.inStaticBlock){this.raise(p.AwaitBindingIdentifierInStaticBlock,{at:e});return}this.expressionScope.recordAsyncArrowParametersError({at:e});}else if(t==="arguments"&&this.scope.inClassAndNotInNonArrowFunction){this.raise(p.ArgumentsInClass,{at:e});return}}isAwaitAllowed(){return !!(this.prodParam.hasAwait||this.options.allowAwaitOutsideFunction&&!this.scope.inFunction)}parseAwait(t){let e=this.startNodeAt(t);return this.expressionScope.recordParameterInitializerError(p.AwaitExpressionFormalParameter,{at:e}),this.eat(55)&&this.raise(p.ObsoleteAwaitStar,{at:e}),!this.scope.inFunction&&!this.options.allowAwaitOutsideFunction&&(this.isAmbiguousAwait()?this.ambiguousScriptDifferentAst=!0:this.sawUnambiguousESM=!0),this.state.soloAwait||(e.argument=this.parseMaybeUnary(null,!0)),this.finishNode(e,"AwaitExpression")}isAmbiguousAwait(){if(this.hasPrecedingLineBreak())return !0;let{type:t}=this.state;return t===53||t===10||t===0||Me(t)||t===101&&!this.state.containsEsc||t===135||t===56||this.hasPlugin("v8intrinsic")&&t===54}parseYield(){let t=this.startNode();this.expressionScope.recordParameterInitializerError(p.YieldInParameter,{at:t}),this.next();let e=!1,s=null;if(!this.hasPrecedingLineBreak())switch(e=this.eat(55),this.state.type){case 13:case 137:case 8:case 11:case 3:case 9:case 14:case 12:if(!e)break;default:s=this.parseMaybeAssign();}return t.delegate=e,t.argument=s,this.finishNode(t,"YieldExpression")}checkPipelineAtInfixOperator(t,e){this.hasPlugin(["pipelineOperator",{proposal:"smart"}])&&t.type==="SequenceExpression"&&this.raise(p.PipelineHeadSequenceExpression,{at:e});}parseSmartPipelineBodyInStyle(t,e){if(this.isSimpleReference(t)){let s=this.startNodeAt(e);return s.callee=t,this.finishNode(s,"PipelineBareFunction")}else {let s=this.startNodeAt(e);return this.checkSmartPipeTopicBodyEarlyErrors(e),s.expression=t,this.finishNode(s,"PipelineTopicExpression")}}isSimpleReference(t){switch(t.type){case"MemberExpression":return !t.computed&&this.isSimpleReference(t.object);case"Identifier":return !0;default:return !1}}checkSmartPipeTopicBodyEarlyErrors(t){if(this.match(19))throw this.raise(p.PipelineBodyNoArrow,{at:this.state.startLoc});this.topicReferenceWasUsedInCurrentContext()||this.raise(p.PipelineTopicUnused,{at:t});}withTopicBindingContext(t){let e=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:1,maxTopicIndex:null};try{return t()}finally{this.state.topicContext=e;}}withSmartMixTopicForbiddingContext(t){if(this.hasPlugin(["pipelineOperator",{proposal:"smart"}])){let e=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null};try{return t()}finally{this.state.topicContext=e;}}else return t()}withSoloAwaitPermittingContext(t){let e=this.state.soloAwait;this.state.soloAwait=!0;try{return t()}finally{this.state.soloAwait=e;}}allowInAnd(t){let e=this.prodParam.currentFlags();if(Q&~e){this.prodParam.enter(e|Q);try{return t()}finally{this.prodParam.exit();}}return t()}disallowInAnd(t){let e=this.prodParam.currentFlags();if(Q&e){this.prodParam.enter(e&~Q);try{return t()}finally{this.prodParam.exit();}}return t()}registerTopicReference(){this.state.topicContext.maxTopicIndex=0;}topicReferenceIsAllowedInCurrentContext(){return this.state.topicContext.maxNumOfResolvableTopics>=1}topicReferenceWasUsedInCurrentContext(){return this.state.topicContext.maxTopicIndex!=null&&this.state.topicContext.maxTopicIndex>=0}parseFSharpPipelineBody(t){let e=this.state.startLoc;this.state.potentialArrowAt=this.state.start;let s=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!0;let i=this.parseExprOp(this.parseMaybeUnaryOrPrivate(),e,t);return this.state.inFSharpPipelineDirectBody=s,i}parseModuleExpression(){this.expectPlugin("moduleBlocks");let t=this.startNode();this.next(),this.match(5)||this.unexpected(null,5);let e=this.startNodeAt(this.state.endLoc);this.next();let s=this.initializeScopes(!0);this.enterInitialScopes();try{t.body=this.parseProgram(e,8,"module");}finally{s();}return this.finishNode(t,"ModuleExpression")}parsePropertyNamePrefixOperator(t){}},Xe={kind:"loop"},Pr={kind:"switch"},gr=/[\uD800-\uDFFF]/u,Ge=/in(?:stanceof)?/y;function Tr(a,t){for(let e=0;e0)for(let[r,n]of Array.from(this.scope.undefinedExports))this.raise(p.ModuleExportUndefined,{at:n,localName:r});let i;return e===137?i=this.finishNode(t,"Program"):i=this.finishNodeAt(t,"Program",L(this.state.startLoc,-1)),i}stmtToDirective(t){let e=t;e.type="Directive",e.value=e.expression,delete e.expression;let s=e.value,i=s.value,r=this.input.slice(s.start,s.end),n=s.value=r.slice(1,-1);return this.addExtra(s,"raw",r),this.addExtra(s,"rawValue",n),this.addExtra(s,"expressionValue",i),s.type="DirectiveLiteral",e}parseInterpreterDirective(){if(!this.match(28))return null;let t=this.startNode();return t.value=this.state.value,this.next(),this.finishNode(t,"InterpreterDirective")}isLet(){return this.isContextual(99)?this.hasFollowingBindingAtom():!1}chStartsBindingIdentifier(t,e){if(j(t)){if(Ge.lastIndex=e,Ge.test(this.input)){let s=this.codePointAtPos(Ge.lastIndex);if(!ee(s)&&s!==92)return !1}return !0}else return t===92}chStartsBindingPattern(t){return t===91||t===123}hasFollowingBindingAtom(){let t=this.nextTokenStart(),e=this.codePointAtPos(t);return this.chStartsBindingPattern(e)||this.chStartsBindingIdentifier(e,t)}hasInLineFollowingBindingIdentifier(){let t=this.nextTokenInLineStart(),e=this.codePointAtPos(t);return this.chStartsBindingIdentifier(e,t)}startsUsingForOf(){let{type:t,containsEsc:e}=this.lookahead();if(t===101&&!e)return !1;if(S(t)&&!this.hasFollowingLineBreak())return this.expectPlugin("explicitResourceManagement"),!0}startsAwaitUsing(){let t=this.nextTokenInLineStart();if(this.isUnparsedContextual(t,"using")){t=this.nextTokenInLineStartSince(t+5);let e=this.codePointAtPos(t);if(this.chStartsBindingIdentifier(e,t))return this.expectPlugin("explicitResourceManagement"),!0}return !1}parseModuleItem(){return this.parseStatementLike(15)}parseStatementListItem(){return this.parseStatementLike(6|(!this.options.annexB||this.state.strict?0:8))}parseStatementOrSloppyAnnexBFunctionDeclaration(t=!1){let e=0;return this.options.annexB&&!this.state.strict&&(e|=4,t&&(e|=8)),this.parseStatementLike(e)}parseStatement(){return this.parseStatementLike(0)}parseStatementLike(t){let e=null;return this.match(26)&&(e=this.parseDecorators(!0)),this.parseStatementContent(t,e)}parseStatementContent(t,e){let s=this.state.type,i=this.startNode(),r=!!(t&2),n=!!(t&4),o=t&1;switch(s){case 60:return this.parseBreakContinueStatement(i,!0);case 63:return this.parseBreakContinueStatement(i,!1);case 64:return this.parseDebuggerStatement(i);case 90:return this.parseDoWhileStatement(i);case 91:return this.parseForStatement(i);case 68:if(this.lookaheadCharCode()===46)break;return n||this.raise(this.state.strict?p.StrictFunction:this.options.annexB?p.SloppyFunctionAnnexB:p.SloppyFunction,{at:this.state.startLoc}),this.parseFunctionStatement(i,!1,!r&&n);case 80:return r||this.unexpected(),this.parseClass(this.maybeTakeDecorators(e,i),!0);case 69:return this.parseIfStatement(i);case 70:return this.parseReturnStatement(i);case 71:return this.parseSwitchStatement(i);case 72:return this.parseThrowStatement(i);case 73:return this.parseTryStatement(i);case 96:if(!this.state.containsEsc&&this.startsAwaitUsing())return this.isAwaitAllowed()?r||this.raise(p.UnexpectedLexicalDeclaration,{at:i}):this.raise(p.AwaitUsingNotInAsyncContext,{at:i}),this.next(),this.parseVarStatement(i,"await using");break;case 105:if(this.state.containsEsc||!this.hasInLineFollowingBindingIdentifier())break;return this.expectPlugin("explicitResourceManagement"),!this.scope.inModule&&this.scope.inTopLevel?this.raise(p.UnexpectedUsingDeclaration,{at:this.state.startLoc}):r||this.raise(p.UnexpectedLexicalDeclaration,{at:this.state.startLoc}),this.parseVarStatement(i,"using");case 99:{if(this.state.containsEsc)break;let c=this.nextTokenStart(),u=this.codePointAtPos(c);if(u!==91&&(!r&&this.hasFollowingLineBreak()||!this.chStartsBindingIdentifier(u,c)&&u!==123))break}case 75:r||this.raise(p.UnexpectedLexicalDeclaration,{at:this.state.startLoc});case 74:{let c=this.state.value;return this.parseVarStatement(i,c)}case 92:return this.parseWhileStatement(i);case 76:return this.parseWithStatement(i);case 5:return this.parseBlock();case 13:return this.parseEmptyStatement(i);case 83:{let c=this.lookaheadCharCode();if(c===40||c===46)break}case 82:{!this.options.allowImportExportEverywhere&&!o&&this.raise(p.UnexpectedImportExport,{at:this.state.startLoc}),this.next();let c;return s===83?(c=this.parseImport(i),c.type==="ImportDeclaration"&&(!c.importKind||c.importKind==="value")&&(this.sawUnambiguousESM=!0)):(c=this.parseExport(i,e),(c.type==="ExportNamedDeclaration"&&(!c.exportKind||c.exportKind==="value")||c.type==="ExportAllDeclaration"&&(!c.exportKind||c.exportKind==="value")||c.type==="ExportDefaultDeclaration")&&(this.sawUnambiguousESM=!0)),this.assertModuleNodeAllowed(c),c}default:if(this.isAsyncFunction())return r||this.raise(p.AsyncFunctionInSingleStatementContext,{at:this.state.startLoc}),this.next(),this.parseFunctionStatement(i,!0,!r&&n)}let h=this.state.value,l=this.parseExpression();return S(s)&&l.type==="Identifier"&&this.eat(14)?this.parseLabeledStatement(i,h,l,t):this.parseExpressionStatement(i,l,e)}assertModuleNodeAllowed(t){!this.options.allowImportExportEverywhere&&!this.inModule&&this.raise(p.ImportOutsideModule,{at:t});}decoratorsEnabledBeforeExport(){return this.hasPlugin("decorators-legacy")?!0:this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")!==!1}maybeTakeDecorators(t,e,s){return t&&(e.decorators&&e.decorators.length>0?(typeof this.getPluginOption("decorators","decoratorsBeforeExport")!="boolean"&&this.raise(p.DecoratorsBeforeAfterExport,{at:e.decorators[0]}),e.decorators.unshift(...t)):e.decorators=t,this.resetStartLocationFromNode(e,t[0]),s&&this.resetStartLocationFromNode(s,e)),e}canHaveLeadingDecorator(){return this.match(80)}parseDecorators(t){let e=[];do e.push(this.parseDecorator());while(this.match(26));if(this.match(82))t||this.unexpected(),this.decoratorsEnabledBeforeExport()||this.raise(p.DecoratorExportClass,{at:this.state.startLoc});else if(!this.canHaveLeadingDecorator())throw this.raise(p.UnexpectedLeadingDecorator,{at:this.state.startLoc});return e}parseDecorator(){this.expectOnePlugin(["decorators","decorators-legacy"]);let t=this.startNode();if(this.next(),this.hasPlugin("decorators")){let e=this.state.startLoc,s;if(this.match(10)){let i=this.state.startLoc;this.next(),s=this.parseExpression(),this.expect(11),s=this.wrapParenthesis(i,s);let r=this.state.startLoc;t.expression=this.parseMaybeDecoratorArguments(s),this.getPluginOption("decorators","allowCallParenthesized")===!1&&t.expression!==s&&this.raise(p.DecoratorArgumentsOutsideParentheses,{at:r});}else {for(s=this.parseIdentifier(!1);this.eat(16);){let i=this.startNodeAt(e);i.object=s,this.match(136)?(this.classScope.usePrivateName(this.state.value,this.state.startLoc),i.property=this.parsePrivateName()):i.property=this.parseIdentifier(!0),i.computed=!1,s=this.finishNode(i,"MemberExpression");}t.expression=this.parseMaybeDecoratorArguments(s);}}else t.expression=this.parseExprSubscripts();return this.finishNode(t,"Decorator")}parseMaybeDecoratorArguments(t){if(this.eat(10)){let e=this.startNodeAtNode(t);return e.callee=t,e.arguments=this.parseCallExpressionArguments(11,!1),this.toReferencedList(e.arguments),this.finishNode(e,"CallExpression")}return t}parseBreakContinueStatement(t,e){return this.next(),this.isLineTerminator()?t.label=null:(t.label=this.parseIdentifier(),this.semicolon()),this.verifyBreakContinue(t,e),this.finishNode(t,e?"BreakStatement":"ContinueStatement")}verifyBreakContinue(t,e){let s;for(s=0;sthis.parseStatement()),this.state.labels.pop(),this.expect(92),t.test=this.parseHeaderExpression(),this.eat(13),this.finishNode(t,"DoWhileStatement")}parseForStatement(t){this.next(),this.state.labels.push(Xe);let e=null;if(this.isAwaitAllowed()&&this.eatContextual(96)&&(e=this.state.lastTokStartLoc),this.scope.enter(0),this.expect(10),this.match(13))return e!==null&&this.unexpected(e),this.parseFor(t,null);let s=this.isContextual(99);{let h=this.isContextual(96)&&this.startsAwaitUsing(),l=h||this.isContextual(105)&&this.startsUsingForOf(),c=s&&this.hasFollowingBindingAtom()||l;if(this.match(74)||this.match(75)||c){let u=this.startNode(),f;h?(f="await using",this.isAwaitAllowed()||this.raise(p.AwaitUsingNotInAsyncContext,{at:this.state.startLoc}),this.next()):f=this.state.value,this.next(),this.parseVar(u,!0,f);let d=this.finishNode(u,"VariableDeclaration"),x=this.match(58);return x&&l&&this.raise(p.ForInUsing,{at:d}),(x||this.isContextual(101))&&d.declarations.length===1?this.parseForIn(t,d,e):(e!==null&&this.unexpected(e),this.parseFor(t,d))}}let i=this.isContextual(95),r=new se,n=this.parseExpression(!0,r),o=this.isContextual(101);if(o&&(s&&this.raise(p.ForOfLet,{at:n}),e===null&&i&&n.type==="Identifier"&&this.raise(p.ForOfAsync,{at:n})),o||this.match(58)){this.checkDestructuringPrivate(r),this.toAssignable(n,!0);let h=o?"ForOfStatement":"ForInStatement";return this.checkLVal(n,{in:{type:h}}),this.parseForIn(t,n,e)}else this.checkExpressionErrors(r,!0);return e!==null&&this.unexpected(e),this.parseFor(t,n)}parseFunctionStatement(t,e,s){return this.next(),this.parseFunction(t,1|(s?2:0)|(e?8:0))}parseIfStatement(t){return this.next(),t.test=this.parseHeaderExpression(),t.consequent=this.parseStatementOrSloppyAnnexBFunctionDeclaration(),t.alternate=this.eat(66)?this.parseStatementOrSloppyAnnexBFunctionDeclaration():null,this.finishNode(t,"IfStatement")}parseReturnStatement(t){return !this.prodParam.hasReturn&&!this.options.allowReturnOutsideFunction&&this.raise(p.IllegalReturn,{at:this.state.startLoc}),this.next(),this.isLineTerminator()?t.argument=null:(t.argument=this.parseExpression(),this.semicolon()),this.finishNode(t,"ReturnStatement")}parseSwitchStatement(t){this.next(),t.discriminant=this.parseHeaderExpression();let e=t.cases=[];this.expect(5),this.state.labels.push(Pr),this.scope.enter(0);let s;for(let i;!this.match(8);)if(this.match(61)||this.match(65)){let r=this.match(61);s&&this.finishNode(s,"SwitchCase"),e.push(s=this.startNode()),s.consequent=[],this.next(),r?s.test=this.parseExpression():(i&&this.raise(p.MultipleDefaultsInSwitch,{at:this.state.lastTokStartLoc}),i=!0,s.test=null),this.expect(14);}else s?s.consequent.push(this.parseStatementListItem()):this.unexpected();return this.scope.exit(),s&&this.finishNode(s,"SwitchCase"),this.next(),this.state.labels.pop(),this.finishNode(t,"SwitchStatement")}parseThrowStatement(t){return this.next(),this.hasPrecedingLineBreak()&&this.raise(p.NewlineAfterThrow,{at:this.state.lastTokEndLoc}),t.argument=this.parseExpression(),this.semicolon(),this.finishNode(t,"ThrowStatement")}parseCatchClauseParam(){let t=this.parseBindingAtom();return this.scope.enter(this.options.annexB&&t.type==="Identifier"?8:0),this.checkLVal(t,{in:{type:"CatchClause"},binding:9}),t}parseTryStatement(t){if(this.next(),t.block=this.parseBlock(),t.handler=null,this.match(62)){let e=this.startNode();this.next(),this.match(10)?(this.expect(10),e.param=this.parseCatchClauseParam(),this.expect(11)):(e.param=null,this.scope.enter(0)),e.body=this.withSmartMixTopicForbiddingContext(()=>this.parseBlock(!1,!1)),this.scope.exit(),t.handler=this.finishNode(e,"CatchClause");}return t.finalizer=this.eat(67)?this.parseBlock():null,!t.handler&&!t.finalizer&&this.raise(p.NoCatchOrFinally,{at:t}),this.finishNode(t,"TryStatement")}parseVarStatement(t,e,s=!1){return this.next(),this.parseVar(t,!1,e,s),this.semicolon(),this.finishNode(t,"VariableDeclaration")}parseWhileStatement(t){return this.next(),t.test=this.parseHeaderExpression(),this.state.labels.push(Xe),t.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.state.labels.pop(),this.finishNode(t,"WhileStatement")}parseWithStatement(t){return this.state.strict&&this.raise(p.StrictWith,{at:this.state.startLoc}),this.next(),t.object=this.parseHeaderExpression(),t.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.finishNode(t,"WithStatement")}parseEmptyStatement(t){return this.next(),this.finishNode(t,"EmptyStatement")}parseLabeledStatement(t,e,s,i){for(let n of this.state.labels)n.name===e&&this.raise(p.LabelRedeclaration,{at:s,labelName:e});let r=bi(this.state.type)?"loop":this.match(71)?"switch":null;for(let n=this.state.labels.length-1;n>=0;n--){let o=this.state.labels[n];if(o.statementStart===t.start)o.statementStart=this.state.start,o.kind=r;else break}return this.state.labels.push({name:e,kind:r,statementStart:this.state.start}),t.body=i&8?this.parseStatementOrSloppyAnnexBFunctionDeclaration(!0):this.parseStatement(),this.state.labels.pop(),t.label=s,this.finishNode(t,"LabeledStatement")}parseExpressionStatement(t,e,s){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")}parseBlock(t=!1,e=!0,s){let i=this.startNode();return t&&this.state.strictErrors.clear(),this.expect(5),e&&this.scope.enter(0),this.parseBlockBody(i,t,!1,8,s),e&&this.scope.exit(),this.finishNode(i,"BlockStatement")}isValidDirective(t){return t.type==="ExpressionStatement"&&t.expression.type==="StringLiteral"&&!t.expression.extra.parenthesized}parseBlockBody(t,e,s,i,r){let n=t.body=[],o=t.directives=[];this.parseBlockOrModuleBlockBody(n,e?o:void 0,s,i,r);}parseBlockOrModuleBlockBody(t,e,s,i,r){let n=this.state.strict,o=!1,h=!1;for(;!this.match(i);){let l=s?this.parseModuleItem():this.parseStatementListItem();if(e&&!h){if(this.isValidDirective(l)){let c=this.stmtToDirective(l);e.push(c),!o&&c.value.value==="use strict"&&(o=!0,this.setStrict(!0));continue}h=!0,this.state.strictErrors.clear();}t.push(l);}r==null||r.call(this,o),n||this.setStrict(!1),this.next();}parseFor(t,e){return t.init=e,this.semicolon(!1),t.test=this.match(13)?null:this.parseExpression(),this.semicolon(!1),t.update=this.match(11)?null:this.parseExpression(),this.expect(11),t.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.scope.exit(),this.state.labels.pop(),this.finishNode(t,"ForStatement")}parseForIn(t,e,s){let i=this.match(58);return this.next(),i?s!==null&&this.unexpected(s):t.await=s!==null,e.type==="VariableDeclaration"&&e.declarations[0].init!=null&&(!i||!this.options.annexB||this.state.strict||e.kind!=="var"||e.declarations[0].id.type!=="Identifier")&&this.raise(p.ForInOfLoopInitializer,{at:e,type:i?"ForInStatement":"ForOfStatement"}),e.type==="AssignmentPattern"&&this.raise(p.InvalidLhs,{at:e,ancestor:{type:"ForStatement"}}),t.left=e,t.right=i?this.parseExpression():this.parseMaybeAssignAllowIn(),this.expect(11),t.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.scope.exit(),this.state.labels.pop(),this.finishNode(t,i?"ForInStatement":"ForOfStatement")}parseVar(t,e,s,i=!1){let r=t.declarations=[];for(t.kind=s;;){let n=this.startNode();if(this.parseVarId(n,s),n.init=this.eat(29)?e?this.parseMaybeAssignDisallowIn():this.parseMaybeAssignAllowIn():null,n.init===null&&!i&&(n.id.type!=="Identifier"&&!(e&&(this.match(58)||this.isContextual(101)))?this.raise(p.DeclarationMissingInitializer,{at:this.state.lastTokEndLoc,kind:"destructuring"}):s==="const"&&!(this.match(58)||this.isContextual(101))&&this.raise(p.DeclarationMissingInitializer,{at:this.state.lastTokEndLoc,kind:"const"})),r.push(this.finishNode(n,"VariableDeclarator")),!this.eat(12))break}return t}parseVarId(t,e){let s=this.parseBindingAtom();this.checkLVal(s,{in:{type:"VariableDeclarator"},binding:e==="var"?5:8201}),t.id=s;}parseAsyncFunctionExpression(t){return this.parseFunction(t,8)}parseFunction(t,e=0){let s=e&2,i=!!(e&1),r=i&&!(e&4),n=!!(e&8);this.initFunction(t,n),this.match(55)&&(s&&this.raise(p.GeneratorInSingleStatementContext,{at:this.state.startLoc}),this.next(),t.generator=!0),i&&(t.id=this.parseFunctionId(r));let o=this.state.maybeInArrowParameters;return this.state.maybeInArrowParameters=!1,this.scope.enter(2),this.prodParam.enter(ve(n,t.generator)),i||(t.id=this.parseFunctionId()),this.parseFunctionParams(t,!1),this.withSmartMixTopicForbiddingContext(()=>{this.parseFunctionBodyAndFinish(t,i?"FunctionDeclaration":"FunctionExpression");}),this.prodParam.exit(),this.scope.exit(),i&&!s&&this.registerFunctionStatementId(t),this.state.maybeInArrowParameters=o,t}parseFunctionId(t){return t||S(this.state.type)?this.parseIdentifier():null}parseFunctionParams(t,e){this.expect(10),this.expressionScope.enter(Hi()),t.params=this.parseBindingList(11,41,2|(e?4:0)),this.expressionScope.exit();}registerFunctionStatementId(t){t.id&&this.scope.declareName(t.id.name,!this.options.annexB||this.state.strict||t.generator||t.async?this.scope.treatFunctionsAsVar?5:8201:17,t.id.loc.start);}parseClass(t,e,s){this.next();let i=this.state.strict;return this.state.strict=!0,this.parseClassId(t,e,s),this.parseClassSuper(t),t.body=this.parseClassBody(!!t.superClass,i),this.finishNode(t,e?"ClassDeclaration":"ClassExpression")}isClassProperty(){return this.match(29)||this.match(13)||this.match(8)}isClassMethod(){return this.match(10)}isNonstaticConstructor(t){return !t.computed&&!t.static&&(t.key.name==="constructor"||t.key.value==="constructor")}parseClassBody(t,e){this.classScope.enter();let s={hadConstructor:!1,hadSuperClass:t},i=[],r=this.startNode();if(r.body=[],this.expect(5),this.withSmartMixTopicForbiddingContext(()=>{for(;!this.match(8);){if(this.eat(13)){if(i.length>0)throw this.raise(p.DecoratorSemicolon,{at:this.state.lastTokEndLoc});continue}if(this.match(26)){i.push(this.parseDecorator());continue}let n=this.startNode();i.length&&(n.decorators=i,this.resetStartLocationFromNode(n,i[0]),i=[]),this.parseClassMember(r,n,s),n.kind==="constructor"&&n.decorators&&n.decorators.length>0&&this.raise(p.DecoratorConstructor,{at:n});}}),this.state.strict=e,this.next(),i.length)throw this.raise(p.TrailingDecorator,{at:this.state.startLoc});return this.classScope.exit(),this.finishNode(r,"ClassBody")}parseClassMemberFromModifier(t,e){let s=this.parseIdentifier(!0);if(this.isClassMethod()){let i=e;return i.kind="method",i.computed=!1,i.key=s,i.static=!1,this.pushClassMethod(t,i,!1,!1,!1,!1),!0}else if(this.isClassProperty()){let i=e;return i.computed=!1,i.key=s,i.static=!1,t.body.push(this.parseClassProperty(i)),!0}return this.resetPreviousNodeTrailingComments(s),!1}parseClassMember(t,e,s){let i=this.isContextual(104);if(i){if(this.parseClassMemberFromModifier(t,e))return;if(this.eat(5)){this.parseClassStaticBlock(t,e);return}}this.parseClassMemberWithIsStatic(t,e,s,i);}parseClassMemberWithIsStatic(t,e,s,i){let r=e,n=e,o=e,h=e,l=e,c=r,u=r;if(e.static=i,this.parsePropertyNamePrefixOperator(e),this.eat(55)){c.kind="method";let C=this.match(136);if(this.parseClassElementName(c),C){this.pushClassPrivateMethod(t,n,!0,!1);return}this.isNonstaticConstructor(r)&&this.raise(p.ConstructorIsGenerator,{at:r.key}),this.pushClassMethod(t,r,!0,!1,!1,!1);return}let f=S(this.state.type)&&!this.state.containsEsc,d=this.match(136),x=this.parseClassElementName(e),I=this.state.startLoc;if(this.parsePostMemberNameModifiers(u),this.isClassMethod()){if(c.kind="method",d){this.pushClassPrivateMethod(t,n,!1,!1);return}let C=this.isNonstaticConstructor(r),E=!1;C&&(r.kind="constructor",s.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(p.DuplicateConstructor,{at:x}),C&&this.hasPlugin("typescript")&&e.override&&this.raise(p.OverrideOnConstructor,{at:x}),s.hadConstructor=!0,E=s.hadSuperClass),this.pushClassMethod(t,r,!1,!1,C,E);}else if(this.isClassProperty())d?this.pushClassPrivateProperty(t,h):this.pushClassProperty(t,o);else if(f&&x.name==="async"&&!this.isLineTerminator()){this.resetPreviousNodeTrailingComments(x);let C=this.eat(55);u.optional&&this.unexpected(I),c.kind="method";let E=this.match(136);this.parseClassElementName(c),this.parsePostMemberNameModifiers(u),E?this.pushClassPrivateMethod(t,n,C,!0):(this.isNonstaticConstructor(r)&&this.raise(p.ConstructorIsAsync,{at:r.key}),this.pushClassMethod(t,r,C,!0,!1,!1));}else if(f&&(x.name==="get"||x.name==="set")&&!(this.match(55)&&this.isLineTerminator())){this.resetPreviousNodeTrailingComments(x),c.kind=x.name;let C=this.match(136);this.parseClassElementName(r),C?this.pushClassPrivateMethod(t,n,!1,!1):(this.isNonstaticConstructor(r)&&this.raise(p.ConstructorIsAccessor,{at:r.key}),this.pushClassMethod(t,r,!1,!1,!1,!1)),this.checkGetterSetterParams(r);}else if(f&&x.name==="accessor"&&!this.isLineTerminator()){this.expectPlugin("decoratorAutoAccessors"),this.resetPreviousNodeTrailingComments(x);let C=this.match(136);this.parseClassElementName(o),this.pushClassAccessorProperty(t,l,C);}else this.isLineTerminator()?d?this.pushClassPrivateProperty(t,h):this.pushClassProperty(t,o):this.unexpected();}parseClassElementName(t){let{type:e,value:s}=this.state;if((e===130||e===131)&&t.static&&s==="prototype"&&this.raise(p.StaticPrototype,{at:this.state.startLoc}),e===136){s==="constructor"&&this.raise(p.ConstructorClassPrivateField,{at:this.state.startLoc});let i=this.parsePrivateName();return t.key=i,i}return this.parsePropertyName(t)}parseClassStaticBlock(t,e){var s;this.scope.enter(208);let i=this.state.labels;this.state.labels=[],this.prodParam.enter(te);let r=e.body=[];this.parseBlockOrModuleBlockBody(r,void 0,!1,8),this.prodParam.exit(),this.scope.exit(),this.state.labels=i,t.body.push(this.finishNode(e,"StaticBlock")),(s=e.decorators)!=null&&s.length&&this.raise(p.DecoratorStaticBlock,{at:e});}pushClassProperty(t,e){!e.computed&&(e.key.name==="constructor"||e.key.value==="constructor")&&this.raise(p.ConstructorClassField,{at:e.key}),t.body.push(this.parseClassProperty(e));}pushClassPrivateProperty(t,e){let s=this.parseClassPrivateProperty(e);t.body.push(s),this.classScope.declarePrivateName(this.getPrivateNameSV(s.key),0,s.key.loc.start);}pushClassAccessorProperty(t,e,s){if(!s&&!e.computed){let r=e.key;(r.name==="constructor"||r.value==="constructor")&&this.raise(p.ConstructorClassField,{at:r});}let i=this.parseClassAccessorProperty(e);t.body.push(i),s&&this.classScope.declarePrivateName(this.getPrivateNameSV(i.key),0,i.key.loc.start);}pushClassMethod(t,e,s,i,r,n){t.body.push(this.parseMethod(e,s,i,r,n,"ClassMethod",!0));}pushClassPrivateMethod(t,e,s,i){let r=this.parseMethod(e,s,i,!1,!1,"ClassPrivateMethod",!0);t.body.push(r);let n=r.kind==="get"?r.static?6:2:r.kind==="set"?r.static?5:1:0;this.declareClassPrivateMethodInScope(r,n);}declareClassPrivateMethodInScope(t,e){this.classScope.declarePrivateName(this.getPrivateNameSV(t.key),e,t.key.loc.start);}parsePostMemberNameModifiers(t){}parseClassPrivateProperty(t){return this.parseInitializer(t),this.semicolon(),this.finishNode(t,"ClassPrivateProperty")}parseClassProperty(t){return this.parseInitializer(t),this.semicolon(),this.finishNode(t,"ClassProperty")}parseClassAccessorProperty(t){return this.parseInitializer(t),this.semicolon(),this.finishNode(t,"ClassAccessorProperty")}parseInitializer(t){this.scope.enter(80),this.expressionScope.enter(hs()),this.prodParam.enter(te),t.value=this.eat(29)?this.parseMaybeAssignAllowIn():null,this.expressionScope.exit(),this.prodParam.exit(),this.scope.exit();}parseClassId(t,e,s,i=8331){if(S(this.state.type))t.id=this.parseIdentifier(),e&&this.declareNameFromIdentifier(t.id,i);else if(s||!e)t.id=null;else throw this.raise(p.MissingClassName,{at:this.state.startLoc})}parseClassSuper(t){t.superClass=this.eat(81)?this.parseExprSubscripts():null;}parseExport(t,e){let s=this.parseMaybeImportPhase(t,!0),i=this.maybeParseExportDefaultSpecifier(t,s),r=!i||this.eat(12),n=r&&this.eatExportStar(t),o=n&&this.maybeParseExportNamespaceSpecifier(t),h=r&&(!o||this.eat(12)),l=i||n;if(n&&!o){if(i&&this.unexpected(),e)throw this.raise(p.UnsupportedDecoratorExport,{at:t});return this.parseExportFrom(t,!0),this.finishNode(t,"ExportAllDeclaration")}let c=this.maybeParseExportNamedSpecifiers(t);i&&r&&!n&&!c&&this.unexpected(null,5),o&&h&&this.unexpected(null,97);let u;if(l||c){if(u=!1,e)throw this.raise(p.UnsupportedDecoratorExport,{at:t});this.parseExportFrom(t,l);}else u=this.maybeParseExportDeclaration(t);if(l||c||u){var f;let d=t;if(this.checkExport(d,!0,!1,!!d.source),((f=d.declaration)==null?void 0:f.type)==="ClassDeclaration")this.maybeTakeDecorators(e,d.declaration,d);else if(e)throw this.raise(p.UnsupportedDecoratorExport,{at:t});return this.finishNode(d,"ExportNamedDeclaration")}if(this.eat(65)){let d=t,x=this.parseExportDefaultExpression();if(d.declaration=x,x.type==="ClassDeclaration")this.maybeTakeDecorators(e,x,d);else if(e)throw this.raise(p.UnsupportedDecoratorExport,{at:t});return this.checkExport(d,!0,!0),this.finishNode(d,"ExportDefaultDeclaration")}this.unexpected(null,5);}eatExportStar(t){return this.eat(55)}maybeParseExportDefaultSpecifier(t,e){if(e||this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom",e==null?void 0:e.loc.start);let s=e||this.parseIdentifier(!0),i=this.startNodeAtNode(s);return i.exported=s,t.specifiers=[this.finishNode(i,"ExportDefaultSpecifier")],!0}return !1}maybeParseExportNamespaceSpecifier(t){if(this.isContextual(93)){t.specifiers||(t.specifiers=[]);let e=this.startNodeAt(this.state.lastTokStartLoc);return this.next(),e.exported=this.parseModuleExportName(),t.specifiers.push(this.finishNode(e,"ExportNamespaceSpecifier")),!0}return !1}maybeParseExportNamedSpecifiers(t){if(this.match(5)){t.specifiers||(t.specifiers=[]);let e=t.exportKind==="type";return t.specifiers.push(...this.parseExportSpecifiers(e)),t.source=null,t.declaration=null,this.hasPlugin("importAssertions")&&(t.assertions=[]),!0}return !1}maybeParseExportDeclaration(t){return this.shouldParseExportDeclaration()?(t.specifiers=[],t.source=null,this.hasPlugin("importAssertions")&&(t.assertions=[]),t.declaration=this.parseExportDeclaration(t),!0):!1}isAsyncFunction(){if(!this.isContextual(95))return !1;let t=this.nextTokenInLineStart();return this.isUnparsedContextual(t,"function")}parseExportDefaultExpression(){let t=this.startNode();if(this.match(68))return this.next(),this.parseFunction(t,5);if(this.isAsyncFunction())return this.next(),this.next(),this.parseFunction(t,13);if(this.match(80))return this.parseClass(t,!0,!0);if(this.match(26))return this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")===!0&&this.raise(p.DecoratorBeforeExport,{at:this.state.startLoc}),this.parseClass(this.maybeTakeDecorators(this.parseDecorators(!1),this.startNode()),!0,!0);if(this.match(75)||this.match(74)||this.isLet())throw this.raise(p.UnsupportedDefaultExport,{at:this.state.startLoc});let e=this.parseMaybeAssignAllowIn();return this.semicolon(),e}parseExportDeclaration(t){return this.match(80)?this.parseClass(this.startNode(),!0,!1):this.parseStatementListItem()}isExportDefaultSpecifier(){let{type:t}=this.state;if(S(t)){if(t===95&&!this.state.containsEsc||t===99)return !1;if((t===128||t===127)&&!this.state.containsEsc){let{type:i}=this.lookahead();if(S(i)&&i!==97||i===5)return this.expectOnePlugin(["flow","typescript"]),!1}}else if(!this.match(65))return !1;let e=this.nextTokenStart(),s=this.isUnparsedContextual(e,"from");if(this.input.charCodeAt(e)===44||S(this.state.type)&&s)return !0;if(this.match(65)&&s){let i=this.input.charCodeAt(this.nextTokenStartSince(e+4));return i===34||i===39}return !1}parseExportFrom(t,e){this.eatContextual(97)?(t.source=this.parseImportSource(),this.checkExport(t),this.maybeParseImportAttributes(t),this.checkJSONModuleImport(t)):e&&this.unexpected(),this.semicolon();}shouldParseExportDeclaration(){let{type:t}=this.state;return t===26&&(this.expectOnePlugin(["decorators","decorators-legacy"]),this.hasPlugin("decorators"))?(this.getPluginOption("decorators","decoratorsBeforeExport")===!0&&this.raise(p.DecoratorBeforeExport,{at:this.state.startLoc}),!0):t===74||t===75||t===68||t===80||this.isLet()||this.isAsyncFunction()}checkExport(t,e,s,i){if(e){var r;if(s){if(this.checkDuplicateExports(t,"default"),this.hasPlugin("exportDefaultFrom")){var n;let o=t.declaration;o.type==="Identifier"&&o.name==="from"&&o.end-o.start===4&&!((n=o.extra)!=null&&n.parenthesized)&&this.raise(p.ExportDefaultFromAsIdentifier,{at:o});}}else if((r=t.specifiers)!=null&&r.length)for(let o of t.specifiers){let{exported:h}=o,l=h.type==="Identifier"?h.name:h.value;if(this.checkDuplicateExports(o,l),!i&&o.local){let{local:c}=o;c.type!=="Identifier"?this.raise(p.ExportBindingIsString,{at:o,localName:c.value,exportName:l}):(this.checkReservedWord(c.name,c.loc.start,!0,!1),this.scope.checkLocalExport(c));}}else if(t.declaration){if(t.declaration.type==="FunctionDeclaration"||t.declaration.type==="ClassDeclaration"){let o=t.declaration.id;if(!o)throw new Error("Assertion failure");this.checkDuplicateExports(t,o.name);}else if(t.declaration.type==="VariableDeclaration")for(let o of t.declaration.declarations)this.checkDeclaration(o.id);}}}checkDeclaration(t){if(t.type==="Identifier")this.checkDuplicateExports(t,t.name);else if(t.type==="ObjectPattern")for(let e of t.properties)this.checkDeclaration(e);else if(t.type==="ArrayPattern")for(let e of t.elements)e&&this.checkDeclaration(e);else t.type==="ObjectProperty"?this.checkDeclaration(t.value):t.type==="RestElement"?this.checkDeclaration(t.argument):t.type==="AssignmentPattern"&&this.checkDeclaration(t.left);}checkDuplicateExports(t,e){this.exportedIdentifiers.has(e)&&(e==="default"?this.raise(p.DuplicateDefaultExport,{at:t}):this.raise(p.DuplicateExport,{at:t,exportName:e})),this.exportedIdentifiers.add(e);}parseExportSpecifiers(t){let e=[],s=!0;for(this.expect(5);!this.eat(8);){if(s)s=!1;else if(this.expect(12),this.eat(8))break;let i=this.isContextual(128),r=this.match(131),n=this.startNode();n.local=this.parseModuleExportName(),e.push(this.parseExportSpecifier(n,r,t,i));}return e}parseExportSpecifier(t,e,s,i){return this.eatContextual(93)?t.exported=this.parseModuleExportName():e?t.exported=Gi(t.local):t.exported||(t.exported=V(t.local)),this.finishNode(t,"ExportSpecifier")}parseModuleExportName(){if(this.match(131)){let t=this.parseStringLiteral(this.state.value),e=t.value.match(gr);return e&&this.raise(p.ModuleExportNameHasLoneSurrogate,{at:t,surrogateCharCode:e[0].charCodeAt(0)}),t}return this.parseIdentifier(!0)}isJSONModuleImport(t){return t.assertions!=null?t.assertions.some(({key:e,value:s})=>s.value==="json"&&(e.type==="Identifier"?e.name==="type":e.value==="type")):!1}checkImportReflection(t){if(t.module){var e;(t.specifiers.length!==1||t.specifiers[0].type!=="ImportDefaultSpecifier")&&this.raise(p.ImportReflectionNotBinding,{at:t.specifiers[0].loc.start}),((e=t.assertions)==null?void 0:e.length)>0&&this.raise(p.ImportReflectionHasAssertion,{at:t.specifiers[0].loc.start});}}checkJSONModuleImport(t){if(this.isJSONModuleImport(t)&&t.type!=="ExportAllDeclaration"){let{specifiers:e}=t;if(e!=null){let s=e.find(i=>{let r;if(i.type==="ExportSpecifier"?r=i.local:i.type==="ImportSpecifier"&&(r=i.imported),r!==void 0)return r.type==="Identifier"?r.name!=="default":r.value!=="default"});s!==void 0&&this.raise(p.ImportJSONBindingNotDefault,{at:s.loc.start});}}}isPotentialImportPhase(t){return !t&&this.isContextual(125)}applyImportPhase(t,e,s,i){e||(s==="module"?(this.expectPlugin("importReflection",i),t.module=!0):this.hasPlugin("importReflection")&&(t.module=!1));}parseMaybeImportPhase(t,e){if(!this.isPotentialImportPhase(e))return this.applyImportPhase(t,e,null),null;let s=this.parseIdentifier(!0),{type:i}=this.state;return (M(i)?i!==97||this.lookaheadCharCode()===102:i!==12)?(this.resetPreviousIdentifierLeadingComments(s),this.applyImportPhase(t,e,s.name,s.loc.start),null):(this.applyImportPhase(t,e,null),s)}isPrecedingIdImportPhase(t){let{type:e}=this.state;return S(e)?e!==97||this.lookaheadCharCode()===102:e!==12}parseImport(t){return this.match(131)?this.parseImportSourceAndAttributes(t):this.parseImportSpecifiersAndAfter(t,this.parseMaybeImportPhase(t,!1))}parseImportSpecifiersAndAfter(t,e){t.specifiers=[];let i=!this.maybeParseDefaultImportSpecifier(t,e)||this.eat(12),r=i&&this.maybeParseStarImportSpecifier(t);return i&&!r&&this.parseNamedImportSpecifiers(t),this.expectContextual(97),this.parseImportSourceAndAttributes(t)}parseImportSourceAndAttributes(t){return (t.specifiers)!=null||(t.specifiers=[]),t.source=this.parseImportSource(),this.maybeParseImportAttributes(t),this.checkImportReflection(t),this.checkJSONModuleImport(t),this.semicolon(),this.finishNode(t,"ImportDeclaration")}parseImportSource(){return this.match(131)||this.unexpected(),this.parseExprAtom()}parseImportSpecifierLocal(t,e,s){e.local=this.parseIdentifier(),t.specifiers.push(this.finishImportSpecifier(e,s));}finishImportSpecifier(t,e,s=8201){return this.checkLVal(t.local,{in:{type:e},binding:s}),this.finishNode(t,e)}parseImportAttributes(){this.expect(5);let t=[],e=new Set;do{if(this.match(8))break;let s=this.startNode(),i=this.state.value;if(e.has(i)&&this.raise(p.ModuleAttributesWithDuplicateKeys,{at:this.state.startLoc,key:i}),e.add(i),this.match(131)?s.key=this.parseStringLiteral(i):s.key=this.parseIdentifier(!0),this.expect(14),!this.match(131))throw this.raise(p.ModuleAttributeInvalidValue,{at:this.state.startLoc});s.value=this.parseStringLiteral(this.state.value),t.push(this.finishNode(s,"ImportAttribute"));}while(this.eat(12));return this.expect(8),t}parseModuleAttributes(){let t=[],e=new Set;do{let s=this.startNode();if(s.key=this.parseIdentifier(!0),s.key.name!=="type"&&this.raise(p.ModuleAttributeDifferentFromType,{at:s.key}),e.has(s.key.name)&&this.raise(p.ModuleAttributesWithDuplicateKeys,{at:s.key,key:s.key.name}),e.add(s.key.name),this.expect(14),!this.match(131))throw this.raise(p.ModuleAttributeInvalidValue,{at:this.state.startLoc});s.value=this.parseStringLiteral(this.state.value),t.push(this.finishNode(s,"ImportAttribute"));}while(this.eat(12));return t}maybeParseImportAttributes(t){let e,s=!1;if(this.match(76)){if(this.hasPrecedingLineBreak()&&this.lookaheadCharCode()===40)return;this.next(),this.hasPlugin("moduleAttributes")?e=this.parseModuleAttributes():(this.expectImportAttributesPlugin(),e=this.parseImportAttributes()),s=!0;}else if(this.isContextual(94)&&!this.hasPrecedingLineBreak())this.hasPlugin("importAttributes")?(this.getPluginOption("importAttributes","deprecatedAssertSyntax")!==!0&&this.raise(p.ImportAttributesUseAssert,{at:this.state.startLoc}),this.addExtra(t,"deprecatedAssertSyntax",!0)):this.expectOnePlugin(["importAttributes","importAssertions"]),this.next(),e=this.parseImportAttributes();else if(this.hasPlugin("importAttributes")||this.hasPlugin("importAssertions"))e=[];else if(this.hasPlugin("moduleAttributes"))e=[];else return;!s&&this.hasPlugin("importAssertions")?t.assertions=e:t.attributes=e;}maybeParseDefaultImportSpecifier(t,e){if(e){let s=this.startNodeAtNode(e);return s.local=e,t.specifiers.push(this.finishImportSpecifier(s,"ImportDefaultSpecifier")),!0}else if(M(this.state.type))return this.parseImportSpecifierLocal(t,this.startNode(),"ImportDefaultSpecifier"),!0;return !1}maybeParseStarImportSpecifier(t){if(this.match(55)){let e=this.startNode();return this.next(),this.expectContextual(93),this.parseImportSpecifierLocal(t,e,"ImportNamespaceSpecifier"),!0}return !1}parseNamedImportSpecifiers(t){let e=!0;for(this.expect(5);!this.eat(8);){if(e)e=!1;else {if(this.eat(14))throw this.raise(p.DestructureNamedImport,{at:this.state.startLoc});if(this.expect(12),this.eat(8))break}let s=this.startNode(),i=this.match(131),r=this.isContextual(128);s.imported=this.parseModuleExportName();let n=this.parseImportSpecifier(s,i,t.importKind==="type"||t.importKind==="typeof",r,void 0);t.specifiers.push(n);}}parseImportSpecifier(t,e,s,i,r){if(this.eatContextual(93))t.local=this.parseIdentifier();else {let{imported:n}=t;if(e)throw this.raise(p.ImportBindingIsString,{at:t,importName:n.value});this.checkReservedWord(n.name,t.loc.start,!0,!0),t.local||(t.local=V(n));}return this.finishImportSpecifier(t,"ImportSpecifier",r)}isThisParam(t){return t.type==="Identifier"&&t.name==="this"}},Fe=class extends Pt{constructor(t,e){t=xr(t),super(t,e),this.options=t,this.initializeScopes(),this.plugins=br(this.options.plugins),this.filename=t.sourceFilename;}getScopeHandler(){return ge}parse(){this.enterInitialScopes();let t=this.startNode(),e=this.startNode();return this.nextToken(),t.errors=null,this.parseTopLevel(t,e),t.errors=this.state.errors,t}};function br(a){let t=new Map;for(let e of a){let[s,i]=Array.isArray(e)?e:[e,{}];t.has(s)||t.set(s,i||{});}return t}function Ar(a,t){var e;if(((e=t)==null?void 0:e.sourceType)==="unambiguous"){t=Object.assign({},t);try{t.sourceType="module";let s=me(t,a),i=s.parse();if(s.sawUnambiguousESM)return i;if(s.ambiguousScriptDifferentAst)try{return t.sourceType="script",me(t,a).parse()}catch{}else i.program.sourceType="script";return i}catch(s){try{return t.sourceType="script",me(t,a).parse()}catch{}throw s}}else return me(t,a).parse()}function Sr(a,t){let e=me(t,a);return e.options.strictMode&&(e.state.strict=!0),e.getExpression()}function wr(a){let t={};for(let e of Object.keys(a))t[e]=_(a[e]);return t}var Cr=wr(xi);function me(a,t){let e=Fe;return a!=null&&a.plugins&&(mr(a.plugins),e=Er(a.plugins)),new e(a,t)}var Gt={};function Er(a){let t=yr.filter(i=>k(a,i)),e=t.join("/"),s=Gt[e];if(!s){s=Fe;for(let i of t)s=fs[i](s);Gt[e]=s;}return s}Re.parse=Ar;Re.parseExpression=Sr;Re.tokTypes=Cr;});var Ns=Bt(G=>{Object.defineProperty(G,"__esModule",{value:!0});G.extract=_r;G.parse=jr;G.parseWithComments=Is;G.print=$r;G.strip=Ur;var Mr=/\*\/$/,Or=/^\/\*\*?/,Cs=/^\s*(\/\*\*?(.|\r?\n)*?\*\/)/,Fr=/(^|\s+)\/\/([^\r\n]*)/g,As=/^(\r?\n)+/,Br=/(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g,Ss=/(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g,Rr=/(\r?\n|^) *\* ?/g,Es=[];function _r(a){let t=a.match(Cs);return t?t[0].trimLeft():""}function Ur(a){let t=a.match(Cs);return t&&t[0]?a.substring(t[0].length):a}function jr(a){return Is(a).pragmas}function Is(a){let t=` -`;a=a.replace(Or,"").replace(Mr,"").replace(Rr,"$1");let e="";for(;e!==a;)e=a,a=a.replace(Br,`${t}$1 $2${t}`);a=a.replace(As,"").trimRight();let s=Object.create(null),i=a.replace(Ss,"").replace(As,"").trimRight(),r;for(;r=Ss.exec(a);){let n=r[2].replace(Fr,"");typeof s[r[1]]=="string"||Array.isArray(s[r[1]])?s[r[1]]=Es.concat(s[r[1]],n):s[r[1]]=n;}return {comments:i,pragmas:s}}function $r({comments:a="",pragmas:t={}}){let e=` -`,s="/**",i=" *",r=" */",n=Object.keys(t),o=n.map(l=>ws(l,t[l])).reduce((l,c)=>l.concat(c),[]).map(l=>`${i} ${l}${e}`).join("");if(!a){if(n.length===0)return "";if(n.length===1&&!Array.isArray(t[n[0]])){let l=t[n[0]];return `${s} ${ws(n[0],l)[0]}${r}`}}let h=a.split(e).map(l=>`${i} ${l}`).join(e)+e;return s+e+(a?h:"")+(a&&n.length?i+e:"")+o+r}function ws(a,t){return Es.concat(t).map(e=>`@${a} ${e}`.trim())}});var Ft={};si(Ft,{parsers:()=>da});var ze=qe(kt(),1);function Ir(a){let t=[];for(let e of a)try{return e()}catch(s){t.push(s);}throw Object.assign(new Error("All combinations failed"),{errors:t})}var ms=Ir;function Nr(a){if(!a.startsWith("#!"))return "";let t=a.indexOf(` -`);return t===-1?a:a.slice(0,t)}var _e=Nr;function kr(a,t){if(t===!1)return !1;if(a.charAt(t)==="/"&&a.charAt(t+1)==="*"){for(let e=t+2;e{let i=!!(s!=null&&s.backwards);if(e===!1)return !1;let{length:r}=t,n=e;for(;n>=0&&n0}var Y=zr;function D(a){var s;let t=a.range?a.range[0]:a.start,e=((s=a.declaration)==null?void 0:s.decorators)??a.decorators;return Y(e)?Math.min(D(e[0]),t):t}function B(a){return a.range?a.range[1]:a.end}function Kr(a){return a=typeof a=="function"?{parse:a}:a,{astFormat:"estree",hasPragma:ks,locStart:D,locEnd:B,...a}}var oe=Kr;function qr(a,t){let e=new SyntaxError(a+" ("+t.loc.start.line+":"+t.loc.start.column+")");return Object.assign(e,t)}var je=qr;function Hr(a){let{message:t,loc:e}=a;return je(t.replace(/ \(.*\)$/,""),{loc:{start:{line:e?e.line:0,column:e?e.column+1:0}},cause:a})}var be=Hr;var Wr=(a,t,e)=>{if(!(a&&t==null))return Array.isArray(t)||typeof t=="string"?t[e<0?t.length+e:e]:t.at(e)},vt=Wr;function Jr(a){return a=new Set(a),t=>a.has(t==null?void 0:t.type)}var vs=Jr;var Xr=vs(["Block","CommentBlock","MultiLine"]),Ae=Xr;function Gr(a){return Ae(a)&&a.value[0]==="*"&&/@(?:type|satisfies)\b/.test(a.value)}var Ls=Gr;function Yr(a){let t=`*${a.value}*`.split(` -`);return t.length>1&&t.every(e=>e.trimStart()[0]==="*")}var Lt=Yr;var Se=null;function we(a){if(Se!==null&&typeof Se.property){let t=Se;return Se=we.prototype=null,t}return Se=we.prototype=a??Object.create(null),new we}var Qr=10;for(let a=0;a<=Qr;a++)we();function Dt(a){return we(a)}function Zr(a,t="type"){Dt(a);function e(s){let i=s[t],r=a[i];if(!Array.isArray(r))throw Object.assign(new Error(`Missing visitor keys for '${i}'.`),{node:s});return r}return e}var Ds=Zr;var Ms={ArrayExpression:["elements"],AssignmentExpression:["left","right"],BinaryExpression:["left","right"],InterpreterDirective:[],Directive:["value"],DirectiveLiteral:[],BlockStatement:["directives","body"],BreakStatement:["label"],CallExpression:["callee","arguments","typeParameters","typeArguments"],CatchClause:["param","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DoWhileStatement:["test","body"],EmptyStatement:[],ExpressionStatement:["expression"],File:["program"],ForInStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","body","returnType","typeParameters","predicate"],FunctionExpression:["id","params","body","returnType","typeParameters"],Identifier:["typeAnnotation","decorators"],IfStatement:["test","consequent","alternate"],LabeledStatement:["label","body"],StringLiteral:[],NumericLiteral:[],NullLiteral:[],BooleanLiteral:[],RegExpLiteral:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],NewExpression:["callee","arguments","typeParameters","typeArguments"],Program:["directives","body"],ObjectExpression:["properties"],ObjectMethod:["key","params","body","decorators","returnType","typeParameters"],ObjectProperty:["key","value","decorators"],RestElement:["argument","typeAnnotation","decorators"],ReturnStatement:["argument"],SequenceExpression:["expressions"],ParenthesizedExpression:["expression"],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handler","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],AssignmentPattern:["left","right","decorators","typeAnnotation"],ArrayPattern:["elements","typeAnnotation","decorators"],ArrowFunctionExpression:["params","body","returnType","typeParameters","predicate"],ClassBody:["body"],ClassExpression:["id","body","superClass","mixins","typeParameters","superTypeParameters","implements","decorators","superTypeArguments"],ClassDeclaration:["id","body","superClass","mixins","typeParameters","superTypeParameters","implements","decorators","superTypeArguments"],ExportAllDeclaration:["source","attributes","assertions","exported"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:["declaration","specifiers","source","attributes","assertions"],ExportSpecifier:["local","exported"],ForOfStatement:["left","right","body"],ImportDeclaration:["specifiers","source","attributes","assertions"],ImportDefaultSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportSpecifier:["local","imported"],MetaProperty:["meta","property"],ClassMethod:["key","params","body","decorators","returnType","typeParameters"],ObjectPattern:["properties","typeAnnotation","decorators"],SpreadElement:["argument"],Super:[],TaggedTemplateExpression:["tag","quasi","typeParameters","typeArguments"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],YieldExpression:["argument"],AwaitExpression:["argument"],Import:[],BigIntLiteral:[],ExportNamespaceSpecifier:["exported"],OptionalMemberExpression:["object","property"],OptionalCallExpression:["callee","arguments","typeParameters","typeArguments"],ClassProperty:["key","value","typeAnnotation","decorators","variance"],ClassAccessorProperty:["key","value","typeAnnotation","decorators"],ClassPrivateProperty:["key","value","decorators","typeAnnotation","variance"],ClassPrivateMethod:["key","params","body","decorators","returnType","typeParameters"],PrivateName:["id"],StaticBlock:["body"],AnyTypeAnnotation:[],ArrayTypeAnnotation:["elementType"],BooleanTypeAnnotation:[],BooleanLiteralTypeAnnotation:[],NullLiteralTypeAnnotation:[],ClassImplements:["id","typeParameters"],DeclareClass:["id","typeParameters","extends","mixins","implements","body"],DeclareFunction:["id","predicate"],DeclareInterface:["id","typeParameters","extends","body"],DeclareModule:["id","body"],DeclareModuleExports:["typeAnnotation"],DeclareTypeAlias:["id","typeParameters","right"],DeclareOpaqueType:["id","typeParameters","supertype"],DeclareVariable:["id"],DeclareExportDeclaration:["declaration","specifiers","source"],DeclareExportAllDeclaration:["source"],DeclaredPredicate:["value"],ExistsTypeAnnotation:[],FunctionTypeAnnotation:["typeParameters","params","rest","returnType","this"],FunctionTypeParam:["name","typeAnnotation"],GenericTypeAnnotation:["id","typeParameters"],InferredPredicate:[],InterfaceExtends:["id","typeParameters"],InterfaceDeclaration:["id","typeParameters","extends","body"],InterfaceTypeAnnotation:["extends","body"],IntersectionTypeAnnotation:["types"],MixedTypeAnnotation:[],EmptyTypeAnnotation:[],NullableTypeAnnotation:["typeAnnotation"],NumberLiteralTypeAnnotation:[],NumberTypeAnnotation:[],ObjectTypeAnnotation:["properties","indexers","callProperties","internalSlots"],ObjectTypeInternalSlot:["id","value","optional","static","method"],ObjectTypeCallProperty:["value"],ObjectTypeIndexer:["id","key","value","variance"],ObjectTypeProperty:["key","value","variance"],ObjectTypeSpreadProperty:["argument"],OpaqueType:["id","typeParameters","supertype","impltype"],QualifiedTypeIdentifier:["id","qualification"],StringLiteralTypeAnnotation:[],StringTypeAnnotation:[],SymbolTypeAnnotation:[],ThisTypeAnnotation:[],TupleTypeAnnotation:["types","elementTypes"],TypeofTypeAnnotation:["argument"],TypeAlias:["id","typeParameters","right"],TypeAnnotation:["typeAnnotation"],TypeCastExpression:["expression","typeAnnotation"],TypeParameter:["bound","default","variance"],TypeParameterDeclaration:["params"],TypeParameterInstantiation:["params"],UnionTypeAnnotation:["types"],Variance:[],VoidTypeAnnotation:[],EnumDeclaration:["id","body"],EnumBooleanBody:["members"],EnumNumberBody:["members"],EnumStringBody:["members"],EnumSymbolBody:["members"],EnumBooleanMember:["id","init"],EnumNumberMember:["id","init"],EnumStringMember:["id","init"],EnumDefaultedMember:["id"],IndexedAccessType:["objectType","indexType"],OptionalIndexedAccessType:["objectType","indexType"],JSXAttribute:["name","value"],JSXClosingElement:["name"],JSXElement:["openingElement","children","closingElement"],JSXEmptyExpression:[],JSXExpressionContainer:["expression"],JSXSpreadChild:["expression"],JSXIdentifier:[],JSXMemberExpression:["object","property"],JSXNamespacedName:["namespace","name"],JSXOpeningElement:["name","attributes","typeArguments","typeParameters"],JSXSpreadAttribute:["argument"],JSXText:[],JSXFragment:["openingFragment","children","closingFragment"],JSXOpeningFragment:[],JSXClosingFragment:[],Noop:[],Placeholder:[],V8IntrinsicIdentifier:[],ArgumentPlaceholder:[],BindExpression:["object","callee"],ImportAttribute:["key","value"],Decorator:["expression"],DoExpression:["body"],ExportDefaultSpecifier:["exported"],RecordExpression:["properties"],TupleExpression:["elements"],DecimalLiteral:[],ModuleExpression:["body"],TopicReference:[],PipelineTopicExpression:["expression"],PipelineBareFunction:["callee"],PipelinePrimaryTopicReference:[],TSParameterProperty:["parameter","decorators"],TSDeclareFunction:["id","typeParameters","params","returnType","body"],TSDeclareMethod:["decorators","key","typeParameters","params","returnType"],TSQualifiedName:["left","right"],TSCallSignatureDeclaration:["typeParameters","parameters","typeAnnotation","params","returnType"],TSConstructSignatureDeclaration:["typeParameters","parameters","typeAnnotation","params","returnType"],TSPropertySignature:["key","typeAnnotation"],TSMethodSignature:["key","typeParameters","parameters","typeAnnotation","params","returnType"],TSIndexSignature:["parameters","typeAnnotation"],TSAnyKeyword:[],TSBooleanKeyword:[],TSBigIntKeyword:[],TSIntrinsicKeyword:[],TSNeverKeyword:[],TSNullKeyword:[],TSNumberKeyword:[],TSObjectKeyword:[],TSStringKeyword:[],TSSymbolKeyword:[],TSUndefinedKeyword:[],TSUnknownKeyword:[],TSVoidKeyword:[],TSThisType:[],TSFunctionType:["typeParameters","parameters","typeAnnotation","params","returnType"],TSConstructorType:["typeParameters","parameters","typeAnnotation","params","returnType"],TSTypeReference:["typeName","typeParameters","typeArguments"],TSTypePredicate:["parameterName","typeAnnotation"],TSTypeQuery:["exprName","typeParameters","typeArguments"],TSTypeLiteral:["members"],TSArrayType:["elementType"],TSTupleType:["elementTypes"],TSOptionalType:["typeAnnotation"],TSRestType:["typeAnnotation"],TSNamedTupleMember:["label","elementType"],TSUnionType:["types"],TSIntersectionType:["types"],TSConditionalType:["checkType","extendsType","trueType","falseType"],TSInferType:["typeParameter"],TSParenthesizedType:["typeAnnotation"],TSTypeOperator:["typeAnnotation"],TSIndexedAccessType:["objectType","indexType"],TSMappedType:["typeParameter","typeAnnotation","nameType"],TSLiteralType:["literal"],TSExpressionWithTypeArguments:["expression","typeParameters"],TSInterfaceDeclaration:["id","typeParameters","extends","body"],TSInterfaceBody:["body"],TSTypeAliasDeclaration:["id","typeParameters","typeAnnotation"],TSInstantiationExpression:["expression","typeParameters","typeArguments"],TSAsExpression:["expression","typeAnnotation"],TSSatisfiesExpression:["expression","typeAnnotation"],TSTypeAssertion:["typeAnnotation","expression"],TSEnumDeclaration:["id","members"],TSEnumMember:["id","initializer"],TSModuleDeclaration:["id","body"],TSModuleBlock:["body"],TSImportType:["argument","qualifier","typeParameters","typeArguments"],TSImportEqualsDeclaration:["id","moduleReference"],TSExternalModuleReference:["expression"],TSNonNullExpression:["expression"],TSExportAssignment:["expression"],TSNamespaceExportDeclaration:["id"],TSTypeAnnotation:["typeAnnotation"],TSTypeParameterInstantiation:["params"],TSTypeParameterDeclaration:["params"],TSTypeParameter:["constraint","default","name"],ChainExpression:["expression"],ExperimentalRestProperty:["argument"],ExperimentalSpreadProperty:["argument"],ImportExpression:["source","attributes"],Literal:[],MethodDefinition:["decorators","key","value"],PrivateIdentifier:[],Property:["key","value"],PropertyDefinition:["decorators","key","typeAnnotation","value","variance"],AccessorProperty:["decorators","key","typeAnnotation","value"],TSAbstractAccessorProperty:["decorators","key","typeAnnotation"],TSAbstractKeyword:[],TSAbstractMethodDefinition:["key","value"],TSAbstractPropertyDefinition:["decorators","key","typeAnnotation"],TSAsyncKeyword:[],TSClassImplements:["expression","typeArguments","typeParameters"],TSDeclareKeyword:[],TSEmptyBodyFunctionExpression:["id","typeParameters","params","returnType"],TSExportKeyword:[],TSInterfaceHeritage:["expression","typeArguments","typeParameters"],TSPrivateKeyword:[],TSProtectedKeyword:[],TSPublicKeyword:[],TSReadonlyKeyword:[],TSStaticKeyword:[],TSTemplateLiteralType:["quasis","types"],BigIntLiteralTypeAnnotation:[],BigIntTypeAnnotation:[],ConditionalTypeAnnotation:["checkType","extendsType","trueType","falseType"],DeclareEnum:["id","body"],InferTypeAnnotation:["typeParameter"],KeyofTypeAnnotation:["argument"],ObjectTypeMappedTypeProperty:["keyTparam","propType","sourceType","variance"],QualifiedTypeofIdentifier:["qualification","id"],TupleTypeLabeledElement:["label","elementType","variance"],TupleTypeSpreadElement:["label","typeAnnotation"],TypePredicate:["parameterName","typeAnnotation","asserts"],NGRoot:["node"],NGPipeExpression:["left","right","arguments"],NGChainedExpression:["expressions"],NGEmptyExpression:[],NGMicrosyntax:["body"],NGMicrosyntaxKey:[],NGMicrosyntaxExpression:["expression","alias"],NGMicrosyntaxKeyedExpression:["key","expression"],NGMicrosyntaxLet:["key","value"],NGMicrosyntaxAs:["key","alias"],JsExpressionRoot:["node"],JsonRoot:["node"],TSJSDocAllType:[],TSJSDocUnknownType:[],TSJSDocNullableType:["typeAnnotation"],TSJSDocNonNullableType:["typeAnnotation"],NeverTypeAnnotation:[],UndefinedTypeAnnotation:[],UnknownTypeAnnotation:[]};var ea=Ds(Ms),Os=ea;function Mt(a,t){if(!(a!==null&&typeof a=="object"))return a;if(Array.isArray(a)){for(let s=0;s{var o;(o=n.leadingComments)!=null&&o.some(Ls)&&r.add(D(n));}),a=$e(a,n=>{if(n.type==="ParenthesizedExpression"){let{expression:o}=n;if(o.type==="TypeCastExpression")return o.range=n.range,o;let h=D(n);if(!r.has(h))return o.extra={...o.extra,parenthesized:!0},o}});}if(a=$e(a,r=>{switch(r.type){case"LogicalExpression":if(Fs(r))return Ot(r);break;case"VariableDeclaration":{let n=vt(!1,r.declarations,-1);n!=null&&n.init&&i(r,n);break}case"TSParenthesizedType":return r.typeAnnotation;case"TSTypeParameter":if(typeof r.name=="string"){let n=D(r);r.name={type:"Identifier",name:r.name,range:[n,n+r.name.length]};}break;case"TopicReference":a.extra={...a.extra,__isUsingHackPipeline:!0};break;case"ExportAllDeclaration":{let{exported:n}=r;if(e==="meriyah"&&(n==null?void 0:n.type)==="Identifier"){let o=s.slice(D(n),B(n));(o.startsWith('"')||o.startsWith("'"))&&(r.exported={...r.exported,type:"Literal",value:r.exported.name,raw:o});}break}case"TSUnionType":case"TSIntersectionType":if(r.types.length===1)return r.types[0];break}}),Y(a.comments)){let r=vt(!1,a.comments,-1);for(let n=a.comments.length-2;n>=0;n--){let o=a.comments[n];B(o)===D(r)&&Ae(o)&&Ae(r)&&Lt(o)&&Lt(r)&&(a.comments.splice(n+1,1),o.value+="*//*"+r.value,o.range=[D(o),B(r)]),r=o;}}return a.type==="Program"&&(a.range=[0,s.length]),a;function i(r,n){s[B(n)]!==";"&&(r.range=[D(r),B(n)]);}}function Fs(a){return a.type==="LogicalExpression"&&a.right.type==="LogicalExpression"&&a.operator===a.right.operator}function Ot(a){return Fs(a)?Ot({type:"LogicalExpression",operator:a.operator,left:Ot({type:"LogicalExpression",operator:a.operator,left:a.left,right:a.right.left,range:[D(a.left),B(a.right.left)]}),right:a.right.right,range:[D(a),B(a)]}):a}var Bs=ta;function sa(a){let{filepath:t}=a;if(t){if(t=t.toLowerCase(),t.endsWith(".cjs"))return "script";if(t.endsWith(".mjs"))return "module"}}var Rs=sa;function ia(a,t){let{type:e="JsExpressionRoot",rootMarker:s,text:i}=t,{tokens:r,comments:n}=a;return delete a.tokens,delete a.comments,{tokens:r,comments:n,type:e,node:a,range:[0,i.length],rootMarker:s}}var Ve=ia;var he=a=>oe(la(a)),ra={sourceType:"module",allowImportExportEverywhere:!0,allowReturnOutsideFunction:!0,allowNewTargetOutsideFunction:!0,allowSuperOutsideMethod:!0,allowUndeclaredExports:!0,errorRecovery:!0,createParenthesizedExpressions:!0,plugins:["doExpressions","exportDefaultFrom","functionBind","functionSent","throwExpressions","partialApplication","decorators","decimal","moduleBlocks","asyncDoExpressions","regexpUnicodeSets","destructuringPrivate","decoratorAutoAccessors","importReflection","explicitResourceManagement",["importAttributes",{deprecatedAssertSyntax:!0}]],tokens:!0,ranges:!0},aa=["recordAndTuple",{syntaxType:"hash"}],_s="v8intrinsic",Us=[["pipelineOperator",{proposal:"hack",topicToken:"%"}],["pipelineOperator",{proposal:"minimal"}],["pipelineOperator",{proposal:"fsharp"}]],R=(a,t=ra)=>({...t,plugins:[...t.plugins,...a]}),na=/@(?:no)?flow\b/;function oa(a,t){var i;if((i=t.filepath)!=null&&i.endsWith(".js.flow"))return !0;let e=_e(a);e&&(a=a.slice(e.length));let s=bs(a,0);return s!==!1&&(a=a.slice(0,s)),na.test(a)}function ha(a,t,e){let s=a(t,e),i=s.errors.find(r=>!ca.has(r.reasonCode));if(i)throw i;return s}function la({isExpression:a=!1,optionsCombinations:t}){return (e,s={})=>{if((s.parser==="babel"||s.parser==="__babel_estree")&&oa(e,s))return s.parser="babel-flow",qs.parse(e,s);let i=t;(s.__babelSourceType??Rs(s))==="script"&&(i=i.map(l=>({...l,sourceType:"script"}))),/#[[{]/.test(e)&&(i=i.map(l=>R([aa],l)));let n=/%[A-Z]/.test(e);e.includes("|>")?i=(n?[...Us,_s]:Us).flatMap(c=>i.map(u=>R([c],u))):n&&(i=i.map(l=>R([_s],l)));let o=a?ze.parseExpression:ze.parse,h;try{h=ms(i.map(l=>()=>ha(o,e,l)));}catch({errors:[l]}){throw be(l)}return a&&(h=Ve(h,{text:e,rootMarker:s.rootMarker})),Bs(h,{parser:"babel",text:e})}}var ca=new Set(["StrictNumericEscape","StrictWith","StrictOctalLiteral","StrictDelete","StrictEvalArguments","StrictEvalArgumentsBinding","StrictFunction","EmptyTypeArguments","EmptyTypeParameters","ConstructorHasTypeParameters","UnsupportedParameterPropertyKind","MixedLabeledAndUnlabeledElements","DuplicateAccessibilityModifier","DecoratorExportClass","ParamDupe","InvalidDecimal","RestTrailingComma","UnsupportedParameterDecorator","UnterminatedJsxContent","UnexpectedReservedWord","ModuleAttributesWithDuplicateKeys","LineTerminatorBeforeArrow","InvalidEscapeSequenceTemplate","NonAbstractClassHasAbstractMethod","OptionalTypeBeforeRequired","PatternIsOptional","OptionalBindingPattern","DeclareClassFieldHasInitializer","TypeImportCannotSpecifyDefaultAndNamed","DeclareFunctionHasImplementation","ConstructorClassField","VarRedeclaration","InvalidPrivateFieldResolution","DuplicateExport"]),Ks=[R(["jsx"])],js=he({optionsCombinations:Ks}),$s=he({optionsCombinations:[R(["jsx","typescript"]),R(["typescript"])]}),Vs=he({isExpression:!0,optionsCombinations:[R(["jsx"])]}),zs=he({isExpression:!0,optionsCombinations:[R(["typescript"])]}),qs=he({optionsCombinations:[R(["jsx",["flow",{all:!0,enums:!0}],"flowComments"])]}),pa=he({optionsCombinations:Ks.map(a=>R(["estree"],a))}),Hs={babel:js,"babel-flow":qs,"babel-ts":$s,__js_expression:Vs,__ts_expression:zs,__vue_expression:Vs,__vue_ts_expression:zs,__vue_event_binding:js,__vue_ts_event_binding:$s,__babel_estree:pa};var Js=qe(kt(),1);function Xs(a={}){let{allowComments:t=!0}=a;return function(s){let i;try{i=(0,Js.parseExpression)(s,{tokens:!0,ranges:!0});}catch(r){throw (r==null?void 0:r.reasonCode)==="MissingPlugin"||(r==null?void 0:r.reasonCode)==="MissingOneOfPlugins"?be({message:"Unexpected token",loc:r.loc}):be(r)}if(!t&&Y(i.comments))throw H(i.comments[0],"Comment");return le(i),Ve(i,{type:"JsonRoot",text:s})}}function H(a,t){let[e,s]=[a.loc.start,a.loc.end].map(({line:i,column:r})=>({line:i,column:r+1}));return je(`${t} is not allowed in JSON.`,{loc:{start:e,end:s}})}function le(a){switch(a.type){case"ArrayExpression":for(let t of a.elements)t!==null&&le(t);return;case"ObjectExpression":for(let t of a.properties)le(t);return;case"ObjectProperty":if(a.computed)throw H(a.key,"Computed key");if(a.shorthand)throw H(a.key,"Shorthand property");a.key.type!=="Identifier"&&le(a.key),le(a.value);return;case"UnaryExpression":{let{operator:t,argument:e}=a;if(t!=="+"&&t!=="-")throw H(a,`Operator '${a.operator}'`);if(e.type==="NumericLiteral"||e.type==="Identifier"&&(e.name==="Infinity"||e.name==="NaN"))return;throw H(e,`Operator '${t}' before '${e.type}'`)}case"Identifier":if(a.name!=="Infinity"&&a.name!=="NaN"&&a.name!=="undefined")throw H(a,`Identifier '${a.name}'`);return;case"TemplateLiteral":if(Y(a.expressions))throw H(a.expressions[0],"'TemplateLiteral' with expression");for(let t of a.quasis)le(t);return;case"NullLiteral":case"BooleanLiteral":case"NumericLiteral":case"StringLiteral":case"TemplateElement":return;default:throw H(a,`'${a.type}'`)}}var Ws=Xs(),ua={json:oe({parse:Ws,hasPragma(){return !0}}),json5:oe(Ws),"json-stringify":oe({parse:Xs({allowComments:!1}),astFormat:"estree-json"})},Gs=ua;var da={...Hs,...Gs};var Kn=Ft; - -export { Kn as default, da as parsers }; diff --git a/src/lib/prettier-estree.js b/src/lib/prettier-estree.js deleted file mode 100644 index ead56e774..000000000 --- a/src/lib/prettier-estree.js +++ /dev/null @@ -1,37 +0,0 @@ -var ua=Object.create;var Tn=Object.defineProperty;var ia=Object.getOwnPropertyDescriptor;var aa=Object.getOwnPropertyNames;var oa=Object.getPrototypeOf,pa=Object.prototype.hasOwnProperty;var ca=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),or=(e,t)=>{for(var r in t)Tn(e,r,{get:t[r],enumerable:!0});},la=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of aa(t))!pa.call(e,s)&&s!==r&&Tn(e,s,{get:()=>t[s],enumerable:!(n=ia(t,s))||n.enumerable});return e};var ma=(e,t,r)=>(r=e!=null?ua(oa(e)):{},la(t||!e||!e.__esModule?Tn(r,"default",{value:e,enumerable:!0}):r,e));var Bs=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var st=(e,t,r)=>(Bs(e,t,"read from private field"),r?r.call(e):t.get(e)),bs=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r);},Ps=(e,t,r,n)=>(Bs(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Hi=ca(ht=>{Object.defineProperty(ht,"__esModule",{value:!0});ht.extract=el;ht.parse=rl;ht.parseWithComments=Vi;ht.print=nl;ht.strip=tl;var Hc=/\*\/$/,Kc=/^\/\*\*?/,Xi=/^\s*(\/\*\*?(.|\r?\n)*?\*\/)/,zc=/(^|\s+)\/\/([^\r\n]*)/g,qi=/^(\r?\n)+/,Qc=/(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g,Wi=/(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g,Zc=/(\r?\n|^) *\* ?/g,$i=[];function el(e){let t=e.match(Xi);return t?t[0].trimLeft():""}function tl(e){let t=e.match(Xi);return t&&t[0]?e.substring(t[0].length):e}function rl(e){return Vi(e).pragmas}function Vi(e){let t=` -`;e=e.replace(Kc,"").replace(Hc,"").replace(Zc,"$1");let r="";for(;r!==e;)r=e,e=e.replace(Qc,`${t}$1 $2${t}`);e=e.replace(qi,"").trimRight();let n=Object.create(null),s=e.replace(Wi,"").replace(qi,"").trimRight(),u;for(;u=Wi.exec(e);){let i=u[2].replace(zc,"");typeof n[u[1]]=="string"||Array.isArray(n[u[1]])?n[u[1]]=$i.concat(n[u[1]],i):n[u[1]]=i;}return {comments:s,pragmas:n}}function nl({comments:e="",pragmas:t={}}){let r=` -`,n="/**",s=" *",u=" */",i=Object.keys(t),a=i.map(p=>Yi(p,t[p])).reduce((p,m)=>p.concat(m),[]).map(p=>`${s} ${p}${r}`).join("");if(!e){if(i.length===0)return "";if(i.length===1&&!Array.isArray(t[i[0]])){let p=t[i[0]];return `${n} ${Yi(i[0],p)[0]}${u}`}}let o=e.split(r).map(p=>`${s} ${p}`).join(r)+r;return n+r+(e?o:"")+(e&&i.length?s+r:"")+a+u}function Yi(e,t){return $i.concat(t).map(r=>`@${e} ${r}`.trim())}});var Ss={};or(Ss,{languages:()=>yl,options:()=>sa,printers:()=>ml});var gs={};or(gs,{canAttachComment:()=>Wo,embed:()=>Ni,experimentalFeatures:()=>il,getCommentChildNodes:()=>Yo,getVisitorKeys:()=>fr,handleComments:()=>Kn,insertPragma:()=>zi,isBlockComment:()=>ae,isGap:()=>Xo,massageAstNode:()=>Gi,print:()=>Ii,printComment:()=>Tu,willPrintOwnComments:()=>zn});function ya(e,t){let{originalText:r,[Symbol.for("comments")]:n,locStart:s,locEnd:u,[Symbol.for("printedComments")]:i}=t,{node:a}=e,o=s(a),p=u(a);for(let m of n)s(m)>=o&&u(m)<=p&&i.add(m);return r.slice(o,p)}var ks=ya;var Ke="string",je="array",ze="cursor",Me="indent",Re="align",Qe="trim",ue="group",ye="fill",Fe="if-break",Je="indent-if-break",Ne="line-suffix",Ue="line-suffix-boundary",ie="line",be="label",Pe="break-parent",pr=new Set([ze,Me,Re,Qe,ue,ye,Fe,Je,Ne,Ue,ie,be,Pe]);function Da(e){if(typeof e=="string")return Ke;if(Array.isArray(e))return je;if(!e)return;let{type:t}=e;if(pr.has(t))return t}var Ze=Da;var fa=e=>new Intl.ListFormat("en-US",{type:"disjunction"}).format(e);function Ea(e){let t=e===null?"null":typeof e;if(t!=="string"&&t!=="object")return `Unexpected doc '${t}', -Expected it to be 'string' or 'object'.`;if(Ze(e))throw new Error("doc is valid.");let r=Object.prototype.toString.call(e);if(r!=="[object Object]")return `Unexpected doc '${r}'.`;let n=fa([...pr].map(s=>`'${s}'`));return `Unexpected doc.type '${e.type}'. -Expected it to be ${n}.`}var xn=class extends Error{name="InvalidDocError";constructor(t){super(Ea(t)),this.doc=t;}},lt=xn;var Is={};function Fa(e,t,r,n){let s=[e];for(;s.length>0;){let u=s.pop();if(u===Is){r(s.pop());continue}r&&s.push(u,Is);let i=Ze(u);if(!i)throw new lt(u);if((t==null?void 0:t(u))!==!1)switch(i){case je:case ye:{let a=i===je?u:u.parts;for(let o=a.length,p=o-1;p>=0;--p)s.push(a[p]);break}case Fe:s.push(u.flatContents,u.breakContents);break;case ue:if(n&&u.expandedStates)for(let a=u.expandedStates.length,o=a-1;o>=0;--o)s.push(u.expandedStates[o]);else s.push(u.contents);break;case Re:case Me:case Je:case be:case Ne:s.push(u.contents);break;case Ke:case ze:case Qe:case Ue:case ie:case Pe:break;default:throw new lt(u)}}}var gn=Fa;var Ls=()=>{},cr=Ls;function E(e){return {type:Me,contents:e}}function De(e,t){return {type:Re,contents:t,n:e}}function y(e,t={}){return cr(t.expandedStates),{type:ue,id:t.id,contents:e,break:!!t.shouldBreak,expandedStates:t.expandedStates}}function ws(e){return De(Number.NEGATIVE_INFINITY,e)}function Os(e){return De(-1,e)}function qe(e,t){return y(e[0],{...t,expandedStates:e})}function St(e){return {type:ye,parts:e}}function P(e,t="",r={}){return {type:Fe,breakContents:e,flatContents:t,groupId:r.groupId}}function mt(e,t){return {type:Je,contents:e,groupId:t.groupId,negate:t.negate}}function hn(e){return {type:Ne,contents:e}}var Ae={type:Ue},Te={type:Pe};var Sn={type:ie,hard:!0},Ca={type:ie,hard:!0,literal:!0},A={type:ie},F={type:ie,soft:!0},C=[Sn,Te],lr=[Ca,Te],Bn={type:ze};function B(e,t){let r=[];for(let n=0;n0){for(let s=0;s{if(!(e&&t==null))return Array.isArray(t)||typeof t=="string"?t[r<0?t.length+r:r]:t.at(r)},w=da;var mr=e=>{if(Array.isArray(e))return e;if(e.type!==ye)throw new Error(`Expect doc to be 'array' or '${ye}'.`);return e.parts};function ut(e,t){if(typeof e=="string")return t(e);let r=new Map;return n(e);function n(u){if(r.has(u))return r.get(u);let i=s(u);return r.set(u,i),i}function s(u){switch(Ze(u)){case je:return t(u.map(n));case ye:return t({...u,parts:u.parts.map(n)});case Fe:return t({...u,breakContents:n(u.breakContents),flatContents:n(u.flatContents)});case ue:{let{expandedStates:i,contents:a}=u;return i?(i=i.map(n),a=i[0]):a=n(a),t({...u,contents:a,expandedStates:i})}case Re:case Me:case Je:case be:case Ne:return t({...u,contents:n(u.contents)});case Ke:case ze:case Qe:case Ue:case ie:case Pe:return t(u);default:throw new lt(u)}}}function js(e,t,r){let n=r,s=!1;function u(i){if(s)return !1;let a=t(i);a!==void 0&&(s=!0,n=a);}return gn(e,u),n}function Aa(e){if(e.type===ue&&e.break||e.type===ie&&e.hard||e.type===Pe)return !0}function K(e){return js(e,Aa,!1)}function _s(e){if(e.length>0){let t=w(!1,e,-1);!t.expandedStates&&!t.break&&(t.break="propagated");}return null}function Ms(e){let t=new Set,r=[];function n(u){if(u.type===Pe&&_s(r),u.type===ue){if(r.push(u),t.has(u))return !1;t.add(u);}}function s(u){u.type===ue&&r.pop().break&&_s(r);}gn(e,n,s,!0);}function Ta(e){return e.type===ie&&!e.hard?e.soft?"":" ":e.type===Fe?e.flatContents:e}function Ut(e){return ut(e,Ta)}function xa(e){switch(Ze(e)){case ye:if(e.parts.every(t=>t===""))return "";break;case ue:if(!e.contents&&!e.id&&!e.break&&!e.expandedStates)return "";if(e.contents.type===ue&&e.contents.id===e.id&&e.contents.break===e.break&&e.contents.expandedStates===e.expandedStates)return e.contents;break;case Re:case Me:case Je:case Ne:if(!e.contents)return "";break;case Fe:if(!e.flatContents&&!e.breakContents)return "";break;case je:{let t=[];for(let r of e){if(!r)continue;let[n,...s]=Array.isArray(r)?r:[r];typeof n=="string"&&typeof w(!1,t,-1)=="string"?t[t.length-1]+=n:t.push(n),t.push(...s);}return t.length===0?"":t.length===1?t[0]:t}case Ke:case ze:case Qe:case Ue:case ie:case be:case Pe:break;default:throw new lt(e)}return e}function Bt(e){return ut(e,t=>xa(t))}function xe(e,t=lr){return ut(e,r=>typeof r=="string"?B(t,r.split(` -`)):r)}function ga(e){if(e.type===ie)return !0}function Rs(e){return js(e,ga,!1)}function Gt(e,t){return e.type===be?{...e,contents:t(e.contents)}:t(e)}function ha(e){return Array.isArray(e)&&e.length>0}var b=ha;var Sa=/^[\$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\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\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\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][\$0-9A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\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\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\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\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\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-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\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]*$/,Ba=e=>Sa.test(e),Js=Ba;function ba(e){return e!==null&&typeof e=="object"}var Ns=ba;function*Pa(e,t){let{getVisitorKeys:r,filter:n=()=>!0}=t,s=u=>Ns(u)&&n(u);for(let u of r(e)){let i=e[u];if(Array.isArray(i))for(let a of i)s(a)&&(yield a);else s(i)&&(yield i);}}function*ka(e,t){let r=[e];for(let n=0;n{let s=!!(n!=null&&n.backwards);if(r===!1)return !1;let{length:u}=t,i=r;for(;i>=0&&i/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26F9(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC3\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC08\uDC26](?:\u200D\u2B1B)?|[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC2\uDECE-\uDEDB\uDEE0-\uDEE8]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;var Ys={eastAsianWidth(e){var t=e.charCodeAt(0),r=e.length==2?e.charCodeAt(1):0,n=t;return 55296<=t&&t<=56319&&56320<=r&&r<=57343&&(t&=1023,r&=1023,n=t<<10|r,n+=65536),n==12288||65281<=n&&n<=65376||65504<=n&&n<=65510?"F":4352<=n&&n<=4447||4515<=n&&n<=4519||4602<=n&&n<=4607||9001<=n&&n<=9002||11904<=n&&n<=11929||11931<=n&&n<=12019||12032<=n&&n<=12245||12272<=n&&n<=12283||12289<=n&&n<=12350||12353<=n&&n<=12438||12441<=n&&n<=12543||12549<=n&&n<=12589||12593<=n&&n<=12686||12688<=n&&n<=12730||12736<=n&&n<=12771||12784<=n&&n<=12830||12832<=n&&n<=12871||12880<=n&&n<=13054||13056<=n&&n<=19903||19968<=n&&n<=42124||42128<=n&&n<=42182||43360<=n&&n<=43388||44032<=n&&n<=55203||55216<=n&&n<=55238||55243<=n&&n<=55291||63744<=n&&n<=64255||65040<=n&&n<=65049||65072<=n&&n<=65106||65108<=n&&n<=65126||65128<=n&&n<=65131||110592<=n&&n<=110593||127488<=n&&n<=127490||127504<=n&&n<=127546||127552<=n&&n<=127560||127568<=n&&n<=127569||131072<=n&&n<=194367||177984<=n&&n<=196605||196608<=n&&n<=262141?"W":"N"}};var _a=/[^\x20-\x7F]/;function ja(e){if(!e)return 0;if(!_a.test(e))return e.length;e=e.replace(Ws()," ");let t=0;for(let r of e){let n=r.codePointAt(0);if(n<=31||n>=127&&n<=159||n>=768&&n<=879)continue;let s=Ys.eastAsianWidth(r);t+=s==="F"||s==="W"?2:1;}return t}var tt=ja;function U(e){var n;let t=e.range?e.range[0]:e.start,r=((n=e.declaration)==null?void 0:n.decorators)??e.decorators;return b(r)?Math.min(U(r[0]),t):t}function O(e){return e.range?e.range[1]:e.end}function yt(e,t){let r=U(e);return Number.isInteger(r)&&r===U(t)}function Ma(e,t){let r=O(e);return Number.isInteger(r)&&r===O(t)}function Xs(e,t){return yt(e,t)&&Ma(e,t)}var qt=null;function Wt(e){if(qt!==null&&typeof qt.property){let t=qt;return qt=Wt.prototype=null,t}return qt=Wt.prototype=e??Object.create(null),new Wt}var Ra=10;for(let e=0;e<=Ra;e++)Wt();function bn(e){return Wt(e)}function Ja(e,t="type"){bn(e);function r(n){let s=n[t],u=e[s];if(!Array.isArray(u))throw Object.assign(new Error(`Missing visitor keys for '${s}'.`),{node:n});return u}return r}var Dr=Ja;var $s={ArrayExpression:["elements"],AssignmentExpression:["left","right"],BinaryExpression:["left","right"],InterpreterDirective:[],Directive:["value"],DirectiveLiteral:[],BlockStatement:["directives","body"],BreakStatement:["label"],CallExpression:["callee","arguments","typeParameters","typeArguments"],CatchClause:["param","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DoWhileStatement:["test","body"],EmptyStatement:[],ExpressionStatement:["expression"],File:["program"],ForInStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","body","returnType","typeParameters","predicate"],FunctionExpression:["id","params","body","returnType","typeParameters"],Identifier:["typeAnnotation","decorators"],IfStatement:["test","consequent","alternate"],LabeledStatement:["label","body"],StringLiteral:[],NumericLiteral:[],NullLiteral:[],BooleanLiteral:[],RegExpLiteral:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],NewExpression:["callee","arguments","typeParameters","typeArguments"],Program:["directives","body"],ObjectExpression:["properties"],ObjectMethod:["key","params","body","decorators","returnType","typeParameters"],ObjectProperty:["key","value","decorators"],RestElement:["argument","typeAnnotation","decorators"],ReturnStatement:["argument"],SequenceExpression:["expressions"],ParenthesizedExpression:["expression"],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handler","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],AssignmentPattern:["left","right","decorators","typeAnnotation"],ArrayPattern:["elements","typeAnnotation","decorators"],ArrowFunctionExpression:["params","body","returnType","typeParameters","predicate"],ClassBody:["body"],ClassExpression:["id","body","superClass","mixins","typeParameters","superTypeParameters","implements","decorators","superTypeArguments"],ClassDeclaration:["id","body","superClass","mixins","typeParameters","superTypeParameters","implements","decorators","superTypeArguments"],ExportAllDeclaration:["source","attributes","assertions","exported"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:["declaration","specifiers","source","attributes","assertions"],ExportSpecifier:["local","exported"],ForOfStatement:["left","right","body"],ImportDeclaration:["specifiers","source","attributes","assertions"],ImportDefaultSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportSpecifier:["local","imported"],MetaProperty:["meta","property"],ClassMethod:["key","params","body","decorators","returnType","typeParameters"],ObjectPattern:["properties","typeAnnotation","decorators"],SpreadElement:["argument"],Super:[],TaggedTemplateExpression:["tag","quasi","typeParameters","typeArguments"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],YieldExpression:["argument"],AwaitExpression:["argument"],Import:[],BigIntLiteral:[],ExportNamespaceSpecifier:["exported"],OptionalMemberExpression:["object","property"],OptionalCallExpression:["callee","arguments","typeParameters","typeArguments"],ClassProperty:["key","value","typeAnnotation","decorators","variance"],ClassAccessorProperty:["key","value","typeAnnotation","decorators"],ClassPrivateProperty:["key","value","decorators","typeAnnotation","variance"],ClassPrivateMethod:["key","params","body","decorators","returnType","typeParameters"],PrivateName:["id"],StaticBlock:["body"],AnyTypeAnnotation:[],ArrayTypeAnnotation:["elementType"],BooleanTypeAnnotation:[],BooleanLiteralTypeAnnotation:[],NullLiteralTypeAnnotation:[],ClassImplements:["id","typeParameters"],DeclareClass:["id","typeParameters","extends","mixins","implements","body"],DeclareFunction:["id","predicate"],DeclareInterface:["id","typeParameters","extends","body"],DeclareModule:["id","body"],DeclareModuleExports:["typeAnnotation"],DeclareTypeAlias:["id","typeParameters","right"],DeclareOpaqueType:["id","typeParameters","supertype"],DeclareVariable:["id"],DeclareExportDeclaration:["declaration","specifiers","source"],DeclareExportAllDeclaration:["source"],DeclaredPredicate:["value"],ExistsTypeAnnotation:[],FunctionTypeAnnotation:["typeParameters","params","rest","returnType","this"],FunctionTypeParam:["name","typeAnnotation"],GenericTypeAnnotation:["id","typeParameters"],InferredPredicate:[],InterfaceExtends:["id","typeParameters"],InterfaceDeclaration:["id","typeParameters","extends","body"],InterfaceTypeAnnotation:["extends","body"],IntersectionTypeAnnotation:["types"],MixedTypeAnnotation:[],EmptyTypeAnnotation:[],NullableTypeAnnotation:["typeAnnotation"],NumberLiteralTypeAnnotation:[],NumberTypeAnnotation:[],ObjectTypeAnnotation:["properties","indexers","callProperties","internalSlots"],ObjectTypeInternalSlot:["id","value","optional","static","method"],ObjectTypeCallProperty:["value"],ObjectTypeIndexer:["id","key","value","variance"],ObjectTypeProperty:["key","value","variance"],ObjectTypeSpreadProperty:["argument"],OpaqueType:["id","typeParameters","supertype","impltype"],QualifiedTypeIdentifier:["id","qualification"],StringLiteralTypeAnnotation:[],StringTypeAnnotation:[],SymbolTypeAnnotation:[],ThisTypeAnnotation:[],TupleTypeAnnotation:["types","elementTypes"],TypeofTypeAnnotation:["argument"],TypeAlias:["id","typeParameters","right"],TypeAnnotation:["typeAnnotation"],TypeCastExpression:["expression","typeAnnotation"],TypeParameter:["bound","default","variance"],TypeParameterDeclaration:["params"],TypeParameterInstantiation:["params"],UnionTypeAnnotation:["types"],Variance:[],VoidTypeAnnotation:[],EnumDeclaration:["id","body"],EnumBooleanBody:["members"],EnumNumberBody:["members"],EnumStringBody:["members"],EnumSymbolBody:["members"],EnumBooleanMember:["id","init"],EnumNumberMember:["id","init"],EnumStringMember:["id","init"],EnumDefaultedMember:["id"],IndexedAccessType:["objectType","indexType"],OptionalIndexedAccessType:["objectType","indexType"],JSXAttribute:["name","value"],JSXClosingElement:["name"],JSXElement:["openingElement","children","closingElement"],JSXEmptyExpression:[],JSXExpressionContainer:["expression"],JSXSpreadChild:["expression"],JSXIdentifier:[],JSXMemberExpression:["object","property"],JSXNamespacedName:["namespace","name"],JSXOpeningElement:["name","attributes","typeArguments","typeParameters"],JSXSpreadAttribute:["argument"],JSXText:[],JSXFragment:["openingFragment","children","closingFragment"],JSXOpeningFragment:[],JSXClosingFragment:[],Noop:[],Placeholder:[],V8IntrinsicIdentifier:[],ArgumentPlaceholder:[],BindExpression:["object","callee"],ImportAttribute:["key","value"],Decorator:["expression"],DoExpression:["body"],ExportDefaultSpecifier:["exported"],RecordExpression:["properties"],TupleExpression:["elements"],DecimalLiteral:[],ModuleExpression:["body"],TopicReference:[],PipelineTopicExpression:["expression"],PipelineBareFunction:["callee"],PipelinePrimaryTopicReference:[],TSParameterProperty:["parameter","decorators"],TSDeclareFunction:["id","typeParameters","params","returnType","body"],TSDeclareMethod:["decorators","key","typeParameters","params","returnType"],TSQualifiedName:["left","right"],TSCallSignatureDeclaration:["typeParameters","parameters","typeAnnotation","params","returnType"],TSConstructSignatureDeclaration:["typeParameters","parameters","typeAnnotation","params","returnType"],TSPropertySignature:["key","typeAnnotation"],TSMethodSignature:["key","typeParameters","parameters","typeAnnotation","params","returnType"],TSIndexSignature:["parameters","typeAnnotation"],TSAnyKeyword:[],TSBooleanKeyword:[],TSBigIntKeyword:[],TSIntrinsicKeyword:[],TSNeverKeyword:[],TSNullKeyword:[],TSNumberKeyword:[],TSObjectKeyword:[],TSStringKeyword:[],TSSymbolKeyword:[],TSUndefinedKeyword:[],TSUnknownKeyword:[],TSVoidKeyword:[],TSThisType:[],TSFunctionType:["typeParameters","parameters","typeAnnotation","params","returnType"],TSConstructorType:["typeParameters","parameters","typeAnnotation","params","returnType"],TSTypeReference:["typeName","typeParameters","typeArguments"],TSTypePredicate:["parameterName","typeAnnotation"],TSTypeQuery:["exprName","typeParameters","typeArguments"],TSTypeLiteral:["members"],TSArrayType:["elementType"],TSTupleType:["elementTypes"],TSOptionalType:["typeAnnotation"],TSRestType:["typeAnnotation"],TSNamedTupleMember:["label","elementType"],TSUnionType:["types"],TSIntersectionType:["types"],TSConditionalType:["checkType","extendsType","trueType","falseType"],TSInferType:["typeParameter"],TSParenthesizedType:["typeAnnotation"],TSTypeOperator:["typeAnnotation"],TSIndexedAccessType:["objectType","indexType"],TSMappedType:["typeParameter","typeAnnotation","nameType"],TSLiteralType:["literal"],TSExpressionWithTypeArguments:["expression","typeParameters"],TSInterfaceDeclaration:["id","typeParameters","extends","body"],TSInterfaceBody:["body"],TSTypeAliasDeclaration:["id","typeParameters","typeAnnotation"],TSInstantiationExpression:["expression","typeParameters","typeArguments"],TSAsExpression:["expression","typeAnnotation"],TSSatisfiesExpression:["expression","typeAnnotation"],TSTypeAssertion:["typeAnnotation","expression"],TSEnumDeclaration:["id","members"],TSEnumMember:["id","initializer"],TSModuleDeclaration:["id","body"],TSModuleBlock:["body"],TSImportType:["argument","qualifier","typeParameters","typeArguments"],TSImportEqualsDeclaration:["id","moduleReference"],TSExternalModuleReference:["expression"],TSNonNullExpression:["expression"],TSExportAssignment:["expression"],TSNamespaceExportDeclaration:["id"],TSTypeAnnotation:["typeAnnotation"],TSTypeParameterInstantiation:["params"],TSTypeParameterDeclaration:["params"],TSTypeParameter:["constraint","default","name"],ChainExpression:["expression"],ExperimentalRestProperty:["argument"],ExperimentalSpreadProperty:["argument"],ImportExpression:["source","attributes"],Literal:[],MethodDefinition:["decorators","key","value"],PrivateIdentifier:[],Property:["key","value"],PropertyDefinition:["decorators","key","typeAnnotation","value","variance"],AccessorProperty:["decorators","key","typeAnnotation","value"],TSAbstractAccessorProperty:["decorators","key","typeAnnotation"],TSAbstractKeyword:[],TSAbstractMethodDefinition:["key","value"],TSAbstractPropertyDefinition:["decorators","key","typeAnnotation"],TSAsyncKeyword:[],TSClassImplements:["expression","typeArguments","typeParameters"],TSDeclareKeyword:[],TSEmptyBodyFunctionExpression:["id","typeParameters","params","returnType"],TSExportKeyword:[],TSInterfaceHeritage:["expression","typeArguments","typeParameters"],TSPrivateKeyword:[],TSProtectedKeyword:[],TSPublicKeyword:[],TSReadonlyKeyword:[],TSStaticKeyword:[],TSTemplateLiteralType:["quasis","types"],BigIntLiteralTypeAnnotation:[],BigIntTypeAnnotation:[],ConditionalTypeAnnotation:["checkType","extendsType","trueType","falseType"],DeclareEnum:["id","body"],InferTypeAnnotation:["typeParameter"],KeyofTypeAnnotation:["argument"],ObjectTypeMappedTypeProperty:["keyTparam","propType","sourceType","variance"],QualifiedTypeofIdentifier:["qualification","id"],TupleTypeLabeledElement:["label","elementType","variance"],TupleTypeSpreadElement:["label","typeAnnotation"],TypePredicate:["parameterName","typeAnnotation","asserts"],NGRoot:["node"],NGPipeExpression:["left","right","arguments"],NGChainedExpression:["expressions"],NGEmptyExpression:[],NGMicrosyntax:["body"],NGMicrosyntaxKey:[],NGMicrosyntaxExpression:["expression","alias"],NGMicrosyntaxKeyedExpression:["key","expression"],NGMicrosyntaxLet:["key","value"],NGMicrosyntaxAs:["key","alias"],JsExpressionRoot:["node"],JsonRoot:["node"],TSJSDocAllType:[],TSJSDocUnknownType:[],TSJSDocNullableType:["typeAnnotation"],TSJSDocNonNullableType:["typeAnnotation"],NeverTypeAnnotation:[],UndefinedTypeAnnotation:[],UnknownTypeAnnotation:[]};var Na=Dr($s),fr=Na;function Ua(e){return e=new Set(e),t=>e.has(t==null?void 0:t.type)}var j=Ua;var Ga=j(["Block","CommentBlock","MultiLine"]),ae=Ga;function qa(e,t){let r=t.split(".");for(let n=r.length-1;n>=0;n--){let s=r[n];if(n===0)return e.type==="Identifier"&&e.name===s;if(e.type!=="MemberExpression"||e.optional||e.computed||e.property.type!=="Identifier"||e.property.name!==s)return !1;e=e.object;}}function Wa(e,t){return t.some(r=>qa(e,r))}var Vs=Wa;var Ya=j(["AnyTypeAnnotation","ThisTypeAnnotation","NumberTypeAnnotation","VoidTypeAnnotation","BooleanTypeAnnotation","BigIntTypeAnnotation","SymbolTypeAnnotation","StringTypeAnnotation","NeverTypeAnnotation","UndefinedTypeAnnotation","UnknownTypeAnnotation","EmptyTypeAnnotation","MixedTypeAnnotation"]),Er=Ya;function Xa({type:e}){return e.startsWith("TS")&&e.endsWith("Keyword")}var Fr=Xa;function Xt(e,t){return t(e)||Us(e,{getVisitorKeys:fr,predicate:t})}function Lt(e){return e.type==="AssignmentExpression"||e.type==="BinaryExpression"||e.type==="LogicalExpression"||e.type==="NGPipeExpression"||e.type==="ConditionalExpression"||k(e)||J(e)||e.type==="SequenceExpression"||e.type==="TaggedTemplateExpression"||e.type==="BindExpression"||e.type==="UpdateExpression"&&!e.prefix||Le(e)||e.type==="TSNonNullExpression"||e.type==="ChainExpression"}function zs(e){return e.expressions?e.expressions[0]:e.left??e.test??e.callee??e.object??e.tag??e.argument??e.expression}function dr(e){if(e.expressions)return ["expressions",0];if(e.left)return ["left"];if(e.test)return ["test"];if(e.object)return ["object"];if(e.callee)return ["callee"];if(e.tag)return ["tag"];if(e.argument)return ["argument"];if(e.expression)return ["expression"];throw new Error("Unexpected node has no left side.")}var $t=j(["Line","CommentLine","SingleLine","HashbangComment","HTMLOpen","HTMLClose","Hashbang","InterpreterDirective"]),Qs=j(["ExportDefaultDeclaration","DeclareExportDeclaration","ExportNamedDeclaration","ExportAllDeclaration","DeclareExportAllDeclaration"]),G=j(["ArrayExpression","TupleExpression"]),ee=j(["ObjectExpression","RecordExpression"]);function he(e){return e.type==="NumericLiteral"||e.type==="Literal"&&typeof e.value=="number"}function Ar(e){return e.type==="UnaryExpression"&&(e.operator==="+"||e.operator==="-")&&he(e.argument)}function Q(e){return e.type==="StringLiteral"||e.type==="Literal"&&typeof e.value=="string"}function wn(e){return e.type==="RegExpLiteral"||e.type==="Literal"&&!!e.regex}var ke=j(["ObjectTypeAnnotation","TSTypeLiteral","TSMappedType"]),It=j(["FunctionExpression","ArrowFunctionExpression"]);function $a(e){return e.type==="FunctionExpression"||e.type==="ArrowFunctionExpression"&&e.body.type==="BlockStatement"}function Pn(e){return k(e)&&e.callee.type==="Identifier"&&["async","inject","fakeAsync","waitForAsync"].includes(e.callee.name)}var Y=j(["JSXElement","JSXFragment"]);function On(e){return e.kind==="get"||e.kind==="set"}function vn(e){return On(e)||yt(e,e.value)}function Tr(e){return (e.type==="ObjectTypeProperty"||e.type==="ObjectTypeInternalSlot")&&e.value.type==="FunctionTypeAnnotation"&&!e.static&&!vn(e)}function Zs(e){return (e.type==="TypeAnnotation"||e.type==="TSTypeAnnotation")&&e.typeAnnotation.type==="FunctionTypeAnnotation"&&!e.static&&!yt(e,e.typeAnnotation)}var ce=j(["BinaryExpression","LogicalExpression","NGPipeExpression"]);function Dt(e){return J(e)||e.type==="BindExpression"&&!!e.object}var Va=j(["TSThisType","NullLiteralTypeAnnotation","BooleanLiteralTypeAnnotation","StringLiteralTypeAnnotation","BigIntLiteralTypeAnnotation","NumberLiteralTypeAnnotation","TSLiteralType","TSTemplateLiteralType"]);function wt(e){return Fr(e)||Er(e)||Va(e)||(e.type==="GenericTypeAnnotation"||e.type==="TSTypeReference")&&!e.typeParameters}function Ha(e){let t=/^(?:before|after)(?:Each|All)$/;return e.callee.type==="Identifier"&&e.arguments.length===1&&t.test(e.callee.name)}var Ka=["it","it.only","it.skip","describe","describe.only","describe.skip","test","test.only","test.skip","test.step","test.describe","test.describe.only","test.describe.parallel","test.describe.parallel.only","test.describe.serial","test.describe.serial.only","skip","xit","xdescribe","xtest","fit","fdescribe","ftest"];function za(e){return Vs(e,Ka)}function Ct(e,t){if(e.type!=="CallExpression")return !1;if(e.arguments.length===1){if(Pn(e)&&t&&Ct(t))return It(e.arguments[0]);if(Ha(e))return Pn(e.arguments[0])}else if((e.arguments.length===2||e.arguments.length===3)&&(e.arguments[0].type==="TemplateLiteral"||Q(e.arguments[0]))&&za(e.callee))return e.arguments[2]&&!he(e.arguments[2])?!1:(e.arguments.length===2?It(e.arguments[1]):$a(e.arguments[1])&&X(e.arguments[1]).length<=1)||Pn(e.arguments[1]);return !1}var k=j(["CallExpression","OptionalCallExpression"]),J=j(["MemberExpression","OptionalMemberExpression"]);function eu(e){let t="expressions";e.type==="TSTemplateLiteralType"&&(t="types");let r=e[t];return r.length===0?!1:r.every(n=>{if(d(n))return !1;if(n.type==="Identifier"||n.type==="ThisExpression")return !0;if(n.type==="ChainExpression"&&(n=n.expression),J(n)){let s=n;for(;J(s);)if(s.property.type!=="Identifier"&&s.property.type!=="Literal"&&s.property.type!=="StringLiteral"&&s.property.type!=="NumericLiteral"||(s=s.object,d(s)))return !1;return s.type==="Identifier"||s.type==="ThisExpression"}return !1})}function Ie(e,t){return Y(t)?dt(t):d(t,x.Leading,r=>z(e,O(r)))}function _n(e,t){return t.parser!=="json"&&Q(e.key)&&oe(e.key).slice(1,-1)===e.key.value&&(Js(e.key.value)&&!(t.parser==="babel-ts"&&e.type==="ClassProperty"||t.parser==="typescript"&&e.type==="PropertyDefinition")||jn(e.key.value)&&String(Number(e.key.value))===e.key.value&&(t.parser==="babel"||t.parser==="acorn"||t.parser==="espree"||t.parser==="meriyah"||t.parser==="__babel_estree"))}function jn(e){return /^(?:\d+|\d+\.\d+)$/.test(e)}function Hs(e){return e.quasis.some(t=>t.value.raw.includes(` -`))}function xr(e,t){return (e.type==="TemplateLiteral"&&Hs(e)||e.type==="TaggedTemplateExpression"&&Hs(e.quasi))&&!z(t,U(e),{backwards:!0})}function gr(e){if(!d(e))return !1;let t=w(!1,Kt(e,x.Dangling),-1);return t&&!ae(t)}function tu(e){if(e.length<=1)return !1;let t=0;for(let r of e)if(It(r)){if(t+=1,t>1)return !0}else if(k(r)){for(let n of r.arguments)if(It(n))return !0}return !1}function hr(e){let{node:t,parent:r,key:n}=e;return n==="callee"&&k(t)&&k(r)&&r.arguments.length>0&&t.arguments.length>r.arguments.length}var Qa=new Set(["!","-","+","~"]);function ge(e,t=2){if(t<=0)return !1;let r=n=>ge(n,t-1);if(wn(e))return tt(e.pattern??e.regex.pattern)<=5;if(e.type==="Literal"||e.type==="BigIntLiteral"||e.type==="DecimalLiteral"||e.type==="BooleanLiteral"||e.type==="NullLiteral"||e.type==="NumericLiteral"||e.type==="StringLiteral"||e.type==="Identifier"||e.type==="ThisExpression"||e.type==="Super"||e.type==="PrivateName"||e.type==="PrivateIdentifier"||e.type==="ArgumentPlaceholder"||e.type==="Import")return !0;if(e.type==="TemplateLiteral")return e.quasis.every(n=>!n.value.raw.includes(` -`))&&e.expressions.every(r);if(ee(e))return e.properties.every(n=>!n.computed&&(n.shorthand||n.value&&r(n.value)));if(G(e))return e.elements.every(n=>n===null||r(n));if(it(e)){if(e.type==="ImportExpression"||ge(e.callee,t)){let n=Ce(e);return n.length<=t&&n.every(r)}return !1}return J(e)?ge(e.object,t)&&ge(e.property,t):e.type==="UnaryExpression"&&Qa.has(e.operator)||e.type==="UpdateExpression"?ge(e.argument,t):e.type==="TSNonNullExpression"?ge(e.expression,t):!1}function oe(e){var t;return ((t=e.extra)==null?void 0:t.raw)??e.raw}function ru(e){return e}function le(e,t="es5"){return e.trailingComma==="es5"&&t==="es5"||e.trailingComma==="all"&&(t==="all"||t==="es5")}function re(e,t){switch(e.type){case"BinaryExpression":case"LogicalExpression":case"AssignmentExpression":case"NGPipeExpression":return re(e.left,t);case"MemberExpression":case"OptionalMemberExpression":return re(e.object,t);case"TaggedTemplateExpression":return e.tag.type==="FunctionExpression"?!1:re(e.tag,t);case"CallExpression":case"OptionalCallExpression":return e.callee.type==="FunctionExpression"?!1:re(e.callee,t);case"ConditionalExpression":return re(e.test,t);case"UpdateExpression":return !e.prefix&&re(e.argument,t);case"BindExpression":return e.object&&re(e.object,t);case"SequenceExpression":return re(e.expressions[0],t);case"ChainExpression":case"TSSatisfiesExpression":case"TSAsExpression":case"TSNonNullExpression":return re(e.expression,t);default:return t(e)}}var Ks={"==":!0,"!=":!0,"===":!0,"!==":!0},Cr={"*":!0,"/":!0,"%":!0},Ln={">>":!0,">>>":!0,"<<":!0};function Vt(e,t){return !(Yt(t)!==Yt(e)||e==="**"||Ks[e]&&Ks[t]||t==="%"&&Cr[e]||e==="%"&&Cr[t]||t!==e&&Cr[t]&&Cr[e]||Ln[e]&&Ln[t])}var Za=new Map([["|>"],["??"],["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]].flatMap((e,t)=>e.map(r=>[r,t])));function Yt(e){return Za.get(e)}function nu(e){return !!Ln[e]||e==="|"||e==="^"||e==="&"}function su(e){var r;if(e.rest)return !0;let t=X(e);return ((r=w(!1,t,-1))==null?void 0:r.type)==="RestElement"}var kn=new WeakMap;function X(e){if(kn.has(e))return kn.get(e);let t=[];return e.this&&t.push(e.this),Array.isArray(e.parameters)?t.push(...e.parameters):Array.isArray(e.params)&&t.push(...e.params),e.rest&&t.push(e.rest),kn.set(e,t),t}function uu(e,t){let{node:r}=e,n=0,s=u=>t(u,n++);r.this&&e.call(s,"this"),Array.isArray(r.parameters)?e.each(s,"parameters"):Array.isArray(r.params)&&e.each(s,"params"),r.rest&&e.call(s,"rest");}var In=new WeakMap;function Ce(e){if(In.has(e))return In.get(e);let t=e.arguments;return e.type==="ImportExpression"&&(t=[e.source],e.attributes&&t.push(e.attributes)),In.set(e,t),t}function Sr(e,t){let{node:r}=e;r.type==="ImportExpression"?(e.call(n=>t(n,0),"source"),r.attributes&&e.call(n=>t(n,1),"attributes")):e.each(t,"arguments");}function Mn(e,t){if(e.type==="ImportExpression"){if(t===0||t===(e.attributes?-2:-1))return "source";if(e.attributes&&(t===1||t===-1))return "attributes";throw new RangeError("Invalid argument index")}if(t<0&&(t=e.arguments.length+t),t<0||t>=e.arguments.length)throw new RangeError("Invalid argument index");return ["arguments",t]}function Ht(e){return e.value.trim()==="prettier-ignore"&&!e.unignore}function dt(e){return (e==null?void 0:e.prettierIgnore)||d(e,x.PrettierIgnore)}var x={Leading:2,Trailing:4,Dangling:8,Block:16,Line:32,PrettierIgnore:64,First:128,Last:256},iu=(e,t)=>{if(typeof e=="function"&&(t=e,e=0),e||t)return (r,n,s)=>!(e&x.Leading&&!r.leading||e&x.Trailing&&!r.trailing||e&x.Dangling&&(r.leading||r.trailing)||e&x.Block&&!ae(r)||e&x.Line&&!$t(r)||e&x.First&&n!==0||e&x.Last&&n!==s.length-1||e&x.PrettierIgnore&&!Ht(r)||t&&!t(r))};function d(e,t,r){if(!b(e==null?void 0:e.comments))return !1;let n=iu(t,r);return n?e.comments.some(n):!0}function Kt(e,t,r){if(!Array.isArray(e==null?void 0:e.comments))return [];let n=iu(t,r);return n?e.comments.filter(n):e.comments}var me=(e,{originalText:t})=>kt(t,O(e));function it(e){return k(e)||e.type==="NewExpression"||e.type==="ImportExpression"}function fe(e){return e&&(e.type==="ObjectProperty"||e.type==="Property"&&!e.method&&e.kind==="init")}var zt=Symbol("ifWithoutBlockAndSameLineComment"),Le=j(["TSAsExpression","TSSatisfiesExpression"]);function Rn(e,t){var u,i,a,o,p,m,D;if(e.isRoot)return !1;let{node:r,key:n,parent:s}=e;if(t.__isInHtmlInterpolation&&!t.bracketSpacing&&no(r)&&Qt(e))return !0;if(eo(r))return !1;if(r.type==="Identifier"){if((u=r.extra)!=null&&u.parenthesized&&/^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(r.name)||n==="left"&&(r.name==="async"&&!s.await||r.name==="let")&&s.type==="ForOfStatement")return !0;if(r.name==="let"){let c=(i=e.findAncestor(f=>f.type==="ForOfStatement"))==null?void 0:i.left;if(c&&re(c,f=>f===r))return !0}if(n==="object"&&r.name==="let"&&s.type==="MemberExpression"&&s.computed&&!s.optional){let c=e.findAncestor(l=>l.type==="ExpressionStatement"||l.type==="ForStatement"||l.type==="ForInStatement"),f=c?c.type==="ExpressionStatement"?c.expression:c.type==="ForStatement"?c.init:c.left:void 0;if(f&&re(f,l=>l===r))return !0}return !1}if(r.type==="ObjectExpression"||r.type==="FunctionExpression"||r.type==="ClassExpression"||r.type==="DoExpression"){let c=(a=e.findAncestor(f=>f.type==="ExpressionStatement"))==null?void 0:a.expression;if(c&&re(c,f=>f===r))return !0}if(r.type==="ObjectExpression"){let c=(o=e.findAncestor(f=>f.type==="ArrowFunctionExpression"))==null?void 0:o.body;if(c&&c.type!=="SequenceExpression"&&c.type!=="AssignmentExpression"&&re(c,f=>f===r))return !0}switch(s.type){case"ParenthesizedExpression":return !1;case"ClassDeclaration":case"ClassExpression":if(n==="superClass"&&(r.type==="ArrowFunctionExpression"||r.type==="AssignmentExpression"||r.type==="AwaitExpression"||r.type==="BinaryExpression"||r.type==="ConditionalExpression"||r.type==="LogicalExpression"||r.type==="NewExpression"||r.type==="ObjectExpression"||r.type==="SequenceExpression"||r.type==="TaggedTemplateExpression"||r.type==="UnaryExpression"||r.type==="UpdateExpression"||r.type==="YieldExpression"||r.type==="TSNonNullExpression"||r.type==="ClassExpression"&&b(r.decorators)))return !0;break;case"ExportDefaultDeclaration":return au(e,t)||r.type==="SequenceExpression";case"Decorator":if(n==="expression"){if(J(r)&&r.computed)return !0;let c=!1,f=!1,l=r;for(;l;)switch(l.type){case"MemberExpression":f=!0,l=l.object;break;case"CallExpression":if(f||c)return t.parser!=="typescript";c=!0,l=l.callee;break;case"Identifier":return !1;case"TaggedTemplateExpression":return t.parser!=="typescript";default:return !0}return !0}break;case"TypeAnnotation":if(e.match(void 0,void 0,(c,f)=>f==="returnType"&&c.type==="ArrowFunctionExpression")&&ro(r))return !0;break}switch(r.type){case"UpdateExpression":if(s.type==="UnaryExpression")return r.prefix&&(r.operator==="++"&&s.operator==="+"||r.operator==="--"&&s.operator==="-");case"UnaryExpression":switch(s.type){case"UnaryExpression":return r.operator===s.operator&&(r.operator==="+"||r.operator==="-");case"BindExpression":return !0;case"MemberExpression":case"OptionalMemberExpression":return n==="object";case"TaggedTemplateExpression":return !0;case"NewExpression":case"CallExpression":case"OptionalCallExpression":return n==="callee";case"BinaryExpression":return n==="left"&&s.operator==="**";case"TSNonNullExpression":return !0;default:return !1}case"BinaryExpression":if(s.type==="UpdateExpression"||r.operator==="in"&&to(e))return !0;if(r.operator==="|>"&&((p=r.extra)!=null&&p.parenthesized)){let c=e.grandparent;if(c.type==="BinaryExpression"&&c.operator==="|>")return !0}case"TSTypeAssertion":case"TSAsExpression":case"TSSatisfiesExpression":case"LogicalExpression":switch(s.type){case"TSAsExpression":case"TSSatisfiesExpression":return !Le(r);case"ConditionalExpression":return Le(r);case"CallExpression":case"NewExpression":case"OptionalCallExpression":return n==="callee";case"ClassExpression":case"ClassDeclaration":return n==="superClass";case"TSTypeAssertion":case"TaggedTemplateExpression":case"UnaryExpression":case"JSXSpreadAttribute":case"SpreadElement":case"BindExpression":case"AwaitExpression":case"TSNonNullExpression":case"UpdateExpression":return !0;case"MemberExpression":case"OptionalMemberExpression":return n==="object";case"AssignmentExpression":case"AssignmentPattern":return n==="left"&&(r.type==="TSTypeAssertion"||Le(r));case"LogicalExpression":if(r.type==="LogicalExpression")return s.operator!==r.operator;case"BinaryExpression":{let{operator:c,type:f}=r;if(!c&&f!=="TSTypeAssertion")return !0;let l=Yt(c),h=s.operator,g=Yt(h);return g>l||n==="right"&&g===l||g===l&&!Vt(h,c)?!0:g");default:return !1}case"TSFunctionType":if(e.match(c=>c.type==="TSFunctionType",(c,f)=>f==="typeAnnotation"&&c.type==="TSTypeAnnotation",(c,f)=>f==="returnType"&&c.type==="ArrowFunctionExpression"))return !0;case"TSConditionalType":case"TSConstructorType":if(n==="extendsType"&&s.type==="TSConditionalType"){if(r.type==="TSConditionalType")return !0;let{typeAnnotation:c}=r.returnType||r.typeAnnotation;if(c.type==="TSTypePredicate"&&c.typeAnnotation&&(c=c.typeAnnotation.typeAnnotation),c.type==="TSInferType"&&c.typeParameter.constraint)return !0}if(n==="checkType"&&s.type==="TSConditionalType")return !0;case"TSUnionType":case"TSIntersectionType":if((s.type==="TSUnionType"||s.type==="TSIntersectionType")&&s.types.length>1&&(!r.types||r.types.length>1))return !0;case"TSInferType":if(r.type==="TSInferType"&&s.type==="TSRestType")return !1;case"TSTypeOperator":return s.type==="TSArrayType"||s.type==="TSOptionalType"||s.type==="TSRestType"||n==="objectType"&&s.type==="TSIndexedAccessType"||s.type==="TSTypeOperator"||s.type==="TSTypeAnnotation"&&e.grandparent.type.startsWith("TSJSDoc");case"TSTypeQuery":return n==="objectType"&&s.type==="TSIndexedAccessType"||n==="elementType"&&s.type==="TSArrayType";case"TypeofTypeAnnotation":return n==="objectType"&&(s.type==="IndexedAccessType"||s.type==="OptionalIndexedAccessType")||n==="elementType"&&s.type==="ArrayTypeAnnotation";case"ArrayTypeAnnotation":return s.type==="NullableTypeAnnotation";case"IntersectionTypeAnnotation":case"UnionTypeAnnotation":return s.type==="ArrayTypeAnnotation"||s.type==="NullableTypeAnnotation"||s.type==="IntersectionTypeAnnotation"||s.type==="UnionTypeAnnotation"||n==="objectType"&&(s.type==="IndexedAccessType"||s.type==="OptionalIndexedAccessType");case"InferTypeAnnotation":case"NullableTypeAnnotation":return s.type==="ArrayTypeAnnotation"||n==="objectType"&&(s.type==="IndexedAccessType"||s.type==="OptionalIndexedAccessType");case"FunctionTypeAnnotation":{if(e.match(void 0,(f,l)=>l==="typeAnnotation"&&f.type==="TypeAnnotation",(f,l)=>l==="returnType"&&f.type==="ArrowFunctionExpression")||e.match(void 0,(f,l)=>l==="typeAnnotation"&&f.type==="TypePredicate",(f,l)=>l==="typeAnnotation"&&f.type==="TypeAnnotation",(f,l)=>l==="returnType"&&f.type==="ArrowFunctionExpression"))return !0;let c=s.type==="NullableTypeAnnotation"?e.grandparent:s;return c.type==="UnionTypeAnnotation"||c.type==="IntersectionTypeAnnotation"||c.type==="ArrayTypeAnnotation"||n==="objectType"&&(c.type==="IndexedAccessType"||c.type==="OptionalIndexedAccessType")||n==="checkType"&&s.type==="ConditionalTypeAnnotation"||n==="extendsType"&&s.type==="ConditionalTypeAnnotation"&&r.returnType.type==="InferTypeAnnotation"&&r.returnType.typeParameter.bound||c.type==="NullableTypeAnnotation"||s.type==="FunctionTypeParam"&&s.name===null&&X(r).some(f=>{var l;return ((l=f.typeAnnotation)==null?void 0:l.type)==="NullableTypeAnnotation"})}case"ConditionalTypeAnnotation":if(n==="extendsType"&&s.type==="ConditionalTypeAnnotation"&&r.type==="ConditionalTypeAnnotation"||n==="checkType"&&s.type==="ConditionalTypeAnnotation")return !0;case"OptionalIndexedAccessType":return n==="objectType"&&s.type==="IndexedAccessType";case"StringLiteral":case"NumericLiteral":case"Literal":if(typeof r.value=="string"&&s.type==="ExpressionStatement"&&!s.directive){let c=e.grandparent;return c.type==="Program"||c.type==="BlockStatement"}return n==="object"&&s.type==="MemberExpression"&&typeof r.value=="number";case"AssignmentExpression":{let c=e.grandparent;return n==="body"&&s.type==="ArrowFunctionExpression"?!0:n==="key"&&(s.type==="ClassProperty"||s.type==="PropertyDefinition")&&s.computed||(n==="init"||n==="update")&&s.type==="ForStatement"?!1:s.type==="ExpressionStatement"?r.left.type==="ObjectPattern":!(n==="key"&&s.type==="TSPropertySignature"||s.type==="AssignmentExpression"||s.type==="SequenceExpression"&&c.type==="ForStatement"&&(c.init===s||c.update===s)||n==="value"&&s.type==="Property"&&c.type==="ObjectPattern"&&c.properties.includes(s)||s.type==="NGChainedExpression")}case"ConditionalExpression":switch(s.type){case"TaggedTemplateExpression":case"UnaryExpression":case"SpreadElement":case"BinaryExpression":case"LogicalExpression":case"NGPipeExpression":case"ExportDefaultDeclaration":case"AwaitExpression":case"JSXSpreadAttribute":case"TSTypeAssertion":case"TypeCastExpression":case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return !0;case"NewExpression":case"CallExpression":case"OptionalCallExpression":return n==="callee";case"ConditionalExpression":return n==="test";case"MemberExpression":case"OptionalMemberExpression":return n==="object";default:return !1}case"FunctionExpression":switch(s.type){case"NewExpression":case"CallExpression":case"OptionalCallExpression":return n==="callee";case"TaggedTemplateExpression":return !0;default:return !1}case"ArrowFunctionExpression":switch(s.type){case"BinaryExpression":return s.operator!=="|>"||((m=r.extra)==null?void 0:m.parenthesized);case"NewExpression":case"CallExpression":case"OptionalCallExpression":return n==="callee";case"MemberExpression":case"OptionalMemberExpression":return n==="object";case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"BindExpression":case"TaggedTemplateExpression":case"UnaryExpression":case"LogicalExpression":case"AwaitExpression":case"TSTypeAssertion":return !0;case"ConditionalExpression":return n==="test";default:return !1}case"ClassExpression":switch(s.type){case"NewExpression":return n==="callee";default:return !1}case"OptionalMemberExpression":case"OptionalCallExpression":case"CallExpression":case"MemberExpression":if(so(e))return !0;case"TaggedTemplateExpression":case"TSNonNullExpression":if(n==="callee"&&(s.type==="BindExpression"||s.type==="NewExpression")){let c=r;for(;c;)switch(c.type){case"CallExpression":case"OptionalCallExpression":return !0;case"MemberExpression":case"OptionalMemberExpression":case"BindExpression":c=c.object;break;case"TaggedTemplateExpression":c=c.tag;break;case"TSNonNullExpression":c=c.expression;break;default:return !1}}return !1;case"BindExpression":return n==="callee"&&(s.type==="BindExpression"||s.type==="NewExpression")||n==="object"&&J(s);case"NGPipeExpression":return !(s.type==="NGRoot"||s.type==="NGMicrosyntaxExpression"||s.type==="ObjectProperty"&&!((D=r.extra)!=null&&D.parenthesized)||G(s)||n==="arguments"&&k(s)||n==="right"&&s.type==="NGPipeExpression"||n==="property"&&s.type==="MemberExpression"||s.type==="AssignmentExpression");case"JSXFragment":case"JSXElement":return n==="callee"||n==="left"&&s.type==="BinaryExpression"&&s.operator==="<"||!G(s)&&s.type!=="ArrowFunctionExpression"&&s.type!=="AssignmentExpression"&&s.type!=="AssignmentPattern"&&s.type!=="BinaryExpression"&&s.type!=="NewExpression"&&s.type!=="ConditionalExpression"&&s.type!=="ExpressionStatement"&&s.type!=="JsExpressionRoot"&&s.type!=="JSXAttribute"&&s.type!=="JSXElement"&&s.type!=="JSXExpressionContainer"&&s.type!=="JSXFragment"&&s.type!=="LogicalExpression"&&!k(s)&&!fe(s)&&s.type!=="ReturnStatement"&&s.type!=="ThrowStatement"&&s.type!=="TypeCastExpression"&&s.type!=="VariableDeclarator"&&s.type!=="YieldExpression";case"TSInstantiationExpression":return n==="object"&&J(s)}return !1}var eo=j(["BlockStatement","BreakStatement","ClassBody","ClassDeclaration","ClassMethod","ClassProperty","PropertyDefinition","ClassPrivateProperty","ContinueStatement","DebuggerStatement","DeclareClass","DeclareExportAllDeclaration","DeclareExportDeclaration","DeclareFunction","DeclareInterface","DeclareModule","DeclareModuleExports","DeclareVariable","DeclareEnum","DoWhileStatement","EnumDeclaration","ExportAllDeclaration","ExportDefaultDeclaration","ExportNamedDeclaration","ExpressionStatement","ForInStatement","ForOfStatement","ForStatement","FunctionDeclaration","IfStatement","ImportDeclaration","InterfaceDeclaration","LabeledStatement","MethodDefinition","ReturnStatement","SwitchStatement","ThrowStatement","TryStatement","TSDeclareFunction","TSEnumDeclaration","TSImportEqualsDeclaration","TSInterfaceDeclaration","TSModuleDeclaration","TSNamespaceExportDeclaration","TypeAlias","VariableDeclaration","WhileStatement","WithStatement"]);function to(e){let t=0,{node:r}=e;for(;r;){let n=e.getParentNode(t++);if((n==null?void 0:n.type)==="ForStatement"&&n.init===r)return !0;r=n;}return !1}function ro(e){return Xt(e,t=>t.type==="ObjectTypeAnnotation"&&Xt(t,r=>r.type==="FunctionTypeAnnotation"))}function no(e){return ee(e)}function Qt(e){let{parent:t,key:r}=e;switch(t.type){case"NGPipeExpression":if(r==="arguments"&&e.isLast)return e.callParent(Qt);break;case"ObjectProperty":if(r==="value")return e.callParent(()=>e.key==="properties"&&e.isLast);break;case"BinaryExpression":case"LogicalExpression":if(r==="right")return e.callParent(Qt);break;case"ConditionalExpression":if(r==="alternate")return e.callParent(Qt);break;case"UnaryExpression":if(t.prefix)return e.callParent(Qt);break}return !1}function au(e,t){let{node:r,parent:n}=e;return r.type==="FunctionExpression"||r.type==="ClassExpression"?n.type==="ExportDefaultDeclaration"||!Rn(e,t):!Lt(r)||n.type!=="ExportDefaultDeclaration"&&Rn(e,t)?!1:e.call(()=>au(e,t),...dr(r))}function so(e){let{node:t,parent:r,grandparent:n,key:s}=e;return !!((t.type==="OptionalMemberExpression"||t.type==="OptionalCallExpression")&&(s==="object"&&r.type==="MemberExpression"||s==="callee"&&(r.type==="CallExpression"||r.type==="NewExpression")||r.type==="TSNonNullExpression"&&n.type==="MemberExpression"&&n.object===r)||e.match(()=>t.type==="CallExpression"||t.type==="MemberExpression",(u,i)=>i==="expression"&&u.type==="ChainExpression")&&(e.match(void 0,void 0,(u,i)=>i==="callee"&&(u.type==="CallExpression"&&!u.optional||u.type==="NewExpression")||i==="object"&&u.type==="MemberExpression"&&!u.optional)||e.match(void 0,void 0,(u,i)=>i==="expression"&&u.type==="TSNonNullExpression",(u,i)=>i==="object"&&u.type==="MemberExpression"))||e.match(()=>t.type==="CallExpression"||t.type==="MemberExpression",(u,i)=>i==="expression"&&u.type==="TSNonNullExpression",(u,i)=>i==="expression"&&u.type==="ChainExpression",(u,i)=>i==="object"&&u.type==="MemberExpression"))}var we=Rn;var uo=(e,t,r,n)=>{if(!(e&&t==null))return t.replaceAll?t.replaceAll(r,n):r.global?t.replace(r,n):t.split(r).join(n)},H=uo;function io(e,t){let r=t-1;r=We(e,r,{backwards:!0}),r=Ye(e,r,{backwards:!0}),r=We(e,r,{backwards:!0});let n=Ye(e,r,{backwards:!0});return r!==n}var ou=io;var ao=()=>!0;function Jn(e,t){let r=e.node;return r.printed=!0,t.printer.printComment(e,t)}function oo(e,t){var m;let r=e.node,n=[Jn(e,t)],{printer:s,originalText:u,locStart:i,locEnd:a}=t;if((m=s.isBlockComment)==null?void 0:m.call(s,r)){let D=z(u,a(r))?z(u,i(r),{backwards:!0})?C:A:" ";n.push(D);}else n.push(C);let p=Ye(u,We(u,a(r)));return p!==!1&&z(u,p)&&n.push(C),n}function po(e,t,r){var p;let n=e.node,s=Jn(e,t),{printer:u,originalText:i,locStart:a}=t,o=(p=u.isBlockComment)==null?void 0:p.call(u,n);if(r!=null&&r.hasLineSuffix&&!(r!=null&&r.isBlock)||z(i,a(n),{backwards:!0})){let m=ou(i,a(n));return {doc:hn([C,m?C:"",s]),isBlock:o,hasLineSuffix:!0}}return !o||r!=null&&r.hasLineSuffix?{doc:[hn([" ",s]),Te],isBlock:o,hasLineSuffix:!0}:{doc:[" ",s],isBlock:o,hasLineSuffix:!1}}function M(e,t,r={}){let{node:n}=e;if(!b(n==null?void 0:n.comments))return "";let{indent:s=!1,marker:u,filter:i=ao}=r,a=[];if(e.each(({node:p})=>{p.leading||p.trailing||p.marker!==u||!i(p)||a.push(Jn(e,t));},"comments"),a.length===0)return "";let o=B(C,a);return s?E([C,o]):o}function Nn(e,t){let r=e.node;if(!r)return {};let n=t[Symbol.for("printedComments")];if((r.comments||[]).filter(o=>!n.has(o)).length===0)return {leading:"",trailing:""};let u=[],i=[],a;return e.each(()=>{let o=e.node;if(n!=null&&n.has(o))return;let{leading:p,trailing:m}=o;p?u.push(oo(e,t)):m&&(a=po(e,t,a),i.push(a.doc));},"comments"),{leading:u,trailing:i}}function pe(e,t,r){let{leading:n,trailing:s}=Nn(e,r);return !n&&!s?t:Gt(t,u=>[n,u,s])}var Un=class extends Error{name="UnexpectedNodeError";constructor(t,r,n="type"){super(`Unexpected ${r} node ${n}: ${JSON.stringify(t[n])}.`),this.node=t;}},Oe=Un;var Br="'",pu='"';function co(e,t){let r=t===!0||t===Br?Br:pu,n=r===Br?pu:Br,s=0,u=0;for(let i of e)i===r?s++:i===n&&u++;return s>u?n:r}var br=co;function Gn(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}var ve,qn=class{constructor(t){bs(this,ve,void 0);Ps(this,ve,new Set(t));}getLeadingWhitespaceCount(t){let r=st(this,ve),n=0;for(let s=0;s=0&&r.has(t.charAt(s));s--)n++;return n}getLeadingWhitespace(t){let r=this.getLeadingWhitespaceCount(t);return t.slice(0,r)}getTrailingWhitespace(t){let r=this.getTrailingWhitespaceCount(t);return t.slice(t.length-r)}hasLeadingWhitespace(t){return st(this,ve).has(t.charAt(0))}hasTrailingWhitespace(t){return st(this,ve).has(w(!1,t,-1))}trimStart(t){let r=this.getLeadingWhitespaceCount(t);return t.slice(r)}trimEnd(t){let r=this.getTrailingWhitespaceCount(t);return t.slice(0,t.length-r)}trim(t){return this.trimEnd(this.trimStart(t))}split(t,r=!1){let n=`[${Gn([...st(this,ve)].join(""))}]+`,s=new RegExp(r?`(${n})`:n);return t.split(s)}hasWhitespaceCharacter(t){let r=st(this,ve);return Array.prototype.some.call(t,n=>r.has(n))}hasNonWhitespaceCharacter(t){let r=st(this,ve);return Array.prototype.some.call(t,n=>!r.has(n))}isWhitespaceOnly(t){let r=st(this,ve);return Array.prototype.every.call(t,n=>r.has(n))}};ve=new WeakMap;var cu=qn;var Kn={};or(Kn,{endOfLine:()=>Fo,ownLine:()=>Eo,remaining:()=>Co});function lo(e,t){let r=null,n=t;for(;n!==r;)r=n,n=We(e,n),n=bt(e,n),n=Pt(e,n),n=Ye(e,n);return n}var Xe=lo;function mo(e,t){let r=Xe(e,t);return r===!1?"":e.charAt(r)}var $e=mo;function yo(e,t,r){for(let n=t;n20&&(r=r.slice(0,19)+"\u2026"),t+(r?" "+r:"")}function Wn(e,t){(e.comments??(e.comments=[])).push(t),t.printed=!1,t.nodeDescription=Do(e);}function ne(e,t){t.leading=!0,t.trailing=!1,Wn(e,t);}function _e(e,t,r){t.leading=!1,t.trailing=!1,r&&(t.marker=r),Wn(e,t);}function te(e,t){t.leading=!1,t.trailing=!0,Wn(e,t);}function fo(e){return ae(e)&&e.value[0]==="*"&&/@(?:type|satisfies)\b/.test(e.value)}var lu=fo;function Eo(e){return [Cu,fu,To,Xn,$n,mu,yu,Oo,Lo,Hn,Fu,vo,Du,Eu,Vn].some(t=>t(e))}function Fo(e){return [Ao,fu,xo,Fu,Xn,$n,mu,yu,Eu,Io,wo,Hn,Mo,Vn,No].some(t=>t(e))}function Co(e){return [Cu,Xn,$n,go,ko,Du,Hn,Po,bo,Jo,Vn,Ro].some(t=>t(e))}function At(e,t){let r=(e.body||e.properties).find(({type:n})=>n!=="EmptyStatement");r?ne(r,t):_e(e,t);}function Yn(e,t){e.type==="BlockStatement"?At(e,t):ne(e,t);}function Ao({comment:e,followingNode:t}){return t&&lu(e)?(ne(t,e),!0):!1}function Xn({comment:e,precedingNode:t,enclosingNode:r,followingNode:n,text:s}){if((r==null?void 0:r.type)!=="IfStatement"||!n)return !1;if($e(s,O(e))===")")return te(t,e),!0;if(t===r.consequent&&n===r.alternate){if(t.type==="BlockStatement")te(t,e);else {let i=e.type==="SingleLine"||e.loc.start.line===e.loc.end.line,a=e.loc.start.line===t.loc.start.line;i&&a?_e(t,e,t.type==="ExpressionStatement"?zt:void 0):_e(r,e);}return !0}return n.type==="BlockStatement"?(At(n,e),!0):n.type==="IfStatement"?(Yn(n.consequent,e),!0):r.consequent===n?(ne(n,e),!0):!1}function $n({comment:e,precedingNode:t,enclosingNode:r,followingNode:n,text:s}){return (r==null?void 0:r.type)!=="WhileStatement"||!n?!1:$e(s,O(e))===")"?(te(t,e),!0):n.type==="BlockStatement"?(At(n,e),!0):r.body===n?(ne(n,e),!0):!1}function mu({comment:e,precedingNode:t,enclosingNode:r,followingNode:n}){return (r==null?void 0:r.type)!=="TryStatement"&&(r==null?void 0:r.type)!=="CatchClause"||!n?!1:r.type==="CatchClause"&&t?(te(t,e),!0):n.type==="BlockStatement"?(At(n,e),!0):n.type==="TryStatement"?(Yn(n.finalizer,e),!0):n.type==="CatchClause"?(Yn(n.body,e),!0):!1}function To({comment:e,enclosingNode:t,followingNode:r}){return J(t)&&(r==null?void 0:r.type)==="Identifier"?(ne(t,e),!0):!1}function xo({comment:e,precedingNode:t,enclosingNode:r,followingNode:n,text:s}){let u=t&&!rt(s,O(t),U(e));return (!t||!u)&&((r==null?void 0:r.type)==="ConditionalExpression"||(r==null?void 0:r.type)==="TSConditionalType")&&n?(ne(n,e),!0):!1}function go({comment:e,precedingNode:t,enclosingNode:r}){return fe(r)&&r.shorthand&&r.key===t&&r.value.type==="AssignmentPattern"?(te(r.value.left,e),!0):!1}var ho=new Set(["ClassDeclaration","ClassExpression","DeclareClass","DeclareInterface","InterfaceDeclaration","TSInterfaceDeclaration"]);function yu({comment:e,precedingNode:t,enclosingNode:r,followingNode:n}){if(ho.has(r==null?void 0:r.type)){if(b(r.decorators)&&(n==null?void 0:n.type)!=="Decorator")return te(w(!1,r.decorators,-1),e),!0;if(r.body&&n===r.body)return At(r.body,e),!0;if(n){if(r.superClass&&n===r.superClass&&t&&(t===r.id||t===r.typeParameters))return te(t,e),!0;for(let s of ["implements","extends","mixins"])if(r[s]&&n===r[s][0])return t&&(t===r.id||t===r.typeParameters||t===r.superClass)?te(t,e):_e(r,e,s),!0}}return !1}var So=new Set(["ClassMethod","ClassProperty","PropertyDefinition","TSAbstractPropertyDefinition","TSAbstractMethodDefinition","TSDeclareMethod","MethodDefinition","ClassAccessorProperty","AccessorProperty","TSAbstractAccessorProperty"]);function Du({comment:e,precedingNode:t,enclosingNode:r,text:n}){return r&&t&&$e(n,O(e))==="("&&(r.type==="Property"||r.type==="TSDeclareMethod"||r.type==="TSAbstractMethodDefinition")&&t.type==="Identifier"&&r.key===t&&$e(n,O(t))!==":"?(te(t,e),!0):(t==null?void 0:t.type)==="Decorator"&&So.has(r==null?void 0:r.type)?(te(t,e),!0):!1}var Bo=new Set(["FunctionDeclaration","FunctionExpression","ClassMethod","MethodDefinition","ObjectMethod"]);function bo({comment:e,precedingNode:t,enclosingNode:r,text:n}){return $e(n,O(e))!=="("?!1:t&&Bo.has(r==null?void 0:r.type)?(te(t,e),!0):!1}function Po({comment:e,enclosingNode:t,text:r}){if((t==null?void 0:t.type)!=="ArrowFunctionExpression")return !1;let n=Xe(r,O(e));return n!==!1&&r.slice(n,n+2)==="=>"?(_e(t,e),!0):!1}function ko({comment:e,enclosingNode:t,text:r}){return $e(r,O(e))!==")"?!1:t&&(du(t)&&X(t).length===0||it(t)&&Ce(t).length===0)?(_e(t,e),!0):((t==null?void 0:t.type)==="MethodDefinition"||(t==null?void 0:t.type)==="TSAbstractMethodDefinition")&&X(t.value).length===0?(_e(t.value,e),!0):!1}function fu({comment:e,precedingNode:t,enclosingNode:r,followingNode:n,text:s}){if((t==null?void 0:t.type)==="FunctionTypeParam"&&(r==null?void 0:r.type)==="FunctionTypeAnnotation"&&(n==null?void 0:n.type)!=="FunctionTypeParam")return te(t,e),!0;if(((t==null?void 0:t.type)==="Identifier"||(t==null?void 0:t.type)==="AssignmentPattern"||(t==null?void 0:t.type)==="ObjectPattern"||(t==null?void 0:t.type)==="ArrayPattern"||(t==null?void 0:t.type)==="RestElement")&&r&&du(r)&&$e(s,O(e))===")")return te(t,e),!0;if((r==null?void 0:r.type)==="FunctionDeclaration"&&(n==null?void 0:n.type)==="BlockStatement"){let u=(()=>{let i=X(r);if(i.length>0)return Xe(s,O(w(!1,i,-1)));let a=Xe(s,O(r.id));return a!==!1&&Xe(s,a+1)})();if(U(e)>u)return At(n,e),!0}return !1}function Eu({comment:e,enclosingNode:t}){return (t==null?void 0:t.type)==="LabeledStatement"?(ne(t,e),!0):!1}function Vn({comment:e,enclosingNode:t}){return ((t==null?void 0:t.type)==="ContinueStatement"||(t==null?void 0:t.type)==="BreakStatement")&&!t.label?(te(t,e),!0):!1}function Io({comment:e,precedingNode:t,enclosingNode:r}){return k(r)&&t&&r.callee===t&&r.arguments.length>0?(ne(r.arguments[0],e),!0):!1}function Lo({comment:e,precedingNode:t,enclosingNode:r,followingNode:n}){return (r==null?void 0:r.type)==="UnionTypeAnnotation"||(r==null?void 0:r.type)==="TSUnionType"?(Ht(e)&&(n.prettierIgnore=!0,e.unignore=!0),t?(te(t,e),!0):!1):(((n==null?void 0:n.type)==="UnionTypeAnnotation"||(n==null?void 0:n.type)==="TSUnionType")&&Ht(e)&&(n.types[0].prettierIgnore=!0,e.unignore=!0),!1)}function wo({comment:e,enclosingNode:t}){return fe(t)?(ne(t,e),!0):!1}function Hn({comment:e,enclosingNode:t,followingNode:r,ast:n,isLastComment:s}){var u;return ((u=n==null?void 0:n.body)==null?void 0:u.length)===0?(s?_e(n,e):ne(n,e),!0):(t==null?void 0:t.type)==="Program"&&t.body.length===0&&!b(t.directives)?(s?_e(t,e):ne(t,e),!0):(r==null?void 0:r.type)==="Program"&&r.body.length===0&&(t==null?void 0:t.type)==="ModuleExpression"?(_e(r,e),!0):!1}function Oo({comment:e,enclosingNode:t}){return (t==null?void 0:t.type)==="ForInStatement"||(t==null?void 0:t.type)==="ForOfStatement"?(ne(t,e),!0):!1}function Fu({comment:e,precedingNode:t,enclosingNode:r,text:n}){if((r==null?void 0:r.type)==="ImportSpecifier"||(r==null?void 0:r.type)==="ExportSpecifier")return ne(r,e),!0;let s=(t==null?void 0:t.type)==="ImportSpecifier"&&(r==null?void 0:r.type)==="ImportDeclaration",u=(t==null?void 0:t.type)==="ExportSpecifier"&&(r==null?void 0:r.type)==="ExportNamedDeclaration";return (s||u)&&z(n,O(e))?(te(t,e),!0):!1}function vo({comment:e,enclosingNode:t}){return (t==null?void 0:t.type)==="AssignmentPattern"?(ne(t,e),!0):!1}var _o=new Set(["VariableDeclarator","AssignmentExpression","TypeAlias","TSTypeAliasDeclaration"]),jo=new Set(["ObjectExpression","RecordExpression","ArrayExpression","TupleExpression","TemplateLiteral","TaggedTemplateExpression","ObjectTypeAnnotation","TSTypeLiteral"]);function Mo({comment:e,enclosingNode:t,followingNode:r}){return _o.has(t==null?void 0:t.type)&&r&&(jo.has(r.type)||ae(e))?(ne(r,e),!0):!1}function Ro({comment:e,enclosingNode:t,followingNode:r,text:n}){return !r&&((t==null?void 0:t.type)==="TSMethodSignature"||(t==null?void 0:t.type)==="TSDeclareFunction"||(t==null?void 0:t.type)==="TSAbstractMethodDefinition")&&$e(n,O(e))===";"?(te(t,e),!0):!1}function Cu({comment:e,enclosingNode:t,followingNode:r}){if(Ht(e)&&(t==null?void 0:t.type)==="TSMappedType"&&(r==null?void 0:r.type)==="TSTypeParameter"&&r.constraint)return t.prettierIgnore=!0,e.unignore=!0,!0}function Jo({comment:e,precedingNode:t,enclosingNode:r,followingNode:n}){return (r==null?void 0:r.type)!=="TSMappedType"?!1:(n==null?void 0:n.type)==="TSTypeParameter"&&n.name?(ne(n.name,e),!0):(t==null?void 0:t.type)==="TSTypeParameter"&&t.constraint?(te(t.constraint,e),!0):!1}function No({comment:e,enclosingNode:t,followingNode:r}){return !t||t.type!=="SwitchCase"||t.test||!r||r!==t.consequent[0]?!1:(r.type==="BlockStatement"&&$t(e)?At(r,e):_e(t,e),!0)}var du=j(["ArrowFunctionExpression","FunctionExpression","FunctionDeclaration","ObjectMethod","ClassMethod","TSDeclareFunction","TSCallSignatureDeclaration","TSConstructSignatureDeclaration","TSMethodSignature","TSConstructorType","TSFunctionType","TSDeclareMethod"]);function Uo(e){let t=`*${e.value}*`.split(` -`);return t.length>1&&t.every(r=>r.trimStart()[0]==="*")}var Au=Uo;function Tu(e,t){let r=e.node;if($t(r))return t.originalText.slice(U(r),O(r)).trimEnd();if(ae(r))return Au(r)?Go(r):["/*",xe(r.value),"*/"];throw new Error("Not a comment: "+JSON.stringify(r))}function Go(e){let t=e.value.split(` -`);return ["/*",B(C,t.map((r,n)=>n===0?r.trimEnd():" "+(ne===""||e===A||e===C||e===F;function $o(e,t,r){var v,_,R;let{node:n}=e;if(n.type==="JSXElement"&&ap(n))return [r("openingElement"),r("closingElement")];let s=n.type==="JSXElement"?r("openingElement"):r("openingFragment"),u=n.type==="JSXElement"?r("closingElement"):r("closingFragment");if(n.children.length===1&&n.children[0].type==="JSXExpressionContainer"&&(n.children[0].expression.type==="TemplateLiteral"||n.children[0].expression.type==="TaggedTemplateExpression"))return [s,...e.map(r,"children"),u];n.children=n.children.map(T=>op(T)?{type:"JSXText",value:" ",raw:" "}:T);let i=n.children.some(Y),a=n.children.filter(T=>T.type==="JSXExpressionContainer").length>1,o=n.type==="JSXElement"&&n.openingElement.attributes.length>1,p=K(s)||i||o||a,m=e.parent.rootMarker==="mdx",D=t.singleQuote?"{' '}":'{" "}',c=m?" ":P([D,F]," "),f=((_=(v=n.openingElement)==null?void 0:v.name)==null?void 0:_.name)==="fbt",l=Vo(e,t,r,c,f),h=n.children.some(T=>Zt(T));for(let T=l.length-2;T>=0;T--){let N=l[T]===""&&l[T+1]==="",Se=l[T]===C&&l[T+1]===""&&l[T+2]===C,V=(l[T]===F||l[T]===C)&&l[T+1]===""&&l[T+2]===c,Be=l[T]===c&&l[T+1]===""&&(l[T+2]===F||l[T+2]===C),Ee=l[T]===c&&l[T+1]===""&&l[T+2]===c,Cn=l[T]===F&&l[T+1]===""&&l[T+2]===C||l[T]===C&&l[T+1]===""&&l[T+2]===F;Se&&h||N||V||Ee||Cn?l.splice(T,2):Be&&l.splice(T+1,2);}for(;l.length>0&&Qn(w(!1,l,-1));)l.pop();for(;l.length>1&&Qn(l[0])&&Qn(l[1]);)l.shift(),l.shift();let g=[];for(let[T,N]of l.entries()){if(N===c){if(T===1&&l[T-1]===""){if(l.length===2){g.push(D);continue}g.push([D,C]);continue}else if(T===l.length-1){g.push(D);continue}else if(l[T-1]===""&&l[T-2]===C){g.push(D);continue}}g.push(N),K(N)&&(p=!0);}let S=h?St(g):y(g,{shouldBreak:!0});if(((R=t.cursorNode)==null?void 0:R.type)==="JSXText"&&n.children.includes(t.cursorNode)&&(S=[Bn,S,Bn]),m)return S;let I=y([s,E([C,S]),C,u]);return p?I:qe([y([s,...l,u]),I])}function Vo(e,t,r,n,s){let u=[];return e.each(({node:i,next:a})=>{if(i.type==="JSXText"){let o=oe(i);if(Zt(i)){let p=Pr.split(o,!0);p[0]===""&&(u.push(""),p.shift(),/\n/.test(p[0])?u.push(gu(s,p[1],i,a)):u.push(n),p.shift());let m;if(w(!1,p,-1)===""&&(p.pop(),m=p.pop()),p.length===0)return;for(let[D,c]of p.entries())D%2===1?u.push(A):u.push(c);m!==void 0?/\n/.test(m)?u.push(gu(s,w(!1,u,-1),i,a)):u.push(n):u.push(xu(s,w(!1,u,-1),i,a));}else /\n/.test(o)?o.match(/\n/g).length>1&&u.push("",C):u.push("",n);}else {let o=r();if(u.push(o),a&&Zt(a)){let m=Pr.trim(oe(a)),[D]=Pr.split(m);u.push(xu(s,D,i,a));}else u.push(C);}},"children"),u}function xu(e,t,r,n){return e?"":r.type==="JSXElement"&&!r.closingElement||(n==null?void 0:n.type)==="JSXElement"&&!n.closingElement?t.length===1?F:C:F}function gu(e,t,r,n){return e?C:t.length===1?r.type==="JSXElement"&&!r.closingElement||(n==null?void 0:n.type)==="JSXElement"&&!n.closingElement?C:F:C}var Ho=new Set(["ArrayExpression","TupleExpression","JSXAttribute","JSXElement","JSXExpressionContainer","JSXFragment","ExpressionStatement","CallExpression","OptionalCallExpression","ConditionalExpression","JsExpressionRoot"]);function Ko(e,t,r){let{parent:n}=e;if(Ho.has(n.type))return t;let s=e.match(void 0,i=>i.type==="ArrowFunctionExpression",k,i=>i.type==="JSXExpressionContainer"),u=we(e,r);return y([u?"":P("("),E([F,t]),F,u?"":P(")")],{shouldBreak:s})}function zo(e,t,r){let{node:n}=e,s=[];if(s.push(r("name")),n.value){let u;if(Q(n.value)){let i=oe(n.value),a=H(!1,H(!1,i.slice(1,-1),"'","'"),""",'"'),o=br(a,t.jsxSingleQuote);a=o==='"'?H(!1,a,'"',"""):H(!1,a,"'","'"),u=e.call(()=>pe(e,xe(o+a+o),t),"value");}else u=r("value");s.push("=",u);}return s}function Qo(e,t,r){let{node:n}=e,s=(u,i)=>u.type==="JSXEmptyExpression"||!d(u)&&(G(u)||ee(u)||u.type==="ArrowFunctionExpression"||u.type==="AwaitExpression"&&(s(u.argument,u)||u.argument.type==="JSXElement")||k(u)||u.type==="ChainExpression"&&k(u.expression)||u.type==="FunctionExpression"||u.type==="TemplateLiteral"||u.type==="TaggedTemplateExpression"||u.type==="DoExpression"||Y(i)&&(u.type==="ConditionalExpression"||ce(u)));return s(n.expression,e.parent)?y(["{",r("expression"),Ae,"}"]):y(["{",E([F,r("expression")]),F,Ae,"}"])}function Zo(e,t,r){var a,o;let{node:n}=e,s=d(n.name)||d(n.typeParameters);if(n.selfClosing&&n.attributes.length===0&&!s)return ["<",r("name"),r("typeParameters")," />"];if(((a=n.attributes)==null?void 0:a.length)===1&&n.attributes[0].value&&Q(n.attributes[0].value)&&!n.attributes[0].value.value.includes(` -`)&&!s&&!d(n.attributes[0]))return y(["<",r("name"),r("typeParameters")," ",...e.map(r,"attributes"),n.selfClosing?" />":">"]);let u=(o=n.attributes)==null?void 0:o.some(p=>p.value&&Q(p.value)&&p.value.value.includes(` -`)),i=t.singleAttributePerLine&&n.attributes.length>1?C:A;return y(["<",r("name"),r("typeParameters"),E(e.map(()=>[i,r()],"attributes")),...ep(n,t,s)],{shouldBreak:u})}function ep(e,t,r){return e.selfClosing?[A,"/>"]:tp(e,t,r)?[">"]:[F,">"]}function tp(e,t,r){let n=e.attributes.length>0&&d(w(!1,e.attributes,-1),x.Trailing);return e.attributes.length===0&&!r||(t.bracketSameLine||t.jsxBracketSameLine)&&(!r||e.attributes.length>0)&&!n}function rp(e,t,r){let{node:n}=e,s=[];s.push(""),s}function np(e,t){let{node:r}=e,n=d(r),s=d(r,x.Line),u=r.type==="JSXOpeningFragment";return [u?"<":""]}function sp(e,t,r){let n=pe(e,$o(e,t,r),t);return Ko(e,n,t)}function up(e,t){let{node:r}=e,n=d(r,x.Line);return [M(e,t,{indent:n}),n?C:""]}function ip(e,t,r){let{node:n}=e;return ["{",e.call(({node:s})=>{let u=["...",r()];return !d(s)||!zn(e)?u:[E([F,pe(e,u,t)]),F]},n.type==="JSXSpreadAttribute"?"argument":"expression"),"}"]}function hu(e,t,r){let{node:n}=e;if(n.type.startsWith("JSX"))switch(n.type){case"JSXAttribute":return zo(e,t,r);case"JSXIdentifier":return n.name;case"JSXNamespacedName":return B(":",[r("namespace"),r("name")]);case"JSXMemberExpression":return B(".",[r("object"),r("property")]);case"JSXSpreadAttribute":case"JSXSpreadChild":return ip(e,t,r);case"JSXExpressionContainer":return Qo(e,t,r);case"JSXFragment":case"JSXElement":return sp(e,t,r);case"JSXOpeningElement":return Zo(e,t,r);case"JSXClosingElement":return rp(e,t,r);case"JSXOpeningFragment":case"JSXClosingFragment":return np(e,t);case"JSXEmptyExpression":return up(e,t);case"JSXText":throw new Error("JSXText should be handled by JSXElement");default:throw new Oe(n,"JSX")}}function ap(e){if(e.children.length===0)return !0;if(e.children.length>1)return !1;let t=e.children[0];return t.type==="JSXText"&&!Zt(t)}function Zt(e){return e.type==="JSXText"&&(Pr.hasNonWhitespaceCharacter(oe(e))||!/\n/.test(oe(e)))}function op(e){return e.type==="JSXExpressionContainer"&&Q(e.expression)&&e.expression.value===" "&&!d(e.expression)}function Su(e){let{node:t,parent:r}=e;if(!Y(t)||!Y(r))return !1;let{index:n,siblings:s}=e,u;for(let i=n;i>0;i--){let a=s[i-1];if(!(a.type==="JSXText"&&!Zt(a))){u=a;break}}return (u==null?void 0:u.type)==="JSXExpressionContainer"&&u.expression.type==="JSXEmptyExpression"&&dt(u.expression)}function pp(e){return dt(e.node)||Su(e)}var kr=pp;var cp=0;function Ir(e,t,r){var _;let{node:n,parent:s,grandparent:u,key:i}=e,a=i!=="body"&&(s.type==="IfStatement"||s.type==="WhileStatement"||s.type==="SwitchStatement"||s.type==="DoWhileStatement"),o=n.operator==="|>"&&((_=e.root.extra)==null?void 0:_.__isUsingHackPipeline),p=Zn(e,r,t,!1,a);if(a)return p;if(o)return y(p);if(k(s)&&s.callee===n||s.type==="UnaryExpression"||J(s)&&!s.computed)return y([E([F,...p]),F]);let m=s.type==="ReturnStatement"||s.type==="ThrowStatement"||s.type==="JSXExpressionContainer"&&u.type==="JSXAttribute"||n.operator!=="|"&&s.type==="JsExpressionRoot"||n.type!=="NGPipeExpression"&&(s.type==="NGRoot"&&t.parser==="__ng_binding"||s.type==="NGMicrosyntaxExpression"&&u.type==="NGMicrosyntax"&&u.body.length===1)||n===s.body&&s.type==="ArrowFunctionExpression"||n!==s.body&&s.type==="ForStatement"||s.type==="ConditionalExpression"&&u.type!=="ReturnStatement"&&u.type!=="ThrowStatement"&&!k(u)||s.type==="TemplateLiteral",D=s.type==="AssignmentExpression"||s.type==="VariableDeclarator"||s.type==="ClassProperty"||s.type==="PropertyDefinition"||s.type==="TSAbstractPropertyDefinition"||s.type==="ClassPrivateProperty"||fe(s),c=ce(n.left)&&Vt(n.operator,n.left.operator);if(m||Ot(n)&&!c||!Ot(n)&&D)return y(p);if(p.length===0)return "";let f=Y(n.right),l=p.findIndex(R=>typeof R!="string"&&!Array.isArray(R)&&R.type===ue),h=p.slice(0,l===-1?1:l+1),g=p.slice(h.length,f?-1:void 0),S=Symbol("logicalChain-"+ ++cp),I=y([...h,E(g)],{id:S});if(!f)return I;let v=w(!1,p,-1);return y([I,mt(v,{groupId:S})])}function Zn(e,t,r,n,s){var h;let{node:u}=e;if(!ce(u))return [y(t())];let i=[];Vt(u.operator,u.left.operator)?i=e.call(g=>Zn(g,t,r,!0,s),"left"):i.push(y(t("left")));let a=Ot(u),o=(u.operator==="|>"||u.type==="NGPipeExpression"||lp(e,r))&&!Ie(r.originalText,u.right),p=u.type==="NGPipeExpression"?"|":u.operator,m=u.type==="NGPipeExpression"&&u.arguments.length>0?y(E([F,": ",B([A,": "],e.map(()=>De(2,y(t())),"arguments"))])):"",D;if(a)D=[p," ",t("right"),m];else {let S=p==="|>"&&((h=e.root.extra)==null?void 0:h.__isUsingHackPipeline)?e.call(I=>Zn(I,t,r,!0,s),"right"):t("right");D=[o?A:"",p,o?" ":A,S,m];}let{parent:c}=e,f=d(u.left,x.Trailing|x.Line),l=f||!(s&&u.type==="LogicalExpression")&&c.type!==u.type&&u.left.type!==u.type&&u.right.type!==u.type;if(i.push(o?"":" ",l?y(D,{shouldBreak:f}):D),n&&d(u)){let g=Bt(pe(e,i,r));return Array.isArray(g)||g.type===ye?mr(g):[g]}return i}function Ot(e){return e.type!=="LogicalExpression"?!1:!!(ee(e.right)&&e.right.properties.length>0||G(e.right)&&e.right.elements.length>0||Y(e.right))}var Bu=e=>e.type==="BinaryExpression"&&e.operator==="|";function lp(e,t){return (t.parser==="__vue_expression"||t.parser==="__vue_ts_expression")&&Bu(e.node)&&!e.hasAncestor(r=>!Bu(r)&&r.type!=="JsExpressionRoot")}var at=class extends Error{name="ArgExpansionBailout"};function mp(e,t,r,n){let{node:s}=e;return d(s,x.Dangling)?y([r,M(e,t,{indent:!0}),F,n]):[r,n]}function vt(e,t,r){let{node:n}=e,s=[],u=n.type==="TupleExpression"?"#[":"[",i="]",a=n.type==="TupleTypeAnnotation"&&n.types?"types":n.type==="TSTupleType"||n.type==="TupleTypeAnnotation"?"elementTypes":"elements",o=n[a];if(o.length===0)s.push(mp(e,t,u,i));else {let p=w(!1,o,-1),m=(p==null?void 0:p.type)!=="RestElement",D=p===null,c=Symbol("array"),f=!t.__inJestEach&&o.length>1&&o.every((g,S,I)=>{let v=g==null?void 0:g.type;if(!G(g)&&!ee(g))return !1;let _=I[S+1];if(_&&v!==_.type)return !1;let R=G(g)?"elements":"properties";return g[R]&&g[R].length>1}),l=es(n,t),h=m?D?",":le(t)?l?P(",","",{groupId:c}):P(","):"":"";s.push(y([u,E([F,l?Dp(e,t,r,h):[yp(e,t,a,r),h],M(e,t)]),F,i],{shouldBreak:f,id:c}));}return s.push($(e),q(e,r)),s}function es(e,t){return G(e)&&e.elements.length>1&&e.elements.every(r=>r&&(he(r)||Ar(r)&&!d(r.argument))&&!d(r,x.Trailing|x.Line,n=>!z(t.originalText,U(n),{backwards:!0})))}function bu({node:e},{originalText:t}){let r=s=>bt(t,Pt(t,s)),n=s=>t[s]===","?s:n(r(s+1));return kt(t,n(O(e)))}function yp(e,t,r,n){let s=[];return e.each(({node:u,isLast:i})=>{s.push(u?y(n()):""),i||s.push([",",A,u&&bu(e,t)?F:""]);},r),s}function Dp(e,t,r,n){let s=[];return e.each(({isLast:u,next:i})=>{s.push([r(),u?n:","]),u||s.push(bu(e,t)?[C,C]:d(i,x.Leading|x.Line)?C:A);},"elements"),St(s)}function fp(e,t,r){let{node:n}=e,s=Ce(n);if(s.length===0)return ["(",M(e,t),")"];if(Cp(s))return ["(",r(["arguments",0]),", ",r(["arguments",1]),")"];let u=!1,i=s.length-1,a=[];Sr(e,({node:c},f)=>{let l=r();f===i||(me(c,t)?(u=!0,l=[l,",",C,C]):l=[l,",",A]),a.push(l);});let p=!(n.type==="ImportExpression"||n.callee.type==="Import")&&le(t,"all")?",":"";function m(){return y(["(",E([A,...a]),p,A,")"],{shouldBreak:!0})}if(u||e.parent.type!=="Decorator"&&tu(s))return m();if(Fp(s)){let c=a.slice(1);if(c.some(K))return m();let f;try{f=r(Mn(n,0),{expandFirstArg:!0});}catch(l){if(l instanceof at)return m();throw l}return K(f)?[Te,qe([["(",y(f,{shouldBreak:!0}),", ",...c,")"],m()])]:qe([["(",f,", ",...c,")"],["(",y(f,{shouldBreak:!0}),", ",...c,")"],m()])}if(Ep(s,a,t)){let c=a.slice(0,-1);if(c.some(K))return m();let f;try{f=r(Mn(n,-1),{expandLastArg:!0});}catch(l){if(l instanceof at)return m();throw l}return K(f)?[Te,qe([["(",...c,y(f,{shouldBreak:!0}),")"],m()])]:qe([["(",...c,f,")"],["(",...c,y(f,{shouldBreak:!0}),")"],m()])}let D=["(",E([F,...a]),P(p),F,")"];return hr(e)?D:y(D,{shouldBreak:a.some(K)||u})}function er(e,t=!1){return ee(e)&&(e.properties.length>0||d(e))||G(e)&&(e.elements.length>0||d(e))||e.type==="TSTypeAssertion"&&er(e.expression)||Le(e)&&er(e.expression)||e.type==="FunctionExpression"||e.type==="ArrowFunctionExpression"&&(!e.returnType||!e.returnType.typeAnnotation||e.returnType.typeAnnotation.type!=="TSTypeReference"||dp(e.body))&&(e.body.type==="BlockStatement"||e.body.type==="ArrowFunctionExpression"&&er(e.body,!0)||ee(e.body)||G(e.body)||!t&&(k(e.body)||e.body.type==="ConditionalExpression")||Y(e.body))||e.type==="DoExpression"||e.type==="ModuleExpression"}function Ep(e,t,r){var u,i;let n=w(!1,e,-1);if(e.length===1){let a=w(!1,t,-1);if((u=a.label)!=null&&u.embed&&((i=a.label)==null?void 0:i.hug)!==!1)return !0}let s=w(!1,e,-2);return !d(n,x.Leading)&&!d(n,x.Trailing)&&er(n)&&(!s||s.type!==n.type)&&(e.length!==2||s.type!=="ArrowFunctionExpression"||!G(n))&&!(e.length>1&&es(n,r))}function Fp(e){if(e.length!==2)return !1;let[t,r]=e;return t.type==="ModuleExpression"&&Ap(r)?!0:!d(t)&&(t.type==="FunctionExpression"||t.type==="ArrowFunctionExpression"&&t.body.type==="BlockStatement")&&r.type!=="FunctionExpression"&&r.type!=="ArrowFunctionExpression"&&r.type!=="ConditionalExpression"&&Pu(r)&&!er(r)}function Pu(e){var t;if(e.type==="ParenthesizedExpression")return Pu(e.expression);if(Le(e)||e.type==="TypeCastExpression"){let{typeAnnotation:r}=e;return r.type==="TypeAnnotation"&&(r=r.typeAnnotation),r.type==="TSArrayType"&&(r=r.elementType,r.type==="TSArrayType"&&(r=r.elementType)),(r.type==="GenericTypeAnnotation"||r.type==="TSTypeReference")&&((t=r.typeParameters)==null?void 0:t.params.length)===1&&(r=r.typeParameters.params[0]),wt(r)&&ge(e.expression,1)}return it(e)&&Ce(e).length>1?!1:ce(e)?ge(e.left,1)&&ge(e.right,1):wn(e)||ge(e)}function Cp(e){return e.length===2&&e[0].type==="ArrowFunctionExpression"&&X(e[0]).length===0&&e[0].body.type==="BlockStatement"&&e[1].type==="ArrayExpression"&&!e.some(t=>d(t))}function dp(e){return e.type==="BlockStatement"&&(e.body.some(t=>t.type!=="EmptyStatement")||d(e,x.Dangling))}function Ap(e){return e.type==="ObjectExpression"&&e.properties.length===1&&fe(e.properties[0])&&e.properties[0].key.type==="Identifier"&&e.properties[0].key.name==="type"&&Q(e.properties[0].value)&&e.properties[0].value.value==="module"}var tr=fp;function ku(e,t,r){var p;let n=r("object"),s=ts(e,t,r),{node:u,parent:i}=e,a=e.findAncestor(m=>!(J(m)||m.type==="TSNonNullExpression")),o=a&&(a.type==="NewExpression"||a.type==="BindExpression"||a.type==="AssignmentExpression"&&a.left.type!=="Identifier")||u.computed||u.object.type==="Identifier"&&u.property.type==="Identifier"&&!J(i)||(i.type==="AssignmentExpression"||i.type==="VariableDeclarator")&&(k(u.object)&&u.object.arguments.length>0||u.object.type==="TSNonNullExpression"&&k(u.object.expression)&&u.object.expression.arguments.length>0||((p=n.label)==null?void 0:p.memberChain));return et(n.label,[n,o?s:y(E([F,s]))])}function ts(e,t,r){let n=r("property"),{node:s}=e,u=$(e);return s.computed?!s.property||he(s.property)?[u,"[",n,"]"]:y([u,"[",E([F,n]),F,"]"]):[u,".",n]}function Tp(e,t,r){let{parent:n}=e,s=!n||n.type==="ExpressionStatement",u=[];function i(L){let{originalText:W}=t,se=Xe(W,O(L));return W.charAt(se)===")"?se!==!1&&kt(W,se+1):me(L,t)}function a(L){let{node:W}=L;k(W)&&(Dt(W.callee)||k(W.callee))?(u.unshift({node:W,printed:[pe(L,[$(L),Ve(L,t,r),tr(L,t,r)],t),i(W)?C:""]}),L.call(se=>a(se),"callee")):Dt(W)?(u.unshift({node:W,needsParens:we(L,t),printed:pe(L,J(W)?ts(L,t,r):Lr(L,t,r),t)}),L.call(se=>a(se),"object")):W.type==="TSNonNullExpression"?(u.unshift({node:W,printed:pe(L,"!",t)}),L.call(se=>a(se),"expression")):u.unshift({node:W,printed:r()});}let{node:o}=e;u.unshift({node:o,printed:[$(e),Ve(e,t,r),tr(e,t,r)]}),o.callee&&e.call(L=>a(L),"callee");let p=[],m=[u[0]],D=1;for(;D0&&p.push(m);function f(L){return /^[A-Z]|^[$_]+$/.test(L)}function l(L){return L.length<=t.tabWidth}function h(L){var An;let W=(An=L[1][0])==null?void 0:An.node.computed;if(L[0].length===1){let ar=L[0][0].node;return ar.type==="ThisExpression"||ar.type==="Identifier"&&(f(ar.name)||s&&l(ar.name)||W)}let se=w(!1,L[0],-1).node;return J(se)&&se.property.type==="Identifier"&&(f(se.property.name)||W)}let g=p.length>=2&&!d(p[1][0].node)&&h(p);function S(L){let W=L.map(se=>se.printed);return L.length>0&&w(!1,L,-1).needsParens?["(",...W,")"]:W}function I(L){return L.length===0?"":E(y([C,B(C,L.map(S))]))}let v=p.map(S),_=v,R=g?3:2,T=p.flat(),N=T.slice(1,-1).some(L=>d(L.node,x.Leading))||T.slice(0,-1).some(L=>d(L.node,x.Trailing))||p[R]&&d(p[R][0].node,x.Leading);if(p.length<=R&&!N)return hr(e)?_:y(_);let Se=w(!1,p[g?1:0],-1).node,V=!k(Se)&&i(Se),Be=[S(p[0]),g?p.slice(1,2).map(S):"",V?C:"",I(p.slice(g?2:1))],Ee=u.map(({node:L})=>L).filter(k);function Cn(){let L=w(!1,w(!1,p,-1),-1).node,W=w(!1,v,-1);return k(L)&&K(W)&&Ee.slice(0,-1).some(se=>se.arguments.some(It))}let dn;return N||Ee.length>2&&Ee.some(L=>!L.arguments.every(W=>ge(W)))||v.slice(0,-1).some(K)||Cn()?dn=y(Be):dn=[K(_)||V?Te:"",qe([_,Be])],et({memberChain:!0},dn)}var Iu=Tp;function wr(e,t,r){var D;let{node:n,parent:s}=e,u=n.type==="NewExpression",i=n.type==="ImportExpression",a=$(e),o=Ce(n),p=o.length===1&&xr(o[0],t.originalText);if(p||o.length>0&&!u&&!i&&(xp(n,s)||Ct(n,s))){let c=[];if(Sr(e,()=>{c.push(r());}),!(p&&((D=c[0].label)!=null&&D.embed)))return [u?"new ":"",r("callee"),a,Ve(e,t,r),"(",B(", ",c),")"]}if(!i&&!u&&Dt(n.callee)&&!e.call(c=>we(c,t),"callee"))return Iu(e,t,r);let m=[u?"new ":"",i?"import":r("callee"),a,Ve(e,t,r),tr(e,t,r)];return i||k(n.callee)?y(m):m}function xp(e,t){if(e.callee.type!=="Identifier")return !1;if(e.callee.name==="require"){let r=Ce(e);return r.length===1&&Q(r[0])||r.length>1}if(e.callee.name==="define"){let r=Ce(e);return t.type==="ExpressionStatement"&&(r.length===1||r.length===2&&r[0].type==="ArrayExpression"||r.length===3&&Q(r[0])&&r[1].type==="ArrayExpression")}return !1}function gp(e,t,r){let n=t==='"'?"'":'"',u=H(!1,e,/\\(.)|(["'])/gs,(i,a,o)=>a===n?a:o===t?"\\"+o:o||(r&&/^[^\n\r"'0-7\\bfnrt-vx\u2028\u2029]$/.test(a)?a:"\\"+a));return t+u+t}var Lu=gp;function hp(e,t){let r=e.slice(1,-1),n=t.parser==="json"||t.parser==="json5"&&t.quoteProps==="preserve"&&!t.singleQuote?'"':t.__isInHtmlAttribute?"'":br(r,t.singleQuote);return Lu(r,n,!(t.parser==="css"||t.parser==="less"||t.parser==="scss"||t.__embeddedInHtml))}var Tt=hp;function Sp(e){return e.toLowerCase().replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(?=\d)/,"$1$2").replace(/^([+-]?[\d.]+)e[+-]?0+$/,"$1").replace(/^([+-])?\./,"$10.").replace(/(\.\d+?)0+(?=e|$)/,"$1").replace(/\.(?=e|$)/,"")}var He=Sp;function vu(e,t){let{node:r}=e;switch(r.type){case"RegExpLiteral":return wu(r);case"BigIntLiteral":return Or(r.extra.raw);case"NumericLiteral":return He(r.extra.raw);case"StringLiteral":return xe(Tt(r.extra.raw,t));case"NullLiteral":return "null";case"BooleanLiteral":return String(r.value);case"DecimalLiteral":return He(r.value)+"m";case"DirectiveLiteral":return Ou(r.extra.raw,t);case"Literal":{if(r.regex)return wu(r.regex);if(r.bigint)return Or(r.raw);if(r.decimal)return He(r.decimal)+"m";let{value:n}=r;return typeof n=="number"?He(r.raw):typeof n=="string"?Bp(e)?Ou(r.raw,t):xe(Tt(r.raw,t)):String(n)}}}function Bp(e){if(e.key!=="expression")return;let{parent:t}=e;return t.type==="ExpressionStatement"&&t.directive}function Or(e){return e.toLowerCase()}function wu({pattern:e,flags:t}){return t=[...t].sort().join(""),`/${e}/${t}`}function Ou(e,t){let r=e.slice(1,-1);if(r.includes('"')||r.includes("'"))return e;let n=t.singleQuote?"'":'"';return n+r+n}var vr=j(["Literal","BigIntLiteral","BooleanLiteral","DecimalLiteral","DirectiveLiteral","NullLiteral","NumericLiteral","RegExpLiteral","StringLiteral"]);function ft(e,t,r,n,s,u){let i=bp(e,t,r,n,u),a=u?r(u,{assignmentLayout:i}):"";switch(i){case"break-after-operator":return y([y(n),s,y(E([A,a]))]);case"never-break-after-operator":return y([y(n),s," ",a]);case"fluid":{let o=Symbol("assignment");return y([y(n),s,y(E(A),{id:o}),Ae,mt(a,{groupId:o})])}case"break-lhs":return y([n,s," ",y(a)]);case"chain":return [y(n),s,A,a];case"chain-tail":return [y(n),s,E([A,a])];case"chain-tail-arrow-chain":return [y(n),s,a];case"only-left":return n}}function ju(e,t,r){let{node:n}=e;return ft(e,t,r,r("left"),[" ",n.operator],"right")}function Mu(e,t,r){return ft(e,t,r,r("id")," =","init")}function bp(e,t,r,n,s){let{node:u}=e,i=u[s];if(!i)return "only-left";let a=!_r(i);if(e.match(_r,Ru,D=>!a||D.type!=="ExpressionStatement"&&D.type!=="VariableDeclaration"))return a?i.type==="ArrowFunctionExpression"&&i.body.type==="ArrowFunctionExpression"?"chain-tail-arrow-chain":"chain-tail":"chain";if(!a&&_r(i.right)||Ie(t.originalText,i))return "break-after-operator";if(i.type==="CallExpression"&&i.callee.name==="require"||t.parser==="json5"||t.parser==="json")return "never-break-after-operator";if(kp(u)||Ip(u)||Op(u)||rs(u)&&Rs(n))return "break-lhs";let m=Mp(u,n,t);return e.call(()=>Pp(e,t,r,m),s)?"break-after-operator":m||i.type==="TemplateLiteral"||i.type==="TaggedTemplateExpression"||i.type==="BooleanLiteral"||he(i)||i.type==="ClassExpression"?"never-break-after-operator":"fluid"}function Pp(e,t,r,n){let s=e.node;if(ce(s)&&!Ot(s))return !0;switch(s.type){case"StringLiteralTypeAnnotation":case"SequenceExpression":return !0;case"ConditionalExpression":{let{test:a}=s;return ce(a)&&!Ot(a)}case"ClassExpression":return b(s.decorators)}if(n)return !1;let u=s,i=[];for(;;)if(u.type==="UnaryExpression"||u.type==="AwaitExpression"||u.type==="YieldExpression"&&u.argument!==null)u=u.argument,i.push("argument");else if(u.type==="TSNonNullExpression")u=u.expression,i.push("expression");else break;return !!(Q(u)||e.call(()=>Ju(e,t,r),...i))}function kp(e){if(Ru(e)){let t=e.left||e.id;return t.type==="ObjectPattern"&&t.properties.length>2&&t.properties.some(r=>{var n;return fe(r)&&(!r.shorthand||((n=r.value)==null?void 0:n.type)==="AssignmentPattern")})}return !1}function _r(e){return e.type==="AssignmentExpression"}function Ru(e){return _r(e)||e.type==="VariableDeclarator"}function Ip(e){let t=wp(e);if(b(t)){let r=e.type==="TSTypeAliasDeclaration"?"constraint":"bound";if(t.length>1&&t.some(n=>n[r]||n.default))return !0}return !1}var Lp=j(["TSTypeAliasDeclaration","TypeAlias"]);function wp(e){var t;if(Lp(e))return (t=e.typeParameters)==null?void 0:t.params}function Op(e){if(e.type!=="VariableDeclarator")return !1;let{typeAnnotation:t}=e.id;if(!t||!t.typeAnnotation)return !1;let r=_u(t.typeAnnotation);return b(r)&&r.length>1&&r.some(n=>b(_u(n))||n.type==="TSConditionalType")}function rs(e){var t;return e.type==="VariableDeclarator"&&((t=e.init)==null?void 0:t.type)==="ArrowFunctionExpression"}var vp=j(["TSTypeReference","GenericTypeAnnotation"]);function _u(e){var t;if(vp(e))return (t=e.typeParameters)==null?void 0:t.params}function Ju(e,t,r,n=!1){var i;let{node:s}=e,u=()=>Ju(e,t,r,!0);if(s.type==="ChainExpression"||s.type==="TSNonNullExpression")return e.call(u,"expression");if(k(s)){if((i=wr(e,t,r).label)!=null&&i.memberChain)return !1;let o=Ce(s);return !(o.length===0||o.length===1&&jp(o[0],t))||Rp(s,r)?!1:e.call(u,"callee")}return J(s)?e.call(u,"object"):n&&(s.type==="Identifier"||s.type==="ThisExpression")}var _p=.25;function jp(e,{printWidth:t}){if(d(e))return !1;let r=t*_p;if(e.type==="ThisExpression"||e.type==="Identifier"&&e.name.length<=r||Ar(e)&&!d(e.argument))return !0;let n=e.type==="Literal"&&"regex"in e&&e.regex.pattern||e.type==="RegExpLiteral"&&e.pattern;return n?n.length<=r:Q(e)?oe(e).length<=r:e.type==="TemplateLiteral"?e.expressions.length===0&&e.quasis[0].value.raw.length<=r&&!e.quasis[0].value.raw.includes(` -`):vr(e)}function Mp(e,t,r){if(!fe(e))return !1;t=Bt(t);let n=3;return typeof t=="string"&&tt(t)1)return !0;if(r.length===1){let s=r[0];if(s.type==="TSUnionType"||s.type==="UnionTypeAnnotation"||s.type==="TSIntersectionType"||s.type==="IntersectionTypeAnnotation"||s.type==="TSTypeLiteral"||s.type==="ObjectTypeAnnotation")return !0}let n=e.typeParameters?"typeParameters":"typeArguments";if(K(t(n)))return !0}return !1}function Jp(e){var t;return (t=e.typeParameters??e.typeArguments)==null?void 0:t.params}function ot(e,t,r,n,s){let u=e.node,i=X(u),a=s?Ve(e,r,t):"";if(i.length===0)return [a,"(",M(e,r,{filter:l=>$e(r.originalText,O(l))===")"}),")"];let{parent:o}=e,p=Ct(o),m=ns(u),D=[];if(uu(e,(l,h)=>{let g=h===i.length-1;g&&u.rest&&D.push("..."),D.push(t()),!g&&(D.push(","),p||m?D.push(" "):me(i[h],r)?D.push(C,C):D.push(A));}),n&&!Up(e)){if(K(a)||K(D))throw new at;return y([Ut(a),"(",Ut(D),")"])}let c=i.every(l=>!b(l.decorators));return m&&c?[a,"(",...D,")"]:p?[a,"(",...D,")"]:(Tr(o)||Zs(o)||o.type==="TypeAlias"||o.type==="UnionTypeAnnotation"||o.type==="TSUnionType"||o.type==="IntersectionTypeAnnotation"||o.type==="FunctionTypeAnnotation"&&o.returnType===u)&&i.length===1&&i[0].name===null&&u.this!==i[0]&&i[0].typeAnnotation&&u.typeParameters===null&&wt(i[0].typeAnnotation)&&!u.rest?r.arrowParens==="always"?["(",...D,")"]:D:[a,"(",E([F,...D]),P(!su(u)&&le(r,"all")?",":""),F,")"]}function ns(e){if(!e)return !1;let t=X(e);if(t.length!==1)return !1;let[r]=t;return !d(r)&&(r.type==="ObjectPattern"||r.type==="ArrayPattern"||r.type==="Identifier"&&r.typeAnnotation&&(r.typeAnnotation.type==="TypeAnnotation"||r.typeAnnotation.type==="TSTypeAnnotation")&&ke(r.typeAnnotation.typeAnnotation)||r.type==="FunctionTypeParam"&&ke(r.typeAnnotation)&&r!==e.rest||r.type==="AssignmentPattern"&&(r.left.type==="ObjectPattern"||r.left.type==="ArrayPattern")&&(r.right.type==="Identifier"||ee(r.right)&&r.right.properties.length===0||G(r.right)&&r.right.elements.length===0))}function Np(e){let t;return e.returnType?(t=e.returnType,t.typeAnnotation&&(t=t.typeAnnotation)):e.typeAnnotation&&(t=e.typeAnnotation),t}function xt(e,t){var s;let r=Np(e);if(!r)return !1;let n=(s=e.typeParameters)==null?void 0:s.params;if(n){if(n.length>1)return !1;if(n.length===1){let u=n[0];if(u.constraint||u.default)return !1}}return X(e).length===1&&(ke(r)||K(t))}function Up(e){return e.match(t=>t.type==="ArrowFunctionExpression"&&t.body.type==="BlockStatement",(t,r)=>{if(t.type==="CallExpression"&&r==="arguments"&&t.arguments.length===1&&t.callee.type==="CallExpression"){let n=t.callee.callee;return n.type==="Identifier"||n.type==="MemberExpression"&&!n.computed&&n.object.type==="Identifier"&&n.property.type==="Identifier"}return !1},(t,r)=>t.type==="VariableDeclarator"&&r==="init"||t.type==="ExportDefaultDeclaration"&&r==="declaration"||t.type==="TSExportAssignment"&&r==="expression"||t.type==="AssignmentExpression"&&r==="right"&&t.left.type==="MemberExpression"&&t.left.object.type==="Identifier"&&t.left.object.name==="module"&&t.left.property.type==="Identifier"&&t.left.property.name==="exports",t=>t.type!=="VariableDeclaration"||t.kind==="const"&&t.declarations.length===1)}function Nu(e){let t=X(e);return t.length>1&&t.some(r=>r.type==="TSParameterProperty")}function ss(e){if(wt(e)||ke(e))return !0;if(e.type==="UnionTypeAnnotation"||e.type==="TSUnionType"){let t=e.types.filter(s=>s.type==="VoidTypeAnnotation"||s.type==="TSVoidKeyword"||s.type==="NullLiteralTypeAnnotation"||s.type==="TSNullKeyword").length,r=e.types.some(s=>s.type==="ObjectTypeAnnotation"||s.type==="TSTypeLiteral"||s.type==="GenericTypeAnnotation"||s.type==="TSTypeReference"),n=e.types.some(s=>d(s));if(e.types.length-1===t&&r&&!n)return !0}return !1}function Uu(e,t,r){let n=t.semi?";":"",{node:s}=e,u=[Z(e),"opaque type ",r("id"),r("typeParameters")];return s.supertype&&u.push(": ",r("supertype")),s.impltype&&u.push(" = ",r("impltype")),u.push(n),u}function jr(e,t,r){let n=t.semi?";":"",{node:s}=e,u=[Z(e)];u.push("type ",r("id"),r("typeParameters"));let i=s.type==="TSTypeAliasDeclaration"?"typeAnnotation":"right";return [ft(e,t,r,u," =",i),n]}function Mr(e,t,r){let n=!1;return y(e.map(({isFirst:s,previous:u,node:i,index:a})=>{let o=r();if(s)return o;let p=ke(i),m=ke(u);return m&&p?[" & ",n?E(o):o]:!m&&!p?E([" &",A,o]):(a>1&&(n=!0),[" & ",a>1?E(o):o])},"types"))}function Rr(e,t,r){let{node:n}=e,{parent:s}=e,u=s.type!=="TypeParameterInstantiation"&&s.type!=="TSTypeParameterInstantiation"&&s.type!=="GenericTypeAnnotation"&&s.type!=="TSTypeReference"&&s.type!=="TSTypeAssertion"&&s.type!=="TupleTypeAnnotation"&&s.type!=="TSTupleType"&&!(s.type==="FunctionTypeParam"&&!s.name&&e.grandparent.this!==s)&&!((s.type==="TypeAlias"||s.type==="VariableDeclarator"||s.type==="TSTypeAliasDeclaration")&&Ie(t.originalText,n)),i=ss(n),a=e.map(m=>{let D=r();return i||(D=De(2,D)),pe(m,D,t)},"types");if(i)return B(" | ",a);let o=u&&!Ie(t.originalText,n),p=[P([o?A:"","| "]),B([A,"| "],a)];return we(e,t)?y([E(p),F]):(s.type==="TupleTypeAnnotation"||s.type==="TSTupleType")&&s[s.type==="TupleTypeAnnotation"&&s.types?"types":"elementTypes"].length>1?y([E([P(["(",F]),p]),F,P(")")]):y(u?E(p):p)}function Gp(e){var n;let{node:t,parent:r}=e;return t.type==="FunctionTypeAnnotation"&&(Tr(r)||!((r.type==="ObjectTypeProperty"||r.type==="ObjectTypeInternalSlot")&&!r.variance&&!r.optional&&yt(r,t)||r.type==="ObjectTypeCallProperty"||((n=e.getParentNode(2))==null?void 0:n.type)==="DeclareFunction"))}function Jr(e,t,r){let{node:n}=e,s=[_t(e)];(n.type==="TSConstructorType"||n.type==="TSConstructSignatureDeclaration")&&s.push("new ");let u=ot(e,r,t,!1,!0),i=[];return n.type==="FunctionTypeAnnotation"?i.push(Gp(e)?" => ":": ",r("returnType")):i.push(q(e,r,n.returnType?"returnType":"typeAnnotation")),xt(n,i)&&(u=y(u)),s.push(u,i),y(s)}function Nr(e,t,r){return [r("objectType"),$(e),"[",r("indexType"),"]"]}function Ur(e,t,r){return ["infer ",r("typeParameter")]}function us(e,t,r){let{node:n}=e;return [n.postfix?"":r,q(e,t),n.postfix?r:""]}function Gr(e,t,r){let{node:n}=e;return ["...",...n.type==="TupleTypeSpreadElement"&&n.label?[r("label"),": "]:[],r("typeAnnotation")]}function qr(e,t,r){let{node:n}=e;return [n.variance?r("variance"):"",r("label"),n.optional?"?":"",": ",r("elementType")]}var qp=new WeakSet;function q(e,t,r="typeAnnotation"){let{node:{[r]:n}}=e;if(!n)return "";let s=!1;if(n.type==="TSTypeAnnotation"||n.type==="TypeAnnotation"){let u=e.call(Gu,r);(u==="=>"||u===":"&&d(n,x.Leading))&&(s=!0),qp.add(n);}return s?[" ",t(r)]:t(r)}var Gu=e=>e.match(t=>t.type==="TSTypeAnnotation",(t,r)=>(r==="returnType"||r==="typeAnnotation")&&(t.type==="TSFunctionType"||t.type==="TSConstructorType"))?"=>":e.match(t=>t.type==="TSTypeAnnotation",(t,r)=>r==="typeAnnotation"&&(t.type==="TSJSDocNullableType"||t.type==="TSJSDocNonNullableType"||t.type==="TSTypePredicate"))||e.match(t=>t.type==="TypeAnnotation",(t,r)=>r==="typeAnnotation"&&t.type==="Identifier",(t,r)=>r==="id"&&t.type==="DeclareFunction")||e.match(t=>t.type==="TypeAnnotation",(t,r)=>r==="bound"&&t.type==="TypeParameter"&&t.usesExtendsBound)?"":":";function Wr(e,t,r){let n=Gu(e);return n?[n," ",r("typeAnnotation")]:r("typeAnnotation")}function Yr(e){return [e("elementType"),"[]"]}function Xr({node:e},t){return ["typeof ",...e.type==="TSTypeQuery"?[t("exprName"),t("typeParameters")]:[t("argument")]]}function $r(e,t){let{node:r}=e;return [r.asserts?"asserts ":"",t("parameterName"),r.typeAnnotation?[" is ",q(e,t)]:""]}function $(e){let{node:t}=e;return !t.optional||t.type==="Identifier"&&t===e.parent.key?"":k(t)||J(t)&&t.computed||t.type==="OptionalIndexedAccessType"?"?.":"?"}function Vr(e){return e.node.definite||e.match(void 0,(t,r)=>r==="id"&&t.type==="VariableDeclarator"&&t.definite)?"!":""}var Wp=new Set(["DeclareClass","DeclareFunction","DeclareVariable","DeclareExportDeclaration","DeclareExportAllDeclaration","DeclareOpaqueType","DeclareTypeAlias","DeclareEnum","DeclareInterface"]);function Z(e){let{node:t}=e;return t.declare||Wp.has(t.type)&&e.parent.type!=="DeclareExportDeclaration"?"declare ":""}var Yp=new Set(["TSAbstractMethodDefinition","TSAbstractPropertyDefinition","TSAbstractAccessorProperty"]);function _t({node:e}){return e.abstract||Yp.has(e.type)?"abstract ":""}function Ve(e,t,r){let n=e.node;return n.typeArguments?r("typeArguments"):n.typeParameters?r("typeParameters"):""}function Lr(e,t,r){return ["::",r("callee")]}function pt(e,t,r){return e.type==="EmptyStatement"?";":e.type==="BlockStatement"||r?[" ",t]:E([A,t])}function Hr(e,t){return ["...",t("argument"),q(e,t)]}function jt(e){return e.accessibility?e.accessibility+" ":""}function is(e,t,r){let{node:n}=e;return y([B(A,e.map(r,"decorators")),Yu(n,t)?C:A])}function qu(e,t,r){return Xu(e.node)?[B(C,e.map(r,"declaration","decorators")),C]:""}function Wu(e,t,r){let{node:n,parent:s}=e,{decorators:u}=n;if(!b(u)||Xu(s)||kr(e))return "";let i=n.type==="ClassExpression"||n.type==="ClassDeclaration"||Yu(n,t);return [e.key==="declaration"&&Qs(s)?C:i?Te:"",B(A,e.map(r,"decorators")),A]}function Yu(e,t){return e.decorators.some(r=>z(t.originalText,O(r)))}function Xu(e){var r;if(e.type!=="ExportDefaultDeclaration"&&e.type!=="ExportNamedDeclaration"&&e.type!=="DeclareExportDeclaration")return !1;let t=(r=e.declaration)==null?void 0:r.decorators;return b(t)&&yt(e,t[0])}function $u(e,t,r){let{node:n}=e;return ["import",n.module?" module":"",os(n),Ku(e,t,r),Hu(e,t,r),Qu(e,t,r),t.semi?";":""]}var Vu=e=>e.type==="ExportDefaultDeclaration"||e.type==="DeclareExportDeclaration"&&e.default;function Kr(e,t,r){let{node:n}=e,s=[qu(e,t,r),Z(e),"export",Vu(n)?" default":""],{declaration:u,exported:i}=n;return d(n,x.Dangling)&&(s.push(" ",M(e,t)),gr(n)&&s.push(C)),u?s.push(" ",r("declaration")):(s.push(Vp(n)),n.type==="ExportAllDeclaration"||n.type==="DeclareExportAllDeclaration"?(s.push(" *"),i&&s.push(" as ",r("exported"))):s.push(Ku(e,t,r)),s.push(Hu(e,t,r),Qu(e,t,r))),s.push($p(n,t)),s}var Xp=j(["ClassDeclaration","FunctionDeclaration","TSInterfaceDeclaration","DeclareClass","DeclareFunction","TSDeclareFunction","EnumDeclaration"]);function $p(e,t){return t.semi&&(!e.declaration||Vu(e)&&!Xp(e.declaration))?";":""}function as(e,t=!0){return e&&e!=="value"?`${t?" ":""}${e}${t?"":" "}`:""}function os(e,t){return as(e.importKind,t)}function Vp(e){return as(e.exportKind)}function Hu(e,t,r){let{node:n}=e;if(!n.source)return "";let s=[];return zu(n,t)||s.push(" from"),s.push(" ",r("source")),s}function Ku(e,t,r){let{node:n}=e;if(zu(n,t))return "";let s=[" "];if(b(n.specifiers)){let u=[],i=[];e.each(()=>{let a=e.node.type;if(a==="ExportNamespaceSpecifier"||a==="ExportDefaultSpecifier"||a==="ImportNamespaceSpecifier"||a==="ImportDefaultSpecifier")u.push(r());else if(a==="ExportSpecifier"||a==="ImportSpecifier")i.push(r());else throw new Oe(n,"specifier")},"specifiers"),s.push(B(", ",u)),i.length>0&&(u.length>0&&s.push(", "),i.length>1||u.length>0||n.specifiers.some(o=>d(o))?s.push(y(["{",E([t.bracketSpacing?A:F,B([",",A],i)]),P(le(t)?",":""),t.bracketSpacing?A:F,"}"])):s.push(["{",t.bracketSpacing?" ":"",...i,t.bracketSpacing?" ":"","}"]));}else s.push("{}");return s}function zu(e,t){let{type:r,importKind:n,source:s,specifiers:u}=e;return r!=="ImportDeclaration"||b(u)||n==="type"?!1:!/{\s*}/.test(t.originalText.slice(U(e),U(s)))}function Qu(e,t,r){var i;let{node:n}=e,s=b(n.attributes)?"attributes":b(n.assertions)?"assertions":void 0;return s?[` ${s==="assertions"||(i=n.extra)!=null&&i.deprecatedAssertSyntax?"assert":"with"} {`,t.bracketSpacing?" ":"",B(", ",e.map(r,s)),t.bracketSpacing?" ":"","}"]:""}function Zu(e,t,r){let{node:n}=e,{type:s}=n,u=s.startsWith("Import"),i=u?"imported":"local",a=u?"local":"exported",o=n[i],p=n[a],m="",D="";return s==="ExportNamespaceSpecifier"||s==="ImportNamespaceSpecifier"?m="*":o&&(m=r(i)),p&&!Hp(n)&&(D=r(a)),[as(s==="ImportSpecifier"?n.importKind:n.exportKind,!1),m,m&&D?" as ":"",D]}function Hp(e){if(e.type!=="ImportSpecifier"&&e.type!=="ExportSpecifier")return !1;let{local:t,[e.type==="ImportSpecifier"?"imported":"exported"]:r}=e;if(t.type!==r.type||!Xs(t,r))return !1;if(Q(t))return t.value===r.value&&oe(t)===oe(r);switch(t.type){case"Identifier":return t.name===r.name;default:return !1}}function Kp(e){let t=[e];for(let r=0;rc[V]===n),l=c.type===n.type&&!f,h,g,S=0;do g=h||n,h=e.getParentNode(S),S++;while(h&&h.type===n.type&&a.every(V=>h[V]!==g));let I=h||c,v=g;if(s&&(Y(n[a[0]])||Y(o)||Y(p)||Kp(v))){D=!0,l=!0;let V=Ee=>[P("("),E([F,Ee]),F,P(")")],Be=Ee=>Ee.type==="NullLiteral"||Ee.type==="Literal"&&Ee.value===null||Ee.type==="Identifier"&&Ee.name==="undefined";m.push(" ? ",Be(o)?r(u):V(r(u))," : ",p.type===n.type||Be(p)?r(i):V(r(i)));}else {let V=[A,"? ",o.type===n.type?P("","("):"",De(2,r(u)),o.type===n.type?P("",")"):"",A,": ",p.type===n.type?r(i):De(2,r(i))];m.push(c.type!==n.type||c[i]===n||f?V:t.useTabs?Os(E(V)):De(Math.max(0,t.tabWidth-2),V));}let _=[u,i,...a].some(V=>d(n[V],Be=>ae(Be)&&rt(t.originalText,U(Be),O(Be)))),R=V=>c===I?y(V,{shouldBreak:_}):_?[V,Te]:V,T=!D&&(J(c)||c.type==="NGPipeExpression"&&c.left===n)&&!c.computed,N=Zp(e),Se=R([zp(e,t,r),l?m:E(m),s&&T&&!N?F:""]);return f||N?y([E([F,Se]),F]):Se}function ec(e,t,r=0){let n=0;for(let s=r;s0&&o(i),f();}function c(){a>0&&p(a),f();}function f(){i=0,a=0;}}function cs(e){let t=0,r=0,n=e.length;e:for(;n--;){let s=e[n];if(s===rr){r++;continue}for(let u=s.length-1;u>=0;u--){let i=s[u];if(i===" "||i===" ")t++;else {e[n]=s.slice(0,u+1);break e}}}if(t>0||r>0)for(e.length=n+1;r-- >0;)e.push(rr);return t}function zr(e,t,r,n,s,u){if(r===Number.POSITIVE_INFINITY)return !0;let i=t.length,a=[e],o=[];for(;r>=0;){if(a.length===0){if(i===0)return !0;a.push(t[--i]);continue}let{mode:p,doc:m}=a.pop();switch(Ze(m)){case Ke:o.push(m),r-=tt(m);break;case je:case ye:{let D=mr(m);for(let c=D.length-1;c>=0;c--)a.push({mode:p,doc:D[c]});break}case Me:case Re:case Je:case be:a.push({mode:p,doc:m.contents});break;case Qe:r+=cs(o);break;case ue:{if(u&&m.break)return !1;let D=m.break?de:p,c=m.expandedStates&&D===de?w(!1,m.expandedStates,-1):m.contents;a.push({mode:D,doc:c});break}case Fe:{let c=(m.groupId?s[m.groupId]||nt:p)===de?m.breakContents:m.flatContents;c&&a.push({mode:p,doc:c});break}case ie:if(p===de||m.hard)return !0;m.soft||(o.push(" "),r--);break;case Ne:n=!0;break;case Ue:if(n)return !1;break}}return !1}function ls(e,t){let r={},n=t.printWidth,s=ri(t.endOfLine),u=0,i=[{ind:ni(),mode:de,doc:e}],a=[],o=!1,p=[],m=0;for(Ms(e);i.length>0;){let{ind:c,mode:f,doc:l}=i.pop();switch(Ze(l)){case Ke:{let h=s!==` -`?H(!1,l,` -`,s):l;a.push(h),i.length>0&&(u+=tt(h));break}case je:for(let h=l.length-1;h>=0;h--)i.push({ind:c,mode:f,doc:l[h]});break;case ze:if(m>=2)throw new Error("There are too many 'cursor' in doc.");a.push(rr),m++;break;case Me:i.push({ind:rc(c,t),mode:f,doc:l.contents});break;case Re:i.push({ind:nc(c,l.n,t),mode:f,doc:l.contents});break;case Qe:u-=cs(a);break;case ue:switch(f){case nt:if(!o){i.push({ind:c,mode:l.break?de:nt,doc:l.contents});break}case de:{o=!1;let h={ind:c,mode:nt,doc:l.contents},g=n-u,S=p.length>0;if(!l.break&&zr(h,i,g,S,r))i.push(h);else if(l.expandedStates){let I=w(!1,l.expandedStates,-1);if(l.break){i.push({ind:c,mode:de,doc:I});break}else for(let v=1;v=l.expandedStates.length){i.push({ind:c,mode:de,doc:I});break}else {let _=l.expandedStates[v],R={ind:c,mode:nt,doc:_};if(zr(R,i,g,S,r)){i.push(R);break}}}else i.push({ind:c,mode:de,doc:l.contents});break}}l.id&&(r[l.id]=w(!1,i,-1).mode);break;case ye:{let h=n-u,{parts:g}=l;if(g.length===0)break;let[S,I]=g,v={ind:c,mode:nt,doc:S},_={ind:c,mode:de,doc:S},R=zr(v,[],h,p.length>0,r,!0);if(g.length===1){R?i.push(v):i.push(_);break}let T={ind:c,mode:nt,doc:I},N={ind:c,mode:de,doc:I};if(g.length===2){R?i.push(T,v):i.push(N,_);break}g.splice(0,2);let Se={ind:c,mode:f,doc:St(g)},V=g[0];zr({ind:c,mode:nt,doc:[S,I,V]},[],h,p.length>0,r,!0)?i.push(Se,T,v):R?i.push(Se,N,v):i.push(Se,N,_);break}case Fe:case Je:{let h=l.groupId?r[l.groupId]:f;if(h===de){let g=l.type===Fe?l.breakContents:l.negate?l.contents:E(l.contents);g&&i.push({ind:c,mode:f,doc:g});}if(h===nt){let g=l.type===Fe?l.flatContents:l.negate?E(l.contents):l.contents;g&&i.push({ind:c,mode:f,doc:g});}break}case Ne:p.push({ind:c,mode:f,doc:l.contents});break;case Ue:p.length>0&&i.push({ind:c,mode:f,doc:Sn});break;case ie:switch(f){case nt:if(l.hard)o=!0;else {l.soft||(a.push(" "),u+=1);break}case de:if(p.length>0){i.push({ind:c,mode:f,doc:l},...p.reverse()),p.length=0;break}l.literal?c.root?(a.push(s,c.root.value),u=c.root.length):(a.push(s),u=0):(u-=cs(a),a.push(s+c.value),u=c.length);break}break;case be:i.push({ind:c,mode:f,doc:l.contents});break;case Pe:break;default:throw new lt(l)}i.length===0&&p.length>0&&(i.push(...p.reverse()),p.length=0);}let D=a.indexOf(rr);if(D!==-1){let c=a.indexOf(rr,D+1),f=a.slice(0,D).join(""),l=a.slice(D+1,c).join(""),h=a.slice(c+1).join("");return {formatted:f+l+h,cursorNodeStart:f.length,cursorNodeText:l}}return {formatted:a.join("")}}function Qr(e,t,r){let{node:n}=e;if(n.type==="TemplateLiteral"&&ic(e)){let m=sc(e,r,t);if(m)return m}let u="expressions";n.type==="TSTemplateLiteralType"&&(u="types");let i=[],a=e.map(t,u),o=eu(n);o&&(a=a.map(m=>ls(m,{...r,printWidth:Number.POSITIVE_INFINITY}).formatted)),i.push(Ae,"`");let p=0;return e.each(({index:m,node:D})=>{if(i.push(t()),D.tail)return;let{tabWidth:c}=r,f=D.value.raw,l=f.includes(` -`)?ti(f,c):p;p=l;let h=a[m];if(!o){let S=n[u][m];(d(S)||J(S)||S.type==="ConditionalExpression"||S.type==="SequenceExpression"||Le(S)||ce(S))&&(h=[E([F,h]),F]);}let g=l===0&&f.endsWith(` -`)?De(Number.NEGATIVE_INFINITY,h):vs(h,l,c);i.push(y(["${",g,Ae,"}"]));},"quasis"),i.push("`"),i}function si(e){let t=e("quasi");return et(t.label&&{tagged:!0,...t.label},[e("tag"),e("typeParameters"),Ae,t])}function sc(e,t,r){let{node:n}=e,s=n.quasis[0].value.raw.trim().split(/\s*\|\s*/);if(s.length>1||s.some(u=>u.length>0)){t.__inJestEach=!0;let u=e.map(r,"expressions");t.__inJestEach=!1;let i=[],a=u.map(c=>"${"+ls(c,{...t,printWidth:Number.POSITIVE_INFINITY,endOfLine:"lf"}).formatted+"}"),o=[{hasLineBreak:!1,cells:[]}];for(let c=1;cc.cells.length)),m=Array.from({length:p}).fill(0),D=[{cells:s},...o.filter(c=>c.cells.length>0)];for(let{cells:c}of D.filter(f=>!f.hasLineBreak))for(let[f,l]of c.entries())m[f]=Math.max(m[f],tt(l));return i.push(Ae,"`",E([C,B(C,D.map(c=>B(" | ",c.cells.map((f,l)=>c.hasLineBreak?f:f+" ".repeat(m[l]-tt(f))))))]),C,"`"),i}}function uc(e,t){let{node:r}=e,n=t();return d(r)&&(n=y([E([F,n]),F])),["${",n,Ae,"}"]}function Rt(e,t){return e.map(r=>uc(r,t),"expressions")}function Zr(e,t){return ut(e,r=>typeof r=="string"?t?H(!1,r,/(\\*)`/g,"$1$1\\`"):ms(r):r)}function ms(e){return H(!1,e,/([\\`]|\${)/g,"\\$1")}function ic({node:e,parent:t}){let r=/^[fx]?(?:describe|it|test)$/;return t.type==="TaggedTemplateExpression"&&t.quasi===e&&t.tag.type==="MemberExpression"&&t.tag.property.type==="Identifier"&&t.tag.property.name==="each"&&(t.tag.object.type==="Identifier"&&r.test(t.tag.object.name)||t.tag.object.type==="MemberExpression"&&t.tag.object.property.type==="Identifier"&&(t.tag.object.property.name==="only"||t.tag.object.property.name==="skip")&&t.tag.object.object.type==="Identifier"&&r.test(t.tag.object.object.name))}function ac(e){let t=new WeakMap;return function(r){return t.has(r)||t.set(r,Symbol(e)),t.get(r)}}var en=ac;function oc(e){switch(e){case null:return "";case"PlusOptional":return "+?";case"MinusOptional":return "-?";case"Optional":return "?"}}function ui(e,t,r){let{node:n}=e;return y([n.variance?r("variance"):"","[",E([r("keyTparam")," in ",r("sourceType")]),"]",oc(n.optional),": ",r("propType")])}function ys(e,t){return e==="+"||e==="-"?e+t:t}function ii(e,t,r){let{node:n}=e,s=rt(t.originalText,U(n),U(n.typeParameter));return y(["{",E([t.bracketSpacing?A:F,y([r("typeParameter"),n.optional?ys(n.optional,"?"):"",n.typeAnnotation?": ":"",r("typeAnnotation")]),t.semi?P(";"):""]),M(e,t),t.bracketSpacing?A:F,"}"],{shouldBreak:s})}var nr=en("typeParameters");function pc(e,t,r){let{node:n}=e;return X(n).length===1&&n.type.startsWith("TS")&&!n[r][0].constraint&&e.parent.type==="ArrowFunctionExpression"&&!(t.filepath&&/\.ts$/.test(t.filepath))}function gt(e,t,r,n){let{node:s}=e;if(!s[n])return "";if(!Array.isArray(s[n]))return r(n);let u=e.getNode(2),i=u&&Ct(u),a=e.match(m=>!(m[n].length===1&&ke(m[n][0])),void 0,(m,D)=>D==="typeAnnotation",m=>m.type==="Identifier",rs);if(s[n].length===0||!a&&(i||s[n].length===1&&(s[n][0].type==="NullableTypeAnnotation"||ss(s[n][0]))))return ["<",B(", ",e.map(r,n)),cc(e,t),">"];let p=s.type==="TSTypeParameterInstantiation"?"":pc(e,t,n)?",":le(t)?P(","):"";return y(["<",E([F,B([",",A],e.map(r,n))]),p,F,">"],{id:nr(s)})}function cc(e,t){let{node:r}=e;if(!d(r,x.Dangling))return "";let n=!d(r,x.Line),s=M(e,t,{indent:!n});return n?s:[s,C]}function tn(e,t,r){let{node:n,parent:s}=e,u=[n.type==="TSTypeParameter"&&n.const?"const ":""],i=n.type==="TSTypeParameter"?r("name"):n.name;if(s.type==="TSMappedType")return s.readonly&&u.push(ys(s.readonly,"readonly")," "),u.push("[",i),n.constraint&&u.push(" in ",r("constraint")),s.nameType&&u.push(" as ",e.callParent(()=>r("nameType"))),u.push("]"),u;if(n.variance&&u.push(r("variance")),n.in&&u.push("in "),n.out&&u.push("out "),u.push(i),n.bound&&(n.usesExtendsBound&&u.push(" extends "),u.push(q(e,r,"bound"))),n.constraint){let a=Symbol("constraint");u.push(" extends",y(E(A),{id:a}),Ae,mt(r("constraint"),{groupId:a}));}return n.default&&u.push(" = ",r("default")),y(u)}var ai=new Proxy(()=>{},{get:()=>ai}),rn=ai;var nn=new WeakMap;function ct(e,t,r){let{node:n}=e;if(n.computed)return ["[",r("key"),"]"];let{parent:s}=e,{key:u}=n;if(t.quoteProps==="consistent"&&!nn.has(s)){let i=(s.properties||s.body||s.members).some(a=>!a.computed&&a.key&&Q(a.key)&&!_n(a,t));nn.set(s,i);}if((u.type==="Identifier"||he(u)&&jn(He(oe(u)))&&String(u.value)===He(oe(u))&&!(t.parser==="typescript"||t.parser==="babel-ts"))&&(t.parser==="json"||t.quoteProps==="consistent"&&nn.get(s))){let i=Tt(JSON.stringify(u.type==="Identifier"?u.name:u.value.toString()),t);return e.call(a=>pe(a,i,t),"key")}return _n(n,t)&&(t.quoteProps==="as-needed"||t.quoteProps==="consistent"&&!nn.get(s))?e.call(i=>pe(i,/^\d/.test(u.value)?He(u.value):u.value,t),"key"):r("key")}function oi(e,t,r){let{node:n}=e;return n.shorthand?r("value"):ft(e,t,r,ct(e,t,r),":","value")}var lc=e=>e.type==="ObjectMethod"||e.type==="ClassMethod"||e.type==="ClassPrivateMethod"||e.type==="MethodDefinition"||e.type==="TSAbstractMethodDefinition"||e.type==="TSDeclareMethod"||(e.type==="Property"||e.type==="ObjectProperty")&&(e.method||e.kind==="get"||e.kind==="set"),mc=e=>e.node.type==="FunctionExpression"&&e.key==="value"&&lc(e.parent);function sn(e,t,r,n){if(mc(e))return un(e,r,t);let{node:s}=e,u=!1;if((s.type==="FunctionDeclaration"||s.type==="FunctionExpression")&&(n!=null&&n.expandLastArg)){let{parent:m}=e;k(m)&&(Ce(m).length>1||X(s).every(D=>D.type==="Identifier"&&!D.typeAnnotation))&&(u=!0);}let i=[Z(e),s.async?"async ":"",`function${s.generator?"*":""} `,s.id?t("id"):""],a=ot(e,t,r,u),o=on(e,t),p=xt(s,o);return i.push(Ve(e,r,t),y([p?y(a):a,o]),s.body?" ":"",t("body")),r.semi&&(s.declare||!s.body)&&i.push(";"),i}function sr(e,t,r){let{node:n}=e,{kind:s}=n,u=n.value||n,i=[];return !s||s==="init"||s==="method"||s==="constructor"?u.async&&i.push("async "):(rn.ok(s==="get"||s==="set"),i.push(s," ")),u.generator&&i.push("*"),i.push(ct(e,t,r),n.optional||n.key.optional?"?":"",n===u?un(e,t,r):r("value")),i}function un(e,t,r){let{node:n}=e,s=ot(e,r,t),u=on(e,r),i=Nu(n),a=xt(n,u),o=[Ve(e,t,r),y([i?y(s,{shouldBreak:!0}):a?y(s):s,u])];return n.body?o.push(" ",r("body")):o.push(t.semi?";":""),o}function yc(e){let t=X(e);return t.length===1&&!e.typeParameters&&!d(e,x.Dangling)&&t[0].type==="Identifier"&&!t[0].typeAnnotation&&!d(t[0])&&!t[0].optional&&!e.predicate&&!e.returnType}function an(e,t){if(t.arrowParens==="always")return !1;if(t.arrowParens==="avoid"){let{node:r}=e;return yc(r)}return !1}function on(e,t){let{node:r}=e,s=[q(e,t,"returnType")];return r.predicate&&s.push(t("predicate")),s}function pi(e,t,r){let{node:n}=e,s=t.semi?";":"",u=[];if(n.argument){let o=r("argument");Dc(t,n.argument)?o=["(",E([C,o]),C,")"]:(ce(n.argument)||n.argument.type==="SequenceExpression")&&(o=y([P("("),E([F,o]),F,P(")")])),u.push(" ",o);}let i=d(n,x.Dangling),a=s&&i&&d(n,x.Last|x.Line);return a&&u.push(s),i&&u.push(" ",M(e,t)),a||u.push(s),u}function ci(e,t,r){return ["return",pi(e,t,r)]}function li(e,t,r){return ["throw",pi(e,t,r)]}function Dc(e,t){if(Ie(e.originalText,t)||d(t,x.Leading,r=>rt(e.originalText,U(r),O(r)))&&!Y(t))return !0;if(Lt(t)){let r=t,n;for(;n=zs(r);)if(r=n,Ie(e.originalText,r))return !0}return !1}var mi=j(["ClassProperty","PropertyDefinition","ClassPrivateProperty","ClassAccessorProperty","AccessorProperty","TSAbstractPropertyDefinition","TSAbstractAccessorProperty"]);function pn(e,t,r){let{node:n}=e,s=[Z(e),_t(e),"class"],u=d(n.id,x.Trailing)||d(n.typeParameters,x.Trailing)||d(n.superClass)||b(n.extends)||b(n.mixins)||b(n.implements),i=[],a=[];if(n.id&&i.push(" ",r("id")),i.push(r("typeParameters")),n.superClass){let o=[Ec(e,t,r),r("superTypeParameters")],p=e.call(m=>["extends ",pe(m,o,t)],"superClass");u?a.push(A,y(p)):a.push(" ",p);}else a.push(Ds(e,t,r,"extends"));if(a.push(Ds(e,t,r,"mixins"),Ds(e,t,r,"implements")),u){let o;Di(n)?o=[...i,E(a)]:o=E([...i,a]),s.push(y(o,{id:yi(n)}));}else s.push(...i,...a);return s.push(" ",r("body")),s}var yi=en("heritageGroup");function fs(e){return P(C,"",{groupId:yi(e)})}function fc(e){return ["extends","mixins","implements"].reduce((t,r)=>t+(Array.isArray(e[r])?e[r].length:0),e.superClass?1:0)>1}function Di(e){return e.typeParameters&&!d(e.typeParameters,x.Trailing|x.Line)&&!fc(e)}function Ds(e,t,r,n){let{node:s}=e;if(!b(s[n]))return "";let u=M(e,t,{marker:n});return [Di(s)?P(" ",A,{groupId:nr(s.typeParameters)}):A,u,u&&C,n,y(E([A,B([",",A],e.map(r,n))]))]}function Ec(e,t,r){let n=r("superClass"),{parent:s}=e;return s.type==="AssignmentExpression"?y(P(["(",E([F,n]),F,")"],n)):n}function cn(e,t,r){let{node:n}=e,s=[];return b(n.decorators)&&s.push(is(e,t,r)),s.push(jt(n)),n.static&&s.push("static "),s.push(_t(e)),n.override&&s.push("override "),s.push(sr(e,t,r)),s}function ln(e,t,r){let{node:n}=e,s=[],u=t.semi?";":"";b(n.decorators)&&s.push(is(e,t,r)),s.push(jt(n),Z(e)),n.static&&s.push("static "),s.push(_t(e)),n.override&&s.push("override "),n.readonly&&s.push("readonly "),n.variance&&s.push(r("variance")),(n.type==="ClassAccessorProperty"||n.type==="AccessorProperty"||n.type==="TSAbstractAccessorProperty")&&s.push("accessor "),s.push(ct(e,t,r),$(e),Vr(e),q(e,r));let i=n.type==="TSAbstractPropertyDefinition"||n.type==="TSAbstractAccessorProperty";return [ft(e,t,r,s," =",i?void 0:"value"),u]}function fi(e,t,r){let{node:n}=e,s=[];return e.each(({node:u,next:i,isLast:a})=>{s.push(r()),!t.semi&&mi(u)&&Fc(u,i)&&s.push(";"),a||(s.push(C),me(u,t)&&s.push(C));},"body"),d(n,x.Dangling)&&s.push(M(e,t)),[b(n.body)?fs(e.parent):"","{",s.length>0?[E([C,s]),C]:"","}"]}function Fc(e,t){var s;let{type:r,name:n}=e.key;if(!e.computed&&r==="Identifier"&&(n==="static"||n==="get"||n==="set")&&!e.value&&!e.typeAnnotation)return !0;if(!t||t.static||t.accessibility)return !1;if(!t.computed){let u=(s=t.key)==null?void 0:s.name;if(u==="in"||u==="instanceof")return !0}if(mi(t)&&t.variance&&!t.static&&!t.declare)return !0;switch(t.type){case"ClassProperty":case"PropertyDefinition":case"TSAbstractPropertyDefinition":return t.computed;case"MethodDefinition":case"TSAbstractMethodDefinition":case"ClassMethod":case"ClassPrivateMethod":{if((t.value?t.value.async:t.async)||t.kind==="get"||t.kind==="set")return !1;let i=t.value?t.value.generator:t.generator;return !!(t.computed||i)}case"TSIndexSignature":return !0}return !1}function Et(e,t,r){var R;let n=t.semi?";":"",{node:s}=e,u=s.type==="ObjectTypeAnnotation",i=s.type==="TSEnumDeclaration"||s.type==="EnumBooleanBody"||s.type==="EnumNumberBody"||s.type==="EnumStringBody"||s.type==="EnumSymbolBody",a=[s.type==="TSTypeLiteral"||i?"members":s.type==="TSInterfaceBody"?"body":"properties"];u&&a.push("indexers","callProperties","internalSlots");let o=a.flatMap(T=>e.map(({node:N})=>({node:N,printed:r(),loc:U(N)}),T));a.length>1&&o.sort((T,N)=>T.loc-N.loc);let{parent:p,key:m}=e,D=u&&m==="body"&&(p.type==="InterfaceDeclaration"||p.type==="DeclareInterface"||p.type==="DeclareClass"),c=s.type==="TSInterfaceBody"||i||D||s.type==="ObjectPattern"&&p.type!=="FunctionDeclaration"&&p.type!=="FunctionExpression"&&p.type!=="ArrowFunctionExpression"&&p.type!=="ObjectMethod"&&p.type!=="ClassMethod"&&p.type!=="ClassPrivateMethod"&&p.type!=="AssignmentPattern"&&p.type!=="CatchClause"&&s.properties.some(T=>T.value&&(T.value.type==="ObjectPattern"||T.value.type==="ArrayPattern"))||s.type!=="ObjectPattern"&&o.length>0&&rt(t.originalText,U(s),o[0].loc),f=D?";":s.type==="TSInterfaceBody"||s.type==="TSTypeLiteral"?P(n,";"):",",l=s.type==="RecordExpression"?"#{":s.exact?"{|":"{",h=s.exact?"|}":"}",g=[],S=o.map(T=>{let N=[...g,y(T.printed)];return g=[f,A],(T.node.type==="TSPropertySignature"||T.node.type==="TSMethodSignature"||T.node.type==="TSConstructSignatureDeclaration"||T.node.type==="TSCallSignatureDeclaration")&&d(T.node,x.PrettierIgnore)&&g.shift(),me(T.node,t)&&g.push(C),N});if(s.inexact||s.hasUnknownMembers){let T;if(d(s,x.Dangling)){let N=d(s,x.Line);T=[M(e,t),N||z(t.originalText,O(w(!1,Kt(s),-1)))?C:A,"..."];}else T=["..."];S.push([...g,...T]);}let I=(R=w(!1,o,-1))==null?void 0:R.node,v=!(s.inexact||s.hasUnknownMembers||I&&(I.type==="RestElement"||(I.type==="TSPropertySignature"||I.type==="TSCallSignatureDeclaration"||I.type==="TSMethodSignature"||I.type==="TSConstructSignatureDeclaration")&&d(I,x.PrettierIgnore))),_;if(S.length===0){if(!d(s,x.Dangling))return [l,h,q(e,r)];_=y([l,M(e,t,{indent:!0}),F,h,$(e),q(e,r)]);}else _=[D&&b(s.properties)?fs(p):"",l,E([t.bracketSpacing?A:F,...S]),P(v&&(f!==","||le(t))?f:""),t.bracketSpacing?A:F,h,$(e),q(e,r)];return e.match(T=>T.type==="ObjectPattern"&&!b(T.decorators),Es)||ke(s)&&(e.match(void 0,(T,N)=>N==="typeAnnotation",(T,N)=>N==="typeAnnotation",Es)||e.match(void 0,(T,N)=>T.type==="FunctionTypeParam"&&N==="typeAnnotation",Es))||!c&&e.match(T=>T.type==="ObjectPattern",T=>T.type==="AssignmentExpression"||T.type==="VariableDeclarator")?_:y(_,{shouldBreak:c})}function Es(e,t){return (t==="params"||t==="parameters"||t==="this"||t==="rest")&&ns(e)}var Fs=new WeakMap;function Ei(e){return Fs.has(e)||Fs.set(e,e.type==="ConditionalExpression"&&!re(e,t=>t.type==="ObjectExpression")),Fs.get(e)}var Fi=e=>e.type==="SequenceExpression";function Ci(e,t,r,n={}){let s=[],u,i=[],a=!1,o=!n.expandLastArg&&e.node.body.type==="ArrowFunctionExpression",p;(function g(){let{node:S}=e,I=Cc(e,t,r,n);if(s.length===0)s.push(I);else {let{leading:v,trailing:_}=Nn(e,t);s.push([v,I]),i.unshift(_);}o&&(a||(a=S.returnType&&X(S).length>0||S.typeParameters||X(S).some(v=>v.type!=="Identifier"))),!o||S.body.type!=="ArrowFunctionExpression"?(u=r("body",n),p=S.body):e.call(g,"body");})();let m=!Ie(t.originalText,p)&&(Fi(p)||dc(p,u,t)||!a&&Ei(p)),D=e.key==="callee"&&it(e.parent),c=Symbol("arrow-chain"),f=Ac(e,n,{signatureDocs:s,shouldBreak:a}),l,h=!1;return o&&(D||n.assignmentLayout)&&(h=!0,l=n.assignmentLayout==="chain-tail-arrow-chain"||D&&!m),u=Tc(e,t,n,{bodyDoc:u,bodyComments:i,functionBody:p,shouldPutBodyOnSameLine:m}),y([y(h?E([F,f]):f,{shouldBreak:l,id:c})," =>",o?mt(u,{groupId:c}):y(u),o&&D?P(F,"",{groupId:c}):""])}function Cc(e,t,r,n){let{node:s}=e,u=[];if(s.async&&u.push("async "),an(e,t))u.push(r(["params",0]));else {let a=n.expandLastArg||n.expandFirstArg,o=on(e,r);if(a){if(K(o))throw new at;o=y(Ut(o));}u.push(y([ot(e,r,t,a,!0),o]));}let i=M(e,t,{filter(a){let o=Xe(t.originalText,O(a));return o!==!1&&t.originalText.slice(o,o+2)==="=>"}});return i&&u.push(" ",i),u}function dc(e,t,r){var n,s;return G(e)||ee(e)||e.type==="ArrowFunctionExpression"||e.type==="DoExpression"||e.type==="BlockStatement"||Y(e)||((n=t.label)==null?void 0:n.hug)!==!1&&(((s=t.label)==null?void 0:s.embed)||xr(e,r.originalText))}function Ac(e,t,{signatureDocs:r,shouldBreak:n}){if(r.length===1)return r[0];let{parent:s,key:u}=e;return u!=="callee"&&it(s)||ce(s)?y([r[0]," =>",E([A,B([" =>",A],r.slice(1))])],{shouldBreak:n}):u==="callee"&&it(s)||t.assignmentLayout?y(B([" =>",A],r),{shouldBreak:n}):y(E(B([" =>",A],r)),{shouldBreak:n})}function Tc(e,t,r,{bodyDoc:n,bodyComments:s,functionBody:u,shouldPutBodyOnSameLine:i}){let{node:a,parent:o}=e,p=r.expandLastArg&&le(t,"all")?P(","):"",m=(r.expandLastArg||o.type==="JSXExpressionContainer")&&!d(a)?F:"";return i&&Ei(u)?[" ",y([P("","("),E([F,n]),P("",")"),p,m]),s]:(Fi(u)&&(n=y(["(",E([F,n]),F,")"])),i?[" ",n,s]:[E([A,n,s]),p,m])}function ur(e,t,r,n){let{node:s}=e,u=[],i=xc(s[n]);return e.each(({node:a})=>{a.type!=="EmptyStatement"&&(u.push(r()),a!==i&&(u.push(C),me(a,t)&&u.push(C)));},n),u}function xc(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if(r.type!=="EmptyStatement")return r}}function mn(e,t,r){let{node:n}=e,s=[];n.type==="StaticBlock"&&s.push("static "),s.push("{");let u=Cs(e,t,r);if(u)s.push(E([C,u]),C);else {let{parent:i}=e,a=e.grandparent;i.type==="ArrowFunctionExpression"||i.type==="FunctionExpression"||i.type==="FunctionDeclaration"||i.type==="ObjectMethod"||i.type==="ClassMethod"||i.type==="ClassPrivateMethod"||i.type==="ForStatement"||i.type==="WhileStatement"||i.type==="DoWhileStatement"||i.type==="DoExpression"||i.type==="CatchClause"&&!a.finalizer||i.type==="TSModuleDeclaration"||i.type==="TSDeclareFunction"||n.type==="StaticBlock"||s.push(C);}return s.push("}"),s}function Cs(e,t,r){var o;let{node:n}=e,s=b(n.directives),u=n.body.some(p=>p.type!=="EmptyStatement"),i=d(n,x.Dangling);if(!s&&!u&&!i)return "";let a=[];return s&&(a.push(ur(e,t,r,"directives")),(u||i)&&(a.push(C),me(w(!1,n.directives,-1),t)&&a.push(C))),u&&a.push(ur(e,t,r,"body")),i&&a.push(M(e,t)),n.type==="Program"&&((o=e.parent)==null?void 0:o.type)!=="ModuleExpression"&&a.push(C),a}function di(e,t){if(t.semi||ds(e,t)||Ts(e,t))return !1;let{node:r,key:n,parent:s}=e;return !!(r.type==="ExpressionStatement"&&(n==="body"&&(s.type==="Program"||s.type==="BlockStatement"||s.type==="StaticBlock"||s.type==="TSModuleBlock")||n==="consequent"&&s.type==="SwitchCase")&&e.call(()=>Ai(e,t),"expression"))}function Ai(e,t){let{node:r}=e;switch(r.type){case"ParenthesizedExpression":case"TypeCastExpression":case"ArrayExpression":case"ArrayPattern":case"TemplateLiteral":case"TemplateElement":case"RegExpLiteral":return !0;case"ArrowFunctionExpression":if(!an(e,t))return !0;break;case"UnaryExpression":{let{prefix:n,operator:s}=r;if(n&&(s==="+"||s==="-"))return !0;break}case"BindExpression":if(!r.object)return !0;break;case"Literal":if(r.regex)return !0;break;default:if(Y(r))return !0}return we(e,t)?!0:Lt(r)?e.call(()=>Ai(e,t),...dr(r)):!1}function ds({node:e,parent:t},r){return (r.parentParser==="markdown"||r.parentParser==="mdx")&&e.type==="ExpressionStatement"&&Y(e.expression)&&t.type==="Program"&&t.body.length===1}function As(e){switch(e.type){case"MemberExpression":switch(e.property.type){case"Identifier":case"NumericLiteral":case"StringLiteral":return As(e.object)}return !1;case"Identifier":return !0;default:return !1}}function Ts({node:e,parent:t},r){return (r.parser==="__vue_event_binding"||r.parser==="__vue_ts_event_binding")&&e.type==="ExpressionStatement"&&t.type==="Program"&&t.body.length===1}function Ti(e,t,r){let n=[r("expression")];return Ts(e,t)?As(e.node.expression)&&n.push(";"):ds(e,t)||t.semi&&n.push(";"),d(e.node,x.Dangling,({marker:s})=>s===zt)&&n.push(" ",M(e,t,{marker:zt})),n}function xi(e,t,r){if(t.__isVueBindings||t.__isVueForBindingLeft){let n=e.map(r,"program","body",0,"params");if(n.length===1)return n[0];let s=B([",",A],n);return t.__isVueForBindingLeft?["(",E([F,y(s)]),F,")"]:s}if(t.__isEmbeddedTypescriptGenericParameters){let n=e.map(r,"program","body",0,"typeParameters","params");return B([",",A],n)}}function gi(e,t,r,n){let{node:s}=e;if(vr(s))return vu(e,t);let u=t.semi?";":"",i=[];switch(s.type){case"JsExpressionRoot":return r("node");case"JsonRoot":return [r("node"),C];case"File":return xi(e,t,r)??r("program");case"Program":return Cs(e,t,r);case"EmptyStatement":return "";case"ExpressionStatement":return Ti(e,t,r);case"ChainExpression":return r("expression");case"ParenthesizedExpression":return !d(s.expression)&&(ee(s.expression)||G(s.expression))?["(",r("expression"),")"]:y(["(",E([F,r("expression")]),F,")"]);case"AssignmentExpression":return ju(e,t,r);case"VariableDeclarator":return Mu(e,t,r);case"BinaryExpression":case"LogicalExpression":return Ir(e,t,r);case"AssignmentPattern":return [r("left")," = ",r("right")];case"OptionalMemberExpression":case"MemberExpression":return ku(e,t,r);case"MetaProperty":return [r("meta"),".",r("property")];case"BindExpression":return s.object&&i.push(r("object")),i.push(y(E([F,Lr(e,t,r)]))),i;case"Identifier":return [s.name,$(e),Vr(e),q(e,r)];case"V8IntrinsicIdentifier":return ["%",s.name];case"SpreadElement":case"SpreadElementPattern":case"SpreadPropertyPattern":case"RestElement":return Hr(e,r);case"FunctionDeclaration":case"FunctionExpression":return sn(e,r,t,n);case"ArrowFunctionExpression":return Ci(e,t,r,n);case"YieldExpression":return i.push("yield"),s.delegate&&i.push("*"),s.argument&&i.push(" ",r("argument")),i;case"AwaitExpression":if(i.push("await"),s.argument){i.push(" ",r("argument"));let{parent:a}=e;if(k(a)&&a.callee===s||J(a)&&a.object===s){i=[E([F,...i]),F];let o=e.findAncestor(p=>p.type==="AwaitExpression"||p.type==="BlockStatement");if((o==null?void 0:o.type)!=="AwaitExpression"||!re(o.argument,p=>p===s))return y(i)}}return i;case"ExportDefaultDeclaration":case"ExportNamedDeclaration":case"ExportAllDeclaration":return Kr(e,t,r);case"ImportDeclaration":return $u(e,t,r);case"ImportSpecifier":case"ExportSpecifier":case"ImportNamespaceSpecifier":case"ExportNamespaceSpecifier":case"ImportDefaultSpecifier":case"ExportDefaultSpecifier":return Zu(e,t,r);case"ImportAttribute":return [r("key"),": ",r("value")];case"Import":return "import";case"BlockStatement":case"StaticBlock":return mn(e,t,r);case"ClassBody":return fi(e,t,r);case"ThrowStatement":return li(e,t,r);case"ReturnStatement":return ci(e,t,r);case"NewExpression":case"ImportExpression":case"OptionalCallExpression":case"CallExpression":return wr(e,t,r);case"ObjectExpression":case"ObjectPattern":case"RecordExpression":return Et(e,t,r);case"ObjectProperty":case"Property":return s.method||s.kind==="get"||s.kind==="set"?sr(e,t,r):oi(e,t,r);case"ObjectMethod":return sr(e,t,r);case"Decorator":return ["@",r("expression")];case"ArrayExpression":case"ArrayPattern":case"TupleExpression":return vt(e,t,r);case"SequenceExpression":{let{parent:a}=e;if(a.type==="ExpressionStatement"||a.type==="ForStatement"){let o=[];return e.each(({isFirst:p})=>{p?o.push(r()):o.push(",",E([A,r()]));},"expressions"),y(o)}return y(B([",",A],e.map(r,"expressions")))}case"ThisExpression":return "this";case"Super":return "super";case"Directive":return [r("value"),u];case"UnaryExpression":return i.push(s.operator),/[a-z]$/.test(s.operator)&&i.push(" "),d(s.argument)?i.push(y(["(",E([F,r("argument")]),F,")"])):i.push(r("argument")),i;case"UpdateExpression":return i.push(r("argument"),s.operator),s.prefix&&i.reverse(),i;case"ConditionalExpression":return Mt(e,t,r);case"VariableDeclaration":{let a=e.map(r,"declarations"),o=e.parent,p=o.type==="ForStatement"||o.type==="ForInStatement"||o.type==="ForOfStatement",m=s.declarations.some(c=>c.init),D;return a.length===1&&!d(s.declarations[0])?D=a[0]:a.length>0&&(D=E(a[0])),i=[Z(e),s.kind,D?[" ",D]:"",E(a.slice(1).map(c=>[",",m&&!p?C:A,c]))],p&&o.body!==s||i.push(u),y(i)}case"WithStatement":return y(["with (",r("object"),")",pt(s.body,r("body"))]);case"IfStatement":{let a=pt(s.consequent,r("consequent")),o=y(["if (",y([E([F,r("test")]),F]),")",a]);if(i.push(o),s.alternate){let p=d(s.consequent,x.Trailing|x.Line)||gr(s),m=s.consequent.type==="BlockStatement"&&!p;i.push(m?" ":C),d(s,x.Dangling)&&i.push(M(e,t),p?C:" "),i.push("else",y(pt(s.alternate,r("alternate"),s.alternate.type==="IfStatement")));}return i}case"ForStatement":{let a=pt(s.body,r("body")),o=M(e,t),p=o?[o,F]:"";return !s.init&&!s.test&&!s.update?[p,y(["for (;;)",a])]:[p,y(["for (",y([E([F,r("init"),";",A,r("test"),";",A,r("update")]),F]),")",a])]}case"WhileStatement":return y(["while (",y([E([F,r("test")]),F]),")",pt(s.body,r("body"))]);case"ForInStatement":return y(["for (",r("left")," in ",r("right"),")",pt(s.body,r("body"))]);case"ForOfStatement":return y(["for",s.await?" await":""," (",r("left")," of ",r("right"),")",pt(s.body,r("body"))]);case"DoWhileStatement":{let a=pt(s.body,r("body"));return i=[y(["do",a])],s.body.type==="BlockStatement"?i.push(" "):i.push(C),i.push("while (",y([E([F,r("test")]),F]),")",u),i}case"DoExpression":return [s.async?"async ":"","do ",r("body")];case"BreakStatement":case"ContinueStatement":return i.push(s.type==="BreakStatement"?"break":"continue"),s.label&&i.push(" ",r("label")),i.push(u),i;case"LabeledStatement":return s.body.type==="EmptyStatement"?[r("label"),":;"]:[r("label"),": ",r("body")];case"TryStatement":return ["try ",r("block"),s.handler?[" ",r("handler")]:"",s.finalizer?[" finally ",r("finalizer")]:""];case"CatchClause":if(s.param){let a=d(s.param,p=>!ae(p)||p.leading&&z(t.originalText,O(p))||p.trailing&&z(t.originalText,U(p),{backwards:!0})),o=r("param");return ["catch ",a?["(",E([F,o]),F,") "]:["(",o,") "],r("body")]}return ["catch ",r("body")];case"SwitchStatement":return [y(["switch (",E([F,r("discriminant")]),F,")"])," {",s.cases.length>0?E([C,B(C,e.map(({node:a,isLast:o})=>[r(),!o&&me(a,t)?C:""],"cases"))]):"",C,"}"];case"SwitchCase":{s.test?i.push("case ",r("test"),":"):i.push("default:"),d(s,x.Dangling)&&i.push(" ",M(e,t));let a=s.consequent.filter(o=>o.type!=="EmptyStatement");if(a.length>0){let o=ur(e,t,r,"consequent");i.push(a.length===1&&a[0].type==="BlockStatement"?[" ",o]:E([C,o]));}return i}case"DebuggerStatement":return ["debugger",u];case"ClassDeclaration":case"ClassExpression":return pn(e,t,r);case"ClassMethod":case"ClassPrivateMethod":case"MethodDefinition":return cn(e,t,r);case"ClassProperty":case"PropertyDefinition":case"ClassPrivateProperty":case"ClassAccessorProperty":case"AccessorProperty":return ln(e,t,r);case"TemplateElement":return xe(s.value.raw);case"TemplateLiteral":return Qr(e,r,t);case"TaggedTemplateExpression":return si(r);case"PrivateIdentifier":return ["#",s.name];case"PrivateName":return ["#",r("id")];case"TopicReference":return "%";case"ArgumentPlaceholder":return "?";case"ModuleExpression":{i.push("module {");let a=r("body");return a&&i.push(E([C,a]),C),i.push("}"),i}case"InterpreterDirective":default:throw new Oe(s,"ESTree")}}function Si(e,t,r){let{node:n}=e;if(n.type.startsWith("NG"))switch(n.type){case"NGRoot":return [r("node"),d(n.node)?" //"+Kt(n.node)[0].value.trimEnd():""];case"NGPipeExpression":return Ir(e,t,r);case"NGChainedExpression":return y(B([";",A],e.map(()=>hc(e)?r():["(",r(),")"],"expressions")));case"NGEmptyExpression":return "";case"NGMicrosyntax":return e.map(()=>[e.isFirst?"":hi(e)?" ":[";",A],r()],"body");case"NGMicrosyntaxKey":return /^[$_a-z][\w$]*(?:-[$_a-z][\w$])*$/i.test(n.name)?n.name:JSON.stringify(n.name);case"NGMicrosyntaxExpression":return [r("expression"),n.alias===null?"":[" as ",r("alias")]];case"NGMicrosyntaxKeyedExpression":{let{index:s,parent:u}=e,i=hi(e)||(s===1&&(n.key.name==="then"||n.key.name==="else")||s===2&&n.key.name==="else"&&u.body[s-1].type==="NGMicrosyntaxKeyedExpression"&&u.body[s-1].key.name==="then")&&u.body[0].type==="NGMicrosyntaxExpression";return [r("key"),i?" ":": ",r("expression")]}case"NGMicrosyntaxLet":return ["let ",r("key"),n.value===null?"":[" = ",r("value")]];case"NGMicrosyntaxAs":return [r("key")," as ",r("alias")];default:throw new Oe(n,"Angular")}}function hi({node:e,index:t,parent:r}){return e.type==="NGMicrosyntaxKeyedExpression"&&e.key.name==="of"&&t===1&&r.body[0].type==="NGMicrosyntaxLet"&&r.body[0].value===null}var gc=j(["CallExpression","OptionalCallExpression","AssignmentExpression"]);function hc({node:e}){return Xt(e,gc)}function yn(e,t,r){let{node:n}=e,s=[Z(e),"interface"],u=[],i=[];n.type!=="InterfaceTypeAnnotation"&&u.push(" ",r("id"),r("typeParameters"));let a=n.typeParameters&&!d(n.typeParameters,x.Trailing|x.Line);return b(n.extends)&&i.push(a?P(" ",A,{groupId:nr(n.typeParameters)}):A,"extends ",(n.extends.length===1?ru:E)(B([",",A],e.map(r,"extends")))),d(n.id,x.Trailing)||b(n.extends)?a?s.push(y([...u,E(i)])):s.push(y(E([...u,...i]))):s.push(...u,...i),s.push(" ",r("body")),y(s)}function Bi(e,t,r){return Et(e,r,t)}function Dn(e,t){let{node:r}=e,n=t("id");r.computed&&(n=["[",n,"]"]);let s="";return r.initializer&&(s=t("initializer")),r.init&&(s=t("init")),s?[n," = ",s]:n}function bi(e,t,r){let{node:n}=e,s;if(n.type==="EnumSymbolBody"||n.explicitType)switch(n.type){case"EnumBooleanBody":s="boolean";break;case"EnumNumberBody":s="number";break;case"EnumStringBody":s="string";break;case"EnumSymbolBody":s="symbol";break}return [s?`of ${s} `:"",Bi(e,t,r)]}function fn(e,t,r){let{node:n}=e;return [Z(e),n.const?"const ":"","enum ",t("id")," ",n.type==="TSEnumDeclaration"?Bi(e,t,r):t("body")]}function Pi(e,t,r){let{node:n}=e;if(Er(n))return n.type.slice(0,-14).toLowerCase();let s=t.semi?";":"";switch(n.type){case"DeclareClass":return pn(e,t,r);case"DeclareFunction":return [Z(e),"function ",r("id"),r("predicate"),s];case"DeclareModule":return ["declare module ",r("id")," ",r("body")];case"DeclareModuleExports":return ["declare module.exports",q(e,r),s];case"DeclareVariable":return [Z(e),n.kind??"var"," ",r("id"),s];case"DeclareExportDeclaration":case"DeclareExportAllDeclaration":return Kr(e,t,r);case"DeclareOpaqueType":case"OpaqueType":return Uu(e,t,r);case"DeclareTypeAlias":case"TypeAlias":return jr(e,t,r);case"IntersectionTypeAnnotation":return Mr(e,t,r);case"UnionTypeAnnotation":return Rr(e,t,r);case"ConditionalTypeAnnotation":return Mt(e,t,r);case"InferTypeAnnotation":return Ur(e,t,r);case"FunctionTypeAnnotation":return Jr(e,t,r);case"TupleTypeAnnotation":return vt(e,t,r);case"TupleTypeLabeledElement":return qr(e,t,r);case"TupleTypeSpreadElement":return Gr(e,t,r);case"GenericTypeAnnotation":return [r("id"),gt(e,t,r,"typeParameters")];case"IndexedAccessType":case"OptionalIndexedAccessType":return Nr(e,t,r);case"TypeAnnotation":return Wr(e,t,r);case"TypeParameter":return tn(e,t,r);case"TypeofTypeAnnotation":return Xr(e,r);case"ExistsTypeAnnotation":return "*";case"ArrayTypeAnnotation":return Yr(r);case"DeclareEnum":case"EnumDeclaration":return fn(e,r,t);case"EnumBooleanBody":case"EnumNumberBody":case"EnumStringBody":case"EnumSymbolBody":return bi(e,r,t);case"EnumBooleanMember":case"EnumNumberMember":case"EnumStringMember":case"EnumDefaultedMember":return Dn(e,r);case"FunctionTypeParam":{let u=n.name?r("name"):e.parent.this===n?"this":"";return [u,$(e),u?": ":"",r("typeAnnotation")]}case"DeclareInterface":case"InterfaceDeclaration":case"InterfaceTypeAnnotation":return yn(e,t,r);case"ClassImplements":case"InterfaceExtends":return [r("id"),r("typeParameters")];case"NullableTypeAnnotation":return ["?",r("typeAnnotation")];case"Variance":{let{kind:u}=n;return rn.ok(u==="plus"||u==="minus"),u==="plus"?"+":"-"}case"KeyofTypeAnnotation":return ["keyof ",r("argument")];case"ObjectTypeCallProperty":return [n.static?"static ":"",r("value")];case"ObjectTypeMappedTypeProperty":return ui(e,t,r);case"ObjectTypeIndexer":return [n.static?"static ":"",n.variance?r("variance"):"","[",r("id"),n.id?": ":"",r("key"),"]: ",r("value")];case"ObjectTypeProperty":{let u="";return n.proto?u="proto ":n.static&&(u="static "),[u,On(n)?n.kind+" ":"",n.variance?r("variance"):"",ct(e,t,r),$(e),vn(n)?"":": ",r("value")]}case"ObjectTypeAnnotation":return Et(e,t,r);case"ObjectTypeInternalSlot":return [n.static?"static ":"","[[",r("id"),"]]",$(e),n.method?"":": ",r("value")];case"ObjectTypeSpreadProperty":return Hr(e,r);case"QualifiedTypeofIdentifier":case"QualifiedTypeIdentifier":return [r("qualification"),".",r("id")];case"NullLiteralTypeAnnotation":return "null";case"BooleanLiteralTypeAnnotation":return String(n.value);case"StringLiteralTypeAnnotation":return xe(Tt(oe(n),t));case"NumberLiteralTypeAnnotation":return He(n.raw??n.extra.raw);case"BigIntLiteralTypeAnnotation":return Or(n.raw??n.extra.raw);case"TypeCastExpression":return ["(",r("expression"),q(e,r),")"];case"TypePredicate":return $r(e,r);case"TypeParameterDeclaration":case"TypeParameterInstantiation":return gt(e,t,r,"params");case"InferredPredicate":case"DeclaredPredicate":return [e.key==="predicate"&&e.parent.type!=="DeclareFunction"&&!e.parent.returnType?": ":" ","%checks",...n.type==="DeclaredPredicate"?["(",r("value"),")"]:[]]}}function ki(e,t,r){var i;let{node:n}=e;if(!n.type.startsWith("TS"))return;if(Fr(n))return n.type.slice(2,-7).toLowerCase();let s=t.semi?";":"",u=[];switch(n.type){case"TSThisType":return "this";case"TSTypeAssertion":{let a=!(G(n.expression)||ee(n.expression)),o=y(["<",E([F,r("typeAnnotation")]),F,">"]),p=[P("("),E([F,r("expression")]),F,P(")")];return a?qe([[o,r("expression")],[o,y(p,{shouldBreak:!0})],[o,r("expression")]]):y([o,r("expression")])}case"TSDeclareFunction":return sn(e,r,t);case"TSExportAssignment":return ["export = ",r("expression"),s];case"TSModuleBlock":return mn(e,t,r);case"TSInterfaceBody":case"TSTypeLiteral":return Et(e,t,r);case"TSTypeAliasDeclaration":return jr(e,t,r);case"TSQualifiedName":return [r("left"),".",r("right")];case"TSAbstractMethodDefinition":case"TSDeclareMethod":return cn(e,t,r);case"TSAbstractAccessorProperty":case"TSAbstractPropertyDefinition":return ln(e,t,r);case"TSInterfaceHeritage":case"TSClassImplements":case"TSExpressionWithTypeArguments":case"TSInstantiationExpression":return [r("expression"),r("typeParameters")];case"TSTemplateLiteralType":return Qr(e,r,t);case"TSNamedTupleMember":return qr(e,t,r);case"TSRestType":return Gr(e,t,r);case"TSOptionalType":return [r("typeAnnotation"),"?"];case"TSInterfaceDeclaration":return yn(e,t,r);case"TSTypeParameterDeclaration":case"TSTypeParameterInstantiation":return gt(e,t,r,"params");case"TSTypeParameter":return tn(e,t,r);case"TSAsExpression":case"TSSatisfiesExpression":{let a=n.type==="TSAsExpression"?"as":"satisfies";u.push(r("expression"),` ${a} `,r("typeAnnotation"));let{parent:o}=e;return k(o)&&o.callee===n||J(o)&&o.object===n?y([E([F,...u]),F]):u}case"TSArrayType":return Yr(r);case"TSPropertySignature":return [n.readonly?"readonly ":"",ct(e,t,r),$(e),q(e,r)];case"TSParameterProperty":return [jt(n),n.static?"static ":"",n.override?"override ":"",n.readonly?"readonly ":"",r("parameter")];case"TSTypeQuery":return Xr(e,r);case"TSIndexSignature":{let a=n.parameters.length>1?P(le(t)?",":""):"",o=y([E([F,B([", ",F],e.map(r,"parameters"))]),a,F]),p=e.parent.type==="ClassBody"&&e.key==="body";return [p&&n.static?"static ":"",n.readonly?"readonly ":"","[",n.parameters?o:"","]",q(e,r),p?s:""]}case"TSTypePredicate":return $r(e,r);case"TSNonNullExpression":return [r("expression"),"!"];case"TSImportType":return [n.isTypeOf?"typeof ":"","import(",r("argument"),")",n.qualifier?[".",r("qualifier")]:"",gt(e,t,r,n.typeArguments?"typeArguments":"typeParameters")];case"TSLiteralType":return r("literal");case"TSIndexedAccessType":return Nr(e,t,r);case"TSTypeOperator":return [n.operator," ",r("typeAnnotation")];case"TSMappedType":return ii(e,t,r);case"TSMethodSignature":{let a=n.kind&&n.kind!=="method"?`${n.kind} `:"";u.push(jt(n),a,n.computed?"[":"",r("key"),n.computed?"]":"",$(e));let o=ot(e,r,t,!1,!0),p=n.returnType?"returnType":"typeAnnotation",m=n[p],D=m?q(e,r,p):"",c=xt(n,D);return u.push(c?y(o):o),m&&u.push(y(D)),y(u)}case"TSNamespaceExportDeclaration":return ["export as namespace ",r("id"),t.semi?";":""];case"TSEnumDeclaration":return fn(e,r,t);case"TSEnumMember":return Dn(e,r);case"TSImportEqualsDeclaration":return [n.isExport?"export ":"","import ",os(n,!1),r("id")," = ",r("moduleReference"),t.semi?";":""];case"TSExternalModuleReference":return ["require(",r("expression"),")"];case"TSModuleDeclaration":{let{parent:a}=e,o=a.type==="TSModuleDeclaration",p=((i=n.body)==null?void 0:i.type)==="TSModuleDeclaration";if(o)u.push(".");else if(u.push(Z(e)),!(n.kind==="global"||n.global)){let D=n.kind??(Q(n.id)||/(?:^|\s)module(?:\s|$)/.test(t.originalText.slice(U(n),U(n.id)))?"module":"namespace");u.push(D," ");}return u.push(r("id")),p?u.push(r("body")):n.body?u.push(" ",y(r("body"))):u.push(s),u}case"TSConditionalType":return Mt(e,t,r);case"TSInferType":return Ur(e,t,r);case"TSIntersectionType":return Mr(e,t,r);case"TSUnionType":return Rr(e,t,r);case"TSFunctionType":case"TSCallSignatureDeclaration":case"TSConstructorType":case"TSConstructSignatureDeclaration":return Jr(e,t,r);case"TSTupleType":return vt(e,t,r);case"TSTypeReference":return [r("typeName"),gt(e,t,r,"typeParameters")];case"TSTypeAnnotation":return Wr(e,t,r);case"TSEmptyBodyFunctionExpression":return un(e,t,r);case"TSJSDocAllType":return "*";case"TSJSDocUnknownType":return "?";case"TSJSDocNullableType":return us(e,r,"?");case"TSJSDocNonNullableType":return us(e,r,"!");case"TSParenthesizedType":default:throw new Oe(n,"TypeScript")}}function Sc(e,t,r,n){if(kr(e))return ks(e,t);for(let s of [Si,hu,Pi,ki,gi]){let u=s(e,t,r,n);if(u!==void 0)return u}}var Bc=j(["ClassMethod","ClassPrivateMethod","ClassProperty","ClassAccessorProperty","AccessorProperty","TSAbstractAccessorProperty","PropertyDefinition","TSAbstractPropertyDefinition","ClassPrivateProperty","MethodDefinition","TSAbstractMethodDefinition","TSDeclareMethod"]);function bc(e,t,r,n){var D;e.isRoot&&((D=t.__onHtmlBindingRoot)==null||D.call(t,e.node,t));let s=Sc(e,t,r,n);if(!s)return "";let{node:u}=e;if(Bc(u))return s;let i=b(u.decorators),a=Wu(e,t,r),o=u.type==="ClassExpression";if(i&&!o)return Gt(s,c=>y([a,c]));let p=we(e,t),m=di(e,t);return !a&&!p&&!m?s:Gt(s,c=>[m?";":"",p?"(":"",p&&o&&i?[E([A,a,c]),A]:[a,c],p?")":""])}var Ii=bc;var Li=[(e,t)=>e.type==="ObjectExpression"&&t==="properties",(e,t)=>e.type==="CallExpression"&&e.callee.type==="Identifier"&&e.callee.name==="Component"&&t==="arguments",(e,t)=>e.type==="Decorator"&&t==="expression"];function wi(e){return e.match(t=>t.type==="TemplateLiteral",(t,r)=>G(t)&&r==="elements",(t,r)=>fe(t)&&t.key.type==="Identifier"&&t.key.name==="styles"&&r==="value",...Li)}function Oi(e){return e.match(t=>t.type==="TemplateLiteral",(t,r)=>fe(t)&&t.key.type==="Identifier"&&t.key.name==="template"&&r==="value",...Li)}function En(e,t){return d(e,x.Block|x.Leading,({value:r})=>r===` ${t} `)}async function Pc(e,t,r){let{node:n}=r,s=n.quasis.map(m=>m.value.raw),u=0,i=s.reduce((m,D,c)=>c===0?D:m+"@prettier-placeholder-"+u+++"-id"+D,""),a=await e(i,{parser:"scss"}),o=Rt(r,t),p=kc(a,o);if(!p)throw new Error("Couldn't insert all the expressions");return ["`",E([C,p]),F,"`"]}function kc(e,t){if(!b(t))return e;let r=0,n=ut(Bt(e),s=>typeof s!="string"||!s.includes("@prettier-placeholder")?s:s.split(/@prettier-placeholder-(\d+)-id/).map((u,i)=>i%2===0?xe(u):(r++,t[u])));return t.length===r?n:null}function Ic({node:e,parent:t,grandparent:r}){return r&&e.quasis&&t.type==="JSXExpressionContainer"&&r.type==="JSXElement"&&r.openingElement.name.name==="style"&&r.openingElement.attributes.some(n=>n.name.name==="jsx")||(t==null?void 0:t.type)==="TaggedTemplateExpression"&&t.tag.type==="Identifier"&&t.tag.name==="css"||(t==null?void 0:t.type)==="TaggedTemplateExpression"&&t.tag.type==="MemberExpression"&&t.tag.object.name==="css"&&(t.tag.property.name==="global"||t.tag.property.name==="resolve")}function Fn(e){return e.type==="Identifier"&&e.name==="styled"}function vi(e){return /^[A-Z]/.test(e.object.name)&&e.property.name==="extend"}function Lc({parent:e}){if(!e||e.type!=="TaggedTemplateExpression")return !1;let t=e.tag.type==="ParenthesizedExpression"?e.tag.expression:e.tag;switch(t.type){case"MemberExpression":return Fn(t.object)||vi(t);case"CallExpression":return Fn(t.callee)||t.callee.type==="MemberExpression"&&(t.callee.object.type==="MemberExpression"&&(Fn(t.callee.object.object)||vi(t.callee.object))||t.callee.object.type==="CallExpression"&&Fn(t.callee.object.callee));case"Identifier":return t.name==="css";default:return !1}}function wc({parent:e,grandparent:t}){return (t==null?void 0:t.type)==="JSXAttribute"&&e.type==="JSXExpressionContainer"&&t.name.type==="JSXIdentifier"&&t.name.name==="css"}function Oc(e){if(Ic(e)||Lc(e)||wc(e)||wi(e))return Pc}var _i=Oc;async function vc(e,t,r){let{node:n}=r,s=n.quasis.length,u=Rt(r,t),i=[];for(let a=0;a2&&c[0].trim()===""&&c[1].trim()==="",g=f>2&&c[f-1].trim()===""&&c[f-2].trim()==="",S=c.every(v=>/^\s*(?:#[^\n\r]*)?$/.test(v));if(!m&&/#[^\n\r]*$/.test(c[f-1]))return null;let I=null;S?I=_c(c):I=await e(D,{parser:"graphql"}),I?(I=Zr(I,!1),!p&&h&&i.push(""),i.push(I),!m&&g&&i.push("")):!p&&!m&&h&&i.push(""),l&&i.push(l);}return ["`",E([C,B(C,i)]),C,"`"]}function _c(e){let t=[],r=!1,n=e.map(s=>s.trim());for(let[s,u]of n.entries())u!==""&&(n[s-1]===""&&r?t.push([C,u]):t.push(u),r=!0);return t.length===0?null:B(C,t)}function jc({node:e,parent:t}){return En(e,"GraphQL")||t&&(t.type==="TaggedTemplateExpression"&&(t.tag.type==="MemberExpression"&&t.tag.object.name==="graphql"&&t.tag.property.name==="experimental"||t.tag.type==="Identifier"&&(t.tag.name==="gql"||t.tag.name==="graphql"))||t.type==="CallExpression"&&t.callee.type==="Identifier"&&t.callee.name==="graphql")}function Mc(e){if(jc(e))return vc}var ji=Mc;var xs=0;async function Mi(e,t,r,n,s){let{node:u}=n,i=xs;xs=xs+1>>>0;let a=S=>`PRETTIER_HTML_PLACEHOLDER_${S}_${i}_IN_JS`,o=u.quasis.map((S,I,v)=>I===v.length-1?S.value.cooked:S.value.cooked+a(I)).join(""),p=Rt(n,r),m=new RegExp(a("(\\d+)"),"g"),D=0,c=await t(o,{parser:e,__onHtmlRoot(S){D=S.children.length;}}),f=ut(c,S=>{if(typeof S!="string")return S;let I=[],v=S.split(m);for(let _=0;_1?E(y(f)):y(f),h,"`"]))}function Rc(e){return En(e.node,"HTML")||e.match(t=>t.type==="TemplateLiteral",(t,r)=>t.type==="TaggedTemplateExpression"&&t.tag.type==="Identifier"&&t.tag.name==="html"&&r==="quasi")}var Jc=Mi.bind(void 0,"html"),Nc=Mi.bind(void 0,"angular");function Uc(e){if(Rc(e))return Jc;if(Oi(e))return Nc}var Ri=Uc;async function Gc(e,t,r){let{node:n}=r,s=H(!1,n.quasis[0].value.raw,/((?:\\\\)*)\\`/g,(o,p)=>"\\".repeat(p.length/2)+"`"),u=qc(s),i=u!=="";i&&(s=H(!1,s,new RegExp(`^${u}`,"gm"),""));let a=Zr(await e(s,{parser:"markdown",__inJsTemplate:!0}),!0);return ["`",i?E([F,a]):[lr,ws(a)],F,"`"]}function qc(e){let t=e.match(/^([^\S\n]*)\S/m);return t===null?"":t[1]}function Wc(e){if(Yc(e))return Gc}function Yc({node:e,parent:t}){return (t==null?void 0:t.type)==="TaggedTemplateExpression"&&e.quasis.length===1&&t.tag.type==="Identifier"&&(t.tag.name==="md"||t.tag.name==="markdown")}var Ji=Wc;function Xc(e){let{node:t}=e;if(t.type!=="TemplateLiteral"||$c(t))return;let r;for(let n of [_i,ji,Ri,Ji])if(r=n(e),!!r)return t.quasis.length===1&&t.quasis[0].value.raw.trim()===""?"``":async(...s)=>{let u=await r(...s);return u&&et({embed:!0,...u.label},u)}}function $c({quasis:e}){return e.some(({value:{cooked:t}})=>t===null)}var Ni=Xc;var Vc=new Set(["range","raw","comments","leadingComments","trailingComments","innerComments","extra","start","end","loc","flags","errors","tokens"]),Jt=e=>{for(let t of e.quasis)delete t.value;};function Ui(e,t,r){var s,u;if(e.type==="Program"&&delete t.sourceType,(e.type==="BigIntLiteral"||e.type==="BigIntLiteralTypeAnnotation")&&t.value&&(t.value=t.value.toLowerCase()),(e.type==="BigIntLiteral"||e.type==="Literal")&&t.bigint&&(t.bigint=t.bigint.toLowerCase()),e.type==="DecimalLiteral"&&(t.value=Number(t.value)),e.type==="Literal"&&t.decimal&&(t.decimal=Number(t.decimal)),e.type==="EmptyStatement"||e.type==="JSXText"||e.type==="JSXExpressionContainer"&&(e.expression.type==="Literal"||e.expression.type==="StringLiteral")&&e.expression.value===" ")return null;if((e.type==="Property"||e.type==="ObjectProperty"||e.type==="MethodDefinition"||e.type==="ClassProperty"||e.type==="ClassMethod"||e.type==="PropertyDefinition"||e.type==="TSDeclareMethod"||e.type==="TSPropertySignature"||e.type==="ObjectTypeProperty")&&typeof e.key=="object"&&e.key&&(e.key.type==="Literal"||e.key.type==="NumericLiteral"||e.key.type==="StringLiteral"||e.key.type==="Identifier")&&delete t.key,e.type==="JSXElement"&&e.openingElement.name.name==="style"&&e.openingElement.attributes.some(i=>i.type==="JSXAttribute"&&i.name.name==="jsx"))for(let{type:i,expression:a}of t.children)i==="JSXExpressionContainer"&&a.type==="TemplateLiteral"&&Jt(a);e.type==="JSXAttribute"&&e.name.name==="css"&&e.value.type==="JSXExpressionContainer"&&e.value.expression.type==="TemplateLiteral"&&Jt(t.value.expression),e.type==="JSXAttribute"&&((s=e.value)==null?void 0:s.type)==="Literal"&&/["']|"|'/.test(e.value.value)&&(t.value.value=H(!1,t.value.value,/["']|"|'/g,'"'));let n=e.expression||e.callee;if(e.type==="Decorator"&&n.type==="CallExpression"&&n.callee.name==="Component"&&n.arguments.length===1){let i=e.expression.arguments[0].properties;for(let[a,o]of t.expression.arguments[0].properties.entries())switch(i[a].key.name){case"styles":G(o.value)&&Jt(o.value.elements[0]);break;case"template":o.value.type==="TemplateLiteral"&&Jt(o.value);break}}if(e.type==="TaggedTemplateExpression"&&(e.tag.type==="MemberExpression"||e.tag.type==="Identifier"&&(e.tag.name==="gql"||e.tag.name==="graphql"||e.tag.name==="css"||e.tag.name==="md"||e.tag.name==="markdown"||e.tag.name==="html")||e.tag.type==="CallExpression")&&Jt(t.quasi),e.type==="TemplateLiteral"&&((u=e.leadingComments)!=null&&u.some(a=>ae(a)&&["GraphQL","HTML"].some(o=>a.value===` ${o} `))||r.type==="CallExpression"&&r.callee.name==="graphql"||!e.leadingComments)&&Jt(t),(e.type==="TSIntersectionType"||e.type==="TSUnionType")&&e.types.length===1)return t.types[0];e.type==="ChainExpression"&&e.expression.type==="TSNonNullExpression"&&([t.type,t.expression.type]=[t.expression.type,t.type]);}Ui.ignoredProperties=Vc;var Gi=Ui;var Ft=ma(Hi(),1);function sl(e){if(!e.startsWith("#!"))return "";let t=e.indexOf(` -`);return t===-1?e:e.slice(0,t)}var Ki=sl;function ul(e){let t=Ki(e);t&&(e=e.slice(t.length+1));let r=(0, Ft.extract)(e),{pragmas:n,comments:s}=(0, Ft.parseWithComments)(r);return {shebang:t,text:e,pragmas:n,comments:s}}function zi(e){let{shebang:t,text:r,pragmas:n,comments:s}=ul(e),u=(0, Ft.strip)(r),i=(0, Ft.print)({pragmas:{format:"",...n},comments:s.trimStart()});return (t?`${t} -`:"")+i+(u.startsWith(` -`)?` -`:` - -`)+u}var il={avoidAstMutation:!0};var Qi=[{linguistLanguageId:183,name:"JavaScript",type:"programming",tmScope:"source.js",aceMode:"javascript",codemirrorMode:"javascript",codemirrorMimeType:"text/javascript",color:"#f1e05a",aliases:["js","node"],extensions:[".js","._js",".bones",".cjs",".es",".es6",".frag",".gs",".jake",".javascript",".jsb",".jscad",".jsfl",".jslib",".jsm",".jspre",".jss",".mjs",".njs",".pac",".sjs",".ssjs",".xsjs",".xsjslib",".wxs"],filenames:["Jakefile"],interpreters:["chakra","d8","gjs","js","node","nodejs","qjs","rhino","v8","v8-shell","zx"],parsers:["babel","acorn","espree","meriyah","babel-flow","babel-ts","flow","typescript"],vscodeLanguageIds:["javascript","mongo"]},{linguistLanguageId:183,name:"Flow",type:"programming",tmScope:"source.js",aceMode:"javascript",codemirrorMode:"javascript",codemirrorMimeType:"text/javascript",color:"#f1e05a",aliases:[],extensions:[".js.flow"],filenames:[],interpreters:["chakra","d8","gjs","js","node","nodejs","qjs","rhino","v8","v8-shell"],parsers:["flow","babel-flow"],vscodeLanguageIds:["javascript"]},{linguistLanguageId:183,name:"JSX",type:"programming",tmScope:"source.js.jsx",aceMode:"javascript",codemirrorMode:"jsx",codemirrorMimeType:"text/jsx",color:void 0,aliases:void 0,extensions:[".jsx"],filenames:void 0,interpreters:void 0,parsers:["babel","babel-flow","babel-ts","flow","typescript","espree","meriyah"],vscodeLanguageIds:["javascriptreact"],group:"JavaScript"},{linguistLanguageId:378,name:"TypeScript",type:"programming",color:"#3178c6",aliases:["ts"],interpreters:["deno","ts-node"],extensions:[".ts",".cts",".mts"],tmScope:"source.ts",aceMode:"typescript",codemirrorMode:"javascript",codemirrorMimeType:"application/typescript",parsers:["typescript","babel-ts"],vscodeLanguageIds:["typescript"]},{linguistLanguageId:94901924,name:"TSX",type:"programming",color:"#3178c6",group:"TypeScript",extensions:[".tsx"],tmScope:"source.tsx",aceMode:"javascript",codemirrorMode:"jsx",codemirrorMimeType:"text/jsx",parsers:["typescript","babel-ts"],vscodeLanguageIds:["typescriptreact"]}];var hs={};or(hs,{getVisitorKeys:()=>ea,massageAstNode:()=>ra,print:()=>pl});var al={JsonRoot:["node"],ArrayExpression:["elements"],ObjectExpression:["properties"],ObjectProperty:["key","value"],UnaryExpression:["argument"],NullLiteral:[],BooleanLiteral:[],StringLiteral:[],NumericLiteral:[],Identifier:[],TemplateLiteral:["quasis"],TemplateElement:[]},Zi=al;var ol=Dr(Zi),ea=ol;function pl(e,t,r){let{node:n}=e;switch(n.type){case"JsonRoot":return [r("node"),C];case"ArrayExpression":{if(n.elements.length===0)return "[]";let s=e.map(()=>e.node===null?"null":r(),"elements");return ["[",E([C,B([",",C],s)]),C,"]"]}case"ObjectExpression":return n.properties.length===0?"{}":["{",E([C,B([",",C],e.map(r,"properties"))]),C,"}"];case"ObjectProperty":return [r("key"),": ",r("value")];case"UnaryExpression":return [n.operator==="+"?"":n.operator,r("argument")];case"NullLiteral":return "null";case"BooleanLiteral":return n.value?"true":"false";case"StringLiteral":return JSON.stringify(n.value);case"NumericLiteral":return ta(e)?JSON.stringify(String(n.value)):JSON.stringify(n.value);case"Identifier":return ta(e)?JSON.stringify(n.name):n.name;case"TemplateLiteral":return r(["quasis",0]);case"TemplateElement":return JSON.stringify(n.value.cooked);default:throw new Oe(n,"JSON")}}function ta(e){return e.key==="key"&&e.parent.type==="ObjectProperty"}var cl=new Set(["start","end","extra","loc","comments","leadingComments","trailingComments","innerComments","errors","range","tokens"]);function ra(e,t){let{type:r}=e;if(r==="ObjectProperty"){let{key:n}=e;n.type==="Identifier"?t.key={type:"StringLiteral",value:n.name}:n.type==="NumericLiteral"&&(t.key={type:"StringLiteral",value:String(n.value)});return}if(r==="UnaryExpression"&&e.operator==="+")return t.argument;if(r==="ArrayExpression"){for(let[n,s]of e.elements.entries())s===null&&t.elements.splice(n,0,{type:"NullLiteral"});return}if(r==="TemplateLiteral")return {type:"StringLiteral",value:e.quasis[0].value.cooked}}ra.ignoredProperties=cl;var na=[{linguistLanguageId:174,name:"JSON.stringify",type:"data",color:"#292929",tmScope:"source.json",aceMode:"json",codemirrorMode:"javascript",codemirrorMimeType:"application/json",aliases:["geojson","jsonl","topojson"],extensions:[".importmap"],filenames:["package.json","package-lock.json","composer.json"],parsers:["json-stringify"],vscodeLanguageIds:["json"]},{linguistLanguageId:174,name:"JSON",type:"data",color:"#292929",tmScope:"source.json",aceMode:"json",codemirrorMode:"javascript",codemirrorMimeType:"application/json",aliases:["geojson","jsonl","topojson"],extensions:[".json",".4DForm",".4DProject",".avsc",".geojson",".gltf",".har",".ice",".JSON-tmLanguage",".mcmeta",".tfstate",".tfstate.backup",".topojson",".webapp",".webmanifest",".yy",".yyp"],filenames:[".all-contributorsrc",".arcconfig",".auto-changelog",".c8rc",".htmlhintrc",".imgbotconfig",".nycrc",".tern-config",".tern-project",".watchmanconfig","Pipfile.lock","composer.lock","flake.lock","mcmod.info"],parsers:["json"],vscodeLanguageIds:["json"]},{linguistLanguageId:423,name:"JSON with Comments",type:"data",color:"#292929",group:"JSON",tmScope:"source.js",aceMode:"javascript",codemirrorMode:"javascript",codemirrorMimeType:"text/javascript",aliases:["jsonc"],extensions:[".jsonc",".code-snippets",".sublime-build",".sublime-commands",".sublime-completions",".sublime-keymap",".sublime-macro",".sublime-menu",".sublime-mousemap",".sublime-project",".sublime-settings",".sublime-theme",".sublime-workspace",".sublime_metrics",".sublime_session"],filenames:[".babelrc",".devcontainer.json",".eslintrc.json",".jscsrc",".jshintrc",".jslintrc",".swcrc","api-extractor.json","devcontainer.json","jsconfig.json","language-configuration.json","tsconfig.json","tslint.json",".eslintrc"],parsers:["json"],vscodeLanguageIds:["jsonc"]},{linguistLanguageId:175,name:"JSON5",type:"data",color:"#267CB9",extensions:[".json5"],tmScope:"source.js",aceMode:"javascript",codemirrorMode:"javascript",codemirrorMimeType:"application/json",parsers:["json5"],vscodeLanguageIds:["json5"]}];var ir={bracketSpacing:{category:"Common",type:"boolean",default:!0,description:"Print spaces between brackets.",oppositeDescription:"Do not print spaces between brackets."},singleQuote:{category:"Common",type:"boolean",default:!1,description:"Use single quotes instead of double quotes."},proseWrap:{category:"Common",type:"choice",default:"preserve",description:"How to wrap prose.",choices:[{value:"always",description:"Wrap prose if it exceeds the print width."},{value:"never",description:"Do not wrap prose."},{value:"preserve",description:"Wrap prose as-is."}]},bracketSameLine:{category:"Common",type:"boolean",default:!1,description:"Put > of opening tags on the last line instead of on a new line."},singleAttributePerLine:{category:"Common",type:"boolean",default:!1,description:"Enforce single attribute per line in HTML, Vue and JSX."}};var Nt="JavaScript",ll={arrowParens:{category:Nt,type:"choice",default:"always",description:"Include parentheses around a sole arrow function parameter.",choices:[{value:"always",description:"Always include parens. Example: `(x) => x`"},{value:"avoid",description:"Omit parens when possible. Example: `x => x`"}]},bracketSameLine:ir.bracketSameLine,bracketSpacing:ir.bracketSpacing,jsxBracketSameLine:{category:Nt,type:"boolean",description:"Put > on the last line instead of at a new line.",deprecated:"2.4.0"},semi:{category:Nt,type:"boolean",default:!0,description:"Print semicolons.",oppositeDescription:"Do not print semicolons, except at the beginning of lines which may need them."},singleQuote:ir.singleQuote,jsxSingleQuote:{category:Nt,type:"boolean",default:!1,description:"Use single quotes in JSX."},quoteProps:{category:Nt,type:"choice",default:"as-needed",description:"Change when properties in objects are quoted.",choices:[{value:"as-needed",description:"Only add quotes around object properties where required."},{value:"consistent",description:"If at least one property in an object requires quotes, quote all properties."},{value:"preserve",description:"Respect the input use of quotes in object properties."}]},trailingComma:{category:Nt,type:"choice",default:"all",description:"Print trailing commas wherever possible when multi-line.",choices:[{value:"all",description:"Trailing commas wherever possible (including function arguments)."},{value:"es5",description:"Trailing commas where valid in ES5 (objects, arrays, etc.)"},{value:"none",description:"No trailing commas."}]},singleAttributePerLine:ir.singleAttributePerLine},sa=ll;var ml={estree:gs,"estree-json":hs},yl=[...Qi,...na];var FA=Ss; - -export { FA as default, yl as languages, sa as options, ml as printers }; diff --git a/src/lib/prettier-xml.js b/src/lib/prettier-xml.js deleted file mode 100644 index b1fcd8179..000000000 --- a/src/lib/prettier-xml.js +++ /dev/null @@ -1,10961 +0,0 @@ -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -function getAugmentedNamespace(n) { - var f = n.default; - if (typeof f == "function") { - var a = function () { - return f.apply(this, arguments); - }; - a.prototype = f.prototype; - } else a = {}; - Object.defineProperty(a, '__esModule', {value: true}); - Object.keys(n).forEach(function (k) { - var d = Object.getOwnPropertyDescriptor(n, k); - Object.defineProperty(a, k, d.get ? d : { - enumerable: true, - get: function () { - return n[k]; - } - }); - }); - return a; -} - -var parser$2 = {}; - -// needs a separate module as this is required inside chevrotain productive code -// and also in the entry point for webpack(api.ts). -// A separate file avoids cyclic dependencies and webpack errors. -var VERSION = "7.1.1"; - -/* - Utils using lodash style API. (not necessarily 100% compliant) for functional and other utils. - These utils should replace usage of lodash in the production code base. not because they are any better... - but for the purpose of being a dependency free library. - - The hotspots in the code are already written in imperative style for performance reasons. - so writing several dozen utils which may be slower than the original lodash, does not matter as much - considering they will not be invoked in hotspots... - */ -function isEmpty(arr) { - return arr && arr.length === 0; -} -function keys(obj) { - if (obj === undefined || obj === null) { - return []; - } - return Object.keys(obj); -} -function values(obj) { - var vals = []; - var keys = Object.keys(obj); - for (var i = 0; i < keys.length; i++) { - vals.push(obj[keys[i]]); - } - return vals; -} -function mapValues(obj, callback) { - var result = []; - var objKeys = keys(obj); - for (var idx = 0; idx < objKeys.length; idx++) { - var currKey = objKeys[idx]; - result.push(callback.call(null, obj[currKey], currKey)); - } - return result; -} -function map(arr, callback) { - var result = []; - for (var idx = 0; idx < arr.length; idx++) { - result.push(callback.call(null, arr[idx], idx)); - } - return result; -} -function flatten(arr) { - var result = []; - for (var idx = 0; idx < arr.length; idx++) { - var currItem = arr[idx]; - if (Array.isArray(currItem)) { - result = result.concat(flatten(currItem)); - } - else { - result.push(currItem); - } - } - return result; -} -function first$1(arr) { - return isEmpty(arr) ? undefined : arr[0]; -} -function last(arr) { - var len = arr && arr.length; - return len ? arr[len - 1] : undefined; -} -function forEach(collection, iteratorCallback) { - /* istanbul ignore else */ - if (Array.isArray(collection)) { - for (var i = 0; i < collection.length; i++) { - iteratorCallback.call(null, collection[i], i); - } - } - else if (isObject(collection)) { - var colKeys = keys(collection); - for (var i = 0; i < colKeys.length; i++) { - var key = colKeys[i]; - var value = collection[key]; - iteratorCallback.call(null, value, key); - } - } - else { - throw Error("non exhaustive match"); - } -} -function isString(item) { - return typeof item === "string"; -} -function isUndefined(item) { - return item === undefined; -} -function isFunction(item) { - return item instanceof Function; -} -function drop(arr, howMuch) { - if (howMuch === void 0) { howMuch = 1; } - return arr.slice(howMuch, arr.length); -} -function dropRight(arr, howMuch) { - if (howMuch === void 0) { howMuch = 1; } - return arr.slice(0, arr.length - howMuch); -} -function filter(arr, predicate) { - var result = []; - if (Array.isArray(arr)) { - for (var i = 0; i < arr.length; i++) { - var item = arr[i]; - if (predicate.call(null, item)) { - result.push(item); - } - } - } - return result; -} -function reject(arr, predicate) { - return filter(arr, function (item) { return !predicate(item); }); -} -function pick(obj, predicate) { - var keys = Object.keys(obj); - var result = {}; - for (var i = 0; i < keys.length; i++) { - var currKey = keys[i]; - var currItem = obj[currKey]; - if (predicate(currItem)) { - result[currKey] = currItem; - } - } - return result; -} -function has(obj, prop) { - if (isObject(obj)) { - return obj.hasOwnProperty(prop); - } - return false; -} -function contains(arr, item) { - return find(arr, function (currItem) { return currItem === item; }) !== undefined ? true : false; -} -/** - * shallow clone - */ -function cloneArr(arr) { - var newArr = []; - for (var i = 0; i < arr.length; i++) { - newArr.push(arr[i]); - } - return newArr; -} -/** - * shallow clone - */ -function cloneObj(obj) { - var clonedObj = {}; - for (var key in obj) { - /* istanbul ignore else */ - if (Object.prototype.hasOwnProperty.call(obj, key)) { - clonedObj[key] = obj[key]; - } - } - return clonedObj; -} -function find(arr, predicate) { - for (var i = 0; i < arr.length; i++) { - var item = arr[i]; - if (predicate.call(null, item)) { - return item; - } - } - return undefined; -} -function findAll(arr, predicate) { - var found = []; - for (var i = 0; i < arr.length; i++) { - var item = arr[i]; - if (predicate.call(null, item)) { - found.push(item); - } - } - return found; -} -function reduce(arrOrObj, iterator, initial) { - var isArr = Array.isArray(arrOrObj); - var vals = isArr ? arrOrObj : values(arrOrObj); - var objKeys = isArr ? [] : keys(arrOrObj); - var accumulator = initial; - for (var i = 0; i < vals.length; i++) { - accumulator = iterator.call(null, accumulator, vals[i], isArr ? i : objKeys[i]); - } - return accumulator; -} -function compact(arr) { - return reject(arr, function (item) { return item === null || item === undefined; }); -} -function uniq(arr, identity) { - if (identity === void 0) { identity = function (item) { return item; }; } - var identities = []; - return reduce(arr, function (result, currItem) { - var currIdentity = identity(currItem); - if (contains(identities, currIdentity)) { - return result; - } - else { - identities.push(currIdentity); - return result.concat(currItem); - } - }, []); -} -function isArray(obj) { - return Array.isArray(obj); -} -function isRegExp(obj) { - return obj instanceof RegExp; -} -function isObject(obj) { - return obj instanceof Object; -} -function every(arr, predicate) { - for (var i = 0; i < arr.length; i++) { - if (!predicate(arr[i], i)) { - return false; - } - } - return true; -} -function difference(arr, values) { - return reject(arr, function (item) { return contains(values, item); }); -} -function some(arr, predicate) { - for (var i = 0; i < arr.length; i++) { - if (predicate(arr[i])) { - return true; - } - } - return false; -} -function indexOf(arr, value) { - for (var i = 0; i < arr.length; i++) { - if (arr[i] === value) { - return i; - } - } - return -1; -} -/** - * mutates! (and returns) target - */ -function assign(target) { - var sources = []; - for (var _i = 1; _i < arguments.length; _i++) { - sources[_i - 1] = arguments[_i]; - } - for (var i = 0; i < sources.length; i++) { - var curSource = sources[i]; - var currSourceKeys = keys(curSource); - for (var j = 0; j < currSourceKeys.length; j++) { - var currKey = currSourceKeys[j]; - target[currKey] = curSource[currKey]; - } - } - return target; -} -/** - * mutates! (and returns) target - */ -function assignNoOverwrite(target) { - var sources = []; - for (var _i = 1; _i < arguments.length; _i++) { - sources[_i - 1] = arguments[_i]; - } - for (var i = 0; i < sources.length; i++) { - var curSource = sources[i]; - var currSourceKeys = keys(curSource); - for (var j = 0; j < currSourceKeys.length; j++) { - var currKey = currSourceKeys[j]; - if (!has(target, currKey)) { - target[currKey] = curSource[currKey]; - } - } - } - return target; -} -function defaults() { - var sources = []; - for (var _i = 0; _i < arguments.length; _i++) { - sources[_i] = arguments[_i]; - } - return assignNoOverwrite.apply(null, [{}].concat(sources)); -} -function groupBy(arr, groupKeyFunc) { - var result = {}; - forEach(arr, function (item) { - var currGroupKey = groupKeyFunc(item); - var currGroupArr = result[currGroupKey]; - if (currGroupArr) { - currGroupArr.push(item); - } - else { - result[currGroupKey] = [item]; - } - }); - return result; -} -/** - * Merge obj2 into obj1. - * Will overwrite existing properties with the same name - */ -function merge(obj1, obj2) { - var result = cloneObj(obj1); - var keys2 = keys(obj2); - for (var i = 0; i < keys2.length; i++) { - var key = keys2[i]; - var value = obj2[key]; - result[key] = value; - } - return result; -} -function NOOP() { } -function IDENTITY(item) { - return item; -} -/** - * Will return a new packed array with same values. - */ -function packArray(holeyArr) { - var result = []; - for (var i = 0; i < holeyArr.length; i++) { - var orgValue = holeyArr[i]; - result.push(orgValue !== undefined ? orgValue : undefined); - } - return result; -} -function PRINT_ERROR(msg) { - /* istanbul ignore else - can't override global.console in node.js */ - if (console && console.error) { - console.error("Error: " + msg); - } -} -function PRINT_WARNING(msg) { - /* istanbul ignore else - can't override global.console in node.js*/ - if (console && console.warn) { - // TODO: modify docs accordingly - console.warn("Warning: " + msg); - } -} -function isES2015MapSupported() { - return typeof Map === "function"; -} -function applyMixins(derivedCtor, baseCtors) { - baseCtors.forEach(function (baseCtor) { - var baseProto = baseCtor.prototype; - Object.getOwnPropertyNames(baseProto).forEach(function (propName) { - if (propName === "constructor") { - return; - } - var basePropDescriptor = Object.getOwnPropertyDescriptor(baseProto, propName); - // Handle Accessors - if (basePropDescriptor && - (basePropDescriptor.get || basePropDescriptor.set)) { - Object.defineProperty(derivedCtor.prototype, propName, basePropDescriptor); - } - else { - derivedCtor.prototype[propName] = baseCtor.prototype[propName]; - } - }); - }); -} -// base on: https://github.com/petkaantonov/bluebird/blob/b97c0d2d487e8c5076e8bd897e0dcd4622d31846/src/util.js#L201-L216 -function toFastProperties(toBecomeFast) { - function FakeConstructor() { } - // If our object is used as a constructor it would receive - FakeConstructor.prototype = toBecomeFast; - var fakeInstance = new FakeConstructor(); - function fakeAccess() { - return typeof fakeInstance.bar; - } - // help V8 understand this is a "real" prototype by actually using - // the fake instance. - fakeAccess(); - fakeAccess(); - return toBecomeFast; -} -function peek(arr) { - return arr[arr.length - 1]; -} -/* istanbul ignore next - for performance tracing*/ -function timer(func) { - var start = new Date().getTime(); - var val = func(); - var end = new Date().getTime(); - var total = end - start; - return { time: total, value: val }; -} - -var regexpToAst = {exports: {}}; - -(function (module) { -(function(root, factory) { - // istanbul ignore next - if (module.exports) { - module.exports = factory(); - } else { - // istanbul ignore next - root.regexpToAst = factory(); - } - })( - typeof self !== "undefined" - ? // istanbul ignore next - self - : commonjsGlobal, - function() { - // references - // https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983 - // https://www.ecma-international.org/ecma-262/8.0/index.html#prod-Pattern - function RegExpParser() {} - - RegExpParser.prototype.saveState = function() { - return { - idx: this.idx, - input: this.input, - groupIdx: this.groupIdx - } - }; - - RegExpParser.prototype.restoreState = function(newState) { - this.idx = newState.idx; - this.input = newState.input; - this.groupIdx = newState.groupIdx; - }; - - RegExpParser.prototype.pattern = function(input) { - // parser state - this.idx = 0; - this.input = input; - this.groupIdx = 0; - - this.consumeChar("/"); - var value = this.disjunction(); - this.consumeChar("/"); - - var flags = { - type: "Flags", - loc: { begin: this.idx, end: input.length }, - global: false, - ignoreCase: false, - multiLine: false, - unicode: false, - sticky: false - }; - - while (this.isRegExpFlag()) { - switch (this.popChar()) { - case "g": - addFlag(flags, "global"); - break - case "i": - addFlag(flags, "ignoreCase"); - break - case "m": - addFlag(flags, "multiLine"); - break - case "u": - addFlag(flags, "unicode"); - break - case "y": - addFlag(flags, "sticky"); - break - } - } - - if (this.idx !== this.input.length) { - throw Error( - "Redundant input: " + this.input.substring(this.idx) - ) - } - return { - type: "Pattern", - flags: flags, - value: value, - loc: this.loc(0) - } - }; - - RegExpParser.prototype.disjunction = function() { - var alts = []; - var begin = this.idx; - - alts.push(this.alternative()); - - while (this.peekChar() === "|") { - this.consumeChar("|"); - alts.push(this.alternative()); - } - - return { type: "Disjunction", value: alts, loc: this.loc(begin) } - }; - - RegExpParser.prototype.alternative = function() { - var terms = []; - var begin = this.idx; - - while (this.isTerm()) { - terms.push(this.term()); - } - - return { type: "Alternative", value: terms, loc: this.loc(begin) } - }; - - RegExpParser.prototype.term = function() { - if (this.isAssertion()) { - return this.assertion() - } else { - return this.atom() - } - }; - - RegExpParser.prototype.assertion = function() { - var begin = this.idx; - switch (this.popChar()) { - case "^": - return { - type: "StartAnchor", - loc: this.loc(begin) - } - case "$": - return { type: "EndAnchor", loc: this.loc(begin) } - // '\b' or '\B' - case "\\": - switch (this.popChar()) { - case "b": - return { - type: "WordBoundary", - loc: this.loc(begin) - } - case "B": - return { - type: "NonWordBoundary", - loc: this.loc(begin) - } - } - // istanbul ignore next - throw Error("Invalid Assertion Escape") - // '(?=' or '(?!' - case "(": - this.consumeChar("?"); - - var type; - switch (this.popChar()) { - case "=": - type = "Lookahead"; - break - case "!": - type = "NegativeLookahead"; - break - } - ASSERT_EXISTS(type); - - var disjunction = this.disjunction(); - - this.consumeChar(")"); - - return { - type: type, - value: disjunction, - loc: this.loc(begin) - } - } - // istanbul ignore next - ASSERT_NEVER_REACH_HERE(); - }; - - RegExpParser.prototype.quantifier = function(isBacktracking) { - var range; - var begin = this.idx; - switch (this.popChar()) { - case "*": - range = { - atLeast: 0, - atMost: Infinity - }; - break - case "+": - range = { - atLeast: 1, - atMost: Infinity - }; - break - case "?": - range = { - atLeast: 0, - atMost: 1 - }; - break - case "{": - var atLeast = this.integerIncludingZero(); - switch (this.popChar()) { - case "}": - range = { - atLeast: atLeast, - atMost: atLeast - }; - break - case ",": - var atMost; - if (this.isDigit()) { - atMost = this.integerIncludingZero(); - range = { - atLeast: atLeast, - atMost: atMost - }; - } else { - range = { - atLeast: atLeast, - atMost: Infinity - }; - } - this.consumeChar("}"); - break - } - // throwing exceptions from "ASSERT_EXISTS" during backtracking - // causes severe performance degradations - if (isBacktracking === true && range === undefined) { - return undefined - } - ASSERT_EXISTS(range); - break - } - - // throwing exceptions from "ASSERT_EXISTS" during backtracking - // causes severe performance degradations - if (isBacktracking === true && range === undefined) { - return undefined - } - - ASSERT_EXISTS(range); - - if (this.peekChar(0) === "?") { - this.consumeChar("?"); - range.greedy = false; - } else { - range.greedy = true; - } - - range.type = "Quantifier"; - range.loc = this.loc(begin); - return range - }; - - RegExpParser.prototype.atom = function() { - var atom; - var begin = this.idx; - switch (this.peekChar()) { - case ".": - atom = this.dotAll(); - break - case "\\": - atom = this.atomEscape(); - break - case "[": - atom = this.characterClass(); - break - case "(": - atom = this.group(); - break - } - - if (atom === undefined && this.isPatternCharacter()) { - atom = this.patternCharacter(); - } - - ASSERT_EXISTS(atom); - - atom.loc = this.loc(begin); - - if (this.isQuantifier()) { - atom.quantifier = this.quantifier(); - } - - return atom - }; - - RegExpParser.prototype.dotAll = function() { - this.consumeChar("."); - return { - type: "Set", - complement: true, - value: [cc("\n"), cc("\r"), cc("\u2028"), cc("\u2029")] - } - }; - - RegExpParser.prototype.atomEscape = function() { - this.consumeChar("\\"); - - switch (this.peekChar()) { - case "1": - case "2": - case "3": - case "4": - case "5": - case "6": - case "7": - case "8": - case "9": - return this.decimalEscapeAtom() - case "d": - case "D": - case "s": - case "S": - case "w": - case "W": - return this.characterClassEscape() - case "f": - case "n": - case "r": - case "t": - case "v": - return this.controlEscapeAtom() - case "c": - return this.controlLetterEscapeAtom() - case "0": - return this.nulCharacterAtom() - case "x": - return this.hexEscapeSequenceAtom() - case "u": - return this.regExpUnicodeEscapeSequenceAtom() - default: - return this.identityEscapeAtom() - } - }; - - RegExpParser.prototype.decimalEscapeAtom = function() { - var value = this.positiveInteger(); - - return { type: "GroupBackReference", value: value } - }; - - RegExpParser.prototype.characterClassEscape = function() { - var set; - var complement = false; - switch (this.popChar()) { - case "d": - set = digitsCharCodes; - break - case "D": - set = digitsCharCodes; - complement = true; - break - case "s": - set = whitespaceCodes; - break - case "S": - set = whitespaceCodes; - complement = true; - break - case "w": - set = wordCharCodes; - break - case "W": - set = wordCharCodes; - complement = true; - break - } - - ASSERT_EXISTS(set); - - return { type: "Set", value: set, complement: complement } - }; - - RegExpParser.prototype.controlEscapeAtom = function() { - var escapeCode; - switch (this.popChar()) { - case "f": - escapeCode = cc("\f"); - break - case "n": - escapeCode = cc("\n"); - break - case "r": - escapeCode = cc("\r"); - break - case "t": - escapeCode = cc("\t"); - break - case "v": - escapeCode = cc("\v"); - break - } - ASSERT_EXISTS(escapeCode); - - return { type: "Character", value: escapeCode } - }; - - RegExpParser.prototype.controlLetterEscapeAtom = function() { - this.consumeChar("c"); - var letter = this.popChar(); - if (/[a-zA-Z]/.test(letter) === false) { - throw Error("Invalid ") - } - - var letterCode = letter.toUpperCase().charCodeAt(0) - 64; - return { type: "Character", value: letterCode } - }; - - RegExpParser.prototype.nulCharacterAtom = function() { - // TODO implement '[lookahead ∉ DecimalDigit]' - // TODO: for the deprecated octal escape sequence - this.consumeChar("0"); - return { type: "Character", value: cc("\0") } - }; - - RegExpParser.prototype.hexEscapeSequenceAtom = function() { - this.consumeChar("x"); - return this.parseHexDigits(2) - }; - - RegExpParser.prototype.regExpUnicodeEscapeSequenceAtom = function() { - this.consumeChar("u"); - return this.parseHexDigits(4) - }; - - RegExpParser.prototype.identityEscapeAtom = function() { - // TODO: implement "SourceCharacter but not UnicodeIDContinue" - // // http://unicode.org/reports/tr31/#Specific_Character_Adjustments - var escapedChar = this.popChar(); - return { type: "Character", value: cc(escapedChar) } - }; - - RegExpParser.prototype.classPatternCharacterAtom = function() { - switch (this.peekChar()) { - // istanbul ignore next - case "\n": - // istanbul ignore next - case "\r": - // istanbul ignore next - case "\u2028": - // istanbul ignore next - case "\u2029": - // istanbul ignore next - case "\\": - // istanbul ignore next - case "]": - throw Error("TBD") - default: - var nextChar = this.popChar(); - return { type: "Character", value: cc(nextChar) } - } - }; - - RegExpParser.prototype.characterClass = function() { - var set = []; - var complement = false; - this.consumeChar("["); - if (this.peekChar(0) === "^") { - this.consumeChar("^"); - complement = true; - } - - while (this.isClassAtom()) { - var from = this.classAtom(); - var isFromSingleChar = from.type === "Character"; - if (isFromSingleChar && this.isRangeDash()) { - this.consumeChar("-"); - var to = this.classAtom(); - var isToSingleChar = to.type === "Character"; - - // a range can only be used when both sides are single characters - if (isToSingleChar) { - if (to.value < from.value) { - throw Error("Range out of order in character class") - } - set.push({ from: from.value, to: to.value }); - } else { - // literal dash - insertToSet(from.value, set); - set.push(cc("-")); - insertToSet(to.value, set); - } - } else { - insertToSet(from.value, set); - } - } - - this.consumeChar("]"); - - return { type: "Set", complement: complement, value: set } - }; - - RegExpParser.prototype.classAtom = function() { - switch (this.peekChar()) { - // istanbul ignore next - case "]": - // istanbul ignore next - case "\n": - // istanbul ignore next - case "\r": - // istanbul ignore next - case "\u2028": - // istanbul ignore next - case "\u2029": - throw Error("TBD") - case "\\": - return this.classEscape() - default: - return this.classPatternCharacterAtom() - } - }; - - RegExpParser.prototype.classEscape = function() { - this.consumeChar("\\"); - switch (this.peekChar()) { - // Matches a backspace. - // (Not to be confused with \b word boundary outside characterClass) - case "b": - this.consumeChar("b"); - return { type: "Character", value: cc("\u0008") } - case "d": - case "D": - case "s": - case "S": - case "w": - case "W": - return this.characterClassEscape() - case "f": - case "n": - case "r": - case "t": - case "v": - return this.controlEscapeAtom() - case "c": - return this.controlLetterEscapeAtom() - case "0": - return this.nulCharacterAtom() - case "x": - return this.hexEscapeSequenceAtom() - case "u": - return this.regExpUnicodeEscapeSequenceAtom() - default: - return this.identityEscapeAtom() - } - }; - - RegExpParser.prototype.group = function() { - var capturing = true; - this.consumeChar("("); - switch (this.peekChar(0)) { - case "?": - this.consumeChar("?"); - this.consumeChar(":"); - capturing = false; - break - default: - this.groupIdx++; - break - } - var value = this.disjunction(); - this.consumeChar(")"); - - var groupAst = { - type: "Group", - capturing: capturing, - value: value - }; - - if (capturing) { - groupAst.idx = this.groupIdx; - } - - return groupAst - }; - - RegExpParser.prototype.positiveInteger = function() { - var number = this.popChar(); - - // istanbul ignore next - can't ever get here due to previous lookahead checks - // still implementing this error checking in case this ever changes. - if (decimalPatternNoZero.test(number) === false) { - throw Error("Expecting a positive integer") - } - - while (decimalPattern.test(this.peekChar(0))) { - number += this.popChar(); - } - - return parseInt(number, 10) - }; - - RegExpParser.prototype.integerIncludingZero = function() { - var number = this.popChar(); - if (decimalPattern.test(number) === false) { - throw Error("Expecting an integer") - } - - while (decimalPattern.test(this.peekChar(0))) { - number += this.popChar(); - } - - return parseInt(number, 10) - }; - - RegExpParser.prototype.patternCharacter = function() { - var nextChar = this.popChar(); - switch (nextChar) { - // istanbul ignore next - case "\n": - // istanbul ignore next - case "\r": - // istanbul ignore next - case "\u2028": - // istanbul ignore next - case "\u2029": - // istanbul ignore next - case "^": - // istanbul ignore next - case "$": - // istanbul ignore next - case "\\": - // istanbul ignore next - case ".": - // istanbul ignore next - case "*": - // istanbul ignore next - case "+": - // istanbul ignore next - case "?": - // istanbul ignore next - case "(": - // istanbul ignore next - case ")": - // istanbul ignore next - case "[": - // istanbul ignore next - case "|": - // istanbul ignore next - throw Error("TBD") - default: - return { type: "Character", value: cc(nextChar) } - } - }; - RegExpParser.prototype.isRegExpFlag = function() { - switch (this.peekChar(0)) { - case "g": - case "i": - case "m": - case "u": - case "y": - return true - default: - return false - } - }; - - RegExpParser.prototype.isRangeDash = function() { - return this.peekChar() === "-" && this.isClassAtom(1) - }; - - RegExpParser.prototype.isDigit = function() { - return decimalPattern.test(this.peekChar(0)) - }; - - RegExpParser.prototype.isClassAtom = function(howMuch) { - if (howMuch === undefined) { - howMuch = 0; - } - - switch (this.peekChar(howMuch)) { - case "]": - case "\n": - case "\r": - case "\u2028": - case "\u2029": - return false - default: - return true - } - }; - - RegExpParser.prototype.isTerm = function() { - return this.isAtom() || this.isAssertion() - }; - - RegExpParser.prototype.isAtom = function() { - if (this.isPatternCharacter()) { - return true - } - - switch (this.peekChar(0)) { - case ".": - case "\\": // atomEscape - case "[": // characterClass - // TODO: isAtom must be called before isAssertion - disambiguate - case "(": // group - return true - default: - return false - } - }; - - RegExpParser.prototype.isAssertion = function() { - switch (this.peekChar(0)) { - case "^": - case "$": - return true - // '\b' or '\B' - case "\\": - switch (this.peekChar(1)) { - case "b": - case "B": - return true - default: - return false - } - // '(?=' or '(?!' - case "(": - return ( - this.peekChar(1) === "?" && - (this.peekChar(2) === "=" || this.peekChar(2) === "!") - ) - default: - return false - } - }; - - RegExpParser.prototype.isQuantifier = function() { - var prevState = this.saveState(); - try { - return this.quantifier(true) !== undefined - } catch (e) { - return false - } finally { - this.restoreState(prevState); - } - }; - - RegExpParser.prototype.isPatternCharacter = function() { - switch (this.peekChar()) { - case "^": - case "$": - case "\\": - case ".": - case "*": - case "+": - case "?": - case "(": - case ")": - case "[": - case "|": - case "/": - case "\n": - case "\r": - case "\u2028": - case "\u2029": - return false - default: - return true - } - }; - - RegExpParser.prototype.parseHexDigits = function(howMany) { - var hexString = ""; - for (var i = 0; i < howMany; i++) { - var hexChar = this.popChar(); - if (hexDigitPattern.test(hexChar) === false) { - throw Error("Expecting a HexDecimal digits") - } - hexString += hexChar; - } - var charCode = parseInt(hexString, 16); - return { type: "Character", value: charCode } - }; - - RegExpParser.prototype.peekChar = function(howMuch) { - if (howMuch === undefined) { - howMuch = 0; - } - return this.input[this.idx + howMuch] - }; - - RegExpParser.prototype.popChar = function() { - var nextChar = this.peekChar(0); - this.consumeChar(); - return nextChar - }; - - RegExpParser.prototype.consumeChar = function(char) { - if (char !== undefined && this.input[this.idx] !== char) { - throw Error( - "Expected: '" + - char + - "' but found: '" + - this.input[this.idx] + - "' at offset: " + - this.idx - ) - } - - if (this.idx >= this.input.length) { - throw Error("Unexpected end of input") - } - this.idx++; - }; - - RegExpParser.prototype.loc = function(begin) { - return { begin: begin, end: this.idx } - }; - - // consts and utilities - var hexDigitPattern = /[0-9a-fA-F]/; - var decimalPattern = /[0-9]/; - var decimalPatternNoZero = /[1-9]/; - - function cc(char) { - return char.charCodeAt(0) - } - - function insertToSet(item, set) { - if (item.length !== undefined) { - item.forEach(function(subItem) { - set.push(subItem); - }); - } else { - set.push(item); - } - } - - function addFlag(flagObj, flagKey) { - if (flagObj[flagKey] === true) { - throw "duplicate flag " + flagKey - } - - flagObj[flagKey] = true; - } - - function ASSERT_EXISTS(obj) { - // istanbul ignore next - if (obj === undefined) { - throw Error("Internal Error - Should never get here!") - } - } - - // istanbul ignore next - function ASSERT_NEVER_REACH_HERE() { - throw Error("Internal Error - Should never get here!") - } - - var i; - var digitsCharCodes = []; - for (i = cc("0"); i <= cc("9"); i++) { - digitsCharCodes.push(i); - } - - var wordCharCodes = [cc("_")].concat(digitsCharCodes); - for (i = cc("a"); i <= cc("z"); i++) { - wordCharCodes.push(i); - } - - for (i = cc("A"); i <= cc("Z"); i++) { - wordCharCodes.push(i); - } - - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-classes - var whitespaceCodes = [ - cc(" "), - cc("\f"), - cc("\n"), - cc("\r"), - cc("\t"), - cc("\v"), - cc("\t"), - cc("\u00a0"), - cc("\u1680"), - cc("\u2000"), - cc("\u2001"), - cc("\u2002"), - cc("\u2003"), - cc("\u2004"), - cc("\u2005"), - cc("\u2006"), - cc("\u2007"), - cc("\u2008"), - cc("\u2009"), - cc("\u200a"), - cc("\u2028"), - cc("\u2029"), - cc("\u202f"), - cc("\u205f"), - cc("\u3000"), - cc("\ufeff") - ]; - - function BaseRegExpVisitor() {} - - BaseRegExpVisitor.prototype.visitChildren = function(node) { - for (var key in node) { - var child = node[key]; - /* istanbul ignore else */ - if (node.hasOwnProperty(key)) { - if (child.type !== undefined) { - this.visit(child); - } else if (Array.isArray(child)) { - child.forEach(function(subChild) { - this.visit(subChild); - }, this); - } - } - } - }; - - BaseRegExpVisitor.prototype.visit = function(node) { - switch (node.type) { - case "Pattern": - this.visitPattern(node); - break - case "Flags": - this.visitFlags(node); - break - case "Disjunction": - this.visitDisjunction(node); - break - case "Alternative": - this.visitAlternative(node); - break - case "StartAnchor": - this.visitStartAnchor(node); - break - case "EndAnchor": - this.visitEndAnchor(node); - break - case "WordBoundary": - this.visitWordBoundary(node); - break - case "NonWordBoundary": - this.visitNonWordBoundary(node); - break - case "Lookahead": - this.visitLookahead(node); - break - case "NegativeLookahead": - this.visitNegativeLookahead(node); - break - case "Character": - this.visitCharacter(node); - break - case "Set": - this.visitSet(node); - break - case "Group": - this.visitGroup(node); - break - case "GroupBackReference": - this.visitGroupBackReference(node); - break - case "Quantifier": - this.visitQuantifier(node); - break - } - - this.visitChildren(node); - }; - - BaseRegExpVisitor.prototype.visitPattern = function(node) {}; - - BaseRegExpVisitor.prototype.visitFlags = function(node) {}; - - BaseRegExpVisitor.prototype.visitDisjunction = function(node) {}; - - BaseRegExpVisitor.prototype.visitAlternative = function(node) {}; - - // Assertion - BaseRegExpVisitor.prototype.visitStartAnchor = function(node) {}; - - BaseRegExpVisitor.prototype.visitEndAnchor = function(node) {}; - - BaseRegExpVisitor.prototype.visitWordBoundary = function(node) {}; - - BaseRegExpVisitor.prototype.visitNonWordBoundary = function(node) {}; - - BaseRegExpVisitor.prototype.visitLookahead = function(node) {}; - - BaseRegExpVisitor.prototype.visitNegativeLookahead = function(node) {}; - - // atoms - BaseRegExpVisitor.prototype.visitCharacter = function(node) {}; - - BaseRegExpVisitor.prototype.visitSet = function(node) {}; - - BaseRegExpVisitor.prototype.visitGroup = function(node) {}; - - BaseRegExpVisitor.prototype.visitGroupBackReference = function(node) {}; - - BaseRegExpVisitor.prototype.visitQuantifier = function(node) {}; - - return { - RegExpParser: RegExpParser, - BaseRegExpVisitor: BaseRegExpVisitor, - VERSION: "0.5.0" - } - } - ); -} (regexpToAst)); - -var regExpAstCache = {}; -var regExpParser = new regexpToAst.exports.RegExpParser(); -function getRegExpAst(regExp) { - var regExpStr = regExp.toString(); - if (regExpAstCache.hasOwnProperty(regExpStr)) { - return regExpAstCache[regExpStr]; - } - else { - var regExpAst = regExpParser.pattern(regExpStr); - regExpAstCache[regExpStr] = regExpAst; - return regExpAst; - } -} -function clearRegExpParserCache() { - regExpAstCache = {}; -} - -var __extends$a = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var complementErrorMessage = "Complement Sets are not supported for first char optimization"; -var failedOptimizationPrefixMsg = 'Unable to use "first char" lexer optimizations:\n'; -function getOptimizedStartCodesIndices(regExp, ensureOptimizations) { - if (ensureOptimizations === void 0) { ensureOptimizations = false; } - try { - var ast = getRegExpAst(regExp); - var firstChars = firstCharOptimizedIndices(ast.value, {}, ast.flags.ignoreCase); - return firstChars; - } - catch (e) { - /* istanbul ignore next */ - // Testing this relies on the regexp-to-ast library having a bug... */ - // TODO: only the else branch needs to be ignored, try to fix with newer prettier / tsc - if (e.message === complementErrorMessage) { - if (ensureOptimizations) { - PRINT_WARNING("" + failedOptimizationPrefixMsg + - ("\tUnable to optimize: < " + regExp.toString() + " >\n") + - "\tComplement Sets cannot be automatically optimized.\n" + - "\tThis will disable the lexer's first char optimizations.\n" + - "\tSee: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details."); - } - } - else { - var msgSuffix = ""; - if (ensureOptimizations) { - msgSuffix = - "\n\tThis will disable the lexer's first char optimizations.\n" + - "\tSee: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details."; - } - PRINT_ERROR(failedOptimizationPrefixMsg + "\n" + - ("\tFailed parsing: < " + regExp.toString() + " >\n") + - ("\tUsing the regexp-to-ast library version: " + regexpToAst.exports.VERSION + "\n") + - "\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues" + - msgSuffix); - } - } - return []; -} -function firstCharOptimizedIndices(ast, result, ignoreCase) { - switch (ast.type) { - case "Disjunction": - for (var i = 0; i < ast.value.length; i++) { - firstCharOptimizedIndices(ast.value[i], result, ignoreCase); - } - break; - case "Alternative": - var terms = ast.value; - for (var i = 0; i < terms.length; i++) { - var term = terms[i]; - // skip terms that cannot effect the first char results - switch (term.type) { - case "EndAnchor": - // A group back reference cannot affect potential starting char. - // because if a back reference is the first production than automatically - // the group being referenced has had to come BEFORE so its codes have already been added - case "GroupBackReference": - // assertions do not affect potential starting codes - case "Lookahead": - case "NegativeLookahead": - case "StartAnchor": - case "WordBoundary": - case "NonWordBoundary": - continue; - } - var atom = term; - switch (atom.type) { - case "Character": - addOptimizedIdxToResult(atom.value, result, ignoreCase); - break; - case "Set": - if (atom.complement === true) { - throw Error(complementErrorMessage); - } - forEach(atom.value, function (code) { - if (typeof code === "number") { - addOptimizedIdxToResult(code, result, ignoreCase); - } - else { - // range - var range = code; - // cannot optimize when ignoreCase is - if (ignoreCase === true) { - for (var rangeCode = range.from; rangeCode <= range.to; rangeCode++) { - addOptimizedIdxToResult(rangeCode, result, ignoreCase); - } - } - // Optimization (2 orders of magnitude less work for very large ranges) - else { - // handle unoptimized values - for (var rangeCode = range.from; rangeCode <= range.to && rangeCode < minOptimizationVal; rangeCode++) { - addOptimizedIdxToResult(rangeCode, result, ignoreCase); - } - // Less common charCode where we optimize for faster init time, by using larger "buckets" - if (range.to >= minOptimizationVal) { - var minUnOptVal = range.from >= minOptimizationVal - ? range.from - : minOptimizationVal; - var maxUnOptVal = range.to; - var minOptIdx = charCodeToOptimizedIndex(minUnOptVal); - var maxOptIdx = charCodeToOptimizedIndex(maxUnOptVal); - for (var currOptIdx = minOptIdx; currOptIdx <= maxOptIdx; currOptIdx++) { - result[currOptIdx] = currOptIdx; - } - } - } - } - }); - break; - case "Group": - firstCharOptimizedIndices(atom.value, result, ignoreCase); - break; - /* istanbul ignore next */ - default: - throw Error("Non Exhaustive Match"); - } - // reached a mandatory production, no more **start** codes can be found on this alternative - var isOptionalQuantifier = atom.quantifier !== undefined && atom.quantifier.atLeast === 0; - if ( - // A group may be optional due to empty contents /(?:)/ - // or if everything inside it is optional /((a)?)/ - (atom.type === "Group" && isWholeOptional(atom) === false) || - // If this term is not a group it may only be optional if it has an optional quantifier - (atom.type !== "Group" && isOptionalQuantifier === false)) { - break; - } - } - break; - /* istanbul ignore next */ - default: - throw Error("non exhaustive match!"); - } - // console.log(Object.keys(result).length) - return values(result); -} -function addOptimizedIdxToResult(code, result, ignoreCase) { - var optimizedCharIdx = charCodeToOptimizedIndex(code); - result[optimizedCharIdx] = optimizedCharIdx; - if (ignoreCase === true) { - handleIgnoreCase(code, result); - } -} -function handleIgnoreCase(code, result) { - var char = String.fromCharCode(code); - var upperChar = char.toUpperCase(); - /* istanbul ignore else */ - if (upperChar !== char) { - var optimizedCharIdx = charCodeToOptimizedIndex(upperChar.charCodeAt(0)); - result[optimizedCharIdx] = optimizedCharIdx; - } - else { - var lowerChar = char.toLowerCase(); - if (lowerChar !== char) { - var optimizedCharIdx = charCodeToOptimizedIndex(lowerChar.charCodeAt(0)); - result[optimizedCharIdx] = optimizedCharIdx; - } - } -} -function findCode(setNode, targetCharCodes) { - return find(setNode.value, function (codeOrRange) { - if (typeof codeOrRange === "number") { - return contains(targetCharCodes, codeOrRange); - } - else { - // range - var range_1 = codeOrRange; - return (find(targetCharCodes, function (targetCode) { return range_1.from <= targetCode && targetCode <= range_1.to; }) !== undefined); - } - }); -} -function isWholeOptional(ast) { - if (ast.quantifier && ast.quantifier.atLeast === 0) { - return true; - } - if (!ast.value) { - return false; - } - return isArray(ast.value) - ? every(ast.value, isWholeOptional) - : isWholeOptional(ast.value); -} -var CharCodeFinder = /** @class */ (function (_super) { - __extends$a(CharCodeFinder, _super); - function CharCodeFinder(targetCharCodes) { - var _this = _super.call(this) || this; - _this.targetCharCodes = targetCharCodes; - _this.found = false; - return _this; - } - CharCodeFinder.prototype.visitChildren = function (node) { - // No need to keep looking... - if (this.found === true) { - return; - } - // switch lookaheads as they do not actually consume any characters thus - // finding a charCode at lookahead context does not mean that regexp can actually contain it in a match. - switch (node.type) { - case "Lookahead": - this.visitLookahead(node); - return; - case "NegativeLookahead": - this.visitNegativeLookahead(node); - return; - } - _super.prototype.visitChildren.call(this, node); - }; - CharCodeFinder.prototype.visitCharacter = function (node) { - if (contains(this.targetCharCodes, node.value)) { - this.found = true; - } - }; - CharCodeFinder.prototype.visitSet = function (node) { - if (node.complement) { - if (findCode(node, this.targetCharCodes) === undefined) { - this.found = true; - } - } - else { - if (findCode(node, this.targetCharCodes) !== undefined) { - this.found = true; - } - } - }; - return CharCodeFinder; -}(regexpToAst.exports.BaseRegExpVisitor)); -function canMatchCharCode(charCodes, pattern) { - if (pattern instanceof RegExp) { - var ast = getRegExpAst(pattern); - var charCodeFinder = new CharCodeFinder(charCodes); - charCodeFinder.visit(ast); - return charCodeFinder.found; - } - else { - return (find(pattern, function (char) { - return contains(charCodes, char.charCodeAt(0)); - }) !== undefined); - } -} - -var __extends$9 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var PATTERN = "PATTERN"; -var DEFAULT_MODE = "defaultMode"; -var MODES = "modes"; -var SUPPORT_STICKY = typeof new RegExp("(?:)").sticky === "boolean"; -function analyzeTokenTypes(tokenTypes, options) { - options = defaults(options, { - useSticky: SUPPORT_STICKY, - debug: false, - safeMode: false, - positionTracking: "full", - lineTerminatorCharacters: ["\r", "\n"], - tracer: function (msg, action) { return action(); } - }); - var tracer = options.tracer; - tracer("initCharCodeToOptimizedIndexMap", function () { - initCharCodeToOptimizedIndexMap(); - }); - var onlyRelevantTypes; - tracer("Reject Lexer.NA", function () { - onlyRelevantTypes = reject(tokenTypes, function (currType) { - return currType[PATTERN] === Lexer$1.NA; - }); - }); - var hasCustom = false; - var allTransformedPatterns; - tracer("Transform Patterns", function () { - hasCustom = false; - allTransformedPatterns = map(onlyRelevantTypes, function (currType) { - var currPattern = currType[PATTERN]; - /* istanbul ignore else */ - if (isRegExp(currPattern)) { - var regExpSource = currPattern.source; - if (regExpSource.length === 1 && - // only these regExp meta characters which can appear in a length one regExp - regExpSource !== "^" && - regExpSource !== "$" && - regExpSource !== "." && - !currPattern.ignoreCase) { - return regExpSource; - } - else if (regExpSource.length === 2 && - regExpSource[0] === "\\" && - // not a meta character - !contains([ - "d", - "D", - "s", - "S", - "t", - "r", - "n", - "t", - "0", - "c", - "b", - "B", - "f", - "v", - "w", - "W" - ], regExpSource[1])) { - // escaped meta Characters: /\+/ /\[/ - // or redundant escaping: /\a/ - // without the escaping "\" - return regExpSource[1]; - } - else { - return options.useSticky - ? addStickyFlag(currPattern) - : addStartOfInput(currPattern); - } - } - else if (isFunction(currPattern)) { - hasCustom = true; - // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object - return { exec: currPattern }; - } - else if (has(currPattern, "exec")) { - hasCustom = true; - // ICustomPattern - return currPattern; - } - else if (typeof currPattern === "string") { - if (currPattern.length === 1) { - return currPattern; - } - else { - var escapedRegExpString = currPattern.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"); - var wrappedRegExp = new RegExp(escapedRegExpString); - return options.useSticky - ? addStickyFlag(wrappedRegExp) - : addStartOfInput(wrappedRegExp); - } - } - else { - throw Error("non exhaustive match"); - } - }); - }); - var patternIdxToType; - var patternIdxToGroup; - var patternIdxToLongerAltIdx; - var patternIdxToPushMode; - var patternIdxToPopMode; - tracer("misc mapping", function () { - patternIdxToType = map(onlyRelevantTypes, function (currType) { return currType.tokenTypeIdx; }); - patternIdxToGroup = map(onlyRelevantTypes, function (clazz) { - var groupName = clazz.GROUP; - /* istanbul ignore next */ - if (groupName === Lexer$1.SKIPPED) { - return undefined; - } - else if (isString(groupName)) { - return groupName; - } - else if (isUndefined(groupName)) { - return false; - } - else { - throw Error("non exhaustive match"); - } - }); - patternIdxToLongerAltIdx = map(onlyRelevantTypes, function (clazz) { - var longerAltType = clazz.LONGER_ALT; - if (longerAltType) { - var longerAltIdx = indexOf(onlyRelevantTypes, longerAltType); - return longerAltIdx; - } - }); - patternIdxToPushMode = map(onlyRelevantTypes, function (clazz) { return clazz.PUSH_MODE; }); - patternIdxToPopMode = map(onlyRelevantTypes, function (clazz) { - return has(clazz, "POP_MODE"); - }); - }); - var patternIdxToCanLineTerminator; - tracer("Line Terminator Handling", function () { - var lineTerminatorCharCodes = getCharCodes(options.lineTerminatorCharacters); - patternIdxToCanLineTerminator = map(onlyRelevantTypes, function (tokType) { return false; }); - if (options.positionTracking !== "onlyOffset") { - patternIdxToCanLineTerminator = map(onlyRelevantTypes, function (tokType) { - if (has(tokType, "LINE_BREAKS")) { - return tokType.LINE_BREAKS; - } - else { - if (checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false) { - return canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN); - } - } - }); - } - }); - var patternIdxToIsCustom; - var patternIdxToShort; - var emptyGroups; - var patternIdxToConfig; - tracer("Misc Mapping #2", function () { - patternIdxToIsCustom = map(onlyRelevantTypes, isCustomPattern); - patternIdxToShort = map(allTransformedPatterns, isShortPattern); - emptyGroups = reduce(onlyRelevantTypes, function (acc, clazz) { - var groupName = clazz.GROUP; - if (isString(groupName) && !(groupName === Lexer$1.SKIPPED)) { - acc[groupName] = []; - } - return acc; - }, {}); - patternIdxToConfig = map(allTransformedPatterns, function (x, idx) { - return { - pattern: allTransformedPatterns[idx], - longerAlt: patternIdxToLongerAltIdx[idx], - canLineTerminator: patternIdxToCanLineTerminator[idx], - isCustom: patternIdxToIsCustom[idx], - short: patternIdxToShort[idx], - group: patternIdxToGroup[idx], - push: patternIdxToPushMode[idx], - pop: patternIdxToPopMode[idx], - tokenTypeIdx: patternIdxToType[idx], - tokenType: onlyRelevantTypes[idx] - }; - }); - }); - var canBeOptimized = true; - var charCodeToPatternIdxToConfig = []; - if (!options.safeMode) { - tracer("First Char Optimization", function () { - charCodeToPatternIdxToConfig = reduce(onlyRelevantTypes, function (result, currTokType, idx) { - if (typeof currTokType.PATTERN === "string") { - var charCode = currTokType.PATTERN.charCodeAt(0); - var optimizedIdx = charCodeToOptimizedIndex(charCode); - addToMapOfArrays(result, optimizedIdx, patternIdxToConfig[idx]); - } - else if (isArray(currTokType.START_CHARS_HINT)) { - var lastOptimizedIdx_1; - forEach(currTokType.START_CHARS_HINT, function (charOrInt) { - var charCode = typeof charOrInt === "string" - ? charOrInt.charCodeAt(0) - : charOrInt; - var currOptimizedIdx = charCodeToOptimizedIndex(charCode); - // Avoid adding the config multiple times - /* istanbul ignore else */ - // - Difficult to check this scenario effects as it is only a performance - // optimization that does not change correctness - if (lastOptimizedIdx_1 !== currOptimizedIdx) { - lastOptimizedIdx_1 = currOptimizedIdx; - addToMapOfArrays(result, currOptimizedIdx, patternIdxToConfig[idx]); - } - }); - } - else if (isRegExp(currTokType.PATTERN)) { - if (currTokType.PATTERN.unicode) { - canBeOptimized = false; - if (options.ensureOptimizations) { - PRINT_ERROR("" + failedOptimizationPrefixMsg + - ("\tUnable to analyze < " + currTokType.PATTERN.toString() + " > pattern.\n") + - "\tThe regexp unicode flag is not currently supported by the regexp-to-ast library.\n" + - "\tThis will disable the lexer's first char optimizations.\n" + - "\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE"); - } - } - else { - var optimizedCodes = getOptimizedStartCodesIndices(currTokType.PATTERN, options.ensureOptimizations); - /* istanbul ignore if */ - // start code will only be empty given an empty regExp or failure of regexp-to-ast library - // the first should be a different validation and the second cannot be tested. - if (isEmpty(optimizedCodes)) { - // we cannot understand what codes may start possible matches - // The optimization correctness requires knowing start codes for ALL patterns. - // Not actually sure this is an error, no debug message - canBeOptimized = false; - } - forEach(optimizedCodes, function (code) { - addToMapOfArrays(result, code, patternIdxToConfig[idx]); - }); - } - } - else { - if (options.ensureOptimizations) { - PRINT_ERROR("" + failedOptimizationPrefixMsg + - ("\tTokenType: <" + currTokType.name + "> is using a custom token pattern without providing parameter.\n") + - "\tThis will disable the lexer's first char optimizations.\n" + - "\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE"); - } - canBeOptimized = false; - } - return result; - }, []); - }); - } - tracer("ArrayPacking", function () { - charCodeToPatternIdxToConfig = packArray(charCodeToPatternIdxToConfig); - }); - return { - emptyGroups: emptyGroups, - patternIdxToConfig: patternIdxToConfig, - charCodeToPatternIdxToConfig: charCodeToPatternIdxToConfig, - hasCustom: hasCustom, - canBeOptimized: canBeOptimized - }; -} -function validatePatterns(tokenTypes, validModesNames) { - var errors = []; - var missingResult = findMissingPatterns(tokenTypes); - errors = errors.concat(missingResult.errors); - var invalidResult = findInvalidPatterns(missingResult.valid); - var validTokenTypes = invalidResult.valid; - errors = errors.concat(invalidResult.errors); - errors = errors.concat(validateRegExpPattern(validTokenTypes)); - errors = errors.concat(findInvalidGroupType(validTokenTypes)); - errors = errors.concat(findModesThatDoNotExist(validTokenTypes, validModesNames)); - errors = errors.concat(findUnreachablePatterns(validTokenTypes)); - return errors; -} -function validateRegExpPattern(tokenTypes) { - var errors = []; - var withRegExpPatterns = filter(tokenTypes, function (currTokType) { - return isRegExp(currTokType[PATTERN]); - }); - errors = errors.concat(findEndOfInputAnchor(withRegExpPatterns)); - errors = errors.concat(findStartOfInputAnchor(withRegExpPatterns)); - errors = errors.concat(findUnsupportedFlags(withRegExpPatterns)); - errors = errors.concat(findDuplicatePatterns(withRegExpPatterns)); - errors = errors.concat(findEmptyMatchRegExps(withRegExpPatterns)); - return errors; -} -function findMissingPatterns(tokenTypes) { - var tokenTypesWithMissingPattern = filter(tokenTypes, function (currType) { - return !has(currType, PATTERN); - }); - var errors = map(tokenTypesWithMissingPattern, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- missing static 'PATTERN' property", - type: LexerDefinitionErrorType.MISSING_PATTERN, - tokenTypes: [currType] - }; - }); - var valid = difference(tokenTypes, tokenTypesWithMissingPattern); - return { errors: errors, valid: valid }; -} -function findInvalidPatterns(tokenTypes) { - var tokenTypesWithInvalidPattern = filter(tokenTypes, function (currType) { - var pattern = currType[PATTERN]; - return (!isRegExp(pattern) && - !isFunction(pattern) && - !has(pattern, "exec") && - !isString(pattern)); - }); - var errors = map(tokenTypesWithInvalidPattern, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'PATTERN' can only be a RegExp, a" + - " Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.", - type: LexerDefinitionErrorType.INVALID_PATTERN, - tokenTypes: [currType] - }; - }); - var valid = difference(tokenTypes, tokenTypesWithInvalidPattern); - return { errors: errors, valid: valid }; -} -var end_of_input = /[^\\][\$]/; -function findEndOfInputAnchor(tokenTypes) { - var EndAnchorFinder = /** @class */ (function (_super) { - __extends$9(EndAnchorFinder, _super); - function EndAnchorFinder() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.found = false; - return _this; - } - EndAnchorFinder.prototype.visitEndAnchor = function (node) { - this.found = true; - }; - return EndAnchorFinder; - }(regexpToAst.exports.BaseRegExpVisitor)); - var invalidRegex = filter(tokenTypes, function (currType) { - var pattern = currType[PATTERN]; - try { - var regexpAst = getRegExpAst(pattern); - var endAnchorVisitor = new EndAnchorFinder(); - endAnchorVisitor.visit(regexpAst); - return endAnchorVisitor.found; - } - catch (e) { - // old behavior in case of runtime exceptions with regexp-to-ast. - /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/ - return end_of_input.test(pattern.source); - } - }); - var errors = map(invalidRegex, function (currType) { - return { - message: "Unexpected RegExp Anchor Error:\n" + - "\tToken Type: ->" + - currType.name + - "<- static 'PATTERN' cannot contain end of input anchor '$'\n" + - "\tSee sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#ANCHORS" + - "\tfor details.", - type: LexerDefinitionErrorType.EOI_ANCHOR_FOUND, - tokenTypes: [currType] - }; - }); - return errors; -} -function findEmptyMatchRegExps(tokenTypes) { - var matchesEmptyString = filter(tokenTypes, function (currType) { - var pattern = currType[PATTERN]; - return pattern.test(""); - }); - var errors = map(matchesEmptyString, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'PATTERN' must not match an empty string", - type: LexerDefinitionErrorType.EMPTY_MATCH_PATTERN, - tokenTypes: [currType] - }; - }); - return errors; -} -var start_of_input = /[^\\[][\^]|^\^/; -function findStartOfInputAnchor(tokenTypes) { - var StartAnchorFinder = /** @class */ (function (_super) { - __extends$9(StartAnchorFinder, _super); - function StartAnchorFinder() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.found = false; - return _this; - } - StartAnchorFinder.prototype.visitStartAnchor = function (node) { - this.found = true; - }; - return StartAnchorFinder; - }(regexpToAst.exports.BaseRegExpVisitor)); - var invalidRegex = filter(tokenTypes, function (currType) { - var pattern = currType[PATTERN]; - try { - var regexpAst = getRegExpAst(pattern); - var startAnchorVisitor = new StartAnchorFinder(); - startAnchorVisitor.visit(regexpAst); - return startAnchorVisitor.found; - } - catch (e) { - // old behavior in case of runtime exceptions with regexp-to-ast. - /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/ - return start_of_input.test(pattern.source); - } - }); - var errors = map(invalidRegex, function (currType) { - return { - message: "Unexpected RegExp Anchor Error:\n" + - "\tToken Type: ->" + - currType.name + - "<- static 'PATTERN' cannot contain start of input anchor '^'\n" + - "\tSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#ANCHORS" + - "\tfor details.", - type: LexerDefinitionErrorType.SOI_ANCHOR_FOUND, - tokenTypes: [currType] - }; - }); - return errors; -} -function findUnsupportedFlags(tokenTypes) { - var invalidFlags = filter(tokenTypes, function (currType) { - var pattern = currType[PATTERN]; - return pattern instanceof RegExp && (pattern.multiline || pattern.global); - }); - var errors = map(invalidFlags, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'PATTERN' may NOT contain global('g') or multiline('m')", - type: LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND, - tokenTypes: [currType] - }; - }); - return errors; -} -// This can only test for identical duplicate RegExps, not semantically equivalent ones. -function findDuplicatePatterns(tokenTypes) { - var found = []; - var identicalPatterns = map(tokenTypes, function (outerType) { - return reduce(tokenTypes, function (result, innerType) { - if (outerType.PATTERN.source === innerType.PATTERN.source && - !contains(found, innerType) && - innerType.PATTERN !== Lexer$1.NA) { - // this avoids duplicates in the result, each Token Type may only appear in one "set" - // in essence we are creating Equivalence classes on equality relation. - found.push(innerType); - result.push(innerType); - return result; - } - return result; - }, []); - }); - identicalPatterns = compact(identicalPatterns); - var duplicatePatterns = filter(identicalPatterns, function (currIdenticalSet) { - return currIdenticalSet.length > 1; - }); - var errors = map(duplicatePatterns, function (setOfIdentical) { - var tokenTypeNames = map(setOfIdentical, function (currType) { - return currType.name; - }); - var dupPatternSrc = first$1(setOfIdentical).PATTERN; - return { - message: "The same RegExp pattern ->" + dupPatternSrc + "<-" + - ("has been used in all of the following Token Types: " + tokenTypeNames.join(", ") + " <-"), - type: LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND, - tokenTypes: setOfIdentical - }; - }); - return errors; -} -function findInvalidGroupType(tokenTypes) { - var invalidTypes = filter(tokenTypes, function (clazz) { - if (!has(clazz, "GROUP")) { - return false; - } - var group = clazz.GROUP; - return group !== Lexer$1.SKIPPED && group !== Lexer$1.NA && !isString(group); - }); - var errors = map(invalidTypes, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String", - type: LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND, - tokenTypes: [currType] - }; - }); - return errors; -} -function findModesThatDoNotExist(tokenTypes, validModes) { - var invalidModes = filter(tokenTypes, function (clazz) { - return (clazz.PUSH_MODE !== undefined && !contains(validModes, clazz.PUSH_MODE)); - }); - var errors = map(invalidModes, function (tokType) { - var msg = "Token Type: ->" + tokType.name + "<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->" + tokType.PUSH_MODE + "<-" + - "which does not exist"; - return { - message: msg, - type: LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST, - tokenTypes: [tokType] - }; - }); - return errors; -} -function findUnreachablePatterns(tokenTypes) { - var errors = []; - var canBeTested = reduce(tokenTypes, function (result, tokType, idx) { - var pattern = tokType.PATTERN; - if (pattern === Lexer$1.NA) { - return result; - } - // a more comprehensive validation for all forms of regExps would require - // deeper regExp analysis capabilities - if (isString(pattern)) { - result.push({ str: pattern, idx: idx, tokenType: tokType }); - } - else if (isRegExp(pattern) && noMetaChar(pattern)) { - result.push({ str: pattern.source, idx: idx, tokenType: tokType }); - } - return result; - }, []); - forEach(tokenTypes, function (tokType, testIdx) { - forEach(canBeTested, function (_a) { - var str = _a.str, idx = _a.idx, tokenType = _a.tokenType; - if (testIdx < idx && testTokenType(str, tokType.PATTERN)) { - var msg = "Token: ->" + tokenType.name + "<- can never be matched.\n" + - ("Because it appears AFTER the Token Type ->" + tokType.name + "<-") + - "in the lexer's definition.\n" + - "See https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#UNREACHABLE"; - errors.push({ - message: msg, - type: LexerDefinitionErrorType.UNREACHABLE_PATTERN, - tokenTypes: [tokType, tokenType] - }); - } - }); - }); - return errors; -} -function testTokenType(str, pattern) { - /* istanbul ignore else */ - if (isRegExp(pattern)) { - var regExpArray = pattern.exec(str); - return regExpArray !== null && regExpArray.index === 0; - } - else if (isFunction(pattern)) { - // maintain the API of custom patterns - return pattern(str, 0, [], {}); - } - else if (has(pattern, "exec")) { - // maintain the API of custom patterns - return pattern.exec(str, 0, [], {}); - } - else if (typeof pattern === "string") { - return pattern === str; - } - else { - throw Error("non exhaustive match"); - } -} -function noMetaChar(regExp) { - //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp - var metaChars = [ - ".", - "\\", - "[", - "]", - "|", - "^", - "$", - "(", - ")", - "?", - "*", - "+", - "{" - ]; - return (find(metaChars, function (char) { return regExp.source.indexOf(char) !== -1; }) === undefined); -} -function addStartOfInput(pattern) { - var flags = pattern.ignoreCase ? "i" : ""; - // always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input. - // duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/) - return new RegExp("^(?:" + pattern.source + ")", flags); -} -function addStickyFlag(pattern) { - var flags = pattern.ignoreCase ? "iy" : "y"; - // always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input. - // duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/) - return new RegExp("" + pattern.source, flags); -} -function performRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) { - var errors = []; - // some run time checks to help the end users. - if (!has(lexerDefinition, DEFAULT_MODE)) { - errors.push({ - message: "A MultiMode Lexer cannot be initialized without a <" + - DEFAULT_MODE + - "> property in its definition\n", - type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE - }); - } - if (!has(lexerDefinition, MODES)) { - errors.push({ - message: "A MultiMode Lexer cannot be initialized without a <" + - MODES + - "> property in its definition\n", - type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY - }); - } - if (has(lexerDefinition, MODES) && - has(lexerDefinition, DEFAULT_MODE) && - !has(lexerDefinition.modes, lexerDefinition.defaultMode)) { - errors.push({ - message: "A MultiMode Lexer cannot be initialized with a " + DEFAULT_MODE + ": <" + lexerDefinition.defaultMode + ">" + - "which does not exist\n", - type: LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST - }); - } - if (has(lexerDefinition, MODES)) { - forEach(lexerDefinition.modes, function (currModeValue, currModeName) { - forEach(currModeValue, function (currTokType, currIdx) { - if (isUndefined(currTokType)) { - errors.push({ - message: "A Lexer cannot be initialized using an undefined Token Type. Mode:" + - ("<" + currModeName + "> at index: <" + currIdx + ">\n"), - type: LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED - }); - } - }); - }); - } - return errors; -} -function performWarningRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) { - var warnings = []; - var hasAnyLineBreak = false; - var allTokenTypes = compact(flatten(mapValues(lexerDefinition.modes, function (tokTypes) { return tokTypes; }))); - var concreteTokenTypes = reject(allTokenTypes, function (currType) { return currType[PATTERN] === Lexer$1.NA; }); - var terminatorCharCodes = getCharCodes(lineTerminatorCharacters); - if (trackLines) { - forEach(concreteTokenTypes, function (tokType) { - var currIssue = checkLineBreaksIssues(tokType, terminatorCharCodes); - if (currIssue !== false) { - var message = buildLineBreakIssueMessage(tokType, currIssue); - var warningDescriptor = { - message: message, - type: currIssue.issue, - tokenType: tokType - }; - warnings.push(warningDescriptor); - } - else { - // we don't want to attempt to scan if the user explicitly specified the line_breaks option. - if (has(tokType, "LINE_BREAKS")) { - if (tokType.LINE_BREAKS === true) { - hasAnyLineBreak = true; - } - } - else { - if (canMatchCharCode(terminatorCharCodes, tokType.PATTERN)) { - hasAnyLineBreak = true; - } - } - } - }); - } - if (trackLines && !hasAnyLineBreak) { - warnings.push({ - message: "Warning: No LINE_BREAKS Found.\n" + - "\tThis Lexer has been defined to track line and column information,\n" + - "\tBut none of the Token Types can be identified as matching a line terminator.\n" + - "\tSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n" + - "\tfor details.", - type: LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS - }); - } - return warnings; -} -function cloneEmptyGroups(emptyGroups) { - var clonedResult = {}; - var groupKeys = keys(emptyGroups); - forEach(groupKeys, function (currKey) { - var currGroupValue = emptyGroups[currKey]; - /* istanbul ignore else */ - if (isArray(currGroupValue)) { - clonedResult[currKey] = []; - } - else { - throw Error("non exhaustive match"); - } - }); - return clonedResult; -} -// TODO: refactor to avoid duplication -function isCustomPattern(tokenType) { - var pattern = tokenType.PATTERN; - /* istanbul ignore else */ - if (isRegExp(pattern)) { - return false; - } - else if (isFunction(pattern)) { - // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object - return true; - } - else if (has(pattern, "exec")) { - // ICustomPattern - return true; - } - else if (isString(pattern)) { - return false; - } - else { - throw Error("non exhaustive match"); - } -} -function isShortPattern(pattern) { - if (isString(pattern) && pattern.length === 1) { - return pattern.charCodeAt(0); - } - else { - return false; - } -} -/** - * Faster than using a RegExp for default newline detection during lexing. - */ -var LineTerminatorOptimizedTester = { - // implements /\n|\r\n?/g.test - test: function (text) { - var len = text.length; - for (var i = this.lastIndex; i < len; i++) { - var c = text.charCodeAt(i); - if (c === 10) { - this.lastIndex = i + 1; - return true; - } - else if (c === 13) { - if (text.charCodeAt(i + 1) === 10) { - this.lastIndex = i + 2; - } - else { - this.lastIndex = i + 1; - } - return true; - } - } - return false; - }, - lastIndex: 0 -}; -function checkLineBreaksIssues(tokType, lineTerminatorCharCodes) { - if (has(tokType, "LINE_BREAKS")) { - // if the user explicitly declared the line_breaks option we will respect their choice - // and assume it is correct. - return false; - } - else { - /* istanbul ignore else */ - if (isRegExp(tokType.PATTERN)) { - try { - canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN); - } - catch (e) { - /* istanbul ignore next - to test this we would have to mock to throw an error */ - return { - issue: LexerDefinitionErrorType.IDENTIFY_TERMINATOR, - errMsg: e.message - }; - } - return false; - } - else if (isString(tokType.PATTERN)) { - // string literal patterns can always be analyzed to detect line terminator usage - return false; - } - else if (isCustomPattern(tokType)) { - // custom token types - return { issue: LexerDefinitionErrorType.CUSTOM_LINE_BREAK }; - } - else { - throw Error("non exhaustive match"); - } - } -} -function buildLineBreakIssueMessage(tokType, details) { - /* istanbul ignore else */ - if (details.issue === LexerDefinitionErrorType.IDENTIFY_TERMINATOR) { - return ("Warning: unable to identify line terminator usage in pattern.\n" + - ("\tThe problem is in the <" + tokType.name + "> Token Type\n") + - ("\t Root cause: " + details.errMsg + ".\n") + - "\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR"); - } - else if (details.issue === LexerDefinitionErrorType.CUSTOM_LINE_BREAK) { - return ("Warning: A Custom Token Pattern should specify the option.\n" + - ("\tThe problem is in the <" + tokType.name + "> Token Type\n") + - "\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK"); - } - else { - throw Error("non exhaustive match"); - } -} -function getCharCodes(charsOrCodes) { - var charCodes = map(charsOrCodes, function (numOrString) { - if (isString(numOrString) && numOrString.length > 0) { - return numOrString.charCodeAt(0); - } - else { - return numOrString; - } - }); - return charCodes; -} -function addToMapOfArrays(map, key, value) { - if (map[key] === undefined) { - map[key] = [value]; - } - else { - map[key].push(value); - } -} -var minOptimizationVal = 256; -/** - * We ae mapping charCode above ASCI (256) into buckets each in the size of 256. - * This is because ASCI are the most common start chars so each one of those will get its own - * possible token configs vector. - * - * Tokens starting with charCodes "above" ASCI are uncommon, so we can "afford" - * to place these into buckets of possible token configs, What we gain from - * this is avoiding the case of creating an optimization 'charCodeToPatternIdxToConfig' - * which would contain 10,000+ arrays of small size (e.g unicode Identifiers scenario). - * Our 'charCodeToPatternIdxToConfig' max size will now be: - * 256 + (2^16 / 2^8) - 1 === 511 - * - * note the hack for fast division integer part extraction - * See: https://stackoverflow.com/a/4228528 - */ -function charCodeToOptimizedIndex(charCode) { - return charCode < minOptimizationVal - ? charCode - : charCodeToOptimizedIdxMap[charCode]; -} -/** - * This is a compromise between cold start / hot running performance - * Creating this array takes ~3ms on a modern machine, - * But if we perform the computation at runtime as needed the CSS Lexer benchmark - * performance degrades by ~10% - * - * TODO: Perhaps it should be lazy initialized only if a charCode > 255 is used. - */ -var charCodeToOptimizedIdxMap = []; -function initCharCodeToOptimizedIndexMap() { - if (isEmpty(charCodeToOptimizedIdxMap)) { - charCodeToOptimizedIdxMap = new Array(65536); - for (var i = 0; i < 65536; i++) { - /* tslint:disable */ - charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i; - /* tslint:enable */ - } - } -} - -function tokenStructuredMatcher(tokInstance, tokConstructor) { - var instanceType = tokInstance.tokenTypeIdx; - if (instanceType === tokConstructor.tokenTypeIdx) { - return true; - } - else { - return (tokConstructor.isParent === true && - tokConstructor.categoryMatchesMap[instanceType] === true); - } -} -// Optimized tokenMatcher in case our grammar does not use token categories -// Being so tiny it is much more likely to be in-lined and this avoid the function call overhead -function tokenStructuredMatcherNoCategories(token, tokType) { - return token.tokenTypeIdx === tokType.tokenTypeIdx; -} -var tokenShortNameIdx = 1; -var tokenIdxToClass = {}; -function augmentTokenTypes(tokenTypes) { - // collect the parent Token Types as well. - var tokenTypesAndParents = expandCategories(tokenTypes); - // add required tokenType and categoryMatches properties - assignTokenDefaultProps(tokenTypesAndParents); - // fill up the categoryMatches - assignCategoriesMapProp(tokenTypesAndParents); - assignCategoriesTokensProp(tokenTypesAndParents); - forEach(tokenTypesAndParents, function (tokType) { - tokType.isParent = tokType.categoryMatches.length > 0; - }); -} -function expandCategories(tokenTypes) { - var result = cloneArr(tokenTypes); - var categories = tokenTypes; - var searching = true; - while (searching) { - categories = compact(flatten(map(categories, function (currTokType) { return currTokType.CATEGORIES; }))); - var newCategories = difference(categories, result); - result = result.concat(newCategories); - if (isEmpty(newCategories)) { - searching = false; - } - else { - categories = newCategories; - } - } - return result; -} -function assignTokenDefaultProps(tokenTypes) { - forEach(tokenTypes, function (currTokType) { - if (!hasShortKeyProperty(currTokType)) { - tokenIdxToClass[tokenShortNameIdx] = currTokType; - currTokType.tokenTypeIdx = tokenShortNameIdx++; - } - // CATEGORIES? : TokenType | TokenType[] - if (hasCategoriesProperty(currTokType) && - !isArray(currTokType.CATEGORIES) - // && - // !isUndefined(currTokType.CATEGORIES.PATTERN) - ) { - currTokType.CATEGORIES = [currTokType.CATEGORIES]; - } - if (!hasCategoriesProperty(currTokType)) { - currTokType.CATEGORIES = []; - } - if (!hasExtendingTokensTypesProperty(currTokType)) { - currTokType.categoryMatches = []; - } - if (!hasExtendingTokensTypesMapProperty(currTokType)) { - currTokType.categoryMatchesMap = {}; - } - }); -} -function assignCategoriesTokensProp(tokenTypes) { - forEach(tokenTypes, function (currTokType) { - // avoid duplications - currTokType.categoryMatches = []; - forEach(currTokType.categoryMatchesMap, function (val, key) { - currTokType.categoryMatches.push(tokenIdxToClass[key].tokenTypeIdx); - }); - }); -} -function assignCategoriesMapProp(tokenTypes) { - forEach(tokenTypes, function (currTokType) { - singleAssignCategoriesToksMap([], currTokType); - }); -} -function singleAssignCategoriesToksMap(path, nextNode) { - forEach(path, function (pathNode) { - nextNode.categoryMatchesMap[pathNode.tokenTypeIdx] = true; - }); - forEach(nextNode.CATEGORIES, function (nextCategory) { - var newPath = path.concat(nextNode); - // avoids infinite loops due to cyclic categories. - if (!contains(newPath, nextCategory)) { - singleAssignCategoriesToksMap(newPath, nextCategory); - } - }); -} -function hasShortKeyProperty(tokType) { - return has(tokType, "tokenTypeIdx"); -} -function hasCategoriesProperty(tokType) { - return has(tokType, "CATEGORIES"); -} -function hasExtendingTokensTypesProperty(tokType) { - return has(tokType, "categoryMatches"); -} -function hasExtendingTokensTypesMapProperty(tokType) { - return has(tokType, "categoryMatchesMap"); -} -function isTokenType(tokType) { - return has(tokType, "tokenTypeIdx"); -} - -var defaultLexerErrorProvider = { - buildUnableToPopLexerModeMessage: function (token) { - return "Unable to pop Lexer Mode after encountering Token ->" + token.image + "<- The Mode Stack is empty"; - }, - buildUnexpectedCharactersMessage: function (fullText, startOffset, length, line, column) { - return ("unexpected character: ->" + fullText.charAt(startOffset) + "<- at offset: " + startOffset + "," + (" skipped " + length + " characters.")); - } -}; - -var LexerDefinitionErrorType; -(function (LexerDefinitionErrorType) { - LexerDefinitionErrorType[LexerDefinitionErrorType["MISSING_PATTERN"] = 0] = "MISSING_PATTERN"; - LexerDefinitionErrorType[LexerDefinitionErrorType["INVALID_PATTERN"] = 1] = "INVALID_PATTERN"; - LexerDefinitionErrorType[LexerDefinitionErrorType["EOI_ANCHOR_FOUND"] = 2] = "EOI_ANCHOR_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["UNSUPPORTED_FLAGS_FOUND"] = 3] = "UNSUPPORTED_FLAGS_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["DUPLICATE_PATTERNS_FOUND"] = 4] = "DUPLICATE_PATTERNS_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["INVALID_GROUP_TYPE_FOUND"] = 5] = "INVALID_GROUP_TYPE_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["PUSH_MODE_DOES_NOT_EXIST"] = 6] = "PUSH_MODE_DOES_NOT_EXIST"; - LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE"] = 7] = "MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE"; - LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY"] = 8] = "MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY"; - LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST"] = 9] = "MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST"; - LexerDefinitionErrorType[LexerDefinitionErrorType["LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED"] = 10] = "LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED"; - LexerDefinitionErrorType[LexerDefinitionErrorType["SOI_ANCHOR_FOUND"] = 11] = "SOI_ANCHOR_FOUND"; - LexerDefinitionErrorType[LexerDefinitionErrorType["EMPTY_MATCH_PATTERN"] = 12] = "EMPTY_MATCH_PATTERN"; - LexerDefinitionErrorType[LexerDefinitionErrorType["NO_LINE_BREAKS_FLAGS"] = 13] = "NO_LINE_BREAKS_FLAGS"; - LexerDefinitionErrorType[LexerDefinitionErrorType["UNREACHABLE_PATTERN"] = 14] = "UNREACHABLE_PATTERN"; - LexerDefinitionErrorType[LexerDefinitionErrorType["IDENTIFY_TERMINATOR"] = 15] = "IDENTIFY_TERMINATOR"; - LexerDefinitionErrorType[LexerDefinitionErrorType["CUSTOM_LINE_BREAK"] = 16] = "CUSTOM_LINE_BREAK"; -})(LexerDefinitionErrorType || (LexerDefinitionErrorType = {})); -var DEFAULT_LEXER_CONFIG = { - deferDefinitionErrorsHandling: false, - positionTracking: "full", - lineTerminatorsPattern: /\n|\r\n?/g, - lineTerminatorCharacters: ["\n", "\r"], - ensureOptimizations: false, - safeMode: false, - errorMessageProvider: defaultLexerErrorProvider, - traceInitPerf: false, - skipValidations: false -}; -Object.freeze(DEFAULT_LEXER_CONFIG); -var Lexer$1 = /** @class */ (function () { - function Lexer(lexerDefinition, config) { - var _this = this; - if (config === void 0) { config = DEFAULT_LEXER_CONFIG; } - this.lexerDefinition = lexerDefinition; - this.lexerDefinitionErrors = []; - this.lexerDefinitionWarning = []; - this.patternIdxToConfig = {}; - this.charCodeToPatternIdxToConfig = {}; - this.modes = []; - this.emptyGroups = {}; - this.config = undefined; - this.trackStartLines = true; - this.trackEndLines = true; - this.hasCustom = false; - this.canModeBeOptimized = {}; - if (typeof config === "boolean") { - throw Error("The second argument to the Lexer constructor is now an ILexerConfig Object.\n" + - "a boolean 2nd argument is no longer supported"); - } - // todo: defaults func? - this.config = merge(DEFAULT_LEXER_CONFIG, config); - var traceInitVal = this.config.traceInitPerf; - if (traceInitVal === true) { - this.traceInitMaxIdent = Infinity; - this.traceInitPerf = true; - } - else if (typeof traceInitVal === "number") { - this.traceInitMaxIdent = traceInitVal; - this.traceInitPerf = true; - } - this.traceInitIndent = -1; - this.TRACE_INIT("Lexer Constructor", function () { - var actualDefinition; - var hasOnlySingleMode = true; - _this.TRACE_INIT("Lexer Config handling", function () { - if (_this.config.lineTerminatorsPattern === - DEFAULT_LEXER_CONFIG.lineTerminatorsPattern) { - // optimized built-in implementation for the defaults definition of lineTerminators - _this.config.lineTerminatorsPattern = LineTerminatorOptimizedTester; - } - else { - if (_this.config.lineTerminatorCharacters === - DEFAULT_LEXER_CONFIG.lineTerminatorCharacters) { - throw Error("Error: Missing property on the Lexer config.\n" + - "\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS"); - } - } - if (config.safeMode && config.ensureOptimizations) { - throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.'); - } - _this.trackStartLines = /full|onlyStart/i.test(_this.config.positionTracking); - _this.trackEndLines = /full/i.test(_this.config.positionTracking); - // Convert SingleModeLexerDefinition into a IMultiModeLexerDefinition. - if (isArray(lexerDefinition)) { - actualDefinition = { modes: {} }; - actualDefinition.modes[DEFAULT_MODE] = cloneArr(lexerDefinition); - actualDefinition[DEFAULT_MODE] = DEFAULT_MODE; - } - else { - // no conversion needed, input should already be a IMultiModeLexerDefinition - hasOnlySingleMode = false; - actualDefinition = cloneObj(lexerDefinition); - } - }); - if (_this.config.skipValidations === false) { - _this.TRACE_INIT("performRuntimeChecks", function () { - _this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat(performRuntimeChecks(actualDefinition, _this.trackStartLines, _this.config.lineTerminatorCharacters)); - }); - _this.TRACE_INIT("performWarningRuntimeChecks", function () { - _this.lexerDefinitionWarning = _this.lexerDefinitionWarning.concat(performWarningRuntimeChecks(actualDefinition, _this.trackStartLines, _this.config.lineTerminatorCharacters)); - }); - } - // for extra robustness to avoid throwing an none informative error message - actualDefinition.modes = actualDefinition.modes - ? actualDefinition.modes - : {}; - // an error of undefined TokenTypes will be detected in "performRuntimeChecks" above. - // this transformation is to increase robustness in the case of partially invalid lexer definition. - forEach(actualDefinition.modes, function (currModeValue, currModeName) { - actualDefinition.modes[currModeName] = reject(currModeValue, function (currTokType) { return isUndefined(currTokType); }); - }); - var allModeNames = keys(actualDefinition.modes); - forEach(actualDefinition.modes, function (currModDef, currModName) { - _this.TRACE_INIT("Mode: <" + currModName + "> processing", function () { - _this.modes.push(currModName); - if (_this.config.skipValidations === false) { - _this.TRACE_INIT("validatePatterns", function () { - _this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat(validatePatterns(currModDef, allModeNames)); - }); - } - // If definition errors were encountered, the analysis phase may fail unexpectedly/ - // Considering a lexer with definition errors may never be used, there is no point - // to performing the analysis anyhow... - if (isEmpty(_this.lexerDefinitionErrors)) { - augmentTokenTypes(currModDef); - var currAnalyzeResult_1; - _this.TRACE_INIT("analyzeTokenTypes", function () { - currAnalyzeResult_1 = analyzeTokenTypes(currModDef, { - lineTerminatorCharacters: _this.config - .lineTerminatorCharacters, - positionTracking: config.positionTracking, - ensureOptimizations: config.ensureOptimizations, - safeMode: config.safeMode, - tracer: _this.TRACE_INIT.bind(_this) - }); - }); - _this.patternIdxToConfig[currModName] = - currAnalyzeResult_1.patternIdxToConfig; - _this.charCodeToPatternIdxToConfig[currModName] = - currAnalyzeResult_1.charCodeToPatternIdxToConfig; - _this.emptyGroups = merge(_this.emptyGroups, currAnalyzeResult_1.emptyGroups); - _this.hasCustom = currAnalyzeResult_1.hasCustom || _this.hasCustom; - _this.canModeBeOptimized[currModName] = - currAnalyzeResult_1.canBeOptimized; - } - }); - }); - _this.defaultMode = actualDefinition.defaultMode; - if (!isEmpty(_this.lexerDefinitionErrors) && - !_this.config.deferDefinitionErrorsHandling) { - var allErrMessages = map(_this.lexerDefinitionErrors, function (error) { - return error.message; - }); - var allErrMessagesString = allErrMessages.join("-----------------------\n"); - throw new Error("Errors detected in definition of Lexer:\n" + allErrMessagesString); - } - // Only print warning if there are no errors, This will avoid pl - forEach(_this.lexerDefinitionWarning, function (warningDescriptor) { - PRINT_WARNING(warningDescriptor.message); - }); - _this.TRACE_INIT("Choosing sub-methods implementations", function () { - // Choose the relevant internal implementations for this specific parser. - // These implementations should be in-lined by the JavaScript engine - // to provide optimal performance in each scenario. - if (SUPPORT_STICKY) { - _this.chopInput = IDENTITY; - _this.match = _this.matchWithTest; - } - else { - _this.updateLastIndex = NOOP; - _this.match = _this.matchWithExec; - } - if (hasOnlySingleMode) { - _this.handleModes = NOOP; - } - if (_this.trackStartLines === false) { - _this.computeNewColumn = IDENTITY; - } - if (_this.trackEndLines === false) { - _this.updateTokenEndLineColumnLocation = NOOP; - } - if (/full/i.test(_this.config.positionTracking)) { - _this.createTokenInstance = _this.createFullToken; - } - else if (/onlyStart/i.test(_this.config.positionTracking)) { - _this.createTokenInstance = _this.createStartOnlyToken; - } - else if (/onlyOffset/i.test(_this.config.positionTracking)) { - _this.createTokenInstance = _this.createOffsetOnlyToken; - } - else { - throw Error("Invalid config option: \"" + _this.config.positionTracking + "\""); - } - if (_this.hasCustom) { - _this.addToken = _this.addTokenUsingPush; - _this.handlePayload = _this.handlePayloadWithCustom; - } - else { - _this.addToken = _this.addTokenUsingMemberAccess; - _this.handlePayload = _this.handlePayloadNoCustom; - } - }); - _this.TRACE_INIT("Failed Optimization Warnings", function () { - var unOptimizedModes = reduce(_this.canModeBeOptimized, function (cannotBeOptimized, canBeOptimized, modeName) { - if (canBeOptimized === false) { - cannotBeOptimized.push(modeName); - } - return cannotBeOptimized; - }, []); - if (config.ensureOptimizations && !isEmpty(unOptimizedModes)) { - throw Error("Lexer Modes: < " + unOptimizedModes.join(", ") + " > cannot be optimized.\n" + - '\t Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.\n' + - "\t Or inspect the console log for details on how to resolve these issues."); - } - }); - _this.TRACE_INIT("clearRegExpParserCache", function () { - clearRegExpParserCache(); - }); - _this.TRACE_INIT("toFastProperties", function () { - toFastProperties(_this); - }); - }); - } - Lexer.prototype.tokenize = function (text, initialMode) { - if (initialMode === void 0) { initialMode = this.defaultMode; } - if (!isEmpty(this.lexerDefinitionErrors)) { - var allErrMessages = map(this.lexerDefinitionErrors, function (error) { - return error.message; - }); - var allErrMessagesString = allErrMessages.join("-----------------------\n"); - throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n" + - allErrMessagesString); - } - var lexResult = this.tokenizeInternal(text, initialMode); - return lexResult; - }; - // There is quite a bit of duplication between this and "tokenizeInternalLazy" - // This is intentional due to performance considerations. - Lexer.prototype.tokenizeInternal = function (text, initialMode) { - var _this = this; - var i, j, matchAltImage, longerAltIdx, matchedImage, payload, altPayload, imageLength, group, tokType, newToken, errLength, msg, match; - var orgText = text; - var orgLength = orgText.length; - var offset = 0; - var matchedTokensIndex = 0; - // initializing the tokensArray to the "guessed" size. - // guessing too little will still reduce the number of array re-sizes on pushes. - // guessing too large (Tested by guessing x4 too large) may cost a bit more of memory - // but would still have a faster runtime by avoiding (All but one) array resizing. - var guessedNumberOfTokens = this.hasCustom - ? 0 // will break custom token pattern APIs the matchedTokens array will contain undefined elements. - : Math.floor(text.length / 10); - var matchedTokens = new Array(guessedNumberOfTokens); - var errors = []; - var line = this.trackStartLines ? 1 : undefined; - var column = this.trackStartLines ? 1 : undefined; - var groups = cloneEmptyGroups(this.emptyGroups); - var trackLines = this.trackStartLines; - var lineTerminatorPattern = this.config.lineTerminatorsPattern; - var currModePatternsLength = 0; - var patternIdxToConfig = []; - var currCharCodeToPatternIdxToConfig = []; - var modeStack = []; - var emptyArray = []; - Object.freeze(emptyArray); - var getPossiblePatterns = undefined; - function getPossiblePatternsSlow() { - return patternIdxToConfig; - } - function getPossiblePatternsOptimized(charCode) { - var optimizedCharIdx = charCodeToOptimizedIndex(charCode); - var possiblePatterns = currCharCodeToPatternIdxToConfig[optimizedCharIdx]; - if (possiblePatterns === undefined) { - return emptyArray; - } - else { - return possiblePatterns; - } - } - var pop_mode = function (popToken) { - // TODO: perhaps avoid this error in the edge case there is no more input? - if (modeStack.length === 1 && - // if we have both a POP_MODE and a PUSH_MODE this is in-fact a "transition" - // So no error should occur. - popToken.tokenType.PUSH_MODE === undefined) { - // if we try to pop the last mode there lexer will no longer have ANY mode. - // thus the pop is ignored, an error will be created and the lexer will continue parsing in the previous mode. - var msg_1 = _this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(popToken); - errors.push({ - offset: popToken.startOffset, - line: popToken.startLine !== undefined ? popToken.startLine : undefined, - column: popToken.startColumn !== undefined - ? popToken.startColumn - : undefined, - length: popToken.image.length, - message: msg_1 - }); - } - else { - modeStack.pop(); - var newMode = last(modeStack); - patternIdxToConfig = _this.patternIdxToConfig[newMode]; - currCharCodeToPatternIdxToConfig = _this.charCodeToPatternIdxToConfig[newMode]; - currModePatternsLength = patternIdxToConfig.length; - var modeCanBeOptimized = _this.canModeBeOptimized[newMode] && _this.config.safeMode === false; - if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) { - getPossiblePatterns = getPossiblePatternsOptimized; - } - else { - getPossiblePatterns = getPossiblePatternsSlow; - } - } - }; - function push_mode(newMode) { - modeStack.push(newMode); - currCharCodeToPatternIdxToConfig = this.charCodeToPatternIdxToConfig[newMode]; - patternIdxToConfig = this.patternIdxToConfig[newMode]; - currModePatternsLength = patternIdxToConfig.length; - currModePatternsLength = patternIdxToConfig.length; - var modeCanBeOptimized = this.canModeBeOptimized[newMode] && this.config.safeMode === false; - if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) { - getPossiblePatterns = getPossiblePatternsOptimized; - } - else { - getPossiblePatterns = getPossiblePatternsSlow; - } - } - // this pattern seems to avoid a V8 de-optimization, although that de-optimization does not - // seem to matter performance wise. - push_mode.call(this, initialMode); - var currConfig; - while (offset < orgLength) { - matchedImage = null; - var nextCharCode = orgText.charCodeAt(offset); - var chosenPatternIdxToConfig = getPossiblePatterns(nextCharCode); - var chosenPatternsLength = chosenPatternIdxToConfig.length; - for (i = 0; i < chosenPatternsLength; i++) { - currConfig = chosenPatternIdxToConfig[i]; - var currPattern = currConfig.pattern; - payload = null; - // manually in-lined because > 600 chars won't be in-lined in V8 - var singleCharCode = currConfig.short; - if (singleCharCode !== false) { - if (nextCharCode === singleCharCode) { - // single character string - matchedImage = currPattern; - } - } - else if (currConfig.isCustom === true) { - match = currPattern.exec(orgText, offset, matchedTokens, groups); - if (match !== null) { - matchedImage = match[0]; - if (match.payload !== undefined) { - payload = match.payload; - } - } - else { - matchedImage = null; - } - } - else { - this.updateLastIndex(currPattern, offset); - matchedImage = this.match(currPattern, text, offset); - } - if (matchedImage !== null) { - // even though this pattern matched we must try a another longer alternative. - // this can be used to prioritize keywords over identifiers - longerAltIdx = currConfig.longerAlt; - if (longerAltIdx !== undefined) { - // TODO: micro optimize, avoid extra prop access - // by saving/linking longerAlt on the original config? - var longerAltConfig = patternIdxToConfig[longerAltIdx]; - var longerAltPattern = longerAltConfig.pattern; - altPayload = null; - // single Char can never be a longer alt so no need to test it. - // manually in-lined because > 600 chars won't be in-lined in V8 - if (longerAltConfig.isCustom === true) { - match = longerAltPattern.exec(orgText, offset, matchedTokens, groups); - if (match !== null) { - matchAltImage = match[0]; - if (match.payload !== undefined) { - altPayload = match.payload; - } - } - else { - matchAltImage = null; - } - } - else { - this.updateLastIndex(longerAltPattern, offset); - matchAltImage = this.match(longerAltPattern, text, offset); - } - if (matchAltImage && matchAltImage.length > matchedImage.length) { - matchedImage = matchAltImage; - payload = altPayload; - currConfig = longerAltConfig; - } - } - break; - } - } - // successful match - if (matchedImage !== null) { - imageLength = matchedImage.length; - group = currConfig.group; - if (group !== undefined) { - tokType = currConfig.tokenTypeIdx; - // TODO: "offset + imageLength" and the new column may be computed twice in case of "full" location information inside - // createFullToken method - newToken = this.createTokenInstance(matchedImage, offset, tokType, currConfig.tokenType, line, column, imageLength); - this.handlePayload(newToken, payload); - // TODO: optimize NOOP in case there are no special groups? - if (group === false) { - matchedTokensIndex = this.addToken(matchedTokens, matchedTokensIndex, newToken); - } - else { - groups[group].push(newToken); - } - } - text = this.chopInput(text, imageLength); - offset = offset + imageLength; - // TODO: with newlines the column may be assigned twice - column = this.computeNewColumn(column, imageLength); - if (trackLines === true && currConfig.canLineTerminator === true) { - var numOfLTsInMatch = 0; - var foundTerminator = void 0; - var lastLTEndOffset = void 0; - lineTerminatorPattern.lastIndex = 0; - do { - foundTerminator = lineTerminatorPattern.test(matchedImage); - if (foundTerminator === true) { - lastLTEndOffset = lineTerminatorPattern.lastIndex - 1; - numOfLTsInMatch++; - } - } while (foundTerminator === true); - if (numOfLTsInMatch !== 0) { - line = line + numOfLTsInMatch; - column = imageLength - lastLTEndOffset; - this.updateTokenEndLineColumnLocation(newToken, group, lastLTEndOffset, numOfLTsInMatch, line, column, imageLength); - } - } - // will be NOOP if no modes present - this.handleModes(currConfig, pop_mode, push_mode, newToken); - } - else { - // error recovery, drop characters until we identify a valid token's start point - var errorStartOffset = offset; - var errorLine = line; - var errorColumn = column; - var foundResyncPoint = false; - while (!foundResyncPoint && offset < orgLength) { - // drop chars until we succeed in matching something - orgText.charCodeAt(offset); - // Identity Func (when sticky flag is enabled) - text = this.chopInput(text, 1); - offset++; - for (j = 0; j < currModePatternsLength; j++) { - var currConfig_1 = patternIdxToConfig[j]; - var currPattern = currConfig_1.pattern; - // manually in-lined because > 600 chars won't be in-lined in V8 - var singleCharCode = currConfig_1.short; - if (singleCharCode !== false) { - if (orgText.charCodeAt(offset) === singleCharCode) { - // single character string - foundResyncPoint = true; - } - } - else if (currConfig_1.isCustom === true) { - foundResyncPoint = - currPattern.exec(orgText, offset, matchedTokens, groups) !== - null; - } - else { - this.updateLastIndex(currPattern, offset); - foundResyncPoint = currPattern.exec(text) !== null; - } - if (foundResyncPoint === true) { - break; - } - } - } - errLength = offset - errorStartOffset; - // at this point we either re-synced or reached the end of the input text - msg = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(orgText, errorStartOffset, errLength, errorLine, errorColumn); - errors.push({ - offset: errorStartOffset, - line: errorLine, - column: errorColumn, - length: errLength, - message: msg - }); - } - } - // if we do have custom patterns which push directly into the - // TODO: custom tokens should not push directly?? - if (!this.hasCustom) { - // if we guessed a too large size for the tokens array this will shrink it to the right size. - matchedTokens.length = matchedTokensIndex; - } - return { - tokens: matchedTokens, - groups: groups, - errors: errors - }; - }; - Lexer.prototype.handleModes = function (config, pop_mode, push_mode, newToken) { - if (config.pop === true) { - // need to save the PUSH_MODE property as if the mode is popped - // patternIdxToPopMode is updated to reflect the new mode after popping the stack - var pushMode = config.push; - pop_mode(newToken); - if (pushMode !== undefined) { - push_mode.call(this, pushMode); - } - } - else if (config.push !== undefined) { - push_mode.call(this, config.push); - } - }; - Lexer.prototype.chopInput = function (text, length) { - return text.substring(length); - }; - Lexer.prototype.updateLastIndex = function (regExp, newLastIndex) { - regExp.lastIndex = newLastIndex; - }; - // TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler - Lexer.prototype.updateTokenEndLineColumnLocation = function (newToken, group, lastLTIdx, numOfLTsInMatch, line, column, imageLength) { - var lastCharIsLT, fixForEndingInLT; - if (group !== undefined) { - // a none skipped multi line Token, need to update endLine/endColumn - lastCharIsLT = lastLTIdx === imageLength - 1; - fixForEndingInLT = lastCharIsLT ? -1 : 0; - if (!(numOfLTsInMatch === 1 && lastCharIsLT === true)) { - // if a token ends in a LT that last LT only affects the line numbering of following Tokens - newToken.endLine = line + fixForEndingInLT; - // the last LT in a token does not affect the endColumn either as the [columnStart ... columnEnd) - // inclusive to exclusive range. - newToken.endColumn = column - 1 + -fixForEndingInLT; - } - // else single LT in the last character of a token, no need to modify the endLine/EndColumn - } - }; - Lexer.prototype.computeNewColumn = function (oldColumn, imageLength) { - return oldColumn + imageLength; - }; - // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime. - /* istanbul ignore next - place holder */ - Lexer.prototype.createTokenInstance = function () { - return null; - }; - Lexer.prototype.createOffsetOnlyToken = function (image, startOffset, tokenTypeIdx, tokenType) { - return { - image: image, - startOffset: startOffset, - tokenTypeIdx: tokenTypeIdx, - tokenType: tokenType - }; - }; - Lexer.prototype.createStartOnlyToken = function (image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn) { - return { - image: image, - startOffset: startOffset, - startLine: startLine, - startColumn: startColumn, - tokenTypeIdx: tokenTypeIdx, - tokenType: tokenType - }; - }; - Lexer.prototype.createFullToken = function (image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn, imageLength) { - return { - image: image, - startOffset: startOffset, - endOffset: startOffset + imageLength - 1, - startLine: startLine, - endLine: startLine, - startColumn: startColumn, - endColumn: startColumn + imageLength - 1, - tokenTypeIdx: tokenTypeIdx, - tokenType: tokenType - }; - }; - // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime. - /* istanbul ignore next - place holder */ - Lexer.prototype.addToken = function (tokenVector, index, tokenToAdd) { - return 666; - }; - Lexer.prototype.addTokenUsingPush = function (tokenVector, index, tokenToAdd) { - tokenVector.push(tokenToAdd); - return index; - }; - Lexer.prototype.addTokenUsingMemberAccess = function (tokenVector, index, tokenToAdd) { - tokenVector[index] = tokenToAdd; - index++; - return index; - }; - // Place holder, will be replaced by the correct variant according to the hasCustom flag option at runtime. - /* istanbul ignore next - place holder */ - Lexer.prototype.handlePayload = function (token, payload) { }; - Lexer.prototype.handlePayloadNoCustom = function (token, payload) { }; - Lexer.prototype.handlePayloadWithCustom = function (token, payload) { - if (payload !== null) { - token.payload = payload; - } - }; - /* istanbul ignore next - place holder to be replaced with chosen alternative at runtime */ - Lexer.prototype.match = function (pattern, text, offset) { - return null; - }; - Lexer.prototype.matchWithTest = function (pattern, text, offset) { - var found = pattern.test(text); - if (found === true) { - return text.substring(offset, pattern.lastIndex); - } - return null; - }; - Lexer.prototype.matchWithExec = function (pattern, text) { - var regExpArray = pattern.exec(text); - return regExpArray !== null ? regExpArray[0] : regExpArray; - }; - // Duplicated from the parser's perf trace trait to allow future extraction - // of the lexer to a separate package. - Lexer.prototype.TRACE_INIT = function (phaseDesc, phaseImpl) { - // No need to optimize this using NOOP pattern because - // It is not called in a hot spot... - if (this.traceInitPerf === true) { - this.traceInitIndent++; - var indent = new Array(this.traceInitIndent + 1).join("\t"); - if (this.traceInitIndent < this.traceInitMaxIdent) { - console.log(indent + "--> <" + phaseDesc + ">"); - } - var _a = timer(phaseImpl), time = _a.time, value = _a.value; - /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */ - var traceMethod = time > 10 ? console.warn : console.log; - if (this.traceInitIndent < this.traceInitMaxIdent) { - traceMethod(indent + "<-- <" + phaseDesc + "> time: " + time + "ms"); - } - this.traceInitIndent--; - return value; - } - else { - return phaseImpl(); - } - }; - Lexer.SKIPPED = "This marks a skipped Token pattern, this means each token identified by it will" + - "be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace."; - Lexer.NA = /NOT_APPLICABLE/; - return Lexer; -}()); - -function tokenLabel(tokType) { - if (hasTokenLabel(tokType)) { - return tokType.LABEL; - } - else { - return tokType.name; - } -} -function tokenName(tokType) { - return tokType.name; -} -function hasTokenLabel(obj) { - return isString(obj.LABEL) && obj.LABEL !== ""; -} -var PARENT = "parent"; -var CATEGORIES = "categories"; -var LABEL = "label"; -var GROUP = "group"; -var PUSH_MODE = "push_mode"; -var POP_MODE = "pop_mode"; -var LONGER_ALT = "longer_alt"; -var LINE_BREAKS = "line_breaks"; -var START_CHARS_HINT = "start_chars_hint"; -function createToken$1(config) { - return createTokenInternal(config); -} -function createTokenInternal(config) { - var pattern = config.pattern; - var tokenType = {}; - tokenType.name = config.name; - if (!isUndefined(pattern)) { - tokenType.PATTERN = pattern; - } - if (has(config, PARENT)) { - throw ("The parent property is no longer supported.\n" + - "See: https://github.com/SAP/chevrotain/issues/564#issuecomment-349062346 for details."); - } - if (has(config, CATEGORIES)) { - // casting to ANY as this will be fixed inside `augmentTokenTypes`` - tokenType.CATEGORIES = config[CATEGORIES]; - } - augmentTokenTypes([tokenType]); - if (has(config, LABEL)) { - tokenType.LABEL = config[LABEL]; - } - if (has(config, GROUP)) { - tokenType.GROUP = config[GROUP]; - } - if (has(config, POP_MODE)) { - tokenType.POP_MODE = config[POP_MODE]; - } - if (has(config, PUSH_MODE)) { - tokenType.PUSH_MODE = config[PUSH_MODE]; - } - if (has(config, LONGER_ALT)) { - tokenType.LONGER_ALT = config[LONGER_ALT]; - } - if (has(config, LINE_BREAKS)) { - tokenType.LINE_BREAKS = config[LINE_BREAKS]; - } - if (has(config, START_CHARS_HINT)) { - tokenType.START_CHARS_HINT = config[START_CHARS_HINT]; - } - return tokenType; -} -var EOF = createToken$1({ name: "EOF", pattern: Lexer$1.NA }); -augmentTokenTypes([EOF]); -function createTokenInstance(tokType, image, startOffset, endOffset, startLine, endLine, startColumn, endColumn) { - return { - image: image, - startOffset: startOffset, - endOffset: endOffset, - startLine: startLine, - endLine: endLine, - startColumn: startColumn, - endColumn: endColumn, - tokenTypeIdx: tokType.tokenTypeIdx, - tokenType: tokType - }; -} -function tokenMatcher$1(token, tokType) { - return tokenStructuredMatcher(token, tokType); -} - -var __extends$8 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var AbstractProduction = /** @class */ (function () { - function AbstractProduction(_definition) { - this._definition = _definition; - } - Object.defineProperty(AbstractProduction.prototype, "definition", { - get: function () { - return this._definition; - }, - set: function (value) { - this._definition = value; - }, - enumerable: false, - configurable: true - }); - AbstractProduction.prototype.accept = function (visitor) { - visitor.visit(this); - forEach(this.definition, function (prod) { - prod.accept(visitor); - }); - }; - return AbstractProduction; -}()); -var NonTerminal = /** @class */ (function (_super) { - __extends$8(NonTerminal, _super); - function NonTerminal(options) { - var _this = _super.call(this, []) || this; - _this.idx = 1; - assign(_this, pick(options, function (v) { return v !== undefined; })); - return _this; - } - Object.defineProperty(NonTerminal.prototype, "definition", { - get: function () { - if (this.referencedRule !== undefined) { - return this.referencedRule.definition; - } - return []; - }, - set: function (definition) { - // immutable - }, - enumerable: false, - configurable: true - }); - NonTerminal.prototype.accept = function (visitor) { - visitor.visit(this); - // don't visit children of a reference, we will get cyclic infinite loops if we do so - }; - return NonTerminal; -}(AbstractProduction)); -var Rule = /** @class */ (function (_super) { - __extends$8(Rule, _super); - function Rule(options) { - var _this = _super.call(this, options.definition) || this; - _this.orgText = ""; - assign(_this, pick(options, function (v) { return v !== undefined; })); - return _this; - } - return Rule; -}(AbstractProduction)); -var Alternative = /** @class */ (function (_super) { - __extends$8(Alternative, _super); - function Alternative(options) { - var _this = _super.call(this, options.definition) || this; - _this.ignoreAmbiguities = false; - assign(_this, pick(options, function (v) { return v !== undefined; })); - return _this; - } - return Alternative; -}(AbstractProduction)); -var Option = /** @class */ (function (_super) { - __extends$8(Option, _super); - function Option(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - assign(_this, pick(options, function (v) { return v !== undefined; })); - return _this; - } - return Option; -}(AbstractProduction)); -var RepetitionMandatory = /** @class */ (function (_super) { - __extends$8(RepetitionMandatory, _super); - function RepetitionMandatory(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - assign(_this, pick(options, function (v) { return v !== undefined; })); - return _this; - } - return RepetitionMandatory; -}(AbstractProduction)); -var RepetitionMandatoryWithSeparator = /** @class */ (function (_super) { - __extends$8(RepetitionMandatoryWithSeparator, _super); - function RepetitionMandatoryWithSeparator(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - assign(_this, pick(options, function (v) { return v !== undefined; })); - return _this; - } - return RepetitionMandatoryWithSeparator; -}(AbstractProduction)); -var Repetition = /** @class */ (function (_super) { - __extends$8(Repetition, _super); - function Repetition(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - assign(_this, pick(options, function (v) { return v !== undefined; })); - return _this; - } - return Repetition; -}(AbstractProduction)); -var RepetitionWithSeparator = /** @class */ (function (_super) { - __extends$8(RepetitionWithSeparator, _super); - function RepetitionWithSeparator(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - assign(_this, pick(options, function (v) { return v !== undefined; })); - return _this; - } - return RepetitionWithSeparator; -}(AbstractProduction)); -var Alternation = /** @class */ (function (_super) { - __extends$8(Alternation, _super); - function Alternation(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - _this.ignoreAmbiguities = false; - _this.hasPredicates = false; - assign(_this, pick(options, function (v) { return v !== undefined; })); - return _this; - } - Object.defineProperty(Alternation.prototype, "definition", { - get: function () { - return this._definition; - }, - set: function (value) { - this._definition = value; - }, - enumerable: false, - configurable: true - }); - return Alternation; -}(AbstractProduction)); -var Terminal = /** @class */ (function () { - function Terminal(options) { - this.idx = 1; - assign(this, pick(options, function (v) { return v !== undefined; })); - } - Terminal.prototype.accept = function (visitor) { - visitor.visit(this); - }; - return Terminal; -}()); -function serializeGrammar(topRules) { - return map(topRules, serializeProduction); -} -function serializeProduction(node) { - function convertDefinition(definition) { - return map(definition, serializeProduction); - } - /* istanbul ignore else */ - if (node instanceof NonTerminal) { - return { - type: "NonTerminal", - name: node.nonTerminalName, - idx: node.idx - }; - } - else if (node instanceof Alternative) { - return { - type: "Alternative", - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof Option) { - return { - type: "Option", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof RepetitionMandatory) { - return { - type: "RepetitionMandatory", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof RepetitionMandatoryWithSeparator) { - return { - type: "RepetitionMandatoryWithSeparator", - idx: node.idx, - separator: (serializeProduction(new Terminal({ terminalType: node.separator }))), - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof RepetitionWithSeparator) { - return { - type: "RepetitionWithSeparator", - idx: node.idx, - separator: (serializeProduction(new Terminal({ terminalType: node.separator }))), - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof Repetition) { - return { - type: "Repetition", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof Alternation) { - return { - type: "Alternation", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof Terminal) { - var serializedTerminal = { - type: "Terminal", - name: node.terminalType.name, - label: tokenLabel(node.terminalType), - idx: node.idx - }; - var pattern = node.terminalType.PATTERN; - if (node.terminalType.PATTERN) { - serializedTerminal.pattern = isRegExp(pattern) - ? pattern.source - : pattern; - } - return serializedTerminal; - } - else if (node instanceof Rule) { - return { - type: "Rule", - name: node.name, - orgText: node.orgText, - definition: convertDefinition(node.definition) - }; - } - else { - throw Error("non exhaustive match"); - } -} - -/** - * A Grammar Walker that computes the "remaining" grammar "after" a productions in the grammar. - */ -var RestWalker = /** @class */ (function () { - function RestWalker() { - } - RestWalker.prototype.walk = function (prod, prevRest) { - var _this = this; - if (prevRest === void 0) { prevRest = []; } - forEach(prod.definition, function (subProd, index) { - var currRest = drop(prod.definition, index + 1); - /* istanbul ignore else */ - if (subProd instanceof NonTerminal) { - _this.walkProdRef(subProd, currRest, prevRest); - } - else if (subProd instanceof Terminal) { - _this.walkTerminal(subProd, currRest, prevRest); - } - else if (subProd instanceof Alternative) { - _this.walkFlat(subProd, currRest, prevRest); - } - else if (subProd instanceof Option) { - _this.walkOption(subProd, currRest, prevRest); - } - else if (subProd instanceof RepetitionMandatory) { - _this.walkAtLeastOne(subProd, currRest, prevRest); - } - else if (subProd instanceof RepetitionMandatoryWithSeparator) { - _this.walkAtLeastOneSep(subProd, currRest, prevRest); - } - else if (subProd instanceof RepetitionWithSeparator) { - _this.walkManySep(subProd, currRest, prevRest); - } - else if (subProd instanceof Repetition) { - _this.walkMany(subProd, currRest, prevRest); - } - else if (subProd instanceof Alternation) { - _this.walkOr(subProd, currRest, prevRest); - } - else { - throw Error("non exhaustive match"); - } - }); - }; - RestWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { }; - RestWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { }; - RestWalker.prototype.walkFlat = function (flatProd, currRest, prevRest) { - // ABCDEF => after the D the rest is EF - var fullOrRest = currRest.concat(prevRest); - this.walk(flatProd, fullOrRest); - }; - RestWalker.prototype.walkOption = function (optionProd, currRest, prevRest) { - // ABC(DE)?F => after the (DE)? the rest is F - var fullOrRest = currRest.concat(prevRest); - this.walk(optionProd, fullOrRest); - }; - RestWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) { - // ABC(DE)+F => after the (DE)+ the rest is (DE)?F - var fullAtLeastOneRest = [ - new Option({ definition: atLeastOneProd.definition }) - ].concat(currRest, prevRest); - this.walk(atLeastOneProd, fullAtLeastOneRest); - }; - RestWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) { - // ABC DE(,DE)* F => after the (,DE)+ the rest is (,DE)?F - var fullAtLeastOneSepRest = restForRepetitionWithSeparator(atLeastOneSepProd, currRest, prevRest); - this.walk(atLeastOneSepProd, fullAtLeastOneSepRest); - }; - RestWalker.prototype.walkMany = function (manyProd, currRest, prevRest) { - // ABC(DE)*F => after the (DE)* the rest is (DE)?F - var fullManyRest = [ - new Option({ definition: manyProd.definition }) - ].concat(currRest, prevRest); - this.walk(manyProd, fullManyRest); - }; - RestWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) { - // ABC (DE(,DE)*)? F => after the (,DE)* the rest is (,DE)?F - var fullManySepRest = restForRepetitionWithSeparator(manySepProd, currRest, prevRest); - this.walk(manySepProd, fullManySepRest); - }; - RestWalker.prototype.walkOr = function (orProd, currRest, prevRest) { - var _this = this; - // ABC(D|E|F)G => when finding the (D|E|F) the rest is G - var fullOrRest = currRest.concat(prevRest); - // walk all different alternatives - forEach(orProd.definition, function (alt) { - // wrapping each alternative in a single definition wrapper - // to avoid errors in computing the rest of that alternative in the invocation to computeInProdFollows - // (otherwise for OR([alt1,alt2]) alt2 will be considered in 'rest' of alt1 - var prodWrapper = new Alternative({ definition: [alt] }); - _this.walk(prodWrapper, fullOrRest); - }); - }; - return RestWalker; -}()); -function restForRepetitionWithSeparator(repSepProd, currRest, prevRest) { - var repSepRest = [ - new Option({ - definition: [new Terminal({ terminalType: repSepProd.separator })].concat(repSepProd.definition) - }) - ]; - var fullRepSepRest = repSepRest.concat(currRest, prevRest); - return fullRepSepRest; -} - -var GAstVisitor = /** @class */ (function () { - function GAstVisitor() { - } - GAstVisitor.prototype.visit = function (node) { - var nodeAny = node; - switch (nodeAny.constructor) { - case NonTerminal: - return this.visitNonTerminal(nodeAny); - case Alternative: - return this.visitAlternative(nodeAny); - case Option: - return this.visitOption(nodeAny); - case RepetitionMandatory: - return this.visitRepetitionMandatory(nodeAny); - case RepetitionMandatoryWithSeparator: - return this.visitRepetitionMandatoryWithSeparator(nodeAny); - case RepetitionWithSeparator: - return this.visitRepetitionWithSeparator(nodeAny); - case Repetition: - return this.visitRepetition(nodeAny); - case Alternation: - return this.visitAlternation(nodeAny); - case Terminal: - return this.visitTerminal(nodeAny); - case Rule: - return this.visitRule(nodeAny); - /* istanbul ignore next */ - default: - throw Error("non exhaustive match"); - } - }; - GAstVisitor.prototype.visitNonTerminal = function (node) { }; - GAstVisitor.prototype.visitAlternative = function (node) { }; - GAstVisitor.prototype.visitOption = function (node) { }; - GAstVisitor.prototype.visitRepetition = function (node) { }; - GAstVisitor.prototype.visitRepetitionMandatory = function (node) { }; - GAstVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { }; - GAstVisitor.prototype.visitRepetitionWithSeparator = function (node) { }; - GAstVisitor.prototype.visitAlternation = function (node) { }; - GAstVisitor.prototype.visitTerminal = function (node) { }; - GAstVisitor.prototype.visitRule = function (node) { }; - return GAstVisitor; -}()); - -var __extends$7 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -function isSequenceProd(prod) { - return (prod instanceof Alternative || - prod instanceof Option || - prod instanceof Repetition || - prod instanceof RepetitionMandatory || - prod instanceof RepetitionMandatoryWithSeparator || - prod instanceof RepetitionWithSeparator || - prod instanceof Terminal || - prod instanceof Rule); -} -function isOptionalProd(prod, alreadyVisited) { - if (alreadyVisited === void 0) { alreadyVisited = []; } - var isDirectlyOptional = prod instanceof Option || - prod instanceof Repetition || - prod instanceof RepetitionWithSeparator; - if (isDirectlyOptional) { - return true; - } - // note that this can cause infinite loop if one optional empty TOP production has a cyclic dependency with another - // empty optional top rule - // may be indirectly optional ((A?B?C?) | (D?E?F?)) - if (prod instanceof Alternation) { - // for OR its enough for just one of the alternatives to be optional - return some(prod.definition, function (subProd) { - return isOptionalProd(subProd, alreadyVisited); - }); - } - else if (prod instanceof NonTerminal && contains(alreadyVisited, prod)) { - // avoiding stack overflow due to infinite recursion - return false; - } - else if (prod instanceof AbstractProduction) { - if (prod instanceof NonTerminal) { - alreadyVisited.push(prod); - } - return every(prod.definition, function (subProd) { - return isOptionalProd(subProd, alreadyVisited); - }); - } - else { - return false; - } -} -function isBranchingProd(prod) { - return prod instanceof Alternation; -} -function getProductionDslName(prod) { - /* istanbul ignore else */ - if (prod instanceof NonTerminal) { - return "SUBRULE"; - } - else if (prod instanceof Option) { - return "OPTION"; - } - else if (prod instanceof Alternation) { - return "OR"; - } - else if (prod instanceof RepetitionMandatory) { - return "AT_LEAST_ONE"; - } - else if (prod instanceof RepetitionMandatoryWithSeparator) { - return "AT_LEAST_ONE_SEP"; - } - else if (prod instanceof RepetitionWithSeparator) { - return "MANY_SEP"; - } - else if (prod instanceof Repetition) { - return "MANY"; - } - else if (prod instanceof Terminal) { - return "CONSUME"; - } - else { - throw Error("non exhaustive match"); - } -} -var DslMethodsCollectorVisitor = /** @class */ (function (_super) { - __extends$7(DslMethodsCollectorVisitor, _super); - function DslMethodsCollectorVisitor() { - var _this = _super !== null && _super.apply(this, arguments) || this; - // A minus is never valid in an identifier name - _this.separator = "-"; - _this.dslMethods = { - option: [], - alternation: [], - repetition: [], - repetitionWithSeparator: [], - repetitionMandatory: [], - repetitionMandatoryWithSeparator: [] - }; - return _this; - } - DslMethodsCollectorVisitor.prototype.reset = function () { - this.dslMethods = { - option: [], - alternation: [], - repetition: [], - repetitionWithSeparator: [], - repetitionMandatory: [], - repetitionMandatoryWithSeparator: [] - }; - }; - DslMethodsCollectorVisitor.prototype.visitTerminal = function (terminal) { - var key = terminal.terminalType.name + this.separator + "Terminal"; - if (!has(this.dslMethods, key)) { - this.dslMethods[key] = []; - } - this.dslMethods[key].push(terminal); - }; - DslMethodsCollectorVisitor.prototype.visitNonTerminal = function (subrule) { - var key = subrule.nonTerminalName + this.separator + "Terminal"; - if (!has(this.dslMethods, key)) { - this.dslMethods[key] = []; - } - this.dslMethods[key].push(subrule); - }; - DslMethodsCollectorVisitor.prototype.visitOption = function (option) { - this.dslMethods.option.push(option); - }; - DslMethodsCollectorVisitor.prototype.visitRepetitionWithSeparator = function (manySep) { - this.dslMethods.repetitionWithSeparator.push(manySep); - }; - DslMethodsCollectorVisitor.prototype.visitRepetitionMandatory = function (atLeastOne) { - this.dslMethods.repetitionMandatory.push(atLeastOne); - }; - DslMethodsCollectorVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) { - this.dslMethods.repetitionMandatoryWithSeparator.push(atLeastOneSep); - }; - DslMethodsCollectorVisitor.prototype.visitRepetition = function (many) { - this.dslMethods.repetition.push(many); - }; - DslMethodsCollectorVisitor.prototype.visitAlternation = function (or) { - this.dslMethods.alternation.push(or); - }; - return DslMethodsCollectorVisitor; -}(GAstVisitor)); -var collectorVisitor = new DslMethodsCollectorVisitor(); -function collectMethods(rule) { - collectorVisitor.reset(); - rule.accept(collectorVisitor); - var dslMethods = collectorVisitor.dslMethods; - // avoid uncleaned references - collectorVisitor.reset(); - return dslMethods; -} - -function first(prod) { - /* istanbul ignore else */ - if (prod instanceof NonTerminal) { - // this could in theory cause infinite loops if - // (1) prod A refs prod B. - // (2) prod B refs prod A - // (3) AB can match the empty set - // in other words a cycle where everything is optional so the first will keep - // looking ahead for the next optional part and will never exit - // currently there is no safeguard for this unique edge case because - // (1) not sure a grammar in which this can happen is useful for anything (productive) - return first(prod.referencedRule); - } - else if (prod instanceof Terminal) { - return firstForTerminal(prod); - } - else if (isSequenceProd(prod)) { - return firstForSequence(prod); - } - else if (isBranchingProd(prod)) { - return firstForBranching(prod); - } - else { - throw Error("non exhaustive match"); - } -} -function firstForSequence(prod) { - var firstSet = []; - var seq = prod.definition; - var nextSubProdIdx = 0; - var hasInnerProdsRemaining = seq.length > nextSubProdIdx; - var currSubProd; - // so we enter the loop at least once (if the definition is not empty - var isLastInnerProdOptional = true; - // scan a sequence until it's end or until we have found a NONE optional production in it - while (hasInnerProdsRemaining && isLastInnerProdOptional) { - currSubProd = seq[nextSubProdIdx]; - isLastInnerProdOptional = isOptionalProd(currSubProd); - firstSet = firstSet.concat(first(currSubProd)); - nextSubProdIdx = nextSubProdIdx + 1; - hasInnerProdsRemaining = seq.length > nextSubProdIdx; - } - return uniq(firstSet); -} -function firstForBranching(prod) { - var allAlternativesFirsts = map(prod.definition, function (innerProd) { - return first(innerProd); - }); - return uniq(flatten(allAlternativesFirsts)); -} -function firstForTerminal(terminal) { - return [terminal.terminalType]; -} - -// TODO: can this be removed? where is it used? -var IN = "_~IN~_"; - -var __extends$6 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -// This ResyncFollowsWalker computes all of the follows required for RESYNC -// (skipping reference production). -var ResyncFollowsWalker = /** @class */ (function (_super) { - __extends$6(ResyncFollowsWalker, _super); - function ResyncFollowsWalker(topProd) { - var _this = _super.call(this) || this; - _this.topProd = topProd; - _this.follows = {}; - return _this; - } - ResyncFollowsWalker.prototype.startWalking = function () { - this.walk(this.topProd); - return this.follows; - }; - ResyncFollowsWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { - // do nothing! just like in the public sector after 13:00 - }; - ResyncFollowsWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { - var followName = buildBetweenProdsFollowPrefix(refProd.referencedRule, refProd.idx) + - this.topProd.name; - var fullRest = currRest.concat(prevRest); - var restProd = new Alternative({ definition: fullRest }); - var t_in_topProd_follows = first(restProd); - this.follows[followName] = t_in_topProd_follows; - }; - return ResyncFollowsWalker; -}(RestWalker)); -function computeAllProdsFollows(topProductions) { - var reSyncFollows = {}; - forEach(topProductions, function (topProd) { - var currRefsFollow = new ResyncFollowsWalker(topProd).startWalking(); - assign(reSyncFollows, currRefsFollow); - }); - return reSyncFollows; -} -function buildBetweenProdsFollowPrefix(inner, occurenceInParent) { - return inner.name + occurenceInParent + IN; -} - -var defaultParserErrorProvider = { - buildMismatchTokenMessage: function (_a) { - var expected = _a.expected, actual = _a.actual; _a.previous; _a.ruleName; - var hasLabel = hasTokenLabel(expected); - var expectedMsg = hasLabel - ? "--> " + tokenLabel(expected) + " <--" - : "token of type --> " + expected.name + " <--"; - var msg = "Expecting " + expectedMsg + " but found --> '" + actual.image + "' <--"; - return msg; - }, - buildNotAllInputParsedMessage: function (_a) { - var firstRedundant = _a.firstRedundant; _a.ruleName; - return "Redundant input, expecting EOF but found: " + firstRedundant.image; - }, - buildNoViableAltMessage: function (_a) { - var expectedPathsPerAlt = _a.expectedPathsPerAlt, actual = _a.actual; _a.previous; var customUserDescription = _a.customUserDescription; _a.ruleName; - var errPrefix = "Expecting: "; - // TODO: issue: No Viable Alternative Error may have incomplete details. #502 - var actualText = first$1(actual).image; - var errSuffix = "\nbut found: '" + actualText + "'"; - if (customUserDescription) { - return errPrefix + customUserDescription + errSuffix; - } - else { - var allLookAheadPaths = reduce(expectedPathsPerAlt, function (result, currAltPaths) { return result.concat(currAltPaths); }, []); - var nextValidTokenSequences = map(allLookAheadPaths, function (currPath) { - return "[" + map(currPath, function (currTokenType) { return tokenLabel(currTokenType); }).join(", ") + "]"; - }); - var nextValidSequenceItems = map(nextValidTokenSequences, function (itemMsg, idx) { return " " + (idx + 1) + ". " + itemMsg; }); - var calculatedDescription = "one of these possible Token sequences:\n" + nextValidSequenceItems.join("\n"); - return errPrefix + calculatedDescription + errSuffix; - } - }, - buildEarlyExitMessage: function (_a) { - var expectedIterationPaths = _a.expectedIterationPaths, actual = _a.actual, customUserDescription = _a.customUserDescription; _a.ruleName; - var errPrefix = "Expecting: "; - // TODO: issue: No Viable Alternative Error may have incomplete details. #502 - var actualText = first$1(actual).image; - var errSuffix = "\nbut found: '" + actualText + "'"; - if (customUserDescription) { - return errPrefix + customUserDescription + errSuffix; - } - else { - var nextValidTokenSequences = map(expectedIterationPaths, function (currPath) { - return "[" + map(currPath, function (currTokenType) { return tokenLabel(currTokenType); }).join(",") + "]"; - }); - var calculatedDescription = "expecting at least one iteration which starts with one of these possible Token sequences::\n " + - ("<" + nextValidTokenSequences.join(" ,") + ">"); - return errPrefix + calculatedDescription + errSuffix; - } - } -}; -Object.freeze(defaultParserErrorProvider); -var defaultGrammarResolverErrorProvider = { - buildRuleNotFoundError: function (topLevelRule, undefinedRule) { - var msg = "Invalid grammar, reference to a rule which is not defined: ->" + - undefinedRule.nonTerminalName + - "<-\n" + - "inside top level rule: ->" + - topLevelRule.name + - "<-"; - return msg; - } -}; -var defaultGrammarValidatorErrorProvider = { - buildDuplicateFoundError: function (topLevelRule, duplicateProds) { - function getExtraProductionArgument(prod) { - if (prod instanceof Terminal) { - return prod.terminalType.name; - } - else if (prod instanceof NonTerminal) { - return prod.nonTerminalName; - } - else { - return ""; - } - } - var topLevelName = topLevelRule.name; - var duplicateProd = first$1(duplicateProds); - var index = duplicateProd.idx; - var dslName = getProductionDslName(duplicateProd); - var extraArgument = getExtraProductionArgument(duplicateProd); - var hasExplicitIndex = index > 0; - var msg = "->" + dslName + (hasExplicitIndex ? index : "") + "<- " + (extraArgument ? "with argument: ->" + extraArgument + "<-" : "") + "\n appears more than once (" + duplicateProds.length + " times) in the top level rule: ->" + topLevelName + "<-. \n For further details see: https://sap.github.io/chevrotain/docs/FAQ.html#NUMERICAL_SUFFIXES \n "; - // white space trimming time! better to trim afterwards as it allows to use WELL formatted multi line template strings... - msg = msg.replace(/[ \t]+/g, " "); - msg = msg.replace(/\s\s+/g, "\n"); - return msg; - }, - buildNamespaceConflictError: function (rule) { - var errMsg = "Namespace conflict found in grammar.\n" + - ("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <" + rule.name + ">.\n") + - "To resolve this make sure each Terminal and Non-Terminal names are unique\n" + - "This is easy to accomplish by using the convention that Terminal names start with an uppercase letter\n" + - "and Non-Terminal names start with a lower case letter."; - return errMsg; - }, - buildAlternationPrefixAmbiguityError: function (options) { - var pathMsg = map(options.prefixPath, function (currTok) { - return tokenLabel(currTok); - }).join(", "); - var occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx; - var errMsg = "Ambiguous alternatives: <" + options.ambiguityIndices.join(" ,") + "> due to common lookahead prefix\n" + - ("in inside <" + options.topLevelRule.name + "> Rule,\n") + - ("<" + pathMsg + "> may appears as a prefix path in all these alternatives.\n") + - "See: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX\n" + - "For Further details."; - return errMsg; - }, - buildAlternationAmbiguityError: function (options) { - var pathMsg = map(options.prefixPath, function (currtok) { - return tokenLabel(currtok); - }).join(", "); - var occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx; - var currMessage = "Ambiguous Alternatives Detected: <" + options.ambiguityIndices.join(" ,") + "> in " + - (" inside <" + options.topLevelRule.name + "> Rule,\n") + - ("<" + pathMsg + "> may appears as a prefix path in all these alternatives.\n"); - currMessage = - currMessage + - "See: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\n" + - "For Further details."; - return currMessage; - }, - buildEmptyRepetitionError: function (options) { - var dslName = getProductionDslName(options.repetition); - if (options.repetition.idx !== 0) { - dslName += options.repetition.idx; - } - var errMsg = "The repetition <" + dslName + "> within Rule <" + options.topLevelRule.name + "> can never consume any tokens.\n" + - "This could lead to an infinite loop."; - return errMsg; - }, - // TODO: remove - `errors_public` from nyc.config.js exclude - // once this method is fully removed from this file - buildTokenNameError: function (options) { - /* istanbul ignore next */ - return "deprecated"; - }, - buildEmptyAlternationError: function (options) { - var errMsg = "Ambiguous empty alternative: <" + (options.emptyChoiceIdx + 1) + ">" + - (" in inside <" + options.topLevelRule.name + "> Rule.\n") + - "Only the last alternative may be an empty alternative."; - return errMsg; - }, - buildTooManyAlternativesError: function (options) { - var errMsg = "An Alternation cannot have more than 256 alternatives:\n" + - (" inside <" + options.topLevelRule.name + "> Rule.\n has " + (options.alternation.definition.length + 1) + " alternatives."); - return errMsg; - }, - buildLeftRecursionError: function (options) { - var ruleName = options.topLevelRule.name; - var pathNames = map(options.leftRecursionPath, function (currRule) { return currRule.name; }); - var leftRecursivePath = ruleName + " --> " + pathNames - .concat([ruleName]) - .join(" --> "); - var errMsg = "Left Recursion found in grammar.\n" + - ("rule: <" + ruleName + "> can be invoked from itself (directly or indirectly)\n") + - ("without consuming any Tokens. The grammar path that causes this is: \n " + leftRecursivePath + "\n") + - " To fix this refactor your grammar to remove the left recursion.\n" + - "see: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring."; - return errMsg; - }, - // TODO: remove - `errors_public` from nyc.config.js exclude - // once this method is fully removed from this file - buildInvalidRuleNameError: function (options) { - /* istanbul ignore next */ - return "deprecated"; - }, - buildDuplicateRuleNameError: function (options) { - var ruleName; - if (options.topLevelRule instanceof Rule) { - ruleName = options.topLevelRule.name; - } - else { - ruleName = options.topLevelRule; - } - var errMsg = "Duplicate definition, rule: ->" + ruleName + "<- is already defined in the grammar: ->" + options.grammarName + "<-"; - return errMsg; - } -}; - -var __extends$5 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -function resolveGrammar$1(topLevels, errMsgProvider) { - var refResolver = new GastRefResolverVisitor(topLevels, errMsgProvider); - refResolver.resolveRefs(); - return refResolver.errors; -} -var GastRefResolverVisitor = /** @class */ (function (_super) { - __extends$5(GastRefResolverVisitor, _super); - function GastRefResolverVisitor(nameToTopRule, errMsgProvider) { - var _this = _super.call(this) || this; - _this.nameToTopRule = nameToTopRule; - _this.errMsgProvider = errMsgProvider; - _this.errors = []; - return _this; - } - GastRefResolverVisitor.prototype.resolveRefs = function () { - var _this = this; - forEach(values(this.nameToTopRule), function (prod) { - _this.currTopLevel = prod; - prod.accept(_this); - }); - }; - GastRefResolverVisitor.prototype.visitNonTerminal = function (node) { - var ref = this.nameToTopRule[node.nonTerminalName]; - if (!ref) { - var msg = this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel, node); - this.errors.push({ - message: msg, - type: ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF, - ruleName: this.currTopLevel.name, - unresolvedRefName: node.nonTerminalName - }); - } - else { - node.referencedRule = ref; - } - }; - return GastRefResolverVisitor; -}(GAstVisitor)); - -var __extends$4 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var AbstractNextPossibleTokensWalker = /** @class */ (function (_super) { - __extends$4(AbstractNextPossibleTokensWalker, _super); - function AbstractNextPossibleTokensWalker(topProd, path) { - var _this = _super.call(this) || this; - _this.topProd = topProd; - _this.path = path; - _this.possibleTokTypes = []; - _this.nextProductionName = ""; - _this.nextProductionOccurrence = 0; - _this.found = false; - _this.isAtEndOfPath = false; - return _this; - } - AbstractNextPossibleTokensWalker.prototype.startWalking = function () { - this.found = false; - if (this.path.ruleStack[0] !== this.topProd.name) { - throw Error("The path does not start with the walker's top Rule!"); - } - // immutable for the win - this.ruleStack = cloneArr(this.path.ruleStack).reverse(); // intelij bug requires assertion - this.occurrenceStack = cloneArr(this.path.occurrenceStack).reverse(); // intelij bug requires assertion - // already verified that the first production is valid, we now seek the 2nd production - this.ruleStack.pop(); - this.occurrenceStack.pop(); - this.updateExpectedNext(); - this.walk(this.topProd); - return this.possibleTokTypes; - }; - AbstractNextPossibleTokensWalker.prototype.walk = function (prod, prevRest) { - if (prevRest === void 0) { prevRest = []; } - // stop scanning once we found the path - if (!this.found) { - _super.prototype.walk.call(this, prod, prevRest); - } - }; - AbstractNextPossibleTokensWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { - // found the next production, need to keep walking in it - if (refProd.referencedRule.name === this.nextProductionName && - refProd.idx === this.nextProductionOccurrence) { - var fullRest = currRest.concat(prevRest); - this.updateExpectedNext(); - this.walk(refProd.referencedRule, fullRest); - } - }; - AbstractNextPossibleTokensWalker.prototype.updateExpectedNext = function () { - // need to consume the Terminal - if (isEmpty(this.ruleStack)) { - // must reset nextProductionXXX to avoid walking down another Top Level production while what we are - // really seeking is the last Terminal... - this.nextProductionName = ""; - this.nextProductionOccurrence = 0; - this.isAtEndOfPath = true; - } - else { - this.nextProductionName = this.ruleStack.pop(); - this.nextProductionOccurrence = this.occurrenceStack.pop(); - } - }; - return AbstractNextPossibleTokensWalker; -}(RestWalker)); -var NextAfterTokenWalker = /** @class */ (function (_super) { - __extends$4(NextAfterTokenWalker, _super); - function NextAfterTokenWalker(topProd, path) { - var _this = _super.call(this, topProd, path) || this; - _this.path = path; - _this.nextTerminalName = ""; - _this.nextTerminalOccurrence = 0; - _this.nextTerminalName = _this.path.lastTok.name; - _this.nextTerminalOccurrence = _this.path.lastTokOccurrence; - return _this; - } - NextAfterTokenWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { - if (this.isAtEndOfPath && - terminal.terminalType.name === this.nextTerminalName && - terminal.idx === this.nextTerminalOccurrence && - !this.found) { - var fullRest = currRest.concat(prevRest); - var restProd = new Alternative({ definition: fullRest }); - this.possibleTokTypes = first(restProd); - this.found = true; - } - }; - return NextAfterTokenWalker; -}(AbstractNextPossibleTokensWalker)); -/** - * This walker only "walks" a single "TOP" level in the Grammar Ast, this means - * it never "follows" production refs - */ -var AbstractNextTerminalAfterProductionWalker = /** @class */ (function (_super) { - __extends$4(AbstractNextTerminalAfterProductionWalker, _super); - function AbstractNextTerminalAfterProductionWalker(topRule, occurrence) { - var _this = _super.call(this) || this; - _this.topRule = topRule; - _this.occurrence = occurrence; - _this.result = { - token: undefined, - occurrence: undefined, - isEndOfRule: undefined - }; - return _this; - } - AbstractNextTerminalAfterProductionWalker.prototype.startWalking = function () { - this.walk(this.topRule); - return this.result; - }; - return AbstractNextTerminalAfterProductionWalker; -}(RestWalker)); -var NextTerminalAfterManyWalker = /** @class */ (function (_super) { - __extends$4(NextTerminalAfterManyWalker, _super); - function NextTerminalAfterManyWalker() { - return _super !== null && _super.apply(this, arguments) || this; - } - NextTerminalAfterManyWalker.prototype.walkMany = function (manyProd, currRest, prevRest) { - if (manyProd.idx === this.occurrence) { - var firstAfterMany = first$1(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterMany === undefined; - if (firstAfterMany instanceof Terminal) { - this.result.token = firstAfterMany.terminalType; - this.result.occurrence = firstAfterMany.idx; - } - } - else { - _super.prototype.walkMany.call(this, manyProd, currRest, prevRest); - } - }; - return NextTerminalAfterManyWalker; -}(AbstractNextTerminalAfterProductionWalker)); -var NextTerminalAfterManySepWalker = /** @class */ (function (_super) { - __extends$4(NextTerminalAfterManySepWalker, _super); - function NextTerminalAfterManySepWalker() { - return _super !== null && _super.apply(this, arguments) || this; - } - NextTerminalAfterManySepWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) { - if (manySepProd.idx === this.occurrence) { - var firstAfterManySep = first$1(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterManySep === undefined; - if (firstAfterManySep instanceof Terminal) { - this.result.token = firstAfterManySep.terminalType; - this.result.occurrence = firstAfterManySep.idx; - } - } - else { - _super.prototype.walkManySep.call(this, manySepProd, currRest, prevRest); - } - }; - return NextTerminalAfterManySepWalker; -}(AbstractNextTerminalAfterProductionWalker)); -var NextTerminalAfterAtLeastOneWalker = /** @class */ (function (_super) { - __extends$4(NextTerminalAfterAtLeastOneWalker, _super); - function NextTerminalAfterAtLeastOneWalker() { - return _super !== null && _super.apply(this, arguments) || this; - } - NextTerminalAfterAtLeastOneWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) { - if (atLeastOneProd.idx === this.occurrence) { - var firstAfterAtLeastOne = first$1(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterAtLeastOne === undefined; - if (firstAfterAtLeastOne instanceof Terminal) { - this.result.token = firstAfterAtLeastOne.terminalType; - this.result.occurrence = firstAfterAtLeastOne.idx; - } - } - else { - _super.prototype.walkAtLeastOne.call(this, atLeastOneProd, currRest, prevRest); - } - }; - return NextTerminalAfterAtLeastOneWalker; -}(AbstractNextTerminalAfterProductionWalker)); -// TODO: reduce code duplication in the AfterWalkers -var NextTerminalAfterAtLeastOneSepWalker = /** @class */ (function (_super) { - __extends$4(NextTerminalAfterAtLeastOneSepWalker, _super); - function NextTerminalAfterAtLeastOneSepWalker() { - return _super !== null && _super.apply(this, arguments) || this; - } - NextTerminalAfterAtLeastOneSepWalker.prototype.walkAtLeastOneSep = function (atleastOneSepProd, currRest, prevRest) { - if (atleastOneSepProd.idx === this.occurrence) { - var firstAfterfirstAfterAtLeastOneSep = first$1(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterfirstAfterAtLeastOneSep === undefined; - if (firstAfterfirstAfterAtLeastOneSep instanceof Terminal) { - this.result.token = firstAfterfirstAfterAtLeastOneSep.terminalType; - this.result.occurrence = firstAfterfirstAfterAtLeastOneSep.idx; - } - } - else { - _super.prototype.walkAtLeastOneSep.call(this, atleastOneSepProd, currRest, prevRest); - } - }; - return NextTerminalAfterAtLeastOneSepWalker; -}(AbstractNextTerminalAfterProductionWalker)); -function possiblePathsFrom(targetDef, maxLength, currPath) { - if (currPath === void 0) { currPath = []; } - // avoid side effects - currPath = cloneArr(currPath); - var result = []; - var i = 0; - // TODO: avoid inner funcs - function remainingPathWith(nextDef) { - return nextDef.concat(drop(targetDef, i + 1)); - } - // TODO: avoid inner funcs - function getAlternativesForProd(definition) { - var alternatives = possiblePathsFrom(remainingPathWith(definition), maxLength, currPath); - return result.concat(alternatives); - } - /** - * Mandatory productions will halt the loop as the paths computed from their recursive calls will already contain the - * following (rest) of the targetDef. - * - * For optional productions (Option/Repetition/...) the loop will continue to represent the paths that do not include the - * the optional production. - */ - while (currPath.length < maxLength && i < targetDef.length) { - var prod = targetDef[i]; - /* istanbul ignore else */ - if (prod instanceof Alternative) { - return getAlternativesForProd(prod.definition); - } - else if (prod instanceof NonTerminal) { - return getAlternativesForProd(prod.definition); - } - else if (prod instanceof Option) { - result = getAlternativesForProd(prod.definition); - } - else if (prod instanceof RepetitionMandatory) { - var newDef = prod.definition.concat([ - new Repetition({ - definition: prod.definition - }) - ]); - return getAlternativesForProd(newDef); - } - else if (prod instanceof RepetitionMandatoryWithSeparator) { - var newDef = [ - new Alternative({ definition: prod.definition }), - new Repetition({ - definition: [new Terminal({ terminalType: prod.separator })].concat(prod.definition) - }) - ]; - return getAlternativesForProd(newDef); - } - else if (prod instanceof RepetitionWithSeparator) { - var newDef = prod.definition.concat([ - new Repetition({ - definition: [new Terminal({ terminalType: prod.separator })].concat(prod.definition) - }) - ]); - result = getAlternativesForProd(newDef); - } - else if (prod instanceof Repetition) { - var newDef = prod.definition.concat([ - new Repetition({ - definition: prod.definition - }) - ]); - result = getAlternativesForProd(newDef); - } - else if (prod instanceof Alternation) { - forEach(prod.definition, function (currAlt) { - // TODO: this is a limited check for empty alternatives - // It would prevent a common case of infinite loops during parser initialization. - // However **in-directly** empty alternatives may still cause issues. - if (isEmpty(currAlt.definition) === false) { - result = getAlternativesForProd(currAlt.definition); - } - }); - return result; - } - else if (prod instanceof Terminal) { - currPath.push(prod.terminalType); - } - else { - throw Error("non exhaustive match"); - } - i++; - } - result.push({ - partialPath: currPath, - suffixDef: drop(targetDef, i) - }); - return result; -} -function nextPossibleTokensAfter(initialDef, tokenVector, tokMatcher, maxLookAhead) { - var EXIT_NON_TERMINAL = "EXIT_NONE_TERMINAL"; - // to avoid creating a new Array each time. - var EXIT_NON_TERMINAL_ARR = [EXIT_NON_TERMINAL]; - var EXIT_ALTERNATIVE = "EXIT_ALTERNATIVE"; - var foundCompletePath = false; - var tokenVectorLength = tokenVector.length; - var minimalAlternativesIndex = tokenVectorLength - maxLookAhead - 1; - var result = []; - var possiblePaths = []; - possiblePaths.push({ - idx: -1, - def: initialDef, - ruleStack: [], - occurrenceStack: [] - }); - while (!isEmpty(possiblePaths)) { - var currPath = possiblePaths.pop(); - // skip alternatives if no more results can be found (assuming deterministic grammar with fixed lookahead) - if (currPath === EXIT_ALTERNATIVE) { - if (foundCompletePath && - last(possiblePaths).idx <= minimalAlternativesIndex) { - // remove irrelevant alternative - possiblePaths.pop(); - } - continue; - } - var currDef = currPath.def; - var currIdx = currPath.idx; - var currRuleStack = currPath.ruleStack; - var currOccurrenceStack = currPath.occurrenceStack; - // For Example: an empty path could exist in a valid grammar in the case of an EMPTY_ALT - if (isEmpty(currDef)) { - continue; - } - var prod = currDef[0]; - /* istanbul ignore else */ - if (prod === EXIT_NON_TERMINAL) { - var nextPath = { - idx: currIdx, - def: drop(currDef), - ruleStack: dropRight(currRuleStack), - occurrenceStack: dropRight(currOccurrenceStack) - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof Terminal) { - /* istanbul ignore else */ - if (currIdx < tokenVectorLength - 1) { - var nextIdx = currIdx + 1; - var actualToken = tokenVector[nextIdx]; - if (tokMatcher(actualToken, prod.terminalType)) { - var nextPath = { - idx: nextIdx, - def: drop(currDef), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPath); - } - // end of the line - } - else if (currIdx === tokenVectorLength - 1) { - // IGNORE ABOVE ELSE - result.push({ - nextTokenType: prod.terminalType, - nextTokenOccurrence: prod.idx, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }); - foundCompletePath = true; - } - else { - throw Error("non exhaustive match"); - } - } - else if (prod instanceof NonTerminal) { - var newRuleStack = cloneArr(currRuleStack); - newRuleStack.push(prod.nonTerminalName); - var newOccurrenceStack = cloneArr(currOccurrenceStack); - newOccurrenceStack.push(prod.idx); - var nextPath = { - idx: currIdx, - def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, drop(currDef)), - ruleStack: newRuleStack, - occurrenceStack: newOccurrenceStack - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof Option) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - var nextPathWithout = { - idx: currIdx, - def: drop(currDef), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWithout); - // required marker to avoid backtracking paths whose higher priority alternatives already matched - possiblePaths.push(EXIT_ALTERNATIVE); - var nextPathWith = { - idx: currIdx, - def: prod.definition.concat(drop(currDef)), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWith); - } - else if (prod instanceof RepetitionMandatory) { - // TODO:(THE NEW operators here take a while...) (convert once?) - var secondIteration = new Repetition({ - definition: prod.definition, - idx: prod.idx - }); - var nextDef = prod.definition.concat([secondIteration], drop(currDef)); - var nextPath = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof RepetitionMandatoryWithSeparator) { - // TODO:(THE NEW operators here take a while...) (convert once?) - var separatorGast = new Terminal({ - terminalType: prod.separator - }); - var secondIteration = new Repetition({ - definition: [separatorGast].concat(prod.definition), - idx: prod.idx - }); - var nextDef = prod.definition.concat([secondIteration], drop(currDef)); - var nextPath = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof RepetitionWithSeparator) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - var nextPathWithout = { - idx: currIdx, - def: drop(currDef), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWithout); - // required marker to avoid backtracking paths whose higher priority alternatives already matched - possiblePaths.push(EXIT_ALTERNATIVE); - var separatorGast = new Terminal({ - terminalType: prod.separator - }); - var nthRepetition = new Repetition({ - definition: [separatorGast].concat(prod.definition), - idx: prod.idx - }); - var nextDef = prod.definition.concat([nthRepetition], drop(currDef)); - var nextPathWith = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWith); - } - else if (prod instanceof Repetition) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - var nextPathWithout = { - idx: currIdx, - def: drop(currDef), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWithout); - // required marker to avoid backtracking paths whose higher priority alternatives already matched - possiblePaths.push(EXIT_ALTERNATIVE); - // TODO: an empty repetition will cause infinite loops here, will the parser detect this in selfAnalysis? - var nthRepetition = new Repetition({ - definition: prod.definition, - idx: prod.idx - }); - var nextDef = prod.definition.concat([nthRepetition], drop(currDef)); - var nextPathWith = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWith); - } - else if (prod instanceof Alternation) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - for (var i = prod.definition.length - 1; i >= 0; i--) { - var currAlt = prod.definition[i]; - var currAltPath = { - idx: currIdx, - def: currAlt.definition.concat(drop(currDef)), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(currAltPath); - possiblePaths.push(EXIT_ALTERNATIVE); - } - } - else if (prod instanceof Alternative) { - possiblePaths.push({ - idx: currIdx, - def: prod.definition.concat(drop(currDef)), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }); - } - else if (prod instanceof Rule) { - // last because we should only encounter at most a single one of these per invocation. - possiblePaths.push(expandTopLevelRule(prod, currIdx, currRuleStack, currOccurrenceStack)); - } - else { - throw Error("non exhaustive match"); - } - } - return result; -} -function expandTopLevelRule(topRule, currIdx, currRuleStack, currOccurrenceStack) { - var newRuleStack = cloneArr(currRuleStack); - newRuleStack.push(topRule.name); - var newCurrOccurrenceStack = cloneArr(currOccurrenceStack); - // top rule is always assumed to have been called with occurrence index 1 - newCurrOccurrenceStack.push(1); - return { - idx: currIdx, - def: topRule.definition, - ruleStack: newRuleStack, - occurrenceStack: newCurrOccurrenceStack - }; -} - -var __extends$3 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var PROD_TYPE; -(function (PROD_TYPE) { - PROD_TYPE[PROD_TYPE["OPTION"] = 0] = "OPTION"; - PROD_TYPE[PROD_TYPE["REPETITION"] = 1] = "REPETITION"; - PROD_TYPE[PROD_TYPE["REPETITION_MANDATORY"] = 2] = "REPETITION_MANDATORY"; - PROD_TYPE[PROD_TYPE["REPETITION_MANDATORY_WITH_SEPARATOR"] = 3] = "REPETITION_MANDATORY_WITH_SEPARATOR"; - PROD_TYPE[PROD_TYPE["REPETITION_WITH_SEPARATOR"] = 4] = "REPETITION_WITH_SEPARATOR"; - PROD_TYPE[PROD_TYPE["ALTERNATION"] = 5] = "ALTERNATION"; -})(PROD_TYPE || (PROD_TYPE = {})); -function getProdType(prod) { - /* istanbul ignore else */ - if (prod instanceof Option) { - return PROD_TYPE.OPTION; - } - else if (prod instanceof Repetition) { - return PROD_TYPE.REPETITION; - } - else if (prod instanceof RepetitionMandatory) { - return PROD_TYPE.REPETITION_MANDATORY; - } - else if (prod instanceof RepetitionMandatoryWithSeparator) { - return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR; - } - else if (prod instanceof RepetitionWithSeparator) { - return PROD_TYPE.REPETITION_WITH_SEPARATOR; - } - else if (prod instanceof Alternation) { - return PROD_TYPE.ALTERNATION; - } - else { - throw Error("non exhaustive match"); - } -} -function buildLookaheadFuncForOr(occurrence, ruleGrammar, maxLookahead, hasPredicates, dynamicTokensEnabled, laFuncBuilder) { - var lookAheadPaths = getLookaheadPathsForOr(occurrence, ruleGrammar, maxLookahead); - var tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths) - ? tokenStructuredMatcherNoCategories - : tokenStructuredMatcher; - return laFuncBuilder(lookAheadPaths, hasPredicates, tokenMatcher, dynamicTokensEnabled); -} -/** - * When dealing with an Optional production (OPTION/MANY/2nd iteration of AT_LEAST_ONE/...) we need to compare - * the lookahead "inside" the production and the lookahead immediately "after" it in the same top level rule (context free). - * - * Example: given a production: - * ABC(DE)?DF - * - * The optional '(DE)?' should only be entered if we see 'DE'. a single Token 'D' is not sufficient to distinguish between the two - * alternatives. - * - * @returns A Lookahead function which will return true IFF the parser should parse the Optional production. - */ -function buildLookaheadFuncForOptionalProd(occurrence, ruleGrammar, k, dynamicTokensEnabled, prodType, lookaheadBuilder) { - var lookAheadPaths = getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k); - var tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths) - ? tokenStructuredMatcherNoCategories - : tokenStructuredMatcher; - return lookaheadBuilder(lookAheadPaths[0], tokenMatcher, dynamicTokensEnabled); -} -function buildAlternativesLookAheadFunc(alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) { - var numOfAlts = alts.length; - var areAllOneTokenLookahead = every(alts, function (currAlt) { - return every(currAlt, function (currPath) { - return currPath.length === 1; - }); - }); - // This version takes into account the predicates as well. - if (hasPredicates) { - /** - * @returns {number} - The chosen alternative index - */ - return function (orAlts) { - // unfortunately the predicates must be extracted every single time - // as they cannot be cached due to references to parameters(vars) which are no longer valid. - // note that in the common case of no predicates, no cpu time will be wasted on this (see else block) - var predicates = map(orAlts, function (currAlt) { return currAlt.GATE; }); - for (var t = 0; t < numOfAlts; t++) { - var currAlt = alts[t]; - var currNumOfPaths = currAlt.length; - var currPredicate = predicates[t]; - if (currPredicate !== undefined && currPredicate.call(this) === false) { - // if the predicate does not match there is no point in checking the paths - continue; - } - nextPath: for (var j = 0; j < currNumOfPaths; j++) { - var currPath = currAlt[j]; - var currPathLength = currPath.length; - for (var i = 0; i < currPathLength; i++) { - var nextToken = this.LA(i + 1); - if (tokenMatcher(nextToken, currPath[i]) === false) { - // mismatch in current path - // try the next pth - continue nextPath; - } - } - // found a full path that matches. - // this will also work for an empty ALT as the loop will be skipped - return t; - } - // none of the paths for the current alternative matched - // try the next alternative - } - // none of the alternatives could be matched - return undefined; - }; - } - else if (areAllOneTokenLookahead && !dynamicTokensEnabled) { - // optimized (common) case of all the lookaheads paths requiring only - // a single token lookahead. These Optimizations cannot work if dynamically defined Tokens are used. - var singleTokenAlts = map(alts, function (currAlt) { - return flatten(currAlt); - }); - var choiceToAlt_1 = reduce(singleTokenAlts, function (result, currAlt, idx) { - forEach(currAlt, function (currTokType) { - if (!has(result, currTokType.tokenTypeIdx)) { - result[currTokType.tokenTypeIdx] = idx; - } - forEach(currTokType.categoryMatches, function (currExtendingType) { - if (!has(result, currExtendingType)) { - result[currExtendingType] = idx; - } - }); - }); - return result; - }, []); - /** - * @returns {number} - The chosen alternative index - */ - return function () { - var nextToken = this.LA(1); - return choiceToAlt_1[nextToken.tokenTypeIdx]; - }; - } - else { - // optimized lookahead without needing to check the predicates at all. - // this causes code duplication which is intentional to improve performance. - /** - * @returns {number} - The chosen alternative index - */ - return function () { - for (var t = 0; t < numOfAlts; t++) { - var currAlt = alts[t]; - var currNumOfPaths = currAlt.length; - nextPath: for (var j = 0; j < currNumOfPaths; j++) { - var currPath = currAlt[j]; - var currPathLength = currPath.length; - for (var i = 0; i < currPathLength; i++) { - var nextToken = this.LA(i + 1); - if (tokenMatcher(nextToken, currPath[i]) === false) { - // mismatch in current path - // try the next pth - continue nextPath; - } - } - // found a full path that matches. - // this will also work for an empty ALT as the loop will be skipped - return t; - } - // none of the paths for the current alternative matched - // try the next alternative - } - // none of the alternatives could be matched - return undefined; - }; - } -} -function buildSingleAlternativeLookaheadFunction(alt, tokenMatcher, dynamicTokensEnabled) { - var areAllOneTokenLookahead = every(alt, function (currPath) { - return currPath.length === 1; - }); - var numOfPaths = alt.length; - // optimized (common) case of all the lookaheads paths requiring only - // a single token lookahead. - if (areAllOneTokenLookahead && !dynamicTokensEnabled) { - var singleTokensTypes = flatten(alt); - if (singleTokensTypes.length === 1 && - isEmpty(singleTokensTypes[0].categoryMatches)) { - var expectedTokenType = singleTokensTypes[0]; - var expectedTokenUniqueKey_1 = expectedTokenType.tokenTypeIdx; - return function () { - return this.LA(1).tokenTypeIdx === expectedTokenUniqueKey_1; - }; - } - else { - var choiceToAlt_2 = reduce(singleTokensTypes, function (result, currTokType, idx) { - result[currTokType.tokenTypeIdx] = true; - forEach(currTokType.categoryMatches, function (currExtendingType) { - result[currExtendingType] = true; - }); - return result; - }, []); - return function () { - var nextToken = this.LA(1); - return choiceToAlt_2[nextToken.tokenTypeIdx] === true; - }; - } - } - else { - return function () { - nextPath: for (var j = 0; j < numOfPaths; j++) { - var currPath = alt[j]; - var currPathLength = currPath.length; - for (var i = 0; i < currPathLength; i++) { - var nextToken = this.LA(i + 1); - if (tokenMatcher(nextToken, currPath[i]) === false) { - // mismatch in current path - // try the next pth - continue nextPath; - } - } - // found a full path that matches. - return true; - } - // none of the paths matched - return false; - }; - } -} -var RestDefinitionFinderWalker = /** @class */ (function (_super) { - __extends$3(RestDefinitionFinderWalker, _super); - function RestDefinitionFinderWalker(topProd, targetOccurrence, targetProdType) { - var _this = _super.call(this) || this; - _this.topProd = topProd; - _this.targetOccurrence = targetOccurrence; - _this.targetProdType = targetProdType; - return _this; - } - RestDefinitionFinderWalker.prototype.startWalking = function () { - this.walk(this.topProd); - return this.restDef; - }; - RestDefinitionFinderWalker.prototype.checkIsTarget = function (node, expectedProdType, currRest, prevRest) { - if (node.idx === this.targetOccurrence && - this.targetProdType === expectedProdType) { - this.restDef = currRest.concat(prevRest); - return true; - } - // performance optimization, do not iterate over the entire Grammar ast after we have found the target - return false; - }; - RestDefinitionFinderWalker.prototype.walkOption = function (optionProd, currRest, prevRest) { - if (!this.checkIsTarget(optionProd, PROD_TYPE.OPTION, currRest, prevRest)) { - _super.prototype.walkOption.call(this, optionProd, currRest, prevRest); - } - }; - RestDefinitionFinderWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) { - if (!this.checkIsTarget(atLeastOneProd, PROD_TYPE.REPETITION_MANDATORY, currRest, prevRest)) { - _super.prototype.walkOption.call(this, atLeastOneProd, currRest, prevRest); - } - }; - RestDefinitionFinderWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) { - if (!this.checkIsTarget(atLeastOneSepProd, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currRest, prevRest)) { - _super.prototype.walkOption.call(this, atLeastOneSepProd, currRest, prevRest); - } - }; - RestDefinitionFinderWalker.prototype.walkMany = function (manyProd, currRest, prevRest) { - if (!this.checkIsTarget(manyProd, PROD_TYPE.REPETITION, currRest, prevRest)) { - _super.prototype.walkOption.call(this, manyProd, currRest, prevRest); - } - }; - RestDefinitionFinderWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) { - if (!this.checkIsTarget(manySepProd, PROD_TYPE.REPETITION_WITH_SEPARATOR, currRest, prevRest)) { - _super.prototype.walkOption.call(this, manySepProd, currRest, prevRest); - } - }; - return RestDefinitionFinderWalker; -}(RestWalker)); -/** - * Returns the definition of a target production in a top level level rule. - */ -var InsideDefinitionFinderVisitor = /** @class */ (function (_super) { - __extends$3(InsideDefinitionFinderVisitor, _super); - function InsideDefinitionFinderVisitor(targetOccurrence, targetProdType, targetRef) { - var _this = _super.call(this) || this; - _this.targetOccurrence = targetOccurrence; - _this.targetProdType = targetProdType; - _this.targetRef = targetRef; - _this.result = []; - return _this; - } - InsideDefinitionFinderVisitor.prototype.checkIsTarget = function (node, expectedProdName) { - if (node.idx === this.targetOccurrence && - this.targetProdType === expectedProdName && - (this.targetRef === undefined || node === this.targetRef)) { - this.result = node.definition; - } - }; - InsideDefinitionFinderVisitor.prototype.visitOption = function (node) { - this.checkIsTarget(node, PROD_TYPE.OPTION); - }; - InsideDefinitionFinderVisitor.prototype.visitRepetition = function (node) { - this.checkIsTarget(node, PROD_TYPE.REPETITION); - }; - InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatory = function (node) { - this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY); - }; - InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { - this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR); - }; - InsideDefinitionFinderVisitor.prototype.visitRepetitionWithSeparator = function (node) { - this.checkIsTarget(node, PROD_TYPE.REPETITION_WITH_SEPARATOR); - }; - InsideDefinitionFinderVisitor.prototype.visitAlternation = function (node) { - this.checkIsTarget(node, PROD_TYPE.ALTERNATION); - }; - return InsideDefinitionFinderVisitor; -}(GAstVisitor)); -function initializeArrayOfArrays(size) { - var result = new Array(size); - for (var i = 0; i < size; i++) { - result[i] = []; - } - return result; -} -/** - * A sort of hash function between a Path in the grammar and a string. - * Note that this returns multiple "hashes" to support the scenario of token categories. - * - A single path with categories may match multiple **actual** paths. - */ -function pathToHashKeys(path) { - var keys = [""]; - for (var i = 0; i < path.length; i++) { - var tokType = path[i]; - var longerKeys = []; - for (var j = 0; j < keys.length; j++) { - var currShorterKey = keys[j]; - longerKeys.push(currShorterKey + "_" + tokType.tokenTypeIdx); - for (var t = 0; t < tokType.categoryMatches.length; t++) { - var categoriesKeySuffix = "_" + tokType.categoryMatches[t]; - longerKeys.push(currShorterKey + categoriesKeySuffix); - } - } - keys = longerKeys; - } - return keys; -} -/** - * Imperative style due to being called from a hot spot - */ -function isUniquePrefixHash(altKnownPathsKeys, searchPathKeys, idx) { - for (var currAltIdx = 0; currAltIdx < altKnownPathsKeys.length; currAltIdx++) { - // We only want to test vs the other alternatives - if (currAltIdx === idx) { - continue; - } - var otherAltKnownPathsKeys = altKnownPathsKeys[currAltIdx]; - for (var searchIdx = 0; searchIdx < searchPathKeys.length; searchIdx++) { - var searchKey = searchPathKeys[searchIdx]; - if (otherAltKnownPathsKeys[searchKey] === true) { - return false; - } - } - } - // None of the SearchPathKeys were found in any of the other alternatives - return true; -} -function lookAheadSequenceFromAlternatives(altsDefs, k) { - var partialAlts = map(altsDefs, function (currAlt) { return possiblePathsFrom([currAlt], 1); }); - var finalResult = initializeArrayOfArrays(partialAlts.length); - var altsHashes = map(partialAlts, function (currAltPaths) { - var dict = {}; - forEach(currAltPaths, function (item) { - var keys = pathToHashKeys(item.partialPath); - forEach(keys, function (currKey) { - dict[currKey] = true; - }); - }); - return dict; - }); - var newData = partialAlts; - // maxLookahead loop - for (var pathLength = 1; pathLength <= k; pathLength++) { - var currDataset = newData; - newData = initializeArrayOfArrays(currDataset.length); - var _loop_1 = function (altIdx) { - var currAltPathsAndSuffixes = currDataset[altIdx]; - // paths in current alternative loop - for (var currPathIdx = 0; currPathIdx < currAltPathsAndSuffixes.length; currPathIdx++) { - var currPathPrefix = currAltPathsAndSuffixes[currPathIdx].partialPath; - var suffixDef = currAltPathsAndSuffixes[currPathIdx].suffixDef; - var prefixKeys = pathToHashKeys(currPathPrefix); - var isUnique = isUniquePrefixHash(altsHashes, prefixKeys, altIdx); - // End of the line for this path. - if (isUnique || isEmpty(suffixDef) || currPathPrefix.length === k) { - var currAltResult = finalResult[altIdx]; - // TODO: Can we implement a containsPath using Maps/Dictionaries? - if (containsPath(currAltResult, currPathPrefix) === false) { - currAltResult.push(currPathPrefix); - // Update all new keys for the current path. - for (var j = 0; j < prefixKeys.length; j++) { - var currKey = prefixKeys[j]; - altsHashes[altIdx][currKey] = true; - } - } - } - // Expand longer paths - else { - var newPartialPathsAndSuffixes = possiblePathsFrom(suffixDef, pathLength + 1, currPathPrefix); - newData[altIdx] = newData[altIdx].concat(newPartialPathsAndSuffixes); - // Update keys for new known paths - forEach(newPartialPathsAndSuffixes, function (item) { - var prefixKeys = pathToHashKeys(item.partialPath); - forEach(prefixKeys, function (key) { - altsHashes[altIdx][key] = true; - }); - }); - } - } - }; - // alternatives loop - for (var altIdx = 0; altIdx < currDataset.length; altIdx++) { - _loop_1(altIdx); - } - } - return finalResult; -} -function getLookaheadPathsForOr(occurrence, ruleGrammar, k, orProd) { - var visitor = new InsideDefinitionFinderVisitor(occurrence, PROD_TYPE.ALTERNATION, orProd); - ruleGrammar.accept(visitor); - return lookAheadSequenceFromAlternatives(visitor.result, k); -} -function getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k) { - var insideDefVisitor = new InsideDefinitionFinderVisitor(occurrence, prodType); - ruleGrammar.accept(insideDefVisitor); - var insideDef = insideDefVisitor.result; - var afterDefWalker = new RestDefinitionFinderWalker(ruleGrammar, occurrence, prodType); - var afterDef = afterDefWalker.startWalking(); - var insideFlat = new Alternative({ definition: insideDef }); - var afterFlat = new Alternative({ definition: afterDef }); - return lookAheadSequenceFromAlternatives([insideFlat, afterFlat], k); -} -function containsPath(alternative, searchPath) { - compareOtherPath: for (var i = 0; i < alternative.length; i++) { - var otherPath = alternative[i]; - if (otherPath.length !== searchPath.length) { - continue; - } - for (var j = 0; j < otherPath.length; j++) { - var searchTok = searchPath[j]; - var otherTok = otherPath[j]; - var matchingTokens = searchTok === otherTok || - otherTok.categoryMatchesMap[searchTok.tokenTypeIdx] !== undefined; - if (matchingTokens === false) { - continue compareOtherPath; - } - } - return true; - } - return false; -} -function isStrictPrefixOfPath(prefix, other) { - return (prefix.length < other.length && - every(prefix, function (tokType, idx) { - var otherTokType = other[idx]; - return (tokType === otherTokType || - otherTokType.categoryMatchesMap[tokType.tokenTypeIdx]); - })); -} -function areTokenCategoriesNotUsed(lookAheadPaths) { - return every(lookAheadPaths, function (singleAltPaths) { - return every(singleAltPaths, function (singlePath) { - return every(singlePath, function (token) { return isEmpty(token.categoryMatches); }); - }); - }); -} - -var __extends$2 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -function validateGrammar$1(topLevels, globalMaxLookahead, tokenTypes, errMsgProvider, grammarName) { - var duplicateErrors = map(topLevels, function (currTopLevel) { - return validateDuplicateProductions(currTopLevel, errMsgProvider); - }); - var leftRecursionErrors = map(topLevels, function (currTopRule) { - return validateNoLeftRecursion(currTopRule, currTopRule, errMsgProvider); - }); - var emptyAltErrors = []; - var ambiguousAltsErrors = []; - var emptyRepetitionErrors = []; - // left recursion could cause infinite loops in the following validations. - // It is safest to first have the user fix the left recursion errors first and only then examine Further issues. - if (every(leftRecursionErrors, isEmpty)) { - emptyAltErrors = map(topLevels, function (currTopRule) { - return validateEmptyOrAlternative(currTopRule, errMsgProvider); - }); - ambiguousAltsErrors = map(topLevels, function (currTopRule) { - return validateAmbiguousAlternationAlternatives(currTopRule, globalMaxLookahead, errMsgProvider); - }); - emptyRepetitionErrors = validateSomeNonEmptyLookaheadPath(topLevels, globalMaxLookahead, errMsgProvider); - } - var termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider); - var tooManyAltsErrors = map(topLevels, function (curRule) { - return validateTooManyAlts(curRule, errMsgProvider); - }); - var duplicateRulesError = map(topLevels, function (curRule) { - return validateRuleDoesNotAlreadyExist(curRule, topLevels, grammarName, errMsgProvider); - }); - return (flatten(duplicateErrors.concat(emptyRepetitionErrors, leftRecursionErrors, emptyAltErrors, ambiguousAltsErrors, termsNamespaceConflictErrors, tooManyAltsErrors, duplicateRulesError))); -} -function validateDuplicateProductions(topLevelRule, errMsgProvider) { - var collectorVisitor = new OccurrenceValidationCollector(); - topLevelRule.accept(collectorVisitor); - var allRuleProductions = collectorVisitor.allProductions; - var productionGroups = groupBy(allRuleProductions, identifyProductionForDuplicates); - var duplicates = pick(productionGroups, function (currGroup) { - return currGroup.length > 1; - }); - var errors = map(values(duplicates), function (currDuplicates) { - var firstProd = first$1(currDuplicates); - var msg = errMsgProvider.buildDuplicateFoundError(topLevelRule, currDuplicates); - var dslName = getProductionDslName(firstProd); - var defError = { - message: msg, - type: ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS, - ruleName: topLevelRule.name, - dslName: dslName, - occurrence: firstProd.idx - }; - var param = getExtraProductionArgument(firstProd); - if (param) { - defError.parameter = param; - } - return defError; - }); - return errors; -} -function identifyProductionForDuplicates(prod) { - return getProductionDslName(prod) + "_#_" + prod.idx + "_#_" + getExtraProductionArgument(prod); -} -function getExtraProductionArgument(prod) { - if (prod instanceof Terminal) { - return prod.terminalType.name; - } - else if (prod instanceof NonTerminal) { - return prod.nonTerminalName; - } - else { - return ""; - } -} -var OccurrenceValidationCollector = /** @class */ (function (_super) { - __extends$2(OccurrenceValidationCollector, _super); - function OccurrenceValidationCollector() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.allProductions = []; - return _this; - } - OccurrenceValidationCollector.prototype.visitNonTerminal = function (subrule) { - this.allProductions.push(subrule); - }; - OccurrenceValidationCollector.prototype.visitOption = function (option) { - this.allProductions.push(option); - }; - OccurrenceValidationCollector.prototype.visitRepetitionWithSeparator = function (manySep) { - this.allProductions.push(manySep); - }; - OccurrenceValidationCollector.prototype.visitRepetitionMandatory = function (atLeastOne) { - this.allProductions.push(atLeastOne); - }; - OccurrenceValidationCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) { - this.allProductions.push(atLeastOneSep); - }; - OccurrenceValidationCollector.prototype.visitRepetition = function (many) { - this.allProductions.push(many); - }; - OccurrenceValidationCollector.prototype.visitAlternation = function (or) { - this.allProductions.push(or); - }; - OccurrenceValidationCollector.prototype.visitTerminal = function (terminal) { - this.allProductions.push(terminal); - }; - return OccurrenceValidationCollector; -}(GAstVisitor)); -function validateRuleDoesNotAlreadyExist(rule, allRules, className, errMsgProvider) { - var errors = []; - var occurrences = reduce(allRules, function (result, curRule) { - if (curRule.name === rule.name) { - return result + 1; - } - return result; - }, 0); - if (occurrences > 1) { - var errMsg = errMsgProvider.buildDuplicateRuleNameError({ - topLevelRule: rule, - grammarName: className - }); - errors.push({ - message: errMsg, - type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME, - ruleName: rule.name - }); - } - return errors; -} -// TODO: is there anyway to get only the rule names of rules inherited from the super grammars? -// This is not part of the IGrammarErrorProvider because the validation cannot be performed on -// The grammar structure, only at runtime. -function validateRuleIsOverridden(ruleName, definedRulesNames, className) { - var errors = []; - var errMsg; - if (!contains(definedRulesNames, ruleName)) { - errMsg = - "Invalid rule override, rule: ->" + ruleName + "<- cannot be overridden in the grammar: ->" + className + "<-" + - "as it is not defined in any of the super grammars "; - errors.push({ - message: errMsg, - type: ParserDefinitionErrorType.INVALID_RULE_OVERRIDE, - ruleName: ruleName - }); - } - return errors; -} -function validateNoLeftRecursion(topRule, currRule, errMsgProvider, path) { - if (path === void 0) { path = []; } - var errors = []; - var nextNonTerminals = getFirstNoneTerminal(currRule.definition); - if (isEmpty(nextNonTerminals)) { - return []; - } - else { - var ruleName = topRule.name; - var foundLeftRecursion = contains(nextNonTerminals, topRule); - if (foundLeftRecursion) { - errors.push({ - message: errMsgProvider.buildLeftRecursionError({ - topLevelRule: topRule, - leftRecursionPath: path - }), - type: ParserDefinitionErrorType.LEFT_RECURSION, - ruleName: ruleName - }); - } - // we are only looking for cyclic paths leading back to the specific topRule - // other cyclic paths are ignored, we still need this difference to avoid infinite loops... - var validNextSteps = difference(nextNonTerminals, path.concat([topRule])); - var errorsFromNextSteps = map(validNextSteps, function (currRefRule) { - var newPath = cloneArr(path); - newPath.push(currRefRule); - return validateNoLeftRecursion(topRule, currRefRule, errMsgProvider, newPath); - }); - return errors.concat(flatten(errorsFromNextSteps)); - } -} -function getFirstNoneTerminal(definition) { - var result = []; - if (isEmpty(definition)) { - return result; - } - var firstProd = first$1(definition); - /* istanbul ignore else */ - if (firstProd instanceof NonTerminal) { - result.push(firstProd.referencedRule); - } - else if (firstProd instanceof Alternative || - firstProd instanceof Option || - firstProd instanceof RepetitionMandatory || - firstProd instanceof RepetitionMandatoryWithSeparator || - firstProd instanceof RepetitionWithSeparator || - firstProd instanceof Repetition) { - result = result.concat(getFirstNoneTerminal(firstProd.definition)); - } - else if (firstProd instanceof Alternation) { - // each sub definition in alternation is a FLAT - result = flatten(map(firstProd.definition, function (currSubDef) { - return getFirstNoneTerminal(currSubDef.definition); - })); - } - else if (firstProd instanceof Terminal) ; - else { - throw Error("non exhaustive match"); - } - var isFirstOptional = isOptionalProd(firstProd); - var hasMore = definition.length > 1; - if (isFirstOptional && hasMore) { - var rest = drop(definition); - return result.concat(getFirstNoneTerminal(rest)); - } - else { - return result; - } -} -var OrCollector = /** @class */ (function (_super) { - __extends$2(OrCollector, _super); - function OrCollector() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.alternations = []; - return _this; - } - OrCollector.prototype.visitAlternation = function (node) { - this.alternations.push(node); - }; - return OrCollector; -}(GAstVisitor)); -function validateEmptyOrAlternative(topLevelRule, errMsgProvider) { - var orCollector = new OrCollector(); - topLevelRule.accept(orCollector); - var ors = orCollector.alternations; - var errors = reduce(ors, function (errors, currOr) { - var exceptLast = dropRight(currOr.definition); - var currErrors = map(exceptLast, function (currAlternative, currAltIdx) { - var possibleFirstInAlt = nextPossibleTokensAfter([currAlternative], [], null, 1); - if (isEmpty(possibleFirstInAlt)) { - return { - message: errMsgProvider.buildEmptyAlternationError({ - topLevelRule: topLevelRule, - alternation: currOr, - emptyChoiceIdx: currAltIdx - }), - type: ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT, - ruleName: topLevelRule.name, - occurrence: currOr.idx, - alternative: currAltIdx + 1 - }; - } - else { - return null; - } - }); - return errors.concat(compact(currErrors)); - }, []); - return errors; -} -function validateAmbiguousAlternationAlternatives(topLevelRule, globalMaxLookahead, errMsgProvider) { - var orCollector = new OrCollector(); - topLevelRule.accept(orCollector); - var ors = orCollector.alternations; - // New Handling of ignoring ambiguities - // - https://github.com/SAP/chevrotain/issues/869 - ors = reject(ors, function (currOr) { return currOr.ignoreAmbiguities === true; }); - var errors = reduce(ors, function (result, currOr) { - var currOccurrence = currOr.idx; - var actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead; - var alternatives = getLookaheadPathsForOr(currOccurrence, topLevelRule, actualMaxLookahead, currOr); - var altsAmbiguityErrors = checkAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider); - var altsPrefixAmbiguityErrors = checkPrefixAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider); - return result.concat(altsAmbiguityErrors, altsPrefixAmbiguityErrors); - }, []); - return errors; -} -var RepetionCollector = /** @class */ (function (_super) { - __extends$2(RepetionCollector, _super); - function RepetionCollector() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.allProductions = []; - return _this; - } - RepetionCollector.prototype.visitRepetitionWithSeparator = function (manySep) { - this.allProductions.push(manySep); - }; - RepetionCollector.prototype.visitRepetitionMandatory = function (atLeastOne) { - this.allProductions.push(atLeastOne); - }; - RepetionCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) { - this.allProductions.push(atLeastOneSep); - }; - RepetionCollector.prototype.visitRepetition = function (many) { - this.allProductions.push(many); - }; - return RepetionCollector; -}(GAstVisitor)); -function validateTooManyAlts(topLevelRule, errMsgProvider) { - var orCollector = new OrCollector(); - topLevelRule.accept(orCollector); - var ors = orCollector.alternations; - var errors = reduce(ors, function (errors, currOr) { - if (currOr.definition.length > 255) { - errors.push({ - message: errMsgProvider.buildTooManyAlternativesError({ - topLevelRule: topLevelRule, - alternation: currOr - }), - type: ParserDefinitionErrorType.TOO_MANY_ALTS, - ruleName: topLevelRule.name, - occurrence: currOr.idx - }); - } - return errors; - }, []); - return errors; -} -function validateSomeNonEmptyLookaheadPath(topLevelRules, maxLookahead, errMsgProvider) { - var errors = []; - forEach(topLevelRules, function (currTopRule) { - var collectorVisitor = new RepetionCollector(); - currTopRule.accept(collectorVisitor); - var allRuleProductions = collectorVisitor.allProductions; - forEach(allRuleProductions, function (currProd) { - var prodType = getProdType(currProd); - var actualMaxLookahead = currProd.maxLookahead || maxLookahead; - var currOccurrence = currProd.idx; - var paths = getLookaheadPathsForOptionalProd(currOccurrence, currTopRule, prodType, actualMaxLookahead); - var pathsInsideProduction = paths[0]; - if (isEmpty(flatten(pathsInsideProduction))) { - var errMsg = errMsgProvider.buildEmptyRepetitionError({ - topLevelRule: currTopRule, - repetition: currProd - }); - errors.push({ - message: errMsg, - type: ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD, - ruleName: currTopRule.name - }); - } - }); - }); - return errors; -} -function checkAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) { - var foundAmbiguousPaths = []; - var identicalAmbiguities = reduce(alternatives, function (result, currAlt, currAltIdx) { - // ignore (skip) ambiguities with this alternative - if (alternation.definition[currAltIdx].ignoreAmbiguities === true) { - return result; - } - forEach(currAlt, function (currPath) { - var altsCurrPathAppearsIn = [currAltIdx]; - forEach(alternatives, function (currOtherAlt, currOtherAltIdx) { - if (currAltIdx !== currOtherAltIdx && - containsPath(currOtherAlt, currPath) && - // ignore (skip) ambiguities with this "other" alternative - alternation.definition[currOtherAltIdx].ignoreAmbiguities !== true) { - altsCurrPathAppearsIn.push(currOtherAltIdx); - } - }); - if (altsCurrPathAppearsIn.length > 1 && - !containsPath(foundAmbiguousPaths, currPath)) { - foundAmbiguousPaths.push(currPath); - result.push({ - alts: altsCurrPathAppearsIn, - path: currPath - }); - } - }); - return result; - }, []); - var currErrors = map(identicalAmbiguities, function (currAmbDescriptor) { - var ambgIndices = map(currAmbDescriptor.alts, function (currAltIdx) { return currAltIdx + 1; }); - var currMessage = errMsgProvider.buildAlternationAmbiguityError({ - topLevelRule: rule, - alternation: alternation, - ambiguityIndices: ambgIndices, - prefixPath: currAmbDescriptor.path - }); - return { - message: currMessage, - type: ParserDefinitionErrorType.AMBIGUOUS_ALTS, - ruleName: rule.name, - occurrence: alternation.idx, - alternatives: [currAmbDescriptor.alts] - }; - }); - return currErrors; -} -function checkPrefixAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) { - var errors = []; - // flatten - var pathsAndIndices = reduce(alternatives, function (result, currAlt, idx) { - var currPathsAndIdx = map(currAlt, function (currPath) { - return { idx: idx, path: currPath }; - }); - return result.concat(currPathsAndIdx); - }, []); - forEach(pathsAndIndices, function (currPathAndIdx) { - var alternativeGast = alternation.definition[currPathAndIdx.idx]; - // ignore (skip) ambiguities with this alternative - if (alternativeGast.ignoreAmbiguities === true) { - return; - } - var targetIdx = currPathAndIdx.idx; - var targetPath = currPathAndIdx.path; - var prefixAmbiguitiesPathsAndIndices = findAll(pathsAndIndices, function (searchPathAndIdx) { - // prefix ambiguity can only be created from lower idx (higher priority) path - return ( - // ignore (skip) ambiguities with this "other" alternative - alternation.definition[searchPathAndIdx.idx].ignoreAmbiguities !== - true && - searchPathAndIdx.idx < targetIdx && - // checking for strict prefix because identical lookaheads - // will be be detected using a different validation. - isStrictPrefixOfPath(searchPathAndIdx.path, targetPath)); - }); - var currPathPrefixErrors = map(prefixAmbiguitiesPathsAndIndices, function (currAmbPathAndIdx) { - var ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1]; - var occurrence = alternation.idx === 0 ? "" : alternation.idx; - var message = errMsgProvider.buildAlternationPrefixAmbiguityError({ - topLevelRule: rule, - alternation: alternation, - ambiguityIndices: ambgIndices, - prefixPath: currAmbPathAndIdx.path - }); - return { - message: message, - type: ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS, - ruleName: rule.name, - occurrence: occurrence, - alternatives: ambgIndices - }; - }); - errors = errors.concat(currPathPrefixErrors); - }); - return errors; -} -function checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider) { - var errors = []; - var tokenNames = map(tokenTypes, function (currToken) { return currToken.name; }); - forEach(topLevels, function (currRule) { - var currRuleName = currRule.name; - if (contains(tokenNames, currRuleName)) { - var errMsg = errMsgProvider.buildNamespaceConflictError(currRule); - errors.push({ - message: errMsg, - type: ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE, - ruleName: currRuleName - }); - } - }); - return errors; -} - -function resolveGrammar(options) { - options = defaults(options, { - errMsgProvider: defaultGrammarResolverErrorProvider - }); - var topRulesTable = {}; - forEach(options.rules, function (rule) { - topRulesTable[rule.name] = rule; - }); - return resolveGrammar$1(topRulesTable, options.errMsgProvider); -} -function validateGrammar(options) { - options = defaults(options, { - errMsgProvider: defaultGrammarValidatorErrorProvider - }); - return validateGrammar$1(options.rules, options.maxLookahead, options.tokenTypes, options.errMsgProvider, options.grammarName); -} -function assignOccurrenceIndices(options) { - forEach(options.rules, function (currRule) { - var methodsCollector = new DslMethodsCollectorVisitor(); - currRule.accept(methodsCollector); - forEach(methodsCollector.dslMethods, function (methods) { - forEach(methods, function (currMethod, arrIdx) { - currMethod.idx = arrIdx + 1; - }); - }); - }); -} - -var __extends$1 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var MISMATCHED_TOKEN_EXCEPTION = "MismatchedTokenException"; -var NO_VIABLE_ALT_EXCEPTION = "NoViableAltException"; -var EARLY_EXIT_EXCEPTION = "EarlyExitException"; -var NOT_ALL_INPUT_PARSED_EXCEPTION = "NotAllInputParsedException"; -var RECOGNITION_EXCEPTION_NAMES = [ - MISMATCHED_TOKEN_EXCEPTION, - NO_VIABLE_ALT_EXCEPTION, - EARLY_EXIT_EXCEPTION, - NOT_ALL_INPUT_PARSED_EXCEPTION -]; -Object.freeze(RECOGNITION_EXCEPTION_NAMES); -// hacks to bypass no support for custom Errors in javascript/typescript -function isRecognitionException(error) { - // can't do instanceof on hacked custom js exceptions - return contains(RECOGNITION_EXCEPTION_NAMES, error.name); -} -var RecognitionException = /** @class */ (function (_super) { - __extends$1(RecognitionException, _super); - function RecognitionException(message, token) { - var _newTarget = this.constructor; - var _this = _super.call(this, message) || this; - _this.token = token; - _this.resyncedTokens = []; - // fix prototype chain when typescript target is ES5 - Object.setPrototypeOf(_this, _newTarget.prototype); - /* istanbul ignore next - V8 workaround to remove constructor from stacktrace when typescript target is ES5 */ - if (Error.captureStackTrace) { - Error.captureStackTrace(_this, _this.constructor); - } - return _this; - } - return RecognitionException; -}(Error)); -var MismatchedTokenException = /** @class */ (function (_super) { - __extends$1(MismatchedTokenException, _super); - function MismatchedTokenException(message, token, previousToken) { - var _this = _super.call(this, message, token) || this; - _this.previousToken = previousToken; - _this.name = MISMATCHED_TOKEN_EXCEPTION; - return _this; - } - return MismatchedTokenException; -}(RecognitionException)); -var NoViableAltException = /** @class */ (function (_super) { - __extends$1(NoViableAltException, _super); - function NoViableAltException(message, token, previousToken) { - var _this = _super.call(this, message, token) || this; - _this.previousToken = previousToken; - _this.name = NO_VIABLE_ALT_EXCEPTION; - return _this; - } - return NoViableAltException; -}(RecognitionException)); -var NotAllInputParsedException = /** @class */ (function (_super) { - __extends$1(NotAllInputParsedException, _super); - function NotAllInputParsedException(message, token) { - var _this = _super.call(this, message, token) || this; - _this.name = NOT_ALL_INPUT_PARSED_EXCEPTION; - return _this; - } - return NotAllInputParsedException; -}(RecognitionException)); -var EarlyExitException = /** @class */ (function (_super) { - __extends$1(EarlyExitException, _super); - function EarlyExitException(message, token, previousToken) { - var _this = _super.call(this, message, token) || this; - _this.previousToken = previousToken; - _this.name = EARLY_EXIT_EXCEPTION; - return _this; - } - return EarlyExitException; -}(RecognitionException)); - -var EOF_FOLLOW_KEY = {}; -var IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException"; -function InRuleRecoveryException(message) { - this.name = IN_RULE_RECOVERY_EXCEPTION; - this.message = message; -} -InRuleRecoveryException.prototype = Error.prototype; -/** - * This trait is responsible for the error recovery and fault tolerant logic - */ -var Recoverable = /** @class */ (function () { - function Recoverable() { - } - Recoverable.prototype.initRecoverable = function (config) { - this.firstAfterRepMap = {}; - this.resyncFollows = {}; - this.recoveryEnabled = has(config, "recoveryEnabled") - ? config.recoveryEnabled - : DEFAULT_PARSER_CONFIG.recoveryEnabled; - // performance optimization, NOOP will be inlined which - // effectively means that this optional feature does not exist - // when not used. - if (this.recoveryEnabled) { - this.attemptInRepetitionRecovery = attemptInRepetitionRecovery; - } - }; - Recoverable.prototype.getTokenToInsert = function (tokType) { - var tokToInsert = createTokenInstance(tokType, "", NaN, NaN, NaN, NaN, NaN, NaN); - tokToInsert.isInsertedInRecovery = true; - return tokToInsert; - }; - Recoverable.prototype.canTokenTypeBeInsertedInRecovery = function (tokType) { - return true; - }; - Recoverable.prototype.tryInRepetitionRecovery = function (grammarRule, grammarRuleArgs, lookAheadFunc, expectedTokType) { - var _this = this; - // TODO: can the resyncTokenType be cached? - var reSyncTokType = this.findReSyncTokenType(); - var savedLexerState = this.exportLexerState(); - var resyncedTokens = []; - var passedResyncPoint = false; - var nextTokenWithoutResync = this.LA(1); - var currToken = this.LA(1); - var generateErrorMessage = function () { - var previousToken = _this.LA(0); - // we are preemptively re-syncing before an error has been detected, therefor we must reproduce - // the error that would have been thrown - var msg = _this.errorMessageProvider.buildMismatchTokenMessage({ - expected: expectedTokType, - actual: nextTokenWithoutResync, - previous: previousToken, - ruleName: _this.getCurrRuleFullName() - }); - var error = new MismatchedTokenException(msg, nextTokenWithoutResync, _this.LA(0)); - // the first token here will be the original cause of the error, this is not part of the resyncedTokens property. - error.resyncedTokens = dropRight(resyncedTokens); - _this.SAVE_ERROR(error); - }; - while (!passedResyncPoint) { - // re-synced to a point where we can safely exit the repetition/ - if (this.tokenMatcher(currToken, expectedTokType)) { - generateErrorMessage(); - return; // must return here to avoid reverting the inputIdx - } - else if (lookAheadFunc.call(this)) { - // we skipped enough tokens so we can resync right back into another iteration of the repetition grammar rule - generateErrorMessage(); - // recursive invocation in other to support multiple re-syncs in the same top level repetition grammar rule - grammarRule.apply(this, grammarRuleArgs); - return; // must return here to avoid reverting the inputIdx - } - else if (this.tokenMatcher(currToken, reSyncTokType)) { - passedResyncPoint = true; - } - else { - currToken = this.SKIP_TOKEN(); - this.addToResyncTokens(currToken, resyncedTokens); - } - } - // we were unable to find a CLOSER point to resync inside the Repetition, reset the state. - // The parsing exception we were trying to prevent will happen in the NEXT parsing step. it may be handled by - // "between rules" resync recovery later in the flow. - this.importLexerState(savedLexerState); - }; - Recoverable.prototype.shouldInRepetitionRecoveryBeTried = function (expectTokAfterLastMatch, nextTokIdx, notStuck) { - // Edge case of arriving from a MANY repetition which is stuck - // Attempting recovery in this case could cause an infinite loop - if (notStuck === false) { - return false; - } - // arguments to try and perform resync into the next iteration of the many are missing - if (expectTokAfterLastMatch === undefined || nextTokIdx === undefined) { - return false; - } - // no need to recover, next token is what we expect... - if (this.tokenMatcher(this.LA(1), expectTokAfterLastMatch)) { - return false; - } - // error recovery is disabled during backtracking as it can make the parser ignore a valid grammar path - // and prefer some backtracking path that includes recovered errors. - if (this.isBackTracking()) { - return false; - } - // if we can perform inRule recovery (single token insertion or deletion) we always prefer that recovery algorithm - // because if it works, it makes the least amount of changes to the input stream (greedy algorithm) - //noinspection RedundantIfStatementJS - if (this.canPerformInRuleRecovery(expectTokAfterLastMatch, this.getFollowsForInRuleRecovery(expectTokAfterLastMatch, nextTokIdx))) { - return false; - } - return true; - }; - // Error Recovery functionality - Recoverable.prototype.getFollowsForInRuleRecovery = function (tokType, tokIdxInRule) { - var grammarPath = this.getCurrentGrammarPath(tokType, tokIdxInRule); - var follows = this.getNextPossibleTokenTypes(grammarPath); - return follows; - }; - Recoverable.prototype.tryInRuleRecovery = function (expectedTokType, follows) { - if (this.canRecoverWithSingleTokenInsertion(expectedTokType, follows)) { - var tokToInsert = this.getTokenToInsert(expectedTokType); - return tokToInsert; - } - if (this.canRecoverWithSingleTokenDeletion(expectedTokType)) { - var nextTok = this.SKIP_TOKEN(); - this.consumeToken(); - return nextTok; - } - throw new InRuleRecoveryException("sad sad panda"); - }; - Recoverable.prototype.canPerformInRuleRecovery = function (expectedToken, follows) { - return (this.canRecoverWithSingleTokenInsertion(expectedToken, follows) || - this.canRecoverWithSingleTokenDeletion(expectedToken)); - }; - Recoverable.prototype.canRecoverWithSingleTokenInsertion = function (expectedTokType, follows) { - var _this = this; - if (!this.canTokenTypeBeInsertedInRecovery(expectedTokType)) { - return false; - } - // must know the possible following tokens to perform single token insertion - if (isEmpty(follows)) { - return false; - } - var mismatchedTok = this.LA(1); - var isMisMatchedTokInFollows = find(follows, function (possibleFollowsTokType) { - return _this.tokenMatcher(mismatchedTok, possibleFollowsTokType); - }) !== undefined; - return isMisMatchedTokInFollows; - }; - Recoverable.prototype.canRecoverWithSingleTokenDeletion = function (expectedTokType) { - var isNextTokenWhatIsExpected = this.tokenMatcher(this.LA(2), expectedTokType); - return isNextTokenWhatIsExpected; - }; - Recoverable.prototype.isInCurrentRuleReSyncSet = function (tokenTypeIdx) { - var followKey = this.getCurrFollowKey(); - var currentRuleReSyncSet = this.getFollowSetFromFollowKey(followKey); - return contains(currentRuleReSyncSet, tokenTypeIdx); - }; - Recoverable.prototype.findReSyncTokenType = function () { - var allPossibleReSyncTokTypes = this.flattenFollowSet(); - // this loop will always terminate as EOF is always in the follow stack and also always (virtually) in the input - var nextToken = this.LA(1); - var k = 2; - while (true) { - var nextTokenType = nextToken.tokenType; - if (contains(allPossibleReSyncTokTypes, nextTokenType)) { - return nextTokenType; - } - nextToken = this.LA(k); - k++; - } - }; - Recoverable.prototype.getCurrFollowKey = function () { - // the length is at least one as we always add the ruleName to the stack before invoking the rule. - if (this.RULE_STACK.length === 1) { - return EOF_FOLLOW_KEY; - } - var currRuleShortName = this.getLastExplicitRuleShortName(); - var currRuleIdx = this.getLastExplicitRuleOccurrenceIndex(); - var prevRuleShortName = this.getPreviousExplicitRuleShortName(); - return { - ruleName: this.shortRuleNameToFullName(currRuleShortName), - idxInCallingRule: currRuleIdx, - inRule: this.shortRuleNameToFullName(prevRuleShortName) - }; - }; - Recoverable.prototype.buildFullFollowKeyStack = function () { - var _this = this; - var explicitRuleStack = this.RULE_STACK; - var explicitOccurrenceStack = this.RULE_OCCURRENCE_STACK; - return map(explicitRuleStack, function (ruleName, idx) { - if (idx === 0) { - return EOF_FOLLOW_KEY; - } - return { - ruleName: _this.shortRuleNameToFullName(ruleName), - idxInCallingRule: explicitOccurrenceStack[idx], - inRule: _this.shortRuleNameToFullName(explicitRuleStack[idx - 1]) - }; - }); - }; - Recoverable.prototype.flattenFollowSet = function () { - var _this = this; - var followStack = map(this.buildFullFollowKeyStack(), function (currKey) { - return _this.getFollowSetFromFollowKey(currKey); - }); - return flatten(followStack); - }; - Recoverable.prototype.getFollowSetFromFollowKey = function (followKey) { - if (followKey === EOF_FOLLOW_KEY) { - return [EOF]; - } - var followName = followKey.ruleName + followKey.idxInCallingRule + IN + followKey.inRule; - return this.resyncFollows[followName]; - }; - // It does not make any sense to include a virtual EOF token in the list of resynced tokens - // as EOF does not really exist and thus does not contain any useful information (line/column numbers) - Recoverable.prototype.addToResyncTokens = function (token, resyncTokens) { - if (!this.tokenMatcher(token, EOF)) { - resyncTokens.push(token); - } - return resyncTokens; - }; - Recoverable.prototype.reSyncTo = function (tokType) { - var resyncedTokens = []; - var nextTok = this.LA(1); - while (this.tokenMatcher(nextTok, tokType) === false) { - nextTok = this.SKIP_TOKEN(); - this.addToResyncTokens(nextTok, resyncedTokens); - } - // the last token is not part of the error. - return dropRight(resyncedTokens); - }; - Recoverable.prototype.attemptInRepetitionRecovery = function (prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) { - // by default this is a NO-OP - // The actual implementation is with the function(not method) below - }; - Recoverable.prototype.getCurrentGrammarPath = function (tokType, tokIdxInRule) { - var pathRuleStack = this.getHumanReadableRuleStack(); - var pathOccurrenceStack = cloneArr(this.RULE_OCCURRENCE_STACK); - var grammarPath = { - ruleStack: pathRuleStack, - occurrenceStack: pathOccurrenceStack, - lastTok: tokType, - lastTokOccurrence: tokIdxInRule - }; - return grammarPath; - }; - Recoverable.prototype.getHumanReadableRuleStack = function () { - var _this = this; - return map(this.RULE_STACK, function (currShortName) { - return _this.shortRuleNameToFullName(currShortName); - }); - }; - return Recoverable; -}()); -function attemptInRepetitionRecovery(prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) { - var key = this.getKeyForAutomaticLookahead(dslMethodIdx, prodOccurrence); - var firstAfterRepInfo = this.firstAfterRepMap[key]; - if (firstAfterRepInfo === undefined) { - var currRuleName = this.getCurrRuleFullName(); - var ruleGrammar = this.getGAstProductions()[currRuleName]; - var walker = new nextToksWalker(ruleGrammar, prodOccurrence); - firstAfterRepInfo = walker.startWalking(); - this.firstAfterRepMap[key] = firstAfterRepInfo; - } - var expectTokAfterLastMatch = firstAfterRepInfo.token; - var nextTokIdx = firstAfterRepInfo.occurrence; - var isEndOfRule = firstAfterRepInfo.isEndOfRule; - // special edge case of a TOP most repetition after which the input should END. - // this will force an attempt for inRule recovery in that scenario. - if (this.RULE_STACK.length === 1 && - isEndOfRule && - expectTokAfterLastMatch === undefined) { - expectTokAfterLastMatch = EOF; - nextTokIdx = 1; - } - if (this.shouldInRepetitionRecoveryBeTried(expectTokAfterLastMatch, nextTokIdx, notStuck)) { - // TODO: performance optimization: instead of passing the original args here, we modify - // the args param (or create a new one) and make sure the lookahead func is explicitly provided - // to avoid searching the cache for it once more. - this.tryInRepetitionRecovery(prodFunc, args, lookaheadFunc, expectTokAfterLastMatch); - } -} - -// Lookahead keys are 32Bit integers in the form -// TTTTTTTT-ZZZZZZZZZZZZ-YYYY-XXXXXXXX -// XXXX -> Occurrence Index bitmap. -// YYYY -> DSL Method Type bitmap. -// ZZZZZZZZZZZZZZZ -> Rule short Index bitmap. -// TTTTTTTTT -> alternation alternative index bitmap -var BITS_FOR_METHOD_TYPE = 4; -var BITS_FOR_OCCURRENCE_IDX = 8; -// short string used as part of mapping keys. -// being short improves the performance when composing KEYS for maps out of these -// The 5 - 8 bits (16 possible values, are reserved for the DSL method indices) -/* tslint:disable */ -var OR_IDX = 1 << BITS_FOR_OCCURRENCE_IDX; -var OPTION_IDX = 2 << BITS_FOR_OCCURRENCE_IDX; -var MANY_IDX = 3 << BITS_FOR_OCCURRENCE_IDX; -var AT_LEAST_ONE_IDX = 4 << BITS_FOR_OCCURRENCE_IDX; -var MANY_SEP_IDX = 5 << BITS_FOR_OCCURRENCE_IDX; -var AT_LEAST_ONE_SEP_IDX = 6 << BITS_FOR_OCCURRENCE_IDX; -/* tslint:enable */ -// this actually returns a number, but it is always used as a string (object prop key) -function getKeyForAutomaticLookahead(ruleIdx, dslMethodIdx, occurrence) { - /* tslint:disable */ - return occurrence | dslMethodIdx | ruleIdx; - /* tslint:enable */ -} - -/** - * Trait responsible for the lookahead related utilities and optimizations. - */ -var LooksAhead = /** @class */ (function () { - function LooksAhead() { - } - LooksAhead.prototype.initLooksAhead = function (config) { - this.dynamicTokensEnabled = has(config, "dynamicTokensEnabled") - ? config.dynamicTokensEnabled - : DEFAULT_PARSER_CONFIG.dynamicTokensEnabled; - this.maxLookahead = has(config, "maxLookahead") - ? config.maxLookahead - : DEFAULT_PARSER_CONFIG.maxLookahead; - /* istanbul ignore next - Using plain array as dictionary will be tested on older node.js versions and IE11 */ - this.lookAheadFuncsCache = isES2015MapSupported() ? new Map() : []; - // Performance optimization on newer engines that support ES6 Map - // For larger Maps this is slightly faster than using a plain object (array in our case). - /* istanbul ignore else - The else branch will be tested on older node.js versions and IE11 */ - if (isES2015MapSupported()) { - this.getLaFuncFromCache = this.getLaFuncFromMap; - this.setLaFuncCache = this.setLaFuncCacheUsingMap; - } - else { - this.getLaFuncFromCache = this.getLaFuncFromObj; - this.setLaFuncCache = this.setLaFuncUsingObj; - } - }; - LooksAhead.prototype.preComputeLookaheadFunctions = function (rules) { - var _this = this; - forEach(rules, function (currRule) { - _this.TRACE_INIT(currRule.name + " Rule Lookahead", function () { - var _a = collectMethods(currRule), alternation = _a.alternation, repetition = _a.repetition, option = _a.option, repetitionMandatory = _a.repetitionMandatory, repetitionMandatoryWithSeparator = _a.repetitionMandatoryWithSeparator, repetitionWithSeparator = _a.repetitionWithSeparator; - forEach(alternation, function (currProd) { - var prodIdx = currProd.idx === 0 ? "" : currProd.idx; - _this.TRACE_INIT("" + getProductionDslName(currProd) + prodIdx, function () { - var laFunc = buildLookaheadFuncForOr(currProd.idx, currRule, currProd.maxLookahead || _this.maxLookahead, currProd.hasPredicates, _this.dynamicTokensEnabled, _this.lookAheadBuilderForAlternatives); - var key = getKeyForAutomaticLookahead(_this.fullRuleNameToShort[currRule.name], OR_IDX, currProd.idx); - _this.setLaFuncCache(key, laFunc); - }); - }); - forEach(repetition, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, MANY_IDX, PROD_TYPE.REPETITION, currProd.maxLookahead, getProductionDslName(currProd)); - }); - forEach(option, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, OPTION_IDX, PROD_TYPE.OPTION, currProd.maxLookahead, getProductionDslName(currProd)); - }); - forEach(repetitionMandatory, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, AT_LEAST_ONE_IDX, PROD_TYPE.REPETITION_MANDATORY, currProd.maxLookahead, getProductionDslName(currProd)); - }); - forEach(repetitionMandatoryWithSeparator, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, AT_LEAST_ONE_SEP_IDX, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currProd.maxLookahead, getProductionDslName(currProd)); - }); - forEach(repetitionWithSeparator, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, MANY_SEP_IDX, PROD_TYPE.REPETITION_WITH_SEPARATOR, currProd.maxLookahead, getProductionDslName(currProd)); - }); - }); - }); - }; - LooksAhead.prototype.computeLookaheadFunc = function (rule, prodOccurrence, prodKey, prodType, prodMaxLookahead, dslMethodName) { - var _this = this; - this.TRACE_INIT("" + dslMethodName + (prodOccurrence === 0 ? "" : prodOccurrence), function () { - var laFunc = buildLookaheadFuncForOptionalProd(prodOccurrence, rule, prodMaxLookahead || _this.maxLookahead, _this.dynamicTokensEnabled, prodType, _this.lookAheadBuilderForOptional); - var key = getKeyForAutomaticLookahead(_this.fullRuleNameToShort[rule.name], prodKey, prodOccurrence); - _this.setLaFuncCache(key, laFunc); - }); - }; - LooksAhead.prototype.lookAheadBuilderForOptional = function (alt, tokenMatcher, dynamicTokensEnabled) { - return buildSingleAlternativeLookaheadFunction(alt, tokenMatcher, dynamicTokensEnabled); - }; - LooksAhead.prototype.lookAheadBuilderForAlternatives = function (alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) { - return buildAlternativesLookAheadFunc(alts, hasPredicates, tokenMatcher, dynamicTokensEnabled); - }; - // this actually returns a number, but it is always used as a string (object prop key) - LooksAhead.prototype.getKeyForAutomaticLookahead = function (dslMethodIdx, occurrence) { - var currRuleShortName = this.getLastExplicitRuleShortName(); - return getKeyForAutomaticLookahead(currRuleShortName, dslMethodIdx, occurrence); - }; - /* istanbul ignore next */ - LooksAhead.prototype.getLaFuncFromCache = function (key) { - return undefined; - }; - LooksAhead.prototype.getLaFuncFromMap = function (key) { - return this.lookAheadFuncsCache.get(key); - }; - /* istanbul ignore next - Using plain array as dictionary will be tested on older node.js versions and IE11 */ - LooksAhead.prototype.getLaFuncFromObj = function (key) { - return this.lookAheadFuncsCache[key]; - }; - /* istanbul ignore next */ - LooksAhead.prototype.setLaFuncCache = function (key, value) { }; - LooksAhead.prototype.setLaFuncCacheUsingMap = function (key, value) { - this.lookAheadFuncsCache.set(key, value); - }; - /* istanbul ignore next - Using plain array as dictionary will be tested on older node.js versions and IE11 */ - LooksAhead.prototype.setLaFuncUsingObj = function (key, value) { - this.lookAheadFuncsCache[key] = value; - }; - return LooksAhead; -}()); - -/** - * This nodeLocation tracking is not efficient and should only be used - * when error recovery is enabled or the Token Vector contains virtual Tokens - * (e.g, Python Indent/Outdent) - * As it executes the calculation for every single terminal/nonTerminal - * and does not rely on the fact the token vector is **sorted** - */ -function setNodeLocationOnlyOffset(currNodeLocation, newLocationInfo) { - // First (valid) update for this cst node - if (isNaN(currNodeLocation.startOffset) === true) { - // assumption1: Token location information is either NaN or a valid number - // assumption2: Token location information is fully valid if it exist - // (both start/end offsets exist and are numbers). - currNodeLocation.startOffset = newLocationInfo.startOffset; - currNodeLocation.endOffset = newLocationInfo.endOffset; - } - // Once the startOffset has been updated with a valid number it should never receive - // any farther updates as the Token vector is sorted. - // We still have to check this this condition for every new possible location info - // because with error recovery enabled we may encounter invalid tokens (NaN location props) - else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) { - currNodeLocation.endOffset = newLocationInfo.endOffset; - } -} -/** - * This nodeLocation tracking is not efficient and should only be used - * when error recovery is enabled or the Token Vector contains virtual Tokens - * (e.g, Python Indent/Outdent) - * As it executes the calculation for every single terminal/nonTerminal - * and does not rely on the fact the token vector is **sorted** - */ -function setNodeLocationFull(currNodeLocation, newLocationInfo) { - // First (valid) update for this cst node - if (isNaN(currNodeLocation.startOffset) === true) { - // assumption1: Token location information is either NaN or a valid number - // assumption2: Token location information is fully valid if it exist - // (all start/end props exist and are numbers). - currNodeLocation.startOffset = newLocationInfo.startOffset; - currNodeLocation.startColumn = newLocationInfo.startColumn; - currNodeLocation.startLine = newLocationInfo.startLine; - currNodeLocation.endOffset = newLocationInfo.endOffset; - currNodeLocation.endColumn = newLocationInfo.endColumn; - currNodeLocation.endLine = newLocationInfo.endLine; - } - // Once the start props has been updated with a valid number it should never receive - // any farther updates as the Token vector is sorted. - // We still have to check this this condition for every new possible location info - // because with error recovery enabled we may encounter invalid tokens (NaN location props) - else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) { - currNodeLocation.endOffset = newLocationInfo.endOffset; - currNodeLocation.endColumn = newLocationInfo.endColumn; - currNodeLocation.endLine = newLocationInfo.endLine; - } -} -function addTerminalToCst(node, token, tokenTypeName) { - if (node.children[tokenTypeName] === undefined) { - node.children[tokenTypeName] = [token]; - } - else { - node.children[tokenTypeName].push(token); - } -} -function addNoneTerminalToCst(node, ruleName, ruleResult) { - if (node.children[ruleName] === undefined) { - node.children[ruleName] = [ruleResult]; - } - else { - node.children[ruleName].push(ruleResult); - } -} - -function classNameFromInstance(instance) { - return functionName(instance.constructor); -} -var NAME = "name"; -/** - * Utility to obtain Function names. - * Note that there should not be an assumptions on the result of this function. - * E.g: When running from minified source code the result may be auto generated. - */ -function functionName(func) { - // Engines that support Function.prototype.name OR the nth (n>1) time after - // the name has been computed in the following else block. - var existingNameProp = func.name; - /* istanbul ignore else - too many hacks for IE/old versions of node.js here*/ - if (existingNameProp) { - return existingNameProp; - } - else { - return "anonymous"; - } -} -/** - * @returns {boolean} - has the property been successfully defined - */ -function defineNameProp(obj, nameValue) { - var namePropDescriptor = Object.getOwnPropertyDescriptor(obj, NAME); - /* istanbul ignore else -> will only run in old versions of node.js */ - if (isUndefined(namePropDescriptor) || namePropDescriptor.configurable) { - Object.defineProperty(obj, NAME, { - enumerable: false, - configurable: true, - writable: false, - value: nameValue - }); - return true; - } - /* istanbul ignore next -> will only run in old versions of node.js */ - return false; -} - -function defaultVisit(ctx, param) { - var childrenNames = keys(ctx); - var childrenNamesLength = childrenNames.length; - for (var i = 0; i < childrenNamesLength; i++) { - var currChildName = childrenNames[i]; - var currChildArray = ctx[currChildName]; - var currChildArrayLength = currChildArray.length; - for (var j = 0; j < currChildArrayLength; j++) { - var currChild = currChildArray[j]; - // distinction between Tokens Children and CstNode children - if (currChild.tokenTypeIdx === undefined) { - this[currChild.name](currChild.children, param); - } - } - } - // defaultVisit does not support generic out param - return undefined; -} -function createBaseSemanticVisitorConstructor(grammarName, ruleNames) { - var derivedConstructor = function () { }; - // can be overwritten according to: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/ - // name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname - defineNameProp(derivedConstructor, grammarName + "BaseSemantics"); - var semanticProto = { - visit: function (cstNode, param) { - // enables writing more concise visitor methods when CstNode has only a single child - if (isArray(cstNode)) { - // A CST Node's children dictionary can never have empty arrays as values - // If a key is defined there will be at least one element in the corresponding value array. - cstNode = cstNode[0]; - } - // enables passing optional CstNodes concisely. - if (isUndefined(cstNode)) { - return undefined; - } - return this[cstNode.name](cstNode.children, param); - }, - validateVisitor: function () { - var semanticDefinitionErrors = validateVisitor(this, ruleNames); - if (!isEmpty(semanticDefinitionErrors)) { - var errorMessages = map(semanticDefinitionErrors, function (currDefError) { return currDefError.msg; }); - throw Error("Errors Detected in CST Visitor <" + functionName(this.constructor) + ">:\n\t" + ("" + errorMessages.join("\n\n").replace(/\n/g, "\n\t"))); - } - } - }; - derivedConstructor.prototype = semanticProto; - derivedConstructor.prototype.constructor = derivedConstructor; - derivedConstructor._RULE_NAMES = ruleNames; - return derivedConstructor; -} -function createBaseVisitorConstructorWithDefaults(grammarName, ruleNames, baseConstructor) { - var derivedConstructor = function () { }; - // can be overwritten according to: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/ - // name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname - defineNameProp(derivedConstructor, grammarName + "BaseSemanticsWithDefaults"); - var withDefaultsProto = Object.create(baseConstructor.prototype); - forEach(ruleNames, function (ruleName) { - withDefaultsProto[ruleName] = defaultVisit; - }); - derivedConstructor.prototype = withDefaultsProto; - derivedConstructor.prototype.constructor = derivedConstructor; - return derivedConstructor; -} -var CstVisitorDefinitionError; -(function (CstVisitorDefinitionError) { - CstVisitorDefinitionError[CstVisitorDefinitionError["REDUNDANT_METHOD"] = 0] = "REDUNDANT_METHOD"; - CstVisitorDefinitionError[CstVisitorDefinitionError["MISSING_METHOD"] = 1] = "MISSING_METHOD"; -})(CstVisitorDefinitionError || (CstVisitorDefinitionError = {})); -function validateVisitor(visitorInstance, ruleNames) { - var missingErrors = validateMissingCstMethods(visitorInstance, ruleNames); - var redundantErrors = validateRedundantMethods(visitorInstance, ruleNames); - return missingErrors.concat(redundantErrors); -} -function validateMissingCstMethods(visitorInstance, ruleNames) { - var errors = map(ruleNames, function (currRuleName) { - if (!isFunction(visitorInstance[currRuleName])) { - return { - msg: "Missing visitor method: <" + currRuleName + "> on " + functionName(visitorInstance.constructor) + " CST Visitor.", - type: CstVisitorDefinitionError.MISSING_METHOD, - methodName: currRuleName - }; - } - }); - return compact(errors); -} -var VALID_PROP_NAMES = ["constructor", "visit", "validateVisitor"]; -function validateRedundantMethods(visitorInstance, ruleNames) { - var errors = []; - for (var prop in visitorInstance) { - if (isFunction(visitorInstance[prop]) && - !contains(VALID_PROP_NAMES, prop) && - !contains(ruleNames, prop)) { - errors.push({ - msg: "Redundant visitor method: <" + prop + "> on " + functionName(visitorInstance.constructor) + " CST Visitor\n" + - "There is no Grammar Rule corresponding to this method's name.\n", - type: CstVisitorDefinitionError.REDUNDANT_METHOD, - methodName: prop - }); - } - } - return errors; -} - -/** - * This trait is responsible for the CST building logic. - */ -var TreeBuilder = /** @class */ (function () { - function TreeBuilder() { - } - TreeBuilder.prototype.initTreeBuilder = function (config) { - this.CST_STACK = []; - // outputCst is no longer exposed/defined in the pubic API - this.outputCst = config.outputCst; - this.nodeLocationTracking = has(config, "nodeLocationTracking") - ? config.nodeLocationTracking - : DEFAULT_PARSER_CONFIG.nodeLocationTracking; - if (!this.outputCst) { - this.cstInvocationStateUpdate = NOOP; - this.cstFinallyStateUpdate = NOOP; - this.cstPostTerminal = NOOP; - this.cstPostNonTerminal = NOOP; - this.cstPostRule = NOOP; - } - else { - if (/full/i.test(this.nodeLocationTracking)) { - if (this.recoveryEnabled) { - this.setNodeLocationFromToken = setNodeLocationFull; - this.setNodeLocationFromNode = setNodeLocationFull; - this.cstPostRule = NOOP; - this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery; - } - else { - this.setNodeLocationFromToken = NOOP; - this.setNodeLocationFromNode = NOOP; - this.cstPostRule = this.cstPostRuleFull; - this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular; - } - } - else if (/onlyOffset/i.test(this.nodeLocationTracking)) { - if (this.recoveryEnabled) { - this.setNodeLocationFromToken = setNodeLocationOnlyOffset; - this.setNodeLocationFromNode = setNodeLocationOnlyOffset; - this.cstPostRule = NOOP; - this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery; - } - else { - this.setNodeLocationFromToken = NOOP; - this.setNodeLocationFromNode = NOOP; - this.cstPostRule = this.cstPostRuleOnlyOffset; - this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular; - } - } - else if (/none/i.test(this.nodeLocationTracking)) { - this.setNodeLocationFromToken = NOOP; - this.setNodeLocationFromNode = NOOP; - this.cstPostRule = NOOP; - this.setInitialNodeLocation = NOOP; - } - else { - throw Error("Invalid config option: \"" + config.nodeLocationTracking + "\""); - } - } - }; - TreeBuilder.prototype.setInitialNodeLocationOnlyOffsetRecovery = function (cstNode) { - cstNode.location = { - startOffset: NaN, - endOffset: NaN - }; - }; - TreeBuilder.prototype.setInitialNodeLocationOnlyOffsetRegular = function (cstNode) { - cstNode.location = { - // without error recovery the starting Location of a new CstNode is guaranteed - // To be the next Token's startOffset (for valid inputs). - // For invalid inputs there won't be any CSTOutput so this potential - // inaccuracy does not matter - startOffset: this.LA(1).startOffset, - endOffset: NaN - }; - }; - TreeBuilder.prototype.setInitialNodeLocationFullRecovery = function (cstNode) { - cstNode.location = { - startOffset: NaN, - startLine: NaN, - startColumn: NaN, - endOffset: NaN, - endLine: NaN, - endColumn: NaN - }; - }; - /** - * @see setInitialNodeLocationOnlyOffsetRegular for explanation why this work - - * @param cstNode - */ - TreeBuilder.prototype.setInitialNodeLocationFullRegular = function (cstNode) { - var nextToken = this.LA(1); - cstNode.location = { - startOffset: nextToken.startOffset, - startLine: nextToken.startLine, - startColumn: nextToken.startColumn, - endOffset: NaN, - endLine: NaN, - endColumn: NaN - }; - }; - TreeBuilder.prototype.cstInvocationStateUpdate = function (fullRuleName, shortName) { - var cstNode = { - name: fullRuleName, - children: {} - }; - this.setInitialNodeLocation(cstNode); - this.CST_STACK.push(cstNode); - }; - TreeBuilder.prototype.cstFinallyStateUpdate = function () { - this.CST_STACK.pop(); - }; - TreeBuilder.prototype.cstPostRuleFull = function (ruleCstNode) { - var prevToken = this.LA(0); - var loc = ruleCstNode.location; - // If this condition is true it means we consumed at least one Token - // In this CstNode. - if (loc.startOffset <= prevToken.startOffset === true) { - loc.endOffset = prevToken.endOffset; - loc.endLine = prevToken.endLine; - loc.endColumn = prevToken.endColumn; - } - // "empty" CstNode edge case - else { - loc.startOffset = NaN; - loc.startLine = NaN; - loc.startColumn = NaN; - } - }; - TreeBuilder.prototype.cstPostRuleOnlyOffset = function (ruleCstNode) { - var prevToken = this.LA(0); - var loc = ruleCstNode.location; - // If this condition is true it means we consumed at least one Token - // In this CstNode. - if (loc.startOffset <= prevToken.startOffset === true) { - loc.endOffset = prevToken.endOffset; - } - // "empty" CstNode edge case - else { - loc.startOffset = NaN; - } - }; - TreeBuilder.prototype.cstPostTerminal = function (key, consumedToken) { - var rootCst = this.CST_STACK[this.CST_STACK.length - 1]; - addTerminalToCst(rootCst, consumedToken, key); - // This is only used when **both** error recovery and CST Output are enabled. - this.setNodeLocationFromToken(rootCst.location, consumedToken); - }; - TreeBuilder.prototype.cstPostNonTerminal = function (ruleCstResult, ruleName) { - var preCstNode = this.CST_STACK[this.CST_STACK.length - 1]; - addNoneTerminalToCst(preCstNode, ruleName, ruleCstResult); - // This is only used when **both** error recovery and CST Output are enabled. - this.setNodeLocationFromNode(preCstNode.location, ruleCstResult.location); - }; - TreeBuilder.prototype.getBaseCstVisitorConstructor = function () { - if (isUndefined(this.baseCstVisitorConstructor)) { - var newBaseCstVisitorConstructor = createBaseSemanticVisitorConstructor(this.className, keys(this.gastProductionsCache)); - this.baseCstVisitorConstructor = newBaseCstVisitorConstructor; - return newBaseCstVisitorConstructor; - } - return this.baseCstVisitorConstructor; - }; - TreeBuilder.prototype.getBaseCstVisitorConstructorWithDefaults = function () { - if (isUndefined(this.baseCstVisitorWithDefaultsConstructor)) { - var newConstructor = createBaseVisitorConstructorWithDefaults(this.className, keys(this.gastProductionsCache), this.getBaseCstVisitorConstructor()); - this.baseCstVisitorWithDefaultsConstructor = newConstructor; - return newConstructor; - } - return this.baseCstVisitorWithDefaultsConstructor; - }; - TreeBuilder.prototype.getLastExplicitRuleShortName = function () { - var ruleStack = this.RULE_STACK; - return ruleStack[ruleStack.length - 1]; - }; - TreeBuilder.prototype.getPreviousExplicitRuleShortName = function () { - var ruleStack = this.RULE_STACK; - return ruleStack[ruleStack.length - 2]; - }; - TreeBuilder.prototype.getLastExplicitRuleOccurrenceIndex = function () { - var occurrenceStack = this.RULE_OCCURRENCE_STACK; - return occurrenceStack[occurrenceStack.length - 1]; - }; - return TreeBuilder; -}()); - -/** - * Trait responsible abstracting over the interaction with Lexer output (Token vector). - * - * This could be generalized to support other kinds of lexers, e.g. - * - Just in Time Lexing / Lexer-Less parsing. - * - Streaming Lexer. - */ -var LexerAdapter = /** @class */ (function () { - function LexerAdapter() { - } - LexerAdapter.prototype.initLexerAdapter = function () { - this.tokVector = []; - this.tokVectorLength = 0; - this.currIdx = -1; - }; - Object.defineProperty(LexerAdapter.prototype, "input", { - get: function () { - return this.tokVector; - }, - set: function (newInput) { - // @ts-ignore - `this parameter` not supported in setters/getters - // - https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters - if (this.selfAnalysisDone !== true) { - throw Error("Missing invocation at the end of the Parser's constructor."); - } - // @ts-ignore - `this parameter` not supported in setters/getters - // - https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters - this.reset(); - this.tokVector = newInput; - this.tokVectorLength = newInput.length; - }, - enumerable: false, - configurable: true - }); - // skips a token and returns the next token - LexerAdapter.prototype.SKIP_TOKEN = function () { - if (this.currIdx <= this.tokVector.length - 2) { - this.consumeToken(); - return this.LA(1); - } - else { - return END_OF_FILE; - } - }; - // Lexer (accessing Token vector) related methods which can be overridden to implement lazy lexers - // or lexers dependent on parser context. - LexerAdapter.prototype.LA = function (howMuch) { - var soughtIdx = this.currIdx + howMuch; - if (soughtIdx < 0 || this.tokVectorLength <= soughtIdx) { - return END_OF_FILE; - } - else { - return this.tokVector[soughtIdx]; - } - }; - LexerAdapter.prototype.consumeToken = function () { - this.currIdx++; - }; - LexerAdapter.prototype.exportLexerState = function () { - return this.currIdx; - }; - LexerAdapter.prototype.importLexerState = function (newState) { - this.currIdx = newState; - }; - LexerAdapter.prototype.resetLexerState = function () { - this.currIdx = -1; - }; - LexerAdapter.prototype.moveToTerminatedState = function () { - this.currIdx = this.tokVector.length - 1; - }; - LexerAdapter.prototype.getLexerPosition = function () { - return this.exportLexerState(); - }; - return LexerAdapter; -}()); - -/** - * This trait is responsible for implementing the public API - * for defining Chevrotain parsers, i.e: - * - CONSUME - * - RULE - * - OPTION - * - ... - */ -var RecognizerApi = /** @class */ (function () { - function RecognizerApi() { - } - RecognizerApi.prototype.ACTION = function (impl) { - return impl.call(this); - }; - RecognizerApi.prototype.consume = function (idx, tokType, options) { - return this.consumeInternal(tokType, idx, options); - }; - RecognizerApi.prototype.subrule = function (idx, ruleToCall, options) { - return this.subruleInternal(ruleToCall, idx, options); - }; - RecognizerApi.prototype.option = function (idx, actionORMethodDef) { - return this.optionInternal(actionORMethodDef, idx); - }; - RecognizerApi.prototype.or = function (idx, altsOrOpts) { - return this.orInternal(altsOrOpts, idx); - }; - RecognizerApi.prototype.many = function (idx, actionORMethodDef) { - return this.manyInternal(idx, actionORMethodDef); - }; - RecognizerApi.prototype.atLeastOne = function (idx, actionORMethodDef) { - return this.atLeastOneInternal(idx, actionORMethodDef); - }; - RecognizerApi.prototype.CONSUME = function (tokType, options) { - return this.consumeInternal(tokType, 0, options); - }; - RecognizerApi.prototype.CONSUME1 = function (tokType, options) { - return this.consumeInternal(tokType, 1, options); - }; - RecognizerApi.prototype.CONSUME2 = function (tokType, options) { - return this.consumeInternal(tokType, 2, options); - }; - RecognizerApi.prototype.CONSUME3 = function (tokType, options) { - return this.consumeInternal(tokType, 3, options); - }; - RecognizerApi.prototype.CONSUME4 = function (tokType, options) { - return this.consumeInternal(tokType, 4, options); - }; - RecognizerApi.prototype.CONSUME5 = function (tokType, options) { - return this.consumeInternal(tokType, 5, options); - }; - RecognizerApi.prototype.CONSUME6 = function (tokType, options) { - return this.consumeInternal(tokType, 6, options); - }; - RecognizerApi.prototype.CONSUME7 = function (tokType, options) { - return this.consumeInternal(tokType, 7, options); - }; - RecognizerApi.prototype.CONSUME8 = function (tokType, options) { - return this.consumeInternal(tokType, 8, options); - }; - RecognizerApi.prototype.CONSUME9 = function (tokType, options) { - return this.consumeInternal(tokType, 9, options); - }; - RecognizerApi.prototype.SUBRULE = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 0, options); - }; - RecognizerApi.prototype.SUBRULE1 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 1, options); - }; - RecognizerApi.prototype.SUBRULE2 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 2, options); - }; - RecognizerApi.prototype.SUBRULE3 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 3, options); - }; - RecognizerApi.prototype.SUBRULE4 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 4, options); - }; - RecognizerApi.prototype.SUBRULE5 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 5, options); - }; - RecognizerApi.prototype.SUBRULE6 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 6, options); - }; - RecognizerApi.prototype.SUBRULE7 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 7, options); - }; - RecognizerApi.prototype.SUBRULE8 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 8, options); - }; - RecognizerApi.prototype.SUBRULE9 = function (ruleToCall, options) { - return this.subruleInternal(ruleToCall, 9, options); - }; - RecognizerApi.prototype.OPTION = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 0); - }; - RecognizerApi.prototype.OPTION1 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 1); - }; - RecognizerApi.prototype.OPTION2 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 2); - }; - RecognizerApi.prototype.OPTION3 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 3); - }; - RecognizerApi.prototype.OPTION4 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 4); - }; - RecognizerApi.prototype.OPTION5 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 5); - }; - RecognizerApi.prototype.OPTION6 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 6); - }; - RecognizerApi.prototype.OPTION7 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 7); - }; - RecognizerApi.prototype.OPTION8 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 8); - }; - RecognizerApi.prototype.OPTION9 = function (actionORMethodDef) { - return this.optionInternal(actionORMethodDef, 9); - }; - RecognizerApi.prototype.OR = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 0); - }; - RecognizerApi.prototype.OR1 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 1); - }; - RecognizerApi.prototype.OR2 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 2); - }; - RecognizerApi.prototype.OR3 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 3); - }; - RecognizerApi.prototype.OR4 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 4); - }; - RecognizerApi.prototype.OR5 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 5); - }; - RecognizerApi.prototype.OR6 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 6); - }; - RecognizerApi.prototype.OR7 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 7); - }; - RecognizerApi.prototype.OR8 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 8); - }; - RecognizerApi.prototype.OR9 = function (altsOrOpts) { - return this.orInternal(altsOrOpts, 9); - }; - RecognizerApi.prototype.MANY = function (actionORMethodDef) { - this.manyInternal(0, actionORMethodDef); - }; - RecognizerApi.prototype.MANY1 = function (actionORMethodDef) { - this.manyInternal(1, actionORMethodDef); - }; - RecognizerApi.prototype.MANY2 = function (actionORMethodDef) { - this.manyInternal(2, actionORMethodDef); - }; - RecognizerApi.prototype.MANY3 = function (actionORMethodDef) { - this.manyInternal(3, actionORMethodDef); - }; - RecognizerApi.prototype.MANY4 = function (actionORMethodDef) { - this.manyInternal(4, actionORMethodDef); - }; - RecognizerApi.prototype.MANY5 = function (actionORMethodDef) { - this.manyInternal(5, actionORMethodDef); - }; - RecognizerApi.prototype.MANY6 = function (actionORMethodDef) { - this.manyInternal(6, actionORMethodDef); - }; - RecognizerApi.prototype.MANY7 = function (actionORMethodDef) { - this.manyInternal(7, actionORMethodDef); - }; - RecognizerApi.prototype.MANY8 = function (actionORMethodDef) { - this.manyInternal(8, actionORMethodDef); - }; - RecognizerApi.prototype.MANY9 = function (actionORMethodDef) { - this.manyInternal(9, actionORMethodDef); - }; - RecognizerApi.prototype.MANY_SEP = function (options) { - this.manySepFirstInternal(0, options); - }; - RecognizerApi.prototype.MANY_SEP1 = function (options) { - this.manySepFirstInternal(1, options); - }; - RecognizerApi.prototype.MANY_SEP2 = function (options) { - this.manySepFirstInternal(2, options); - }; - RecognizerApi.prototype.MANY_SEP3 = function (options) { - this.manySepFirstInternal(3, options); - }; - RecognizerApi.prototype.MANY_SEP4 = function (options) { - this.manySepFirstInternal(4, options); - }; - RecognizerApi.prototype.MANY_SEP5 = function (options) { - this.manySepFirstInternal(5, options); - }; - RecognizerApi.prototype.MANY_SEP6 = function (options) { - this.manySepFirstInternal(6, options); - }; - RecognizerApi.prototype.MANY_SEP7 = function (options) { - this.manySepFirstInternal(7, options); - }; - RecognizerApi.prototype.MANY_SEP8 = function (options) { - this.manySepFirstInternal(8, options); - }; - RecognizerApi.prototype.MANY_SEP9 = function (options) { - this.manySepFirstInternal(9, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE = function (actionORMethodDef) { - this.atLeastOneInternal(0, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE1 = function (actionORMethodDef) { - return this.atLeastOneInternal(1, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE2 = function (actionORMethodDef) { - this.atLeastOneInternal(2, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE3 = function (actionORMethodDef) { - this.atLeastOneInternal(3, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE4 = function (actionORMethodDef) { - this.atLeastOneInternal(4, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE5 = function (actionORMethodDef) { - this.atLeastOneInternal(5, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE6 = function (actionORMethodDef) { - this.atLeastOneInternal(6, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE7 = function (actionORMethodDef) { - this.atLeastOneInternal(7, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE8 = function (actionORMethodDef) { - this.atLeastOneInternal(8, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE9 = function (actionORMethodDef) { - this.atLeastOneInternal(9, actionORMethodDef); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP = function (options) { - this.atLeastOneSepFirstInternal(0, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP1 = function (options) { - this.atLeastOneSepFirstInternal(1, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP2 = function (options) { - this.atLeastOneSepFirstInternal(2, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP3 = function (options) { - this.atLeastOneSepFirstInternal(3, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP4 = function (options) { - this.atLeastOneSepFirstInternal(4, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP5 = function (options) { - this.atLeastOneSepFirstInternal(5, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP6 = function (options) { - this.atLeastOneSepFirstInternal(6, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP7 = function (options) { - this.atLeastOneSepFirstInternal(7, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP8 = function (options) { - this.atLeastOneSepFirstInternal(8, options); - }; - RecognizerApi.prototype.AT_LEAST_ONE_SEP9 = function (options) { - this.atLeastOneSepFirstInternal(9, options); - }; - RecognizerApi.prototype.RULE = function (name, implementation, config) { - if (config === void 0) { config = DEFAULT_RULE_CONFIG; } - if (contains(this.definedRulesNames, name)) { - var errMsg = defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({ - topLevelRule: name, - grammarName: this.className - }); - var error = { - message: errMsg, - type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME, - ruleName: name - }; - this.definitionErrors.push(error); - } - this.definedRulesNames.push(name); - var ruleImplementation = this.defineRule(name, implementation, config); - this[name] = ruleImplementation; - return ruleImplementation; - }; - RecognizerApi.prototype.OVERRIDE_RULE = function (name, impl, config) { - if (config === void 0) { config = DEFAULT_RULE_CONFIG; } - var ruleErrors = []; - ruleErrors = ruleErrors.concat(validateRuleIsOverridden(name, this.definedRulesNames, this.className)); - this.definitionErrors.push.apply(this.definitionErrors, ruleErrors); // mutability for the win - var ruleImplementation = this.defineRule(name, impl, config); - this[name] = ruleImplementation; - return ruleImplementation; - }; - RecognizerApi.prototype.BACKTRACK = function (grammarRule, args) { - return function () { - // save org state - this.isBackTrackingStack.push(1); - var orgState = this.saveRecogState(); - try { - grammarRule.apply(this, args); - // if no exception was thrown we have succeed parsing the rule. - return true; - } - catch (e) { - if (isRecognitionException(e)) { - return false; - } - else { - throw e; - } - } - finally { - this.reloadRecogState(orgState); - this.isBackTrackingStack.pop(); - } - }; - }; - // GAST export APIs - RecognizerApi.prototype.getGAstProductions = function () { - return this.gastProductionsCache; - }; - RecognizerApi.prototype.getSerializedGastProductions = function () { - return serializeGrammar(values(this.gastProductionsCache)); - }; - return RecognizerApi; -}()); - -/** - * This trait is responsible for the runtime parsing engine - * Used by the official API (recognizer_api.ts) - */ -var RecognizerEngine = /** @class */ (function () { - function RecognizerEngine() { - } - RecognizerEngine.prototype.initRecognizerEngine = function (tokenVocabulary, config) { - this.className = classNameFromInstance(this); - // TODO: would using an ES6 Map or plain object be faster (CST building scenario) - this.shortRuleNameToFull = {}; - this.fullRuleNameToShort = {}; - this.ruleShortNameIdx = 256; - this.tokenMatcher = tokenStructuredMatcherNoCategories; - this.definedRulesNames = []; - this.tokensMap = {}; - this.isBackTrackingStack = []; - this.RULE_STACK = []; - this.RULE_OCCURRENCE_STACK = []; - this.gastProductionsCache = {}; - if (has(config, "serializedGrammar")) { - throw Error("The Parser's configuration can no longer contain a property.\n" + - "\tSee: https://sap.github.io/chevrotain/docs/changes/BREAKING_CHANGES.html#_6-0-0\n" + - "\tFor Further details."); - } - if (isArray(tokenVocabulary)) { - // This only checks for Token vocabularies provided as arrays. - // That is good enough because the main objective is to detect users of pre-V4.0 APIs - // rather than all edge cases of empty Token vocabularies. - if (isEmpty(tokenVocabulary)) { - throw Error("A Token Vocabulary cannot be empty.\n" + - "\tNote that the first argument for the parser constructor\n" + - "\tis no longer a Token vector (since v4.0)."); - } - if (typeof tokenVocabulary[0].startOffset === "number") { - throw Error("The Parser constructor no longer accepts a token vector as the first argument.\n" + - "\tSee: https://sap.github.io/chevrotain/docs/changes/BREAKING_CHANGES.html#_4-0-0\n" + - "\tFor Further details."); - } - } - if (isArray(tokenVocabulary)) { - this.tokensMap = reduce(tokenVocabulary, function (acc, tokType) { - acc[tokType.name] = tokType; - return acc; - }, {}); - } - else if (has(tokenVocabulary, "modes") && - every(flatten(values(tokenVocabulary.modes)), isTokenType)) { - var allTokenTypes = flatten(values(tokenVocabulary.modes)); - var uniqueTokens = uniq(allTokenTypes); - this.tokensMap = reduce(uniqueTokens, function (acc, tokType) { - acc[tokType.name] = tokType; - return acc; - }, {}); - } - else if (isObject(tokenVocabulary)) { - this.tokensMap = cloneObj(tokenVocabulary); - } - else { - throw new Error(" argument must be An Array of Token constructors," + - " A dictionary of Token constructors or an IMultiModeLexerDefinition"); - } - // always add EOF to the tokenNames -> constructors map. it is useful to assure all the input has been - // parsed with a clear error message ("expecting EOF but found ...") - /* tslint:disable */ - this.tokensMap["EOF"] = EOF; - // TODO: This check may not be accurate for multi mode lexers - var noTokenCategoriesUsed = every(values(tokenVocabulary), function (tokenConstructor) { return isEmpty(tokenConstructor.categoryMatches); }); - this.tokenMatcher = noTokenCategoriesUsed - ? tokenStructuredMatcherNoCategories - : tokenStructuredMatcher; - // Because ES2015+ syntax should be supported for creating Token classes - // We cannot assume that the Token classes were created using the "extendToken" utilities - // Therefore we must augment the Token classes both on Lexer initialization and on Parser initialization - augmentTokenTypes(values(this.tokensMap)); - }; - RecognizerEngine.prototype.defineRule = function (ruleName, impl, config) { - if (this.selfAnalysisDone) { - throw Error("Grammar rule <" + ruleName + "> may not be defined after the 'performSelfAnalysis' method has been called'\n" + - "Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called."); - } - var resyncEnabled = has(config, "resyncEnabled") - ? config.resyncEnabled - : DEFAULT_RULE_CONFIG.resyncEnabled; - var recoveryValueFunc = has(config, "recoveryValueFunc") - ? config.recoveryValueFunc - : DEFAULT_RULE_CONFIG.recoveryValueFunc; - // performance optimization: Use small integers as keys for the longer human readable "full" rule names. - // this greatly improves Map access time (as much as 8% for some performance benchmarks). - /* tslint:disable */ - var shortName = this.ruleShortNameIdx << (BITS_FOR_METHOD_TYPE + BITS_FOR_OCCURRENCE_IDX); - /* tslint:enable */ - this.ruleShortNameIdx++; - this.shortRuleNameToFull[shortName] = ruleName; - this.fullRuleNameToShort[ruleName] = shortName; - function invokeRuleWithTry(args) { - try { - if (this.outputCst === true) { - impl.apply(this, args); - var cst = this.CST_STACK[this.CST_STACK.length - 1]; - this.cstPostRule(cst); - return cst; - } - else { - return impl.apply(this, args); - } - } - catch (e) { - return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc); - } - finally { - this.ruleFinallyStateUpdate(); - } - } - var wrappedGrammarRule; - wrappedGrammarRule = function (idxInCallingRule, args) { - if (idxInCallingRule === void 0) { idxInCallingRule = 0; } - this.ruleInvocationStateUpdate(shortName, ruleName, idxInCallingRule); - return invokeRuleWithTry.call(this, args); - }; - var ruleNamePropName = "ruleName"; - wrappedGrammarRule[ruleNamePropName] = ruleName; - wrappedGrammarRule["originalGrammarAction"] = impl; - return wrappedGrammarRule; - }; - RecognizerEngine.prototype.invokeRuleCatch = function (e, resyncEnabledConfig, recoveryValueFunc) { - var isFirstInvokedRule = this.RULE_STACK.length === 1; - // note the reSync is always enabled for the first rule invocation, because we must always be able to - // reSync with EOF and just output some INVALID ParseTree - // during backtracking reSync recovery is disabled, otherwise we can't be certain the backtracking - // path is really the most valid one - var reSyncEnabled = resyncEnabledConfig && !this.isBackTracking() && this.recoveryEnabled; - if (isRecognitionException(e)) { - var recogError = e; - if (reSyncEnabled) { - var reSyncTokType = this.findReSyncTokenType(); - if (this.isInCurrentRuleReSyncSet(reSyncTokType)) { - recogError.resyncedTokens = this.reSyncTo(reSyncTokType); - if (this.outputCst) { - var partialCstResult = this.CST_STACK[this.CST_STACK.length - 1]; - partialCstResult.recoveredNode = true; - return partialCstResult; - } - else { - return recoveryValueFunc(); - } - } - else { - if (this.outputCst) { - var partialCstResult = this.CST_STACK[this.CST_STACK.length - 1]; - partialCstResult.recoveredNode = true; - recogError.partialCstResult = partialCstResult; - } - // to be handled Further up the call stack - throw recogError; - } - } - else if (isFirstInvokedRule) { - // otherwise a Redundant input error will be created as well and we cannot guarantee that this is indeed the case - this.moveToTerminatedState(); - // the parser should never throw one of its own errors outside its flow. - // even if error recovery is disabled - return recoveryValueFunc(); - } - else { - // to be recovered Further up the call stack - throw recogError; - } - } - else { - // some other Error type which we don't know how to handle (for example a built in JavaScript Error) - throw e; - } - }; - // Implementation of parsing DSL - RecognizerEngine.prototype.optionInternal = function (actionORMethodDef, occurrence) { - var key = this.getKeyForAutomaticLookahead(OPTION_IDX, occurrence); - return this.optionInternalLogic(actionORMethodDef, occurrence, key); - }; - RecognizerEngine.prototype.optionInternalLogic = function (actionORMethodDef, occurrence, key) { - var _this = this; - var lookAheadFunc = this.getLaFuncFromCache(key); - var action; - var predicate; - if (actionORMethodDef.DEF !== undefined) { - action = actionORMethodDef.DEF; - predicate = actionORMethodDef.GATE; - // predicate present - if (predicate !== undefined) { - var orgLookaheadFunction_1 = lookAheadFunc; - lookAheadFunc = function () { - return predicate.call(_this) && orgLookaheadFunction_1.call(_this); - }; - } - } - else { - action = actionORMethodDef; - } - if (lookAheadFunc.call(this) === true) { - return action.call(this); - } - return undefined; - }; - RecognizerEngine.prototype.atLeastOneInternal = function (prodOccurrence, actionORMethodDef) { - var laKey = this.getKeyForAutomaticLookahead(AT_LEAST_ONE_IDX, prodOccurrence); - return this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, laKey); - }; - RecognizerEngine.prototype.atLeastOneInternalLogic = function (prodOccurrence, actionORMethodDef, key) { - var _this = this; - var lookAheadFunc = this.getLaFuncFromCache(key); - var action; - var predicate; - if (actionORMethodDef.DEF !== undefined) { - action = actionORMethodDef.DEF; - predicate = actionORMethodDef.GATE; - // predicate present - if (predicate !== undefined) { - var orgLookaheadFunction_2 = lookAheadFunc; - lookAheadFunc = function () { - return predicate.call(_this) && orgLookaheadFunction_2.call(_this); - }; - } - } - else { - action = actionORMethodDef; - } - if (lookAheadFunc.call(this) === true) { - var notStuck = this.doSingleRepetition(action); - while (lookAheadFunc.call(this) === true && - notStuck === true) { - notStuck = this.doSingleRepetition(action); - } - } - else { - throw this.raiseEarlyExitException(prodOccurrence, PROD_TYPE.REPETITION_MANDATORY, actionORMethodDef.ERR_MSG); - } - // note that while it may seem that this can cause an error because by using a recursive call to - // AT_LEAST_ONE we change the grammar to AT_LEAST_TWO, AT_LEAST_THREE ... , the possible recursive call - // from the tryInRepetitionRecovery(...) will only happen IFF there really are TWO/THREE/.... items. - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - this.attemptInRepetitionRecovery(this.atLeastOneInternal, [prodOccurrence, actionORMethodDef], lookAheadFunc, AT_LEAST_ONE_IDX, prodOccurrence, NextTerminalAfterAtLeastOneWalker); - }; - RecognizerEngine.prototype.atLeastOneSepFirstInternal = function (prodOccurrence, options) { - var laKey = this.getKeyForAutomaticLookahead(AT_LEAST_ONE_SEP_IDX, prodOccurrence); - this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey); - }; - RecognizerEngine.prototype.atLeastOneSepFirstInternalLogic = function (prodOccurrence, options, key) { - var _this = this; - var action = options.DEF; - var separator = options.SEP; - var firstIterationLookaheadFunc = this.getLaFuncFromCache(key); - // 1st iteration - if (firstIterationLookaheadFunc.call(this) === true) { - action.call(this); - // TODO: Optimization can move this function construction into "attemptInRepetitionRecovery" - // because it is only needed in error recovery scenarios. - var separatorLookAheadFunc = function () { - return _this.tokenMatcher(_this.LA(1), separator); - }; - // 2nd..nth iterations - while (this.tokenMatcher(this.LA(1), separator) === true) { - // note that this CONSUME will never enter recovery because - // the separatorLookAheadFunc checks that the separator really does exist. - this.CONSUME(separator); - action.call(this); - } - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [ - prodOccurrence, - separator, - separatorLookAheadFunc, - action, - NextTerminalAfterAtLeastOneSepWalker - ], separatorLookAheadFunc, AT_LEAST_ONE_SEP_IDX, prodOccurrence, NextTerminalAfterAtLeastOneSepWalker); - } - else { - throw this.raiseEarlyExitException(prodOccurrence, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, options.ERR_MSG); - } - }; - RecognizerEngine.prototype.manyInternal = function (prodOccurrence, actionORMethodDef) { - var laKey = this.getKeyForAutomaticLookahead(MANY_IDX, prodOccurrence); - return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey); - }; - RecognizerEngine.prototype.manyInternalLogic = function (prodOccurrence, actionORMethodDef, key) { - var _this = this; - var lookaheadFunction = this.getLaFuncFromCache(key); - var action; - var predicate; - if (actionORMethodDef.DEF !== undefined) { - action = actionORMethodDef.DEF; - predicate = actionORMethodDef.GATE; - // predicate present - if (predicate !== undefined) { - var orgLookaheadFunction_3 = lookaheadFunction; - lookaheadFunction = function () { - return predicate.call(_this) && orgLookaheadFunction_3.call(_this); - }; - } - } - else { - action = actionORMethodDef; - } - var notStuck = true; - while (lookaheadFunction.call(this) === true && notStuck === true) { - notStuck = this.doSingleRepetition(action); - } - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - this.attemptInRepetitionRecovery(this.manyInternal, [prodOccurrence, actionORMethodDef], lookaheadFunction, MANY_IDX, prodOccurrence, NextTerminalAfterManyWalker, - // The notStuck parameter is only relevant when "attemptInRepetitionRecovery" - // is invoked from manyInternal, in the MANY_SEP case and AT_LEAST_ONE[_SEP] - // An infinite loop cannot occur as: - // - Either the lookahead is guaranteed to consume something (Single Token Separator) - // - AT_LEAST_ONE by definition is guaranteed to consume something (or error out). - notStuck); - }; - RecognizerEngine.prototype.manySepFirstInternal = function (prodOccurrence, options) { - var laKey = this.getKeyForAutomaticLookahead(MANY_SEP_IDX, prodOccurrence); - this.manySepFirstInternalLogic(prodOccurrence, options, laKey); - }; - RecognizerEngine.prototype.manySepFirstInternalLogic = function (prodOccurrence, options, key) { - var _this = this; - var action = options.DEF; - var separator = options.SEP; - var firstIterationLaFunc = this.getLaFuncFromCache(key); - // 1st iteration - if (firstIterationLaFunc.call(this) === true) { - action.call(this); - var separatorLookAheadFunc = function () { - return _this.tokenMatcher(_this.LA(1), separator); - }; - // 2nd..nth iterations - while (this.tokenMatcher(this.LA(1), separator) === true) { - // note that this CONSUME will never enter recovery because - // the separatorLookAheadFunc checks that the separator really does exist. - this.CONSUME(separator); - // No need for checking infinite loop here due to consuming the separator. - action.call(this); - } - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [ - prodOccurrence, - separator, - separatorLookAheadFunc, - action, - NextTerminalAfterManySepWalker - ], separatorLookAheadFunc, MANY_SEP_IDX, prodOccurrence, NextTerminalAfterManySepWalker); - } - }; - RecognizerEngine.prototype.repetitionSepSecondInternal = function (prodOccurrence, separator, separatorLookAheadFunc, action, nextTerminalAfterWalker) { - while (separatorLookAheadFunc()) { - // note that this CONSUME will never enter recovery because - // the separatorLookAheadFunc checks that the separator really does exist. - this.CONSUME(separator); - action.call(this); - } - // we can only arrive to this function after an error - // has occurred (hence the name 'second') so the following - // IF will always be entered, its possible to remove it... - // however it is kept to avoid confusion and be consistent. - // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled - /* istanbul ignore else */ - this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [ - prodOccurrence, - separator, - separatorLookAheadFunc, - action, - nextTerminalAfterWalker - ], separatorLookAheadFunc, AT_LEAST_ONE_SEP_IDX, prodOccurrence, nextTerminalAfterWalker); - }; - RecognizerEngine.prototype.doSingleRepetition = function (action) { - var beforeIteration = this.getLexerPosition(); - action.call(this); - var afterIteration = this.getLexerPosition(); - // This boolean will indicate if this repetition progressed - // or if we are "stuck" (potential infinite loop in the repetition). - return afterIteration > beforeIteration; - }; - RecognizerEngine.prototype.orInternal = function (altsOrOpts, occurrence) { - var laKey = this.getKeyForAutomaticLookahead(OR_IDX, occurrence); - var alts = isArray(altsOrOpts) - ? altsOrOpts - : altsOrOpts.DEF; - var laFunc = this.getLaFuncFromCache(laKey); - var altIdxToTake = laFunc.call(this, alts); - if (altIdxToTake !== undefined) { - var chosenAlternative = alts[altIdxToTake]; - return chosenAlternative.ALT.call(this); - } - this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG); - }; - RecognizerEngine.prototype.ruleFinallyStateUpdate = function () { - this.RULE_STACK.pop(); - this.RULE_OCCURRENCE_STACK.pop(); - // NOOP when cst is disabled - this.cstFinallyStateUpdate(); - if (this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) { - var firstRedundantTok = this.LA(1); - var errMsg = this.errorMessageProvider.buildNotAllInputParsedMessage({ - firstRedundant: firstRedundantTok, - ruleName: this.getCurrRuleFullName() - }); - this.SAVE_ERROR(new NotAllInputParsedException(errMsg, firstRedundantTok)); - } - }; - RecognizerEngine.prototype.subruleInternal = function (ruleToCall, idx, options) { - var ruleResult; - try { - var args = options !== undefined ? options.ARGS : undefined; - ruleResult = ruleToCall.call(this, idx, args); - this.cstPostNonTerminal(ruleResult, options !== undefined && options.LABEL !== undefined - ? options.LABEL - : ruleToCall.ruleName); - return ruleResult; - } - catch (e) { - this.subruleInternalError(e, options, ruleToCall.ruleName); - } - }; - RecognizerEngine.prototype.subruleInternalError = function (e, options, ruleName) { - if (isRecognitionException(e) && e.partialCstResult !== undefined) { - this.cstPostNonTerminal(e.partialCstResult, options !== undefined && options.LABEL !== undefined - ? options.LABEL - : ruleName); - delete e.partialCstResult; - } - throw e; - }; - RecognizerEngine.prototype.consumeInternal = function (tokType, idx, options) { - var consumedToken; - try { - var nextToken = this.LA(1); - if (this.tokenMatcher(nextToken, tokType) === true) { - this.consumeToken(); - consumedToken = nextToken; - } - else { - this.consumeInternalError(tokType, nextToken, options); - } - } - catch (eFromConsumption) { - consumedToken = this.consumeInternalRecovery(tokType, idx, eFromConsumption); - } - this.cstPostTerminal(options !== undefined && options.LABEL !== undefined - ? options.LABEL - : tokType.name, consumedToken); - return consumedToken; - }; - RecognizerEngine.prototype.consumeInternalError = function (tokType, nextToken, options) { - var msg; - var previousToken = this.LA(0); - if (options !== undefined && options.ERR_MSG) { - msg = options.ERR_MSG; - } - else { - msg = this.errorMessageProvider.buildMismatchTokenMessage({ - expected: tokType, - actual: nextToken, - previous: previousToken, - ruleName: this.getCurrRuleFullName() - }); - } - throw this.SAVE_ERROR(new MismatchedTokenException(msg, nextToken, previousToken)); - }; - RecognizerEngine.prototype.consumeInternalRecovery = function (tokType, idx, eFromConsumption) { - // no recovery allowed during backtracking, otherwise backtracking may recover invalid syntax and accept it - // but the original syntax could have been parsed successfully without any backtracking + recovery - if (this.recoveryEnabled && - // TODO: more robust checking of the exception type. Perhaps Typescript extending expressions? - eFromConsumption.name === "MismatchedTokenException" && - !this.isBackTracking()) { - var follows = this.getFollowsForInRuleRecovery(tokType, idx); - try { - return this.tryInRuleRecovery(tokType, follows); - } - catch (eFromInRuleRecovery) { - if (eFromInRuleRecovery.name === IN_RULE_RECOVERY_EXCEPTION) { - // failed in RuleRecovery. - // throw the original error in order to trigger reSync error recovery - throw eFromConsumption; - } - else { - throw eFromInRuleRecovery; - } - } - } - else { - throw eFromConsumption; - } - }; - RecognizerEngine.prototype.saveRecogState = function () { - // errors is a getter which will clone the errors array - var savedErrors = this.errors; - var savedRuleStack = cloneArr(this.RULE_STACK); - return { - errors: savedErrors, - lexerState: this.exportLexerState(), - RULE_STACK: savedRuleStack, - CST_STACK: this.CST_STACK - }; - }; - RecognizerEngine.prototype.reloadRecogState = function (newState) { - this.errors = newState.errors; - this.importLexerState(newState.lexerState); - this.RULE_STACK = newState.RULE_STACK; - }; - RecognizerEngine.prototype.ruleInvocationStateUpdate = function (shortName, fullName, idxInCallingRule) { - this.RULE_OCCURRENCE_STACK.push(idxInCallingRule); - this.RULE_STACK.push(shortName); - // NOOP when cst is disabled - this.cstInvocationStateUpdate(fullName, shortName); - }; - RecognizerEngine.prototype.isBackTracking = function () { - return this.isBackTrackingStack.length !== 0; - }; - RecognizerEngine.prototype.getCurrRuleFullName = function () { - var shortName = this.getLastExplicitRuleShortName(); - return this.shortRuleNameToFull[shortName]; - }; - RecognizerEngine.prototype.shortRuleNameToFullName = function (shortName) { - return this.shortRuleNameToFull[shortName]; - }; - RecognizerEngine.prototype.isAtEndOfInput = function () { - return this.tokenMatcher(this.LA(1), EOF); - }; - RecognizerEngine.prototype.reset = function () { - this.resetLexerState(); - this.isBackTrackingStack = []; - this.errors = []; - this.RULE_STACK = []; - // TODO: extract a specific reset for TreeBuilder trait - this.CST_STACK = []; - this.RULE_OCCURRENCE_STACK = []; - }; - return RecognizerEngine; -}()); - -/** - * Trait responsible for runtime parsing errors. - */ -var ErrorHandler = /** @class */ (function () { - function ErrorHandler() { - } - ErrorHandler.prototype.initErrorHandler = function (config) { - this._errors = []; - this.errorMessageProvider = has(config, "errorMessageProvider") - ? config.errorMessageProvider - : DEFAULT_PARSER_CONFIG.errorMessageProvider; - }; - ErrorHandler.prototype.SAVE_ERROR = function (error) { - if (isRecognitionException(error)) { - error.context = { - ruleStack: this.getHumanReadableRuleStack(), - ruleOccurrenceStack: cloneArr(this.RULE_OCCURRENCE_STACK) - }; - this._errors.push(error); - return error; - } - else { - throw Error("Trying to save an Error which is not a RecognitionException"); - } - }; - Object.defineProperty(ErrorHandler.prototype, "errors", { - get: function () { - return cloneArr(this._errors); - }, - set: function (newErrors) { - this._errors = newErrors; - }, - enumerable: false, - configurable: true - }); - // TODO: consider caching the error message computed information - ErrorHandler.prototype.raiseEarlyExitException = function (occurrence, prodType, userDefinedErrMsg) { - var ruleName = this.getCurrRuleFullName(); - var ruleGrammar = this.getGAstProductions()[ruleName]; - var lookAheadPathsPerAlternative = getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, this.maxLookahead); - var insideProdPaths = lookAheadPathsPerAlternative[0]; - var actualTokens = []; - for (var i = 1; i <= this.maxLookahead; i++) { - actualTokens.push(this.LA(i)); - } - var msg = this.errorMessageProvider.buildEarlyExitMessage({ - expectedIterationPaths: insideProdPaths, - actual: actualTokens, - previous: this.LA(0), - customUserDescription: userDefinedErrMsg, - ruleName: ruleName - }); - throw this.SAVE_ERROR(new EarlyExitException(msg, this.LA(1), this.LA(0))); - }; - // TODO: consider caching the error message computed information - ErrorHandler.prototype.raiseNoAltException = function (occurrence, errMsgTypes) { - var ruleName = this.getCurrRuleFullName(); - var ruleGrammar = this.getGAstProductions()[ruleName]; - // TODO: getLookaheadPathsForOr can be slow for large enough maxLookahead and certain grammars, consider caching ? - var lookAheadPathsPerAlternative = getLookaheadPathsForOr(occurrence, ruleGrammar, this.maxLookahead); - var actualTokens = []; - for (var i = 1; i <= this.maxLookahead; i++) { - actualTokens.push(this.LA(i)); - } - var previousToken = this.LA(0); - var errMsg = this.errorMessageProvider.buildNoViableAltMessage({ - expectedPathsPerAlt: lookAheadPathsPerAlternative, - actual: actualTokens, - previous: previousToken, - customUserDescription: errMsgTypes, - ruleName: this.getCurrRuleFullName() - }); - throw this.SAVE_ERROR(new NoViableAltException(errMsg, this.LA(1), previousToken)); - }; - return ErrorHandler; -}()); - -var ContentAssist = /** @class */ (function () { - function ContentAssist() { - } - ContentAssist.prototype.initContentAssist = function () { }; - ContentAssist.prototype.computeContentAssist = function (startRuleName, precedingInput) { - var startRuleGast = this.gastProductionsCache[startRuleName]; - if (isUndefined(startRuleGast)) { - throw Error("Rule ->" + startRuleName + "<- does not exist in this grammar."); - } - return nextPossibleTokensAfter([startRuleGast], precedingInput, this.tokenMatcher, this.maxLookahead); - }; - // TODO: should this be a member method or a utility? it does not have any state or usage of 'this'... - // TODO: should this be more explicitly part of the public API? - ContentAssist.prototype.getNextPossibleTokenTypes = function (grammarPath) { - var topRuleName = first$1(grammarPath.ruleStack); - var gastProductions = this.getGAstProductions(); - var topProduction = gastProductions[topRuleName]; - var nextPossibleTokenTypes = new NextAfterTokenWalker(topProduction, grammarPath).startWalking(); - return nextPossibleTokenTypes; - }; - return ContentAssist; -}()); - -var RECORDING_NULL_OBJECT = { - description: "This Object indicates the Parser is during Recording Phase" -}; -Object.freeze(RECORDING_NULL_OBJECT); -var HANDLE_SEPARATOR = true; -var MAX_METHOD_IDX = Math.pow(2, BITS_FOR_OCCURRENCE_IDX) - 1; -var RFT = createToken$1({ name: "RECORDING_PHASE_TOKEN", pattern: Lexer$1.NA }); -augmentTokenTypes([RFT]); -var RECORDING_PHASE_TOKEN = createTokenInstance(RFT, "This IToken indicates the Parser is in Recording Phase\n\t" + - "" + - "See: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details", -// Using "-1" instead of NaN (as in EOF) because an actual number is less likely to -// cause errors if the output of LA or CONSUME would be (incorrectly) used during the recording phase. --1, -1, -1, -1, -1, -1); -Object.freeze(RECORDING_PHASE_TOKEN); -var RECORDING_PHASE_CSTNODE = { - name: "This CSTNode indicates the Parser is in Recording Phase\n\t" + - "See: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details", - children: {} -}; -/** - * This trait handles the creation of the GAST structure for Chevrotain Grammars - */ -var GastRecorder = /** @class */ (function () { - function GastRecorder() { - } - GastRecorder.prototype.initGastRecorder = function (config) { - this.recordingProdStack = []; - this.RECORDING_PHASE = false; - }; - GastRecorder.prototype.enableRecording = function () { - var _this = this; - this.RECORDING_PHASE = true; - this.TRACE_INIT("Enable Recording", function () { - var _loop_1 = function (i) { - var idx = i > 0 ? i : ""; - _this["CONSUME" + idx] = function (arg1, arg2) { - return this.consumeInternalRecord(arg1, i, arg2); - }; - _this["SUBRULE" + idx] = function (arg1, arg2) { - return this.subruleInternalRecord(arg1, i, arg2); - }; - _this["OPTION" + idx] = function (arg1) { - return this.optionInternalRecord(arg1, i); - }; - _this["OR" + idx] = function (arg1) { - return this.orInternalRecord(arg1, i); - }; - _this["MANY" + idx] = function (arg1) { - this.manyInternalRecord(i, arg1); - }; - _this["MANY_SEP" + idx] = function (arg1) { - this.manySepFirstInternalRecord(i, arg1); - }; - _this["AT_LEAST_ONE" + idx] = function (arg1) { - this.atLeastOneInternalRecord(i, arg1); - }; - _this["AT_LEAST_ONE_SEP" + idx] = function (arg1) { - this.atLeastOneSepFirstInternalRecord(i, arg1); - }; - }; - /** - * Warning Dark Voodoo Magic upcoming! - * We are "replacing" the public parsing DSL methods API - * With **new** alternative implementations on the Parser **instance** - * - * So far this is the only way I've found to avoid performance regressions during parsing time. - * - Approx 30% performance regression was measured on Chrome 75 Canary when attempting to replace the "internal" - * implementations directly instead. - */ - for (var i = 0; i < 10; i++) { - _loop_1(i); - } - // DSL methods with the idx(suffix) as an argument - _this["consume"] = function (idx, arg1, arg2) { - return this.consumeInternalRecord(arg1, idx, arg2); - }; - _this["subrule"] = function (idx, arg1, arg2) { - return this.subruleInternalRecord(arg1, idx, arg2); - }; - _this["option"] = function (idx, arg1) { - return this.optionInternalRecord(arg1, idx); - }; - _this["or"] = function (idx, arg1) { - return this.orInternalRecord(arg1, idx); - }; - _this["many"] = function (idx, arg1) { - this.manyInternalRecord(idx, arg1); - }; - _this["atLeastOne"] = function (idx, arg1) { - this.atLeastOneInternalRecord(idx, arg1); - }; - _this.ACTION = _this.ACTION_RECORD; - _this.BACKTRACK = _this.BACKTRACK_RECORD; - _this.LA = _this.LA_RECORD; - }); - }; - GastRecorder.prototype.disableRecording = function () { - var _this = this; - this.RECORDING_PHASE = false; - // By deleting these **instance** properties, any future invocation - // will be deferred to the original methods on the **prototype** object - // This seems to get rid of any incorrect optimizations that V8 may - // do during the recording phase. - this.TRACE_INIT("Deleting Recording methods", function () { - for (var i = 0; i < 10; i++) { - var idx = i > 0 ? i : ""; - delete _this["CONSUME" + idx]; - delete _this["SUBRULE" + idx]; - delete _this["OPTION" + idx]; - delete _this["OR" + idx]; - delete _this["MANY" + idx]; - delete _this["MANY_SEP" + idx]; - delete _this["AT_LEAST_ONE" + idx]; - delete _this["AT_LEAST_ONE_SEP" + idx]; - } - delete _this["consume"]; - delete _this["subrule"]; - delete _this["option"]; - delete _this["or"]; - delete _this["many"]; - delete _this["atLeastOne"]; - delete _this.ACTION; - delete _this.BACKTRACK; - delete _this.LA; - }); - }; - // TODO: is there any way to use this method to check no - // Parser methods are called inside an ACTION? - // Maybe try/catch/finally on ACTIONS while disabling the recorders state changes? - GastRecorder.prototype.ACTION_RECORD = function (impl) { - // NO-OP during recording - return; - }; - // Executing backtracking logic will break our recording logic assumptions - GastRecorder.prototype.BACKTRACK_RECORD = function (grammarRule, args) { - return function () { return true; }; - }; - // LA is part of the official API and may be used for custom lookahead logic - // by end users who may forget to wrap it in ACTION or inside a GATE - GastRecorder.prototype.LA_RECORD = function (howMuch) { - // We cannot use the RECORD_PHASE_TOKEN here because someone may depend - // On LA return EOF at the end of the input so an infinite loop may occur. - return END_OF_FILE; - }; - GastRecorder.prototype.topLevelRuleRecord = function (name, def) { - try { - var newTopLevelRule = new Rule({ definition: [], name: name }); - newTopLevelRule.name = name; - this.recordingProdStack.push(newTopLevelRule); - def.call(this); - this.recordingProdStack.pop(); - return newTopLevelRule; - } - catch (originalError) { - if (originalError.KNOWN_RECORDER_ERROR !== true) { - try { - originalError.message = - originalError.message + - '\n\t This error was thrown during the "grammar recording phase" For more info see:\n\t' + - "https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording"; - } - catch (mutabilityError) { - // We may not be able to modify the original error object - throw originalError; - } - } - throw originalError; - } - }; - // Implementation of parsing DSL - GastRecorder.prototype.optionInternalRecord = function (actionORMethodDef, occurrence) { - return recordProd.call(this, Option, actionORMethodDef, occurrence); - }; - GastRecorder.prototype.atLeastOneInternalRecord = function (occurrence, actionORMethodDef) { - recordProd.call(this, RepetitionMandatory, actionORMethodDef, occurrence); - }; - GastRecorder.prototype.atLeastOneSepFirstInternalRecord = function (occurrence, options) { - recordProd.call(this, RepetitionMandatoryWithSeparator, options, occurrence, HANDLE_SEPARATOR); - }; - GastRecorder.prototype.manyInternalRecord = function (occurrence, actionORMethodDef) { - recordProd.call(this, Repetition, actionORMethodDef, occurrence); - }; - GastRecorder.prototype.manySepFirstInternalRecord = function (occurrence, options) { - recordProd.call(this, RepetitionWithSeparator, options, occurrence, HANDLE_SEPARATOR); - }; - GastRecorder.prototype.orInternalRecord = function (altsOrOpts, occurrence) { - return recordOrProd.call(this, altsOrOpts, occurrence); - }; - GastRecorder.prototype.subruleInternalRecord = function (ruleToCall, occurrence, options) { - assertMethodIdxIsValid(occurrence); - if (!ruleToCall || has(ruleToCall, "ruleName") === false) { - var error = new Error(" argument is invalid" + - (" expecting a Parser method reference but got: <" + JSON.stringify(ruleToCall) + ">") + - ("\n inside top level rule: <" + this.recordingProdStack[0].name + ">")); - error.KNOWN_RECORDER_ERROR = true; - throw error; - } - var prevProd = peek(this.recordingProdStack); - var ruleName = ruleToCall["ruleName"]; - var newNoneTerminal = new NonTerminal({ - idx: occurrence, - nonTerminalName: ruleName, - // The resolving of the `referencedRule` property will be done once all the Rule's GASTs have been created - referencedRule: undefined - }); - prevProd.definition.push(newNoneTerminal); - return this.outputCst ? RECORDING_PHASE_CSTNODE : RECORDING_NULL_OBJECT; - }; - GastRecorder.prototype.consumeInternalRecord = function (tokType, occurrence, options) { - assertMethodIdxIsValid(occurrence); - if (!hasShortKeyProperty(tokType)) { - var error = new Error(" argument is invalid" + - (" expecting a TokenType reference but got: <" + JSON.stringify(tokType) + ">") + - ("\n inside top level rule: <" + this.recordingProdStack[0].name + ">")); - error.KNOWN_RECORDER_ERROR = true; - throw error; - } - var prevProd = peek(this.recordingProdStack); - var newNoneTerminal = new Terminal({ - idx: occurrence, - terminalType: tokType - }); - prevProd.definition.push(newNoneTerminal); - return RECORDING_PHASE_TOKEN; - }; - return GastRecorder; -}()); -function recordProd(prodConstructor, mainProdArg, occurrence, handleSep) { - if (handleSep === void 0) { handleSep = false; } - assertMethodIdxIsValid(occurrence); - var prevProd = peek(this.recordingProdStack); - var grammarAction = isFunction(mainProdArg) ? mainProdArg : mainProdArg.DEF; - var newProd = new prodConstructor({ definition: [], idx: occurrence }); - if (handleSep) { - newProd.separator = mainProdArg.SEP; - } - if (has(mainProdArg, "MAX_LOOKAHEAD")) { - newProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD; - } - this.recordingProdStack.push(newProd); - grammarAction.call(this); - prevProd.definition.push(newProd); - this.recordingProdStack.pop(); - return RECORDING_NULL_OBJECT; -} -function recordOrProd(mainProdArg, occurrence) { - var _this = this; - assertMethodIdxIsValid(occurrence); - var prevProd = peek(this.recordingProdStack); - // Only an array of alternatives - var hasOptions = isArray(mainProdArg) === false; - var alts = hasOptions === false ? mainProdArg : mainProdArg.DEF; - var newOrProd = new Alternation({ - definition: [], - idx: occurrence, - ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true - }); - if (has(mainProdArg, "MAX_LOOKAHEAD")) { - newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD; - } - var hasPredicates = some(alts, function (currAlt) { return isFunction(currAlt.GATE); }); - newOrProd.hasPredicates = hasPredicates; - prevProd.definition.push(newOrProd); - forEach(alts, function (currAlt) { - var currAltFlat = new Alternative({ definition: [] }); - newOrProd.definition.push(currAltFlat); - if (has(currAlt, "IGNORE_AMBIGUITIES")) { - currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES; - } - // **implicit** ignoreAmbiguities due to usage of gate - else if (has(currAlt, "GATE")) { - currAltFlat.ignoreAmbiguities = true; - } - _this.recordingProdStack.push(currAltFlat); - currAlt.ALT.call(_this); - _this.recordingProdStack.pop(); - }); - return RECORDING_NULL_OBJECT; -} -function getIdxSuffix(idx) { - return idx === 0 ? "" : "" + idx; -} -function assertMethodIdxIsValid(idx) { - if (idx < 0 || idx > MAX_METHOD_IDX) { - var error = new Error( - // The stack trace will contain all the needed details - "Invalid DSL Method idx value: <" + idx + ">\n\t" + - ("Idx value must be a none negative value smaller than " + (MAX_METHOD_IDX + 1))); - error.KNOWN_RECORDER_ERROR = true; - throw error; - } -} - -/** - * Trait responsible for runtime parsing errors. - */ -var PerformanceTracer = /** @class */ (function () { - function PerformanceTracer() { - } - PerformanceTracer.prototype.initPerformanceTracer = function (config) { - if (has(config, "traceInitPerf")) { - var userTraceInitPerf = config.traceInitPerf; - var traceIsNumber = typeof userTraceInitPerf === "number"; - this.traceInitMaxIdent = traceIsNumber - ? userTraceInitPerf - : Infinity; - this.traceInitPerf = traceIsNumber - ? userTraceInitPerf > 0 - : userTraceInitPerf; - } - else { - this.traceInitMaxIdent = 0; - this.traceInitPerf = DEFAULT_PARSER_CONFIG.traceInitPerf; - } - this.traceInitIndent = -1; - }; - PerformanceTracer.prototype.TRACE_INIT = function (phaseDesc, phaseImpl) { - // No need to optimize this using NOOP pattern because - // It is not called in a hot spot... - if (this.traceInitPerf === true) { - this.traceInitIndent++; - var indent = new Array(this.traceInitIndent + 1).join("\t"); - if (this.traceInitIndent < this.traceInitMaxIdent) { - console.log(indent + "--> <" + phaseDesc + ">"); - } - var _a = timer(phaseImpl), time = _a.time, value = _a.value; - /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */ - var traceMethod = time > 10 ? console.warn : console.log; - if (this.traceInitIndent < this.traceInitMaxIdent) { - traceMethod(indent + "<-- <" + phaseDesc + "> time: " + time + "ms"); - } - this.traceInitIndent--; - return value; - } - else { - return phaseImpl(); - } - }; - return PerformanceTracer; -}()); - -var __extends = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var END_OF_FILE = createTokenInstance(EOF, "", NaN, NaN, NaN, NaN, NaN, NaN); -Object.freeze(END_OF_FILE); -var DEFAULT_PARSER_CONFIG = Object.freeze({ - recoveryEnabled: false, - maxLookahead: 3, - dynamicTokensEnabled: false, - outputCst: true, - errorMessageProvider: defaultParserErrorProvider, - nodeLocationTracking: "none", - traceInitPerf: false, - skipValidations: false -}); -var DEFAULT_RULE_CONFIG = Object.freeze({ - recoveryValueFunc: function () { return undefined; }, - resyncEnabled: true -}); -var ParserDefinitionErrorType; -(function (ParserDefinitionErrorType) { - ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_NAME"] = 0] = "INVALID_RULE_NAME"; - ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_RULE_NAME"] = 1] = "DUPLICATE_RULE_NAME"; - ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_OVERRIDE"] = 2] = "INVALID_RULE_OVERRIDE"; - ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_PRODUCTIONS"] = 3] = "DUPLICATE_PRODUCTIONS"; - ParserDefinitionErrorType[ParserDefinitionErrorType["UNRESOLVED_SUBRULE_REF"] = 4] = "UNRESOLVED_SUBRULE_REF"; - ParserDefinitionErrorType[ParserDefinitionErrorType["LEFT_RECURSION"] = 5] = "LEFT_RECURSION"; - ParserDefinitionErrorType[ParserDefinitionErrorType["NONE_LAST_EMPTY_ALT"] = 6] = "NONE_LAST_EMPTY_ALT"; - ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_ALTS"] = 7] = "AMBIGUOUS_ALTS"; - ParserDefinitionErrorType[ParserDefinitionErrorType["CONFLICT_TOKENS_RULES_NAMESPACE"] = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE"; - ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_TOKEN_NAME"] = 9] = "INVALID_TOKEN_NAME"; - ParserDefinitionErrorType[ParserDefinitionErrorType["NO_NON_EMPTY_LOOKAHEAD"] = 10] = "NO_NON_EMPTY_LOOKAHEAD"; - ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_PREFIX_ALTS"] = 11] = "AMBIGUOUS_PREFIX_ALTS"; - ParserDefinitionErrorType[ParserDefinitionErrorType["TOO_MANY_ALTS"] = 12] = "TOO_MANY_ALTS"; -})(ParserDefinitionErrorType || (ParserDefinitionErrorType = {})); -function EMPTY_ALT(value) { - if (value === void 0) { value = undefined; } - return function () { - return value; - }; -} -var Parser$2 = /** @class */ (function () { - function Parser(tokenVocabulary, config) { - this.definitionErrors = []; - this.selfAnalysisDone = false; - var that = this; - that.initErrorHandler(config); - that.initLexerAdapter(); - that.initLooksAhead(config); - that.initRecognizerEngine(tokenVocabulary, config); - that.initRecoverable(config); - that.initTreeBuilder(config); - that.initContentAssist(); - that.initGastRecorder(config); - that.initPerformanceTracer(config); - if (has(config, "ignoredIssues")) { - throw new Error("The IParserConfig property has been deprecated.\n\t" + - "Please use the flag on the relevant DSL method instead.\n\t" + - "See: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES\n\t" + - "For further details."); - } - this.skipValidations = has(config, "skipValidations") - ? config.skipValidations - : DEFAULT_PARSER_CONFIG.skipValidations; - } - /** - * @deprecated use the **instance** method with the same name instead - */ - Parser.performSelfAnalysis = function (parserInstance) { - throw Error("The **static** `performSelfAnalysis` method has been deprecated." + - "\t\nUse the **instance** method with the same name instead."); - }; - Parser.prototype.performSelfAnalysis = function () { - var _this = this; - this.TRACE_INIT("performSelfAnalysis", function () { - var defErrorsMsgs; - _this.selfAnalysisDone = true; - var className = _this.className; - _this.TRACE_INIT("toFastProps", function () { - // Without this voodoo magic the parser would be x3-x4 slower - // It seems it is better to invoke `toFastProperties` **before** - // Any manipulations of the `this` object done during the recording phase. - toFastProperties(_this); - }); - _this.TRACE_INIT("Grammar Recording", function () { - try { - _this.enableRecording(); - // Building the GAST - forEach(_this.definedRulesNames, function (currRuleName) { - var wrappedRule = _this[currRuleName]; - var originalGrammarAction = wrappedRule["originalGrammarAction"]; - var recordedRuleGast = undefined; - _this.TRACE_INIT(currRuleName + " Rule", function () { - recordedRuleGast = _this.topLevelRuleRecord(currRuleName, originalGrammarAction); - }); - _this.gastProductionsCache[currRuleName] = recordedRuleGast; - }); - } - finally { - _this.disableRecording(); - } - }); - var resolverErrors = []; - _this.TRACE_INIT("Grammar Resolving", function () { - resolverErrors = resolveGrammar({ - rules: values(_this.gastProductionsCache) - }); - _this.definitionErrors.push.apply(_this.definitionErrors, resolverErrors); // mutability for the win? - }); - _this.TRACE_INIT("Grammar Validations", function () { - // only perform additional grammar validations IFF no resolving errors have occurred. - // as unresolved grammar may lead to unhandled runtime exceptions in the follow up validations. - if (isEmpty(resolverErrors) && _this.skipValidations === false) { - var validationErrors = validateGrammar({ - rules: values(_this.gastProductionsCache), - maxLookahead: _this.maxLookahead, - tokenTypes: values(_this.tokensMap), - errMsgProvider: defaultGrammarValidatorErrorProvider, - grammarName: className - }); - _this.definitionErrors.push.apply(_this.definitionErrors, validationErrors); // mutability for the win? - } - }); - // this analysis may fail if the grammar is not perfectly valid - if (isEmpty(_this.definitionErrors)) { - // The results of these computations are not needed unless error recovery is enabled. - if (_this.recoveryEnabled) { - _this.TRACE_INIT("computeAllProdsFollows", function () { - var allFollows = computeAllProdsFollows(values(_this.gastProductionsCache)); - _this.resyncFollows = allFollows; - }); - } - _this.TRACE_INIT("ComputeLookaheadFunctions", function () { - _this.preComputeLookaheadFunctions(values(_this.gastProductionsCache)); - }); - } - if (!Parser.DEFER_DEFINITION_ERRORS_HANDLING && - !isEmpty(_this.definitionErrors)) { - defErrorsMsgs = map(_this.definitionErrors, function (defError) { return defError.message; }); - throw new Error("Parser Definition Errors detected:\n " + defErrorsMsgs.join("\n-------------------------------\n")); - } - }); - }; - // Set this flag to true if you don't want the Parser to throw error when problems in it's definition are detected. - // (normally during the parser's constructor). - // This is a design time flag, it will not affect the runtime error handling of the parser, just design time errors, - // for example: duplicate rule names, referencing an unresolved subrule, ect... - // This flag should not be enabled during normal usage, it is used in special situations, for example when - // needing to display the parser definition errors in some GUI(online playground). - Parser.DEFER_DEFINITION_ERRORS_HANDLING = false; - return Parser; -}()); -applyMixins(Parser$2, [ - Recoverable, - LooksAhead, - TreeBuilder, - LexerAdapter, - RecognizerEngine, - RecognizerApi, - ErrorHandler, - ContentAssist, - GastRecorder, - PerformanceTracer -]); -var CstParser$1 = /** @class */ (function (_super) { - __extends(CstParser, _super); - function CstParser(tokenVocabulary, config) { - if (config === void 0) { config = DEFAULT_PARSER_CONFIG; } - var _this = this; - var configClone = cloneObj(config); - configClone.outputCst = true; - _this = _super.call(this, tokenVocabulary, configClone) || this; - return _this; - } - return CstParser; -}(Parser$2)); -var EmbeddedActionsParser = /** @class */ (function (_super) { - __extends(EmbeddedActionsParser, _super); - function EmbeddedActionsParser(tokenVocabulary, config) { - if (config === void 0) { config = DEFAULT_PARSER_CONFIG; } - var _this = this; - var configClone = cloneObj(config); - configClone.outputCst = false; - _this = _super.call(this, tokenVocabulary, configClone) || this; - return _this; - } - return EmbeddedActionsParser; -}(Parser$2)); - -function createSyntaxDiagramsCode(grammar, _a) { - var _b = _a === void 0 ? {} : _a, _c = _b.resourceBase, resourceBase = _c === void 0 ? "https://unpkg.com/chevrotain@" + VERSION + "/diagrams/" : _c, _d = _b.css, css = _d === void 0 ? "https://unpkg.com/chevrotain@" + VERSION + "/diagrams/diagrams.css" : _d; - var header = "\n\n\n\n\n\n"; - var cssHtml = "\n\n"; - var scripts = "\n\n\n\n\n"; - var diagramsDiv = "\n
\n"; - var serializedGrammar = "\n\n"; - var initLogic = "\n\n"; - return (header + cssHtml + scripts + diagramsDiv + serializedGrammar + initLogic); -} - -/** - * Missing features - * 1. Rule arguments - * 2. Gates - * 3. embedded actions - */ -var NL = "\n"; -function genUmdModule(options) { - return "\n(function (root, factory) {\n if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define(['chevrotain'], factory);\n } else if (typeof module === 'object' && module.exports) {\n // Node. Does not work with strict CommonJS, but\n // only CommonJS-like environments that support module.exports,\n // like Node.\n module.exports = factory(require('chevrotain'));\n } else {\n // Browser globals (root is window)\n root.returnExports = factory(root.b);\n }\n}(typeof self !== 'undefined' ? self : this, function (chevrotain) {\n\n" + genClass(options) + "\n \nreturn {\n " + options.name + ": " + options.name + " \n}\n}));\n"; -} -function genWrapperFunction(options) { - return " \n" + genClass(options) + "\nreturn new " + options.name + "(tokenVocabulary, config) \n"; -} -function genClass(options) { - // TODO: how to pass the token vocabulary? Constructor? other? - var result = "\nfunction " + options.name + "(tokenVocabulary, config) {\n // invoke super constructor\n // No support for embedded actions currently, so we can 'hardcode'\n // The use of CstParser.\n chevrotain.CstParser.call(this, tokenVocabulary, config)\n\n const $ = this\n\n " + genAllRules(options.rules) + "\n\n // very important to call this after all the rules have been defined.\n // otherwise the parser may not work correctly as it will lack information\n // derived during the self analysis phase.\n this.performSelfAnalysis(this)\n}\n\n// inheritance as implemented in javascript in the previous decade... :(\n" + options.name + ".prototype = Object.create(chevrotain.CstParser.prototype)\n" + options.name + ".prototype.constructor = " + options.name + " \n "; - return result; -} -function genAllRules(rules) { - var rulesText = map(rules, function (currRule) { - return genRule(currRule, 1); - }); - return rulesText.join("\n"); -} -function genRule(prod, n) { - var result = indent$2(n, "$.RULE(\"" + prod.name + "\", function() {") + NL; - result += genDefinition(prod.definition, n + 1); - result += indent$2(n + 1, "})") + NL; - return result; -} -function genTerminal(prod, n) { - var name = prod.terminalType.name; - // TODO: potential performance optimization, avoid tokenMap Dictionary access - return indent$2(n, "$.CONSUME" + prod.idx + "(this.tokensMap." + name + ")" + NL); -} -function genNonTerminal(prod, n) { - return indent$2(n, "$.SUBRULE" + prod.idx + "($." + prod.nonTerminalName + ")" + NL); -} -function genAlternation(prod, n) { - var result = indent$2(n, "$.OR" + prod.idx + "([") + NL; - var alts = map(prod.definition, function (altDef) { return genSingleAlt(altDef, n + 1); }); - result += alts.join("," + NL); - result += NL + indent$2(n, "])" + NL); - return result; -} -function genSingleAlt(prod, n) { - var result = indent$2(n, "{") + NL; - result += indent$2(n + 1, "ALT: function() {") + NL; - result += genDefinition(prod.definition, n + 1); - result += indent$2(n + 1, "}") + NL; - result += indent$2(n, "}"); - return result; -} -function genProd(prod, n) { - /* istanbul ignore else */ - if (prod instanceof NonTerminal) { - return genNonTerminal(prod, n); - } - else if (prod instanceof Option) { - return genDSLRule("OPTION", prod, n); - } - else if (prod instanceof RepetitionMandatory) { - return genDSLRule("AT_LEAST_ONE", prod, n); - } - else if (prod instanceof RepetitionMandatoryWithSeparator) { - return genDSLRule("AT_LEAST_ONE_SEP", prod, n); - } - else if (prod instanceof RepetitionWithSeparator) { - return genDSLRule("MANY_SEP", prod, n); - } - else if (prod instanceof Repetition) { - return genDSLRule("MANY", prod, n); - } - else if (prod instanceof Alternation) { - return genAlternation(prod, n); - } - else if (prod instanceof Terminal) { - return genTerminal(prod, n); - } - else if (prod instanceof Alternative) { - return genDefinition(prod.definition, n); - } - else { - throw Error("non exhaustive match"); - } -} -function genDSLRule(dslName, prod, n) { - var result = indent$2(n, "$." + (dslName + prod.idx) + "("); - if (prod.separator) { - result += "{" + NL; - result += - indent$2(n + 1, "SEP: this.tokensMap." + prod.separator.name) + "," + NL; - result += "DEF: " + genDefFunction(prod.definition, n + 2) + NL; - result += indent$2(n, "}") + NL; - } - else { - result += genDefFunction(prod.definition, n + 1); - } - result += indent$2(n, ")") + NL; - return result; -} -function genDefFunction(definition, n) { - var def = "function() {" + NL; - def += genDefinition(definition, n); - def += indent$2(n, "}") + NL; - return def; -} -function genDefinition(def, n) { - var result = ""; - forEach(def, function (prod) { - result += genProd(prod, n + 1); - }); - return result; -} -function indent$2(howMuch, text) { - var spaces = Array(howMuch * 4 + 1).join(" "); - return spaces + text; -} - -function generateParserFactory(options) { - var wrapperText = genWrapperFunction({ - name: options.name, - rules: options.rules - }); - var constructorWrapper = new Function("tokenVocabulary", "config", "chevrotain", wrapperText); - return function (config) { - return constructorWrapper(options.tokenVocabulary, config, - // TODO: check how the require is transpiled/webpacked - require("../api")); - }; -} -function generateParserModule(options) { - return genUmdModule({ name: options.name, rules: options.rules }); -} - -/* istanbul ignore file - tricky to import some things from this module during testing */ -/* istanbul ignore next */ -function clearCache() { - console.warn("The clearCache function was 'soft' removed from the Chevrotain API." + - "\n\t It performs no action other than printing this message." + - "\n\t Please avoid using it as it will be completely removed in the future"); -} -var Parser$1 = /** @class */ (function () { - function Parser() { - throw new Error("The Parser class has been deprecated, use CstParser or EmbeddedActionsParser instead.\t\n" + - "See: https://sap.github.io/chevrotain/docs/changes/BREAKING_CHANGES.html#_7-0-0"); - } - return Parser; -}()); - -var api$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - clearCache: clearCache, - Parser: Parser$1, - VERSION: VERSION, - CstParser: CstParser$1, - EmbeddedActionsParser: EmbeddedActionsParser, - get ParserDefinitionErrorType () { return ParserDefinitionErrorType; }, - EMPTY_ALT: EMPTY_ALT, - Lexer: Lexer$1, - get LexerDefinitionErrorType () { return LexerDefinitionErrorType; }, - createToken: createToken$1, - createTokenInstance: createTokenInstance, - EOF: EOF, - tokenLabel: tokenLabel, - tokenMatcher: tokenMatcher$1, - tokenName: tokenName, - defaultGrammarResolverErrorProvider: defaultGrammarResolverErrorProvider, - defaultGrammarValidatorErrorProvider: defaultGrammarValidatorErrorProvider, - defaultParserErrorProvider: defaultParserErrorProvider, - EarlyExitException: EarlyExitException, - isRecognitionException: isRecognitionException, - MismatchedTokenException: MismatchedTokenException, - NotAllInputParsedException: NotAllInputParsedException, - NoViableAltException: NoViableAltException, - defaultLexerErrorProvider: defaultLexerErrorProvider, - Alternation: Alternation, - Alternative: Alternative, - NonTerminal: NonTerminal, - Option: Option, - Repetition: Repetition, - RepetitionMandatory: RepetitionMandatory, - RepetitionMandatoryWithSeparator: RepetitionMandatoryWithSeparator, - RepetitionWithSeparator: RepetitionWithSeparator, - Rule: Rule, - Terminal: Terminal, - serializeGrammar: serializeGrammar, - serializeProduction: serializeProduction, - GAstVisitor: GAstVisitor, - assignOccurrenceIndices: assignOccurrenceIndices, - resolveGrammar: resolveGrammar, - validateGrammar: validateGrammar, - createSyntaxDiagramsCode: createSyntaxDiagramsCode, - generateParserFactory: generateParserFactory, - generateParserModule: generateParserModule -}); - -var require$$0 = /*@__PURE__*/getAugmentedNamespace(api$1); - -const { createToken: createTokenOrg, Lexer } = require$$0; - -// A little mini DSL for easier lexer definition. -const fragments = {}; -const f = fragments; - -function FRAGMENT(name, def) { - fragments[name] = typeof def === "string" ? def : def.source; -} - -function makePattern(strings, ...args) { - let combined = ""; - for (let i = 0; i < strings.length; i++) { - combined += strings[i]; - if (i < args.length) { - let pattern = args[i]; - // By wrapping in a RegExp (none) capturing group - // We enabled the safe usage of qualifiers and assertions. - combined += `(?:${pattern})`; - } - } - return new RegExp(combined); -} -const tokensDictionary = {}; - -function createToken(options) { - const newTokenType = createTokenOrg(options); - tokensDictionary[options.name] = newTokenType; - return newTokenType; -} - -FRAGMENT( - "NameStartChar", - "(:|[a-zA-Z]|_|\\u2070-\\u218F|\\u2C00-\\u2FEF|\\u3001-\\uD7FF|\\uF900-\\uFDCF|\\uFDF0-\\uFFFD)" -); - -FRAGMENT( - "NameChar", - makePattern`${f.NameStartChar}|-|\\.|\\d|\\u00B7||[\\u0300-\\u036F]|[\\u203F-\\u2040]` -); -FRAGMENT("Name", makePattern`${f.NameStartChar}(${f.NameChar})*`); - -const Comment = createToken({ - name: "Comment", - pattern: //, - // A Comment may span multiple lines. - line_breaks: true, -}); - -const CData = createToken({ - name: "CData", - pattern: //, - line_breaks: true, -}); - -const DocType = createToken({ - name: "DocType", - pattern: //, - group: Lexer.SKIPPED, -}); - -const EntityRef = createToken({ - name: "EntityRef", - pattern: makePattern`&${f.Name};`, -}); - -const CharRef = createToken({ - name: "CharRef", - pattern: /&#\d+;|&#x[a-fA-F0-9]/, -}); - -const SEA_WS = createToken({ - name: "SEA_WS", - pattern: /( |\t|\n|\r\n)+/, -}); - -const XMLDeclOpen = createToken({ - name: "XMLDeclOpen", - pattern: /<\?xml[ \t\r\n]/, - push_mode: "INSIDE", -}); - -const SLASH_OPEN = createToken({ - name: "SLASH_OPEN", - pattern: /<\//, - push_mode: "INSIDE", -}); - -const INVALID_SLASH_OPEN = createToken({ - name: "INVALID_SLASH_OPEN", - pattern: /<\//, - categories: [SLASH_OPEN], -}); - -const PROCESSING_INSTRUCTION = createToken({ - name: "PROCESSING_INSTRUCTION", - pattern: makePattern`<\\?${f.Name}.*\\?>`, -}); - -const OPEN = createToken({ name: "OPEN", pattern: /john -// - The second '<' will be skipped because in the mode "INSIDE" '<' is not recognized. -// - This means the AST will include only a single element instead of two -const INVALID_OPEN_INSIDE = createToken({ - name: "INVALID_OPEN_INSIDE", - pattern: //, pop_mode: true }); - -const SPECIAL_CLOSE = createToken({ - name: "SPECIAL_CLOSE", - pattern: /\?>/, - pop_mode: true, -}); - -const SLASH_CLOSE = createToken({ - name: "SLASH_CLOSE", - pattern: /\/>/, - pop_mode: true, -}); - -const SLASH = createToken({ name: "SLASH", pattern: /\// }); - -const STRING = createToken({ - name: "STRING", - pattern: /"[^<"]*"|'[^<']*'/, -}); - -const EQUALS = createToken({ name: "EQUALS", pattern: /=/ }); - -const Name = createToken({ name: "Name", pattern: makePattern`${f.Name}` }); - -const S = createToken({ - name: "S", - pattern: /[ \t\r\n]/, - group: Lexer.SKIPPED, -}); - -const xmlLexerDefinition = { - defaultMode: "OUTSIDE", - - modes: { - OUTSIDE: [ - Comment, - CData, - DocType, - IgnoredDTD, - EntityRef, - CharRef, - SEA_WS, - XMLDeclOpen, - SLASH_OPEN, - PROCESSING_INSTRUCTION, - OPEN, - TEXT, - ], - INSIDE: [ - // Tokens from `OUTSIDE` to improve error recovery behavior - Comment, - INVALID_SLASH_OPEN, - INVALID_OPEN_INSIDE, - // "Real" `INSIDE` tokens - CLOSE, - SPECIAL_CLOSE, - SLASH_CLOSE, - SLASH, - EQUALS, - STRING, - Name, - S, - ], - }, -}; - -const xmlLexer$1 = new Lexer(xmlLexerDefinition, { - // Reducing the amount of position tracking can provide a small performance boost (<10%) - // Likely best to keep the full info for better error position reporting and - // to expose "fuller" ITokens from the Lexer. - positionTracking: "full", - ensureOptimizations: false, - - // TODO: inspect definitions for XML line terminators - lineTerminatorCharacters: ["\n"], - lineTerminatorsPattern: /\n|\r\n/g, -}); - -var lexer = { - xmlLexer: xmlLexer$1, - tokensDictionary, -}; - -const { CstParser, tokenMatcher } = require$$0; -const { tokensDictionary: t } = lexer; - -class Parser extends CstParser { - constructor() { - super(t, { - maxLookahead: 1, - recoveryEnabled: true, - nodeLocationTracking: "full", - }); - - this.deletionRecoveryEnabled = true; - - const $ = this; - - $.RULE("document", () => { - $.OPTION(() => { - $.SUBRULE($.prolog); - }); - - $.MANY(() => { - $.SUBRULE($.misc); - }); - - $.OPTION2(() => { - $.SUBRULE($.docTypeDecl); - }); - - $.MANY2(() => { - $.SUBRULE2($.misc); - }); - - $.SUBRULE($.element); - - $.MANY3(() => { - $.SUBRULE3($.misc); - }); - }); - - $.RULE("prolog", () => { - $.CONSUME(t.XMLDeclOpen); - $.MANY(() => { - $.SUBRULE($.attribute); - }); - $.CONSUME(t.SPECIAL_CLOSE); - }); - - // https://www.w3.org/TR/xml/#NT-doctypedecl - $.RULE("docTypeDecl", () => { - $.CONSUME(t.DocType); - $.CONSUME(t.Name); - - $.OPTION(() => { - $.SUBRULE($.externalID); - }); - - // The internal subSet part is intentionally not implemented because we do not at this - // time wish to implement a full DTD Parser as part of this project... - // https://www.w3.org/TR/xml/#NT-intSubset - - $.CONSUME(t.CLOSE); - }); - - $.RULE("externalID", () => { - // Using gates to assert the value of the "Name" Identifiers. - // We could use Categories to model un-reserved keywords, however I am not sure - // The added complexity is needed at this time... - $.OR([ - { - GATE: () => $.LA(1).image === "SYSTEM", - ALT: () => { - $.CONSUME2(t.Name, { LABEL: "System" }); - $.CONSUME(t.STRING, { LABEL: "SystemLiteral" }); - }, - }, - { - GATE: () => $.LA(1).image === "PUBLIC", - ALT: () => { - $.CONSUME3(t.Name, { LABEL: "Public" }); - $.CONSUME2(t.STRING, { LABEL: "PubIDLiteral" }); - $.CONSUME3(t.STRING, { LABEL: "SystemLiteral" }); - }, - }, - ]); - }); - - $.RULE("content", () => { - $.MANY(() => { - $.OR([ - { ALT: () => $.SUBRULE($.element) }, - { ALT: () => $.SUBRULE($.chardata) }, - { ALT: () => $.SUBRULE($.reference) }, - { ALT: () => $.CONSUME(t.CData) }, - { ALT: () => $.CONSUME(t.PROCESSING_INSTRUCTION) }, - { ALT: () => $.CONSUME(t.Comment) }, - ]); - }); - }); - - $.RULE("element", () => { - $.CONSUME(t.OPEN); - try { - this.deletionRecoveryEnabled = false; - // disabling single token deletion here - // because `< - // ` - // will be parsed as: `` - // and the next element will be lost - $.CONSUME(t.Name); - } finally { - this.deletionRecoveryEnabled = true; - } - $.MANY(() => { - $.SUBRULE($.attribute); - }); - - $.OR([ - { - ALT: () => { - $.CONSUME(t.CLOSE, { LABEL: "START_CLOSE" }); - $.SUBRULE($.content); - $.CONSUME(t.SLASH_OPEN); - $.CONSUME2(t.Name, { LABEL: "END_NAME" }); - $.CONSUME2(t.CLOSE, { LABEL: "END" }); - }, - }, - { - ALT: () => { - $.CONSUME(t.SLASH_CLOSE); - }, - }, - ]); - }); - - $.RULE("reference", () => { - $.OR([ - { ALT: () => $.CONSUME(t.EntityRef) }, - { ALT: () => $.CONSUME(t.CharRef) }, - ]); - }); - - $.RULE("attribute", () => { - $.CONSUME(t.Name); - try { - this.deletionRecoveryEnabled = false; - // disabling single token deletion here - // because `attrib1 attrib2="666` - // will be parsed as: `attrib1="666` - $.CONSUME(t.EQUALS); - // disabling single token deletion here - // to avoid new elementName being - $.CONSUME(t.STRING); - } finally { - this.deletionRecoveryEnabled = true; - } - }); - - $.RULE("chardata", () => { - $.OR([ - { ALT: () => $.CONSUME(t.TEXT) }, - { ALT: () => $.CONSUME(t.SEA_WS) }, - ]); - }); - - $.RULE("misc", () => { - $.OR([ - { ALT: () => $.CONSUME(t.Comment) }, - { ALT: () => $.CONSUME(t.PROCESSING_INSTRUCTION) }, - { ALT: () => $.CONSUME(t.SEA_WS) }, - ]); - }); - - this.performSelfAnalysis(); - } - - canRecoverWithSingleTokenDeletion(expectedTokType) { - if (this.deletionRecoveryEnabled === false) { - return false; - } - return super.canRecoverWithSingleTokenDeletion(expectedTokType); - } - - // TODO: provide this fix upstream to chevrotain - // https://github.com/SAP/chevrotain/issues/1055 - /* istanbul ignore next - should be tested as part of Chevrotain */ - findReSyncTokenType() { - const allPossibleReSyncTokTypes = this.flattenFollowSet(); - // this loop will always terminate as EOF is always in the follow stack and also always (virtually) in the input - let nextToken = this.LA(1); - let k = 2; - /* eslint-disable-next-line no-constant-condition -- see above comment */ - while (true) { - const foundMatch = allPossibleReSyncTokTypes.find((resyncTokType) => { - const canMatch = tokenMatcher(nextToken, resyncTokType); - return canMatch; - }); - if (foundMatch !== undefined) { - return foundMatch; - } - nextToken = this.LA(k); - k++; - } - } -} - -// Re-use the same parser instance -const xmlParser$1 = new Parser(); - -var parser$1 = { - xmlParser: xmlParser$1, -}; - -const { xmlLexer } = lexer; -const { xmlParser } = parser$1; - -var api = { - parse: function parse(text) { - const lexResult = xmlLexer.tokenize(text); - // setting a new input will RESET the parser instance's state. - xmlParser.input = lexResult.tokens; - // any top level rule may be used as an entry point - const cst = xmlParser.document(); - - return { - cst: cst, - tokenVector: lexResult.tokens, - lexErrors: lexResult.errors, - parseErrors: xmlParser.errors, - }; - }, - - BaseXmlCstVisitor: xmlParser.getBaseCstVisitorConstructor(), -}; - -Object.defineProperty(parser$2, "__esModule", { value: true }); -const parser_1$1 = api; -const parser = { - parse(text) { - const { lexErrors, parseErrors, cst } = (0, parser_1$1.parse)(text); - // If there are any lexical errors, throw the first of them as an error. - if (lexErrors.length > 0) { - const lexError = lexErrors[0]; - const error = new Error(lexError.message); - error.loc = { - start: { line: lexError.line, column: lexError.column }, - end: { line: lexError.line, column: lexError.column + lexError.length } - }; - throw error; - } - // If there are any parse errors, throw the first of them as an error. - if (parseErrors.length > 0) { - const parseError = parseErrors[0]; - const error = new Error(parseError.message); - const { token } = parseError; - error.loc = { - start: { line: token.startLine, column: token.startColumn }, - end: { line: token.endLine, column: token.endColumn } - }; - throw error; - } - // Otherwise return the CST. - return cst; - }, - astFormat: "xml", - locStart(node) { - return node.location.startOffset; - }, - locEnd(node) { - return node.location.endOffset; - } -}; -parser$2.default = parser; - -var printer$1 = {}; - -var doc = {exports: {}}; - -(function (module, exports) { - (function (factory) { - { - module.exports = factory(); - } - })(function() { - var __getOwnPropNames = Object.getOwnPropertyNames; - var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; - }; - - // dist/_doc.js.umd.js - var require_doc_js_umd = __commonJS({ - "dist/_doc.js.umd.js"(exports, module) { - var __create = Object.create; - var __defProp = Object.defineProperty; - var __getOwnPropDesc = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __getProtoOf = Object.getPrototypeOf; - var __hasOwnProp = Object.prototype.hasOwnProperty; - var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames2(fn)[0]])(fn = 0)), res; - }; - var __commonJS2 = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { - exports: {} - }).exports, mod), mod.exports; - }; - var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { - get: all[name], - enumerable: true - }); - }; - var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { - get: () => from[key], - enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable - }); - } - return to; - }; - var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { - value: mod, - enumerable: true - }) : target, mod)); - var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { - value: true - }), mod); - var init_define_process = __esm({ - ""() { - } - }); - var require_doc_builders = __commonJS2({ - "src/document/doc-builders.js"(exports2, module2) { - init_define_process(); - function concat(parts) { - return { - type: "concat", - parts - }; - } - function indent(contents) { - return { - type: "indent", - contents - }; - } - function align(widthOrString, contents) { - return { - type: "align", - contents, - n: widthOrString - }; - } - function group(contents) { - let opts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; - return { - type: "group", - id: opts.id, - contents, - break: Boolean(opts.shouldBreak), - expandedStates: opts.expandedStates - }; - } - function dedentToRoot(contents) { - return align(Number.NEGATIVE_INFINITY, contents); - } - function markAsRoot(contents) { - return align({ - type: "root" - }, contents); - } - function dedent(contents) { - return align(-1, contents); - } - function conditionalGroup(states, opts) { - return group(states[0], Object.assign(Object.assign({}, opts), {}, { - expandedStates: states - })); - } - function fill(parts) { - return { - type: "fill", - parts - }; - } - function ifBreak(breakContents, flatContents) { - let opts = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; - return { - type: "if-break", - breakContents, - flatContents, - groupId: opts.groupId - }; - } - function indentIfBreak(contents, opts) { - return { - type: "indent-if-break", - contents, - groupId: opts.groupId, - negate: opts.negate - }; - } - function lineSuffix(contents) { - return { - type: "line-suffix", - contents - }; - } - var lineSuffixBoundary = { - type: "line-suffix-boundary" - }; - var breakParent = { - type: "break-parent" - }; - var trim = { - type: "trim" - }; - var hardlineWithoutBreakParent = { - type: "line", - hard: true - }; - var literallineWithoutBreakParent = { - type: "line", - hard: true, - literal: true - }; - var line = { - type: "line" - }; - var softline = { - type: "line", - soft: true - }; - var hardline = concat([hardlineWithoutBreakParent, breakParent]); - var literalline = concat([literallineWithoutBreakParent, breakParent]); - var cursor = { - type: "cursor", - placeholder: Symbol("cursor") - }; - function join(sep, arr) { - const res = []; - for (let i = 0; i < arr.length; i++) { - if (i !== 0) { - res.push(sep); - } - res.push(arr[i]); - } - return concat(res); - } - function addAlignmentToDoc(doc, size, tabWidth) { - let aligned = doc; - if (size > 0) { - for (let i = 0; i < Math.floor(size / tabWidth); ++i) { - aligned = indent(aligned); - } - aligned = align(size % tabWidth, aligned); - aligned = align(Number.NEGATIVE_INFINITY, aligned); - } - return aligned; - } - function label(label2, contents) { - return { - type: "label", - label: label2, - contents - }; - } - module2.exports = { - concat, - join, - line, - softline, - hardline, - literalline, - group, - conditionalGroup, - fill, - lineSuffix, - lineSuffixBoundary, - cursor, - breakParent, - ifBreak, - trim, - indent, - indentIfBreak, - align, - addAlignmentToDoc, - markAsRoot, - dedentToRoot, - dedent, - hardlineWithoutBreakParent, - literallineWithoutBreakParent, - label - }; - } - }); - var require_end_of_line = __commonJS2({ - "src/common/end-of-line.js"(exports2, module2) { - init_define_process(); - function guessEndOfLine(text) { - const index = text.indexOf("\r"); - if (index >= 0) { - return text.charAt(index + 1) === "\n" ? "crlf" : "cr"; - } - return "lf"; - } - function convertEndOfLineToChars(value) { - switch (value) { - case "cr": - return "\r"; - case "crlf": - return "\r\n"; - default: - return "\n"; - } - } - function countEndOfLineChars(text, eol) { - let regex; - switch (eol) { - case "\n": - regex = /\n/g; - break; - case "\r": - regex = /\r/g; - break; - case "\r\n": - regex = /\r\n/g; - break; - default: - throw new Error('Unexpected "eol" '.concat(JSON.stringify(eol), ".")); - } - const endOfLines = text.match(regex); - return endOfLines ? endOfLines.length : 0; - } - function normalizeEndOfLine(text) { - return text.replace(/\r\n?/g, "\n"); - } - module2.exports = { - guessEndOfLine, - convertEndOfLineToChars, - countEndOfLineChars, - normalizeEndOfLine - }; - } - }); - var require_get_last = __commonJS2({ - "src/utils/get-last.js"(exports2, module2) { - init_define_process(); - var getLast = (arr) => arr[arr.length - 1]; - module2.exports = getLast; - } - }); - function ansiRegex() { - let { - onlyFirst = false - } = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; - const pattern = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"); - return new RegExp(pattern, onlyFirst ? void 0 : "g"); - } - var init_ansi_regex = __esm({ - "node_modules/strip-ansi/node_modules/ansi-regex/index.js"() { - init_define_process(); - } - }); - function stripAnsi(string) { - if (typeof string !== "string") { - throw new TypeError("Expected a `string`, got `".concat(typeof string, "`")); - } - return string.replace(ansiRegex(), ""); - } - var init_strip_ansi = __esm({ - "node_modules/strip-ansi/index.js"() { - init_define_process(); - init_ansi_regex(); - } - }); - function isFullwidthCodePoint(codePoint) { - if (!Number.isInteger(codePoint)) { - return false; - } - return codePoint >= 4352 && (codePoint <= 4447 || codePoint === 9001 || codePoint === 9002 || 11904 <= codePoint && codePoint <= 12871 && codePoint !== 12351 || 12880 <= codePoint && codePoint <= 19903 || 19968 <= codePoint && codePoint <= 42182 || 43360 <= codePoint && codePoint <= 43388 || 44032 <= codePoint && codePoint <= 55203 || 63744 <= codePoint && codePoint <= 64255 || 65040 <= codePoint && codePoint <= 65049 || 65072 <= codePoint && codePoint <= 65131 || 65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510 || 110592 <= codePoint && codePoint <= 110593 || 127488 <= codePoint && codePoint <= 127569 || 131072 <= codePoint && codePoint <= 262141); - } - var init_is_fullwidth_code_point = __esm({ - "node_modules/is-fullwidth-code-point/index.js"() { - init_define_process(); - } - }); - var require_emoji_regex = __commonJS2({ - "node_modules/emoji-regex/index.js"(exports2, module2) { - init_define_process(); - module2.exports = function() { - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; - }; - } - }); - var string_width_exports = {}; - __export(string_width_exports, { - default: () => stringWidth - }); - function stringWidth(string) { - if (typeof string !== "string" || string.length === 0) { - return 0; - } - string = stripAnsi(string); - if (string.length === 0) { - return 0; - } - string = string.replace((0, import_emoji_regex.default)(), " "); - let width = 0; - for (let index = 0; index < string.length; index++) { - const codePoint = string.codePointAt(index); - if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) { - continue; - } - if (codePoint >= 768 && codePoint <= 879) { - continue; - } - if (codePoint > 65535) { - index++; - } - width += isFullwidthCodePoint(codePoint) ? 2 : 1; - } - return width; - } - var import_emoji_regex; - var init_string_width = __esm({ - "node_modules/string-width/index.js"() { - init_define_process(); - init_strip_ansi(); - init_is_fullwidth_code_point(); - import_emoji_regex = __toESM(require_emoji_regex()); - } - }); - var require_get_string_width = __commonJS2({ - "src/utils/get-string-width.js"(exports2, module2) { - init_define_process(); - var stringWidth2 = (init_string_width(), __toCommonJS(string_width_exports)).default; - var notAsciiRegex = /[^\x20-\x7F]/; - function getStringWidth(text) { - if (!text) { - return 0; - } - if (!notAsciiRegex.test(text)) { - return text.length; - } - return stringWidth2(text); - } - module2.exports = getStringWidth; - } - }); - var require_doc_utils = __commonJS2({ - "src/document/doc-utils.js"(exports2, module2) { - init_define_process(); - var getLast = require_get_last(); - var { - literalline, - join - } = require_doc_builders(); - var isConcat = (doc) => Array.isArray(doc) || doc && doc.type === "concat"; - var getDocParts = (doc) => { - if (Array.isArray(doc)) { - return doc; - } - if (doc.type !== "concat" && doc.type !== "fill") { - throw new Error("Expect doc type to be `concat` or `fill`."); - } - return doc.parts; - }; - var traverseDocOnExitStackMarker = {}; - function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) { - const docsStack = [doc]; - while (docsStack.length > 0) { - const doc2 = docsStack.pop(); - if (doc2 === traverseDocOnExitStackMarker) { - onExit(docsStack.pop()); - continue; - } - if (onExit) { - docsStack.push(doc2, traverseDocOnExitStackMarker); - } - if (!onEnter || onEnter(doc2) !== false) { - if (isConcat(doc2) || doc2.type === "fill") { - const parts = getDocParts(doc2); - for (let ic = parts.length, i = ic - 1; i >= 0; --i) { - docsStack.push(parts[i]); - } - } else if (doc2.type === "if-break") { - if (doc2.flatContents) { - docsStack.push(doc2.flatContents); - } - if (doc2.breakContents) { - docsStack.push(doc2.breakContents); - } - } else if (doc2.type === "group" && doc2.expandedStates) { - if (shouldTraverseConditionalGroups) { - for (let ic = doc2.expandedStates.length, i = ic - 1; i >= 0; --i) { - docsStack.push(doc2.expandedStates[i]); - } - } else { - docsStack.push(doc2.contents); - } - } else if (doc2.contents) { - docsStack.push(doc2.contents); - } - } - } - } - function mapDoc(doc, cb) { - const mapped = /* @__PURE__ */ new Map(); - return rec(doc); - function rec(doc2) { - if (mapped.has(doc2)) { - return mapped.get(doc2); - } - const result = process2(doc2); - mapped.set(doc2, result); - return result; - } - function process2(doc2) { - if (Array.isArray(doc2)) { - return cb(doc2.map(rec)); - } - if (doc2.type === "concat" || doc2.type === "fill") { - const parts = doc2.parts.map(rec); - return cb(Object.assign(Object.assign({}, doc2), {}, { - parts - })); - } - if (doc2.type === "if-break") { - const breakContents = doc2.breakContents && rec(doc2.breakContents); - const flatContents = doc2.flatContents && rec(doc2.flatContents); - return cb(Object.assign(Object.assign({}, doc2), {}, { - breakContents, - flatContents - })); - } - if (doc2.type === "group" && doc2.expandedStates) { - const expandedStates = doc2.expandedStates.map(rec); - const contents = expandedStates[0]; - return cb(Object.assign(Object.assign({}, doc2), {}, { - contents, - expandedStates - })); - } - if (doc2.contents) { - const contents = rec(doc2.contents); - return cb(Object.assign(Object.assign({}, doc2), {}, { - contents - })); - } - return cb(doc2); - } - } - function findInDoc(doc, fn, defaultValue) { - let result = defaultValue; - let hasStopped = false; - function findInDocOnEnterFn(doc2) { - const maybeResult = fn(doc2); - if (maybeResult !== void 0) { - hasStopped = true; - result = maybeResult; - } - if (hasStopped) { - return false; - } - } - traverseDoc(doc, findInDocOnEnterFn); - return result; - } - function willBreakFn(doc) { - if (doc.type === "group" && doc.break) { - return true; - } - if (doc.type === "line" && doc.hard) { - return true; - } - if (doc.type === "break-parent") { - return true; - } - } - function willBreak(doc) { - return findInDoc(doc, willBreakFn, false); - } - function breakParentGroup(groupStack) { - if (groupStack.length > 0) { - const parentGroup = getLast(groupStack); - if (!parentGroup.expandedStates && !parentGroup.break) { - parentGroup.break = "propagated"; - } - } - return null; - } - function propagateBreaks(doc) { - const alreadyVisitedSet = /* @__PURE__ */ new Set(); - const groupStack = []; - function propagateBreaksOnEnterFn(doc2) { - if (doc2.type === "break-parent") { - breakParentGroup(groupStack); - } - if (doc2.type === "group") { - groupStack.push(doc2); - if (alreadyVisitedSet.has(doc2)) { - return false; - } - alreadyVisitedSet.add(doc2); - } - } - function propagateBreaksOnExitFn(doc2) { - if (doc2.type === "group") { - const group = groupStack.pop(); - if (group.break) { - breakParentGroup(groupStack); - } - } - } - traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn, true); - } - function removeLinesFn(doc) { - if (doc.type === "line" && !doc.hard) { - return doc.soft ? "" : " "; - } - if (doc.type === "if-break") { - return doc.flatContents || ""; - } - return doc; - } - function removeLines(doc) { - return mapDoc(doc, removeLinesFn); - } - var isHardline = (doc, nextDoc) => doc && doc.type === "line" && doc.hard && nextDoc && nextDoc.type === "break-parent"; - function stripDocTrailingHardlineFromDoc(doc) { - if (!doc) { - return doc; - } - if (isConcat(doc) || doc.type === "fill") { - const parts = getDocParts(doc); - while (parts.length > 1 && isHardline(...parts.slice(-2))) { - parts.length -= 2; - } - if (parts.length > 0) { - const lastPart = stripDocTrailingHardlineFromDoc(getLast(parts)); - parts[parts.length - 1] = lastPart; - } - return Array.isArray(doc) ? parts : Object.assign(Object.assign({}, doc), {}, { - parts - }); - } - switch (doc.type) { - case "align": - case "indent": - case "indent-if-break": - case "group": - case "line-suffix": - case "label": { - const contents = stripDocTrailingHardlineFromDoc(doc.contents); - return Object.assign(Object.assign({}, doc), {}, { - contents - }); - } - case "if-break": { - const breakContents = stripDocTrailingHardlineFromDoc(doc.breakContents); - const flatContents = stripDocTrailingHardlineFromDoc(doc.flatContents); - return Object.assign(Object.assign({}, doc), {}, { - breakContents, - flatContents - }); - } - } - return doc; - } - function stripTrailingHardline(doc) { - return stripDocTrailingHardlineFromDoc(cleanDoc(doc)); - } - function cleanDocFn(doc) { - switch (doc.type) { - case "fill": - if (doc.parts.every((part) => part === "")) { - return ""; - } - break; - case "group": - if (!doc.contents && !doc.id && !doc.break && !doc.expandedStates) { - return ""; - } - if (doc.contents.type === "group" && doc.contents.id === doc.id && doc.contents.break === doc.break && doc.contents.expandedStates === doc.expandedStates) { - return doc.contents; - } - break; - case "align": - case "indent": - case "indent-if-break": - case "line-suffix": - if (!doc.contents) { - return ""; - } - break; - case "if-break": - if (!doc.flatContents && !doc.breakContents) { - return ""; - } - break; - } - if (!isConcat(doc)) { - return doc; - } - const parts = []; - for (const part of getDocParts(doc)) { - if (!part) { - continue; - } - const [currentPart, ...restParts] = isConcat(part) ? getDocParts(part) : [part]; - if (typeof currentPart === "string" && typeof getLast(parts) === "string") { - parts[parts.length - 1] += currentPart; - } else { - parts.push(currentPart); - } - parts.push(...restParts); - } - if (parts.length === 0) { - return ""; - } - if (parts.length === 1) { - return parts[0]; - } - return Array.isArray(doc) ? parts : Object.assign(Object.assign({}, doc), {}, { - parts - }); - } - function cleanDoc(doc) { - return mapDoc(doc, (currentDoc) => cleanDocFn(currentDoc)); - } - function normalizeParts(parts) { - const newParts = []; - const restParts = parts.filter(Boolean); - while (restParts.length > 0) { - const part = restParts.shift(); - if (!part) { - continue; - } - if (isConcat(part)) { - restParts.unshift(...getDocParts(part)); - continue; - } - if (newParts.length > 0 && typeof getLast(newParts) === "string" && typeof part === "string") { - newParts[newParts.length - 1] += part; - continue; - } - newParts.push(part); - } - return newParts; - } - function normalizeDoc(doc) { - return mapDoc(doc, (currentDoc) => { - if (Array.isArray(currentDoc)) { - return normalizeParts(currentDoc); - } - if (!currentDoc.parts) { - return currentDoc; - } - return Object.assign(Object.assign({}, currentDoc), {}, { - parts: normalizeParts(currentDoc.parts) - }); - }); - } - function replaceEndOfLine(doc) { - return mapDoc(doc, (currentDoc) => typeof currentDoc === "string" && currentDoc.includes("\n") ? replaceTextEndOfLine(currentDoc) : currentDoc); - } - function replaceTextEndOfLine(text) { - let replacement = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : literalline; - return join(replacement, text.split("\n")).parts; - } - function canBreakFn(doc) { - if (doc.type === "line") { - return true; - } - } - function canBreak(doc) { - return findInDoc(doc, canBreakFn, false); - } - module2.exports = { - isConcat, - getDocParts, - willBreak, - traverseDoc, - findInDoc, - mapDoc, - propagateBreaks, - removeLines, - stripTrailingHardline, - normalizeParts, - normalizeDoc, - cleanDoc, - replaceTextEndOfLine, - replaceEndOfLine, - canBreak - }; - } - }); - var require_doc_printer = __commonJS2({ - "src/document/doc-printer.js"(exports2, module2) { - init_define_process(); - var { - convertEndOfLineToChars - } = require_end_of_line(); - var getLast = require_get_last(); - var getStringWidth = require_get_string_width(); - var { - fill, - cursor, - indent - } = require_doc_builders(); - var { - isConcat, - getDocParts - } = require_doc_utils(); - var groupModeMap; - var MODE_BREAK = 1; - var MODE_FLAT = 2; - function rootIndent() { - return { - value: "", - length: 0, - queue: [] - }; - } - function makeIndent(ind, options) { - return generateInd(ind, { - type: "indent" - }, options); - } - function makeAlign(indent2, widthOrDoc, options) { - if (widthOrDoc === Number.NEGATIVE_INFINITY) { - return indent2.root || rootIndent(); - } - if (widthOrDoc < 0) { - return generateInd(indent2, { - type: "dedent" - }, options); - } - if (!widthOrDoc) { - return indent2; - } - if (widthOrDoc.type === "root") { - return Object.assign(Object.assign({}, indent2), {}, { - root: indent2 - }); - } - const alignType = typeof widthOrDoc === "string" ? "stringAlign" : "numberAlign"; - return generateInd(indent2, { - type: alignType, - n: widthOrDoc - }, options); - } - function generateInd(ind, newPart, options) { - const queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : [...ind.queue, newPart]; - let value = ""; - let length = 0; - let lastTabs = 0; - let lastSpaces = 0; - for (const part of queue) { - switch (part.type) { - case "indent": - flush(); - if (options.useTabs) { - addTabs(1); - } else { - addSpaces(options.tabWidth); - } - break; - case "stringAlign": - flush(); - value += part.n; - length += part.n.length; - break; - case "numberAlign": - lastTabs += 1; - lastSpaces += part.n; - break; - default: - throw new Error("Unexpected type '".concat(part.type, "'")); - } - } - flushSpaces(); - return Object.assign(Object.assign({}, ind), {}, { - value, - length, - queue - }); - function addTabs(count) { - value += " ".repeat(count); - length += options.tabWidth * count; - } - function addSpaces(count) { - value += " ".repeat(count); - length += count; - } - function flush() { - if (options.useTabs) { - flushTabs(); - } else { - flushSpaces(); - } - } - function flushTabs() { - if (lastTabs > 0) { - addTabs(lastTabs); - } - resetLast(); - } - function flushSpaces() { - if (lastSpaces > 0) { - addSpaces(lastSpaces); - } - resetLast(); - } - function resetLast() { - lastTabs = 0; - lastSpaces = 0; - } - } - function trim(out) { - if (out.length === 0) { - return 0; - } - let trimCount = 0; - while (out.length > 0 && typeof getLast(out) === "string" && /^[\t ]*$/.test(getLast(out))) { - trimCount += out.pop().length; - } - if (out.length > 0 && typeof getLast(out) === "string") { - const trimmed = getLast(out).replace(/[\t ]*$/, ""); - trimCount += getLast(out).length - trimmed.length; - out[out.length - 1] = trimmed; - } - return trimCount; - } - function fits(next, restCommands, width, options, hasLineSuffix, mustBeFlat) { - let restIdx = restCommands.length; - const cmds = [next]; - const out = []; - while (width >= 0) { - if (cmds.length === 0) { - if (restIdx === 0) { - return true; - } - cmds.push(restCommands[restIdx - 1]); - restIdx--; - continue; - } - const [ind, mode, doc] = cmds.pop(); - if (typeof doc === "string") { - out.push(doc); - width -= getStringWidth(doc); - } else if (isConcat(doc)) { - const parts = getDocParts(doc); - for (let i = parts.length - 1; i >= 0; i--) { - cmds.push([ind, mode, parts[i]]); - } - } else { - switch (doc.type) { - case "indent": - cmds.push([makeIndent(ind, options), mode, doc.contents]); - break; - case "align": - cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]); - break; - case "trim": - width += trim(out); - break; - case "group": { - if (mustBeFlat && doc.break) { - return false; - } - const groupMode = doc.break ? MODE_BREAK : mode; - cmds.push([ind, groupMode, doc.expandedStates && groupMode === MODE_BREAK ? getLast(doc.expandedStates) : doc.contents]); - if (doc.id) { - groupModeMap[doc.id] = groupMode; - } - break; - } - case "fill": - for (let i = doc.parts.length - 1; i >= 0; i--) { - cmds.push([ind, mode, doc.parts[i]]); - } - break; - case "if-break": - case "indent-if-break": { - const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode; - if (groupMode === MODE_BREAK) { - const breakContents = doc.type === "if-break" ? doc.breakContents : doc.negate ? doc.contents : indent(doc.contents); - if (breakContents) { - cmds.push([ind, mode, breakContents]); - } - } - if (groupMode === MODE_FLAT) { - const flatContents = doc.type === "if-break" ? doc.flatContents : doc.negate ? indent(doc.contents) : doc.contents; - if (flatContents) { - cmds.push([ind, mode, flatContents]); - } - } - break; - } - case "line": - switch (mode) { - case MODE_FLAT: - if (!doc.hard) { - if (!doc.soft) { - out.push(" "); - width -= 1; - } - break; - } - return true; - case MODE_BREAK: - return true; - } - break; - case "line-suffix": - hasLineSuffix = true; - break; - case "line-suffix-boundary": - if (hasLineSuffix) { - return false; - } - break; - case "label": - cmds.push([ind, mode, doc.contents]); - break; - } - } - } - return false; - } - function printDocToString(doc, options) { - groupModeMap = {}; - const width = options.printWidth; - const newLine = convertEndOfLineToChars(options.endOfLine); - let pos = 0; - const cmds = [[rootIndent(), MODE_BREAK, doc]]; - const out = []; - let shouldRemeasure = false; - let lineSuffix = []; - while (cmds.length > 0) { - const [ind, mode, doc2] = cmds.pop(); - if (typeof doc2 === "string") { - const formatted = newLine !== "\n" ? doc2.replace(/\n/g, newLine) : doc2; - out.push(formatted); - pos += getStringWidth(formatted); - } else if (isConcat(doc2)) { - const parts = getDocParts(doc2); - for (let i = parts.length - 1; i >= 0; i--) { - cmds.push([ind, mode, parts[i]]); - } - } else { - switch (doc2.type) { - case "cursor": - out.push(cursor.placeholder); - break; - case "indent": - cmds.push([makeIndent(ind, options), mode, doc2.contents]); - break; - case "align": - cmds.push([makeAlign(ind, doc2.n, options), mode, doc2.contents]); - break; - case "trim": - pos -= trim(out); - break; - case "group": - switch (mode) { - case MODE_FLAT: - if (!shouldRemeasure) { - cmds.push([ind, doc2.break ? MODE_BREAK : MODE_FLAT, doc2.contents]); - break; - } - case MODE_BREAK: { - shouldRemeasure = false; - const next = [ind, MODE_FLAT, doc2.contents]; - const rem = width - pos; - const hasLineSuffix = lineSuffix.length > 0; - if (!doc2.break && fits(next, cmds, rem, options, hasLineSuffix)) { - cmds.push(next); - } else { - if (doc2.expandedStates) { - const mostExpanded = getLast(doc2.expandedStates); - if (doc2.break) { - cmds.push([ind, MODE_BREAK, mostExpanded]); - break; - } else { - for (let i = 1; i < doc2.expandedStates.length + 1; i++) { - if (i >= doc2.expandedStates.length) { - cmds.push([ind, MODE_BREAK, mostExpanded]); - break; - } else { - const state = doc2.expandedStates[i]; - const cmd = [ind, MODE_FLAT, state]; - if (fits(cmd, cmds, rem, options, hasLineSuffix)) { - cmds.push(cmd); - break; - } - } - } - } - } else { - cmds.push([ind, MODE_BREAK, doc2.contents]); - } - } - break; - } - } - if (doc2.id) { - groupModeMap[doc2.id] = getLast(cmds)[1]; - } - break; - case "fill": { - const rem = width - pos; - const { - parts - } = doc2; - if (parts.length === 0) { - break; - } - const [content, whitespace] = parts; - const contentFlatCmd = [ind, MODE_FLAT, content]; - const contentBreakCmd = [ind, MODE_BREAK, content]; - const contentFits = fits(contentFlatCmd, [], rem, options, lineSuffix.length > 0, true); - if (parts.length === 1) { - if (contentFits) { - cmds.push(contentFlatCmd); - } else { - cmds.push(contentBreakCmd); - } - break; - } - const whitespaceFlatCmd = [ind, MODE_FLAT, whitespace]; - const whitespaceBreakCmd = [ind, MODE_BREAK, whitespace]; - if (parts.length === 2) { - if (contentFits) { - cmds.push(whitespaceFlatCmd, contentFlatCmd); - } else { - cmds.push(whitespaceBreakCmd, contentBreakCmd); - } - break; - } - parts.splice(0, 2); - const remainingCmd = [ind, mode, fill(parts)]; - const secondContent = parts[0]; - const firstAndSecondContentFlatCmd = [ind, MODE_FLAT, [content, whitespace, secondContent]]; - const firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], rem, options, lineSuffix.length > 0, true); - if (firstAndSecondContentFits) { - cmds.push(remainingCmd, whitespaceFlatCmd, contentFlatCmd); - } else if (contentFits) { - cmds.push(remainingCmd, whitespaceBreakCmd, contentFlatCmd); - } else { - cmds.push(remainingCmd, whitespaceBreakCmd, contentBreakCmd); - } - break; - } - case "if-break": - case "indent-if-break": { - const groupMode = doc2.groupId ? groupModeMap[doc2.groupId] : mode; - if (groupMode === MODE_BREAK) { - const breakContents = doc2.type === "if-break" ? doc2.breakContents : doc2.negate ? doc2.contents : indent(doc2.contents); - if (breakContents) { - cmds.push([ind, mode, breakContents]); - } - } - if (groupMode === MODE_FLAT) { - const flatContents = doc2.type === "if-break" ? doc2.flatContents : doc2.negate ? indent(doc2.contents) : doc2.contents; - if (flatContents) { - cmds.push([ind, mode, flatContents]); - } - } - break; - } - case "line-suffix": - lineSuffix.push([ind, mode, doc2.contents]); - break; - case "line-suffix-boundary": - if (lineSuffix.length > 0) { - cmds.push([ind, mode, { - type: "line", - hard: true - }]); - } - break; - case "line": - switch (mode) { - case MODE_FLAT: - if (!doc2.hard) { - if (!doc2.soft) { - out.push(" "); - pos += 1; - } - break; - } else { - shouldRemeasure = true; - } - case MODE_BREAK: - if (lineSuffix.length > 0) { - cmds.push([ind, mode, doc2], ...lineSuffix.reverse()); - lineSuffix = []; - break; - } - if (doc2.literal) { - if (ind.root) { - out.push(newLine, ind.root.value); - pos = ind.root.length; - } else { - out.push(newLine); - pos = 0; - } - } else { - pos -= trim(out); - out.push(newLine + ind.value); - pos = ind.length; - } - break; - } - break; - case "label": - cmds.push([ind, mode, doc2.contents]); - break; - } - } - if (cmds.length === 0 && lineSuffix.length > 0) { - cmds.push(...lineSuffix.reverse()); - lineSuffix = []; - } - } - const cursorPlaceholderIndex = out.indexOf(cursor.placeholder); - if (cursorPlaceholderIndex !== -1) { - const otherCursorPlaceholderIndex = out.indexOf(cursor.placeholder, cursorPlaceholderIndex + 1); - const beforeCursor = out.slice(0, cursorPlaceholderIndex).join(""); - const aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join(""); - const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join(""); - return { - formatted: beforeCursor + aroundCursor + afterCursor, - cursorNodeStart: beforeCursor.length, - cursorNodeText: aroundCursor - }; - } - return { - formatted: out.join("") - }; - } - module2.exports = { - printDocToString - }; - } - }); - var require_doc_debug = __commonJS2({ - "src/document/doc-debug.js"(exports2, module2) { - init_define_process(); - var { - isConcat, - getDocParts - } = require_doc_utils(); - function flattenDoc(doc) { - if (!doc) { - return ""; - } - if (isConcat(doc)) { - const res = []; - for (const part of getDocParts(doc)) { - if (isConcat(part)) { - res.push(...flattenDoc(part).parts); - } else { - const flattened = flattenDoc(part); - if (flattened !== "") { - res.push(flattened); - } - } - } - return { - type: "concat", - parts: res - }; - } - if (doc.type === "if-break") { - return Object.assign(Object.assign({}, doc), {}, { - breakContents: flattenDoc(doc.breakContents), - flatContents: flattenDoc(doc.flatContents) - }); - } - if (doc.type === "group") { - return Object.assign(Object.assign({}, doc), {}, { - contents: flattenDoc(doc.contents), - expandedStates: doc.expandedStates && doc.expandedStates.map(flattenDoc) - }); - } - if (doc.type === "fill") { - return { - type: "fill", - parts: doc.parts.map(flattenDoc) - }; - } - if (doc.contents) { - return Object.assign(Object.assign({}, doc), {}, { - contents: flattenDoc(doc.contents) - }); - } - return doc; - } - function printDocToDebug(doc) { - const printedSymbols = /* @__PURE__ */ Object.create(null); - const usedKeysForSymbols = /* @__PURE__ */ new Set(); - return printDoc(flattenDoc(doc)); - function printDoc(doc2, index, parentParts) { - if (typeof doc2 === "string") { - return JSON.stringify(doc2); - } - if (isConcat(doc2)) { - const printed = getDocParts(doc2).map(printDoc).filter(Boolean); - return printed.length === 1 ? printed[0] : "[".concat(printed.join(", "), "]"); - } - if (doc2.type === "line") { - const withBreakParent = Array.isArray(parentParts) && parentParts[index + 1] && parentParts[index + 1].type === "break-parent"; - if (doc2.literal) { - return withBreakParent ? "literalline" : "literallineWithoutBreakParent"; - } - if (doc2.hard) { - return withBreakParent ? "hardline" : "hardlineWithoutBreakParent"; - } - if (doc2.soft) { - return "softline"; - } - return "line"; - } - if (doc2.type === "break-parent") { - const afterHardline = Array.isArray(parentParts) && parentParts[index - 1] && parentParts[index - 1].type === "line" && parentParts[index - 1].hard; - return afterHardline ? void 0 : "breakParent"; - } - if (doc2.type === "trim") { - return "trim"; - } - if (doc2.type === "indent") { - return "indent(" + printDoc(doc2.contents) + ")"; - } - if (doc2.type === "align") { - return doc2.n === Number.NEGATIVE_INFINITY ? "dedentToRoot(" + printDoc(doc2.contents) + ")" : doc2.n < 0 ? "dedent(" + printDoc(doc2.contents) + ")" : doc2.n.type === "root" ? "markAsRoot(" + printDoc(doc2.contents) + ")" : "align(" + JSON.stringify(doc2.n) + ", " + printDoc(doc2.contents) + ")"; - } - if (doc2.type === "if-break") { - return "ifBreak(" + printDoc(doc2.breakContents) + (doc2.flatContents ? ", " + printDoc(doc2.flatContents) : "") + (doc2.groupId ? (!doc2.flatContents ? ', ""' : "") + ", { groupId: ".concat(printGroupId(doc2.groupId), " }") : "") + ")"; - } - if (doc2.type === "indent-if-break") { - const optionsParts = []; - if (doc2.negate) { - optionsParts.push("negate: true"); - } - if (doc2.groupId) { - optionsParts.push("groupId: ".concat(printGroupId(doc2.groupId))); - } - const options = optionsParts.length > 0 ? ", { ".concat(optionsParts.join(", "), " }") : ""; - return "indentIfBreak(".concat(printDoc(doc2.contents)).concat(options, ")"); - } - if (doc2.type === "group") { - const optionsParts = []; - if (doc2.break && doc2.break !== "propagated") { - optionsParts.push("shouldBreak: true"); - } - if (doc2.id) { - optionsParts.push("id: ".concat(printGroupId(doc2.id))); - } - const options = optionsParts.length > 0 ? ", { ".concat(optionsParts.join(", "), " }") : ""; - if (doc2.expandedStates) { - return "conditionalGroup([".concat(doc2.expandedStates.map((part) => printDoc(part)).join(","), "]").concat(options, ")"); - } - return "group(".concat(printDoc(doc2.contents)).concat(options, ")"); - } - if (doc2.type === "fill") { - return "fill([".concat(doc2.parts.map((part) => printDoc(part)).join(", "), "])"); - } - if (doc2.type === "line-suffix") { - return "lineSuffix(" + printDoc(doc2.contents) + ")"; - } - if (doc2.type === "line-suffix-boundary") { - return "lineSuffixBoundary"; - } - if (doc2.type === "label") { - return "label(".concat(JSON.stringify(doc2.label), ", ").concat(printDoc(doc2.contents), ")"); - } - throw new Error("Unknown doc type " + doc2.type); - } - function printGroupId(id) { - if (typeof id !== "symbol") { - return JSON.stringify(String(id)); - } - if (id in printedSymbols) { - return printedSymbols[id]; - } - const prefix = String(id).slice(7, -1) || "symbol"; - for (let counter = 0; ; counter++) { - const key = prefix + (counter > 0 ? " #".concat(counter) : ""); - if (!usedKeysForSymbols.has(key)) { - usedKeysForSymbols.add(key); - return printedSymbols[id] = "Symbol.for(".concat(JSON.stringify(key), ")"); - } - } - } - } - module2.exports = { - printDocToDebug - }; - } - }); - init_define_process(); - module.exports = { - builders: require_doc_builders(), - printer: require_doc_printer(), - utils: require_doc_utils(), - debug: require_doc_debug() - }; - } - }); - return require_doc_js_umd(); - }); -} (doc)); - -var embed$1 = {}; - -Object.defineProperty(embed$1, "__esModule", { value: true }); -const doc_1$1 = doc.exports; -const { dedentToRoot, group: group$1, hardline: hardline$1, indent: indent$1, join: join$1, line: line$1, literalline: literalline$1, softline: softline$1 } = doc_1$1.builders; -// Replace the string content newlines within a doc tree with literallines so -// that all of the indentation lines up appropriately -function replaceNewlines(doc) { - return doc_1$1.utils.mapDoc(doc, (currentDoc) => typeof currentDoc === "string" && currentDoc.includes("\n") - ? currentDoc.split(/(\n)/g).map((v, i) => (i % 2 === 0 ? v : literalline$1)) - : currentDoc); -} -// Get the start and end element tags from the current node on the tree -function getElementTags(path, opts, print) { - const node = path.getValue(); - const { OPEN, Name, attribute, START_CLOSE, SLASH_OPEN, END_NAME, END } = node.children; - const parts = [OPEN[0].image, Name[0].image]; - if (attribute) { - parts.push(indent$1([line$1, join$1(line$1, path.map(print, "children", "attribute"))])); - } - if (!opts.bracketSameLine) { - parts.push(softline$1); - } - return { - openTag: group$1([...parts, START_CLOSE[0].image]), - closeTag: group$1([SLASH_OPEN[0].image, END_NAME[0].image, END[0].image]) - }; -} -// Get the name of the parser that is represented by the given element node, -// return null if a matching parser cannot be found -function getParser(node, opts) { - const { Name, attribute } = node.children; - const parser = Name[0].image.toLowerCase(); - // We don't want to deal with some weird recursive parser situation, so we - // need to explicitly call out the XML parser here and just return null - if (parser === "xml") { - return null; - } - // If this is a style tag with a text/css type, then we can skip straight to - // saying that this needs a CSS parser - if (parser === "style" && - attribute && - attribute.some((attr) => attr.children.Name[0].image === "type" && - attr.children.STRING[0].image === '"text/css"')) { - return "css"; - } - // If there is a plugin that has a parser that matches the name of this - // element, then we're going to assume that's correct for embedding and go - // ahead and switch to that parser - if (opts.plugins.some((plugin) => typeof plugin !== "string" && - plugin.parsers && - Object.prototype.hasOwnProperty.call(plugin.parsers, parser))) { - return parser; - } - return null; -} -// Get the source string that will be passed into the embedded parser from the -// content of the inside of the element node -function getSource(content) { - return content.chardata - .map((node) => { - const { SEA_WS, TEXT } = node.children; - const [{ image }] = SEA_WS || TEXT; - return { - offset: node.location.startOffset, - printed: image - }; - }) - .sort(({ offset }) => offset) - .map(({ printed }) => printed) - .join(""); -} -const embed = (path, print, textToDoc, opts) => { - const node = path.getValue(); - // If the node isn't an element node, then skip - if (node.name !== "element") { - return null; - } - // If the name of the node does not correspond to the name of a parser that - // prettier knows about, then skip - const parser = getParser(node, opts); - if (!parser) { - return null; - } - // If the node does not actually contain content, or it contains any content - // that is not just plain text, then skip - const content = node.children.content[0].children; - if (Object.keys(content).length !== 1 || !content.chardata) { - return null; - } - // Get the open and close tags of this element, then return the properly - // formatted content enclosed within them - const nodePath = path; - const { openTag, closeTag } = getElementTags(nodePath, opts, print); - return group$1([ - openTag, - literalline$1, - dedentToRoot(replaceNewlines(doc_1$1.utils.stripTrailingHardline(textToDoc(getSource(content), { ...opts, parser })))), - hardline$1, - closeTag - ]); -}; -embed$1.default = embed; - -var __importDefault$1 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(printer$1, "__esModule", { value: true }); -const doc_1 = doc.exports; -const embed_1 = __importDefault$1(embed$1); -const { fill, group, hardline, indent, join, line, literalline, softline } = doc_1.builders; -const ignoreStartComment = ""; -const ignoreEndComment = ""; -function hasIgnoreRanges(comments) { - if (!comments || comments.length === 0) { - return false; - } - comments.sort((left, right) => left.startOffset - right.startOffset); - let startFound = false; - for (let idx = 0; idx < comments.length; idx += 1) { - if (comments[idx].image === ignoreStartComment) { - startFound = true; - } - else if (startFound && comments[idx].image === ignoreEndComment) { - return true; - } - } - return false; -} -function isWhitespaceIgnorable(node) { - const { CData, Comment, reference } = node.children; - return !CData && !reference && !hasIgnoreRanges(Comment); -} -function printIToken(path) { - const node = path.getValue(); - return { - offset: node.startOffset, - startLine: node.startLine, - endLine: node.endLine, - printed: node.image - }; -} -function replaceNewlinesWithLiteralLines(content) { - return content - .split(/(\n)/g) - .map((value, idx) => (idx % 2 === 0 ? value : literalline)); -} -const printer = { - embed: embed_1.default, - print(path, opts, print) { - const node = path.getValue(); - switch (node.name) { - case "attribute": { - const { Name, EQUALS, STRING } = node.children; - return [Name[0].image, EQUALS[0].image, STRING[0].image]; - } - case "chardata": { - const { SEA_WS, TEXT } = node.children; - const [{ image }] = SEA_WS || TEXT; - return image - .split(/(\n)/g) - .map((value, index) => (index % 2 === 0 ? value : literalline)); - } - case "content": { - const nodePath = path; - let fragments = nodePath.call((childrenPath) => { - let response = []; - const children = childrenPath.getValue(); - if (children.CData) { - response = response.concat(childrenPath.map(printIToken, "CData")); - } - if (children.Comment) { - response = response.concat(childrenPath.map(printIToken, "Comment")); - } - if (children.chardata) { - response = response.concat(childrenPath.map((charDataPath) => ({ - offset: charDataPath.getValue().location.startOffset, - printed: print(charDataPath) - }), "chardata")); - } - if (children.element) { - response = response.concat(childrenPath.map((elementPath) => ({ - offset: elementPath.getValue().location.startOffset, - printed: print(elementPath) - }), "element")); - } - if (children.PROCESSING_INSTRUCTION) { - response = response.concat(childrenPath.map(printIToken, "PROCESSING_INSTRUCTION")); - } - if (children.reference) { - response = response.concat(childrenPath.map((referencePath) => { - const referenceNode = referencePath.getValue(); - return { - offset: referenceNode.location.startOffset, - printed: (referenceNode.children.CharRef || - referenceNode.children.EntityRef)[0].image - }; - }, "reference")); - } - return response; - }, "children"); - const { Comment } = node.children; - if (hasIgnoreRanges(Comment)) { - Comment.sort((left, right) => left.startOffset - right.startOffset); - const ignoreRanges = []; - let ignoreStart = null; - // Build up a list of ignored ranges from the original text based on the - // special prettier-ignore-* comments - Comment.forEach((comment) => { - if (comment.image === ignoreStartComment) { - ignoreStart = comment; - } - else if (ignoreStart && comment.image === ignoreEndComment) { - ignoreRanges.push({ - start: ignoreStart.startOffset, - end: comment.endOffset - }); - ignoreStart = null; - } - }); - // Filter the printed children to only include the ones that are outside - // of each of the ignored ranges - fragments = fragments.filter((fragment) => ignoreRanges.every(({ start, end }) => fragment.offset < start || fragment.offset > end)); - // Push each of the ignored ranges into the child list as its own element - // so that the original content is still included - ignoreRanges.forEach(({ start, end }) => { - const content = opts.originalText.slice(start, end + 1); - fragments.push({ - offset: start, - printed: replaceNewlinesWithLiteralLines(content) - }); - }); - } - fragments.sort((left, right) => left.offset - right.offset); - return group(fragments.map(({ printed }) => printed)); - } - case "docTypeDecl": { - const { DocType, Name, externalID, CLOSE } = node.children; - const parts = [DocType[0].image, " ", Name[0].image]; - if (externalID) { - parts.push(" ", path.call(print, "children", "externalID", 0)); - } - return group([...parts, CLOSE[0].image]); - } - case "document": { - const { docTypeDecl, element, misc, prolog } = node.children; - const fragments = []; - if (docTypeDecl) { - fragments.push({ - offset: docTypeDecl[0].location.startOffset, - printed: path.call(print, "children", "docTypeDecl", 0) - }); - } - if (prolog) { - fragments.push({ - offset: prolog[0].location.startOffset, - printed: path.call(print, "children", "prolog", 0) - }); - } - if (misc) { - misc.forEach((node) => { - if (node.children.PROCESSING_INSTRUCTION) { - fragments.push({ - offset: node.location.startOffset, - printed: node.children.PROCESSING_INSTRUCTION[0].image - }); - } - else if (node.children.Comment) { - fragments.push({ - offset: node.location.startOffset, - printed: node.children.Comment[0].image - }); - } - }); - } - if (element) { - fragments.push({ - offset: element[0].location.startOffset, - printed: path.call(print, "children", "element", 0) - }); - } - fragments.sort((left, right) => left.offset - right.offset); - return [ - join(hardline, fragments.map(({ printed }) => printed)), - hardline - ]; - } - case "element": { - const { OPEN, Name, attribute, START_CLOSE, content, SLASH_OPEN, END_NAME, END, SLASH_CLOSE } = node.children; - const parts = [OPEN[0].image, Name[0].image]; - if (attribute) { - const separator = opts.singleAttributePerLine ? hardline : line; - parts.push(indent([ - line, - join(separator, path.map(print, "children", "attribute")) - ])); - } - // Determine the value that will go between the <, name, and attributes - // of an element and the /> of an element. - const space = opts.xmlSelfClosingSpace ? line : softline; - if (SLASH_CLOSE) { - return group([...parts, space, SLASH_CLOSE[0].image]); - } - if (Object.keys(content[0].children).length === 0) { - return group([...parts, space, "/>"]); - } - const openTag = group([ - ...parts, - opts.bracketSameLine ? "" : softline, - START_CLOSE[0].image - ]); - const closeTag = group([ - SLASH_OPEN[0].image, - END_NAME[0].image, - END[0].image - ]); - if (opts.xmlWhitespaceSensitivity === "ignore" && - isWhitespaceIgnorable(content[0])) { - const nodePath = path; - const fragments = nodePath.call((childrenPath) => { - const children = childrenPath.getValue(); - let response = []; - if (children.Comment) { - response = response.concat(childrenPath.map(printIToken, "Comment")); - } - if (children.chardata) { - childrenPath.each((charDataPath) => { - const chardata = charDataPath.getValue(); - if (!chardata.children.TEXT) { - return; - } - const content = chardata.children.TEXT[0].image.trim(); - const printed = group(content.split(/(\n)/g).map((value) => { - if (value === "\n") { - return literalline; - } - return fill(value - .split(/\b( +)\b/g) - .map((segment, index) => index % 2 === 0 ? segment : line)); - })); - const location = chardata.location; - response.push({ - offset: location.startOffset, - startLine: location.startLine, - endLine: location.endLine, - printed - }); - }, "chardata"); - } - if (children.element) { - response = response.concat(childrenPath.map((elementPath) => { - const location = elementPath.getValue().location; - return { - offset: location.startOffset, - startLine: location.startLine, - endLine: location.endLine, - printed: print(elementPath) - }; - }, "element")); - } - if (children.PROCESSING_INSTRUCTION) { - response = response.concat(childrenPath.map(printIToken, "PROCESSING_INSTRUCTION")); - } - return response; - }, "children", "content", 0, "children"); - fragments.sort((left, right) => left.offset - right.offset); - // If the only content of this tag is chardata, then use a softline so - // that we won't necessarily break (to allow bar). - if (fragments.length === 1 && - (content[0].children.chardata || []).filter((chardata) => chardata.children.TEXT).length === 1) { - return group([ - openTag, - indent([softline, fragments[0].printed]), - softline, - closeTag - ]); - } - if (fragments.length === 0) { - return group([...parts, space, "/>"]); - } - const docs = []; - let lastLine = fragments[0].startLine; - fragments.forEach((node) => { - if (node.startLine - lastLine >= 2) { - docs.push(hardline, hardline); - } - else { - docs.push(hardline); - } - docs.push(node.printed); - lastLine = node.endLine; - }); - return group([openTag, indent(docs), hardline, closeTag]); - } - return group([ - openTag, - indent(path.call(print, "children", "content", 0)), - closeTag - ]); - } - case "externalID": { - const { Public, PubIDLiteral, System, SystemLiteral } = node.children; - if (System) { - return group([ - System[0].image, - indent([line, SystemLiteral[0].image]) - ]); - } - return group([ - group([Public[0].image, indent([line, PubIDLiteral[0].image])]), - indent([line, SystemLiteral[0].image]) - ]); - } - case "prolog": { - const { XMLDeclOpen, attribute, SPECIAL_CLOSE } = node.children; - const parts = [XMLDeclOpen[0].image]; - if (attribute) { - parts.push(indent([ - softline, - join(line, path.map(print, "children", "attribute")) - ])); - } - const space = opts.xmlSelfClosingSpace ? line : softline; - return group([...parts, space, SPECIAL_CLOSE[0].image]); - } - } - } -}; -printer$1.default = printer; - -var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -const parser_1 = __importDefault(parser$2); -const printer_1 = __importDefault(printer$1); -const plugin = { - languages: [ - { - name: "XML", - parsers: ["xml"], - aliases: ["rss", "xsd", "wsdl"], - extensions: [ - ".xml", - ".adml", - ".admx", - ".ant", - ".axml", - ".builds", - ".ccproj", - ".ccxml", - ".clixml", - ".cproject", - ".cscfg", - ".csdef", - ".csl", - ".csproj", - ".ct", - ".depproj", - ".dita", - ".ditamap", - ".ditaval", - ".dll.config", - ".dotsettings", - ".filters", - ".fsproj", - ".fxml", - ".glade", - ".gml", - ".gmx", - ".grxml", - ".iml", - ".inx", - ".ivy", - ".jelly", - ".jsproj", - ".kml", - ".launch", - ".mdpolicy", - ".mjml", - ".mm", - ".mod", - ".mxml", - ".natvis", - ".ncl", - ".ndproj", - ".nproj", - ".nuspec", - ".odd", - ".osm", - ".pkgproj", - ".pluginspec", - ".proj", - ".props", - ".ps1xml", - ".psc1", - ".pt", - ".rdf", - ".resx", - ".rss", - ".runsettings", - ".sch", - ".scxml", - ".sfproj", - ".shproj", - ".srdf", - ".storyboard", - ".sublime-snippet", - ".targets", - ".tml", - ".ts", - ".tsx", - ".ui", - ".urdf", - ".ux", - ".vbproj", - ".vcxproj", - ".vsixmanifest", - ".vssettings", - ".vstemplate", - ".vxml", - ".wixproj", - ".workflow", - ".wsdl", - ".wsf", - ".wxi", - ".wxl", - ".wxs", - ".x3d", - ".xacro", - ".xaml", - ".xib", - ".xlf", - ".xliff", - ".xmi", - ".xml.dist", - ".xproj", - ".xsd", - ".xsl", - ".xslt", - ".xspec", - ".xul", - ".zcml" - ], - filenames: [ - ".classpath", - ".cproject", - ".project", - "App.config", - "NuGet.config", - "Settings.StyleCop", - "Web.Debug.config", - "Web.Release.config", - "Web.config", - "packages.config" - ], - vscodeLanguageIds: ["xml", "forcesourcemanifest"], - linguistLanguageId: 399 - }, - { - name: "SVG", - parsers: ["xml"], - extensions: [".svg"], - vscodeLanguageIds: ["svg"], - linguistLanguageId: 337 - } - ], - parsers: { - xml: parser_1.default - }, - printers: { - xml: printer_1.default - }, - options: { - xmlSelfClosingSpace: { - type: "boolean", - category: "XML", - default: true, - description: "Adds a space before self-closing tags.", - since: "1.1.0" - }, - xmlWhitespaceSensitivity: { - type: "choice", - category: "XML", - default: "strict", - description: "How to handle whitespaces in XML.", - choices: [ - { - value: "strict", - description: "Whitespaces are considered sensitive in all elements." - }, - { - value: "ignore", - description: "Whitespaces are considered insensitive in all elements." - } - ], - since: "0.6.0" - } - }, - defaultOptions: { - printWidth: 80, - tabWidth: 2 - } -}; -var plugin_1 = plugin; - -export { plugin_1 as default }; diff --git a/src/meson.build b/src/meson.build index 1391225b8..beca3937a 100644 --- a/src/meson.build +++ b/src/meson.build @@ -37,9 +37,10 @@ install_data('langs/vala/workbench.vala', install_dir: pkgdatadir) install_data('langs/javascript/biome.json', install_dir: pkgdatadir) subdir('Previewer') subdir('langs/python') +subdir('langs/css') gjspack = find_program('../troll/gjspack/bin/gjspack') -custom_target('gjspack', +custom_target('workbench', input: ['main.js'], output: app_id + '.src.gresource', command: [ diff --git a/src/window.js b/src/window.js index 8a5fa9b80..40104211c 100644 --- a/src/window.js +++ b/src/window.js @@ -137,7 +137,7 @@ export default function Window({ application, session }) { settings, }); - PanelStyle({ builder, document_css, settings }); + PanelStyle({ builder, settings }); const previewer = Previewer({ output,