kwikqa 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kwikqa.mjs CHANGED
@@ -1,100 +1,100 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __kwikqaCreateRequire } from "node:module";const require=__kwikqaCreateRequire(import.meta.url);
3
- var Sg=Object.create;var Al=Object.defineProperty;var Eg=Object.getOwnPropertyDescriptor;var Cg=Object.getOwnPropertyNames;var Ng=Object.getPrototypeOf,Og=Object.prototype.hasOwnProperty;var Dg=(r,t)=>()=>{try{return t||r((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}};var Lg=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Cg(t))!Og.call(r,i)&&i!==e&&Al(r,i,{get:()=>t[i],enumerable:!(n=Eg(t,i))||n.enumerable});return r};var bi=(r,t,e)=>(e=r!=null?Sg(Ng(r)):{},Lg(t||!r||!r.__esModule?Al(e,"default",{value:r,enumerable:!0}):e,r));var Pn=Dg(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});function Nw(r,t){if(r==null)return{};var e={};for(var n in r)if({}.hasOwnProperty.call(r,n)){if(t.indexOf(n)!==-1)continue;e[n]=r[n]}return e}var lt=class{constructor(t,e,n){this.line=void 0,this.column=void 0,this.index=void 0,this.line=t,this.column=e,this.index=n}},Rr=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 Oe(r,t){let{line:e,column:n,index:i}=r;return new lt(e,n+t,i+t)}var ku="BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED",Ow={ImportMetaOutsideModule:{message:`import.meta may appear only with 'sourceType: "module"'`,code:ku},ImportOutsideModule:{message:`'import' and 'export' may appear only with 'sourceType: "module"'`,code:ku}},Iu={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"},ji=r=>r.type==="UpdateExpression"?Iu.UpdateExpression[`${r.prefix}`]:Iu[r.type],Dw={AccessorIsGenerator:({kind:r})=>`A ${r}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.",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:r})=>`Missing initializer in ${r} 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.",DeferImportRequiresNamespace:'Only `import defer * as x from "./module"` is valid.',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:r})=>`\`${r}\` 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:r,exportName:t})=>`A string literal cannot be used as an exported binding without \`from\`.
3
+ var $g=Object.create;var Dl=Object.defineProperty;var _g=Object.getOwnPropertyDescriptor;var Fg=Object.getOwnPropertyNames;var jg=Object.getPrototypeOf,Bg=Object.prototype.hasOwnProperty;var Vg=(r,t)=>()=>{try{return t||r((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}};var zg=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Fg(t))!Bg.call(r,i)&&i!==e&&Dl(r,i,{get:()=>t[i],enumerable:!(n=_g(t,i))||n.enumerable});return r};var Ii=(r,t,e)=>(e=r!=null?$g(jg(r)):{},zg(t||!r||!r.__esModule?Dl(e,"default",{value:r,enumerable:!0}):e,r));var Rn=Vg(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});function jw(r,t){if(r==null)return{};var e={};for(var n in r)if({}.hasOwnProperty.call(r,n)){if(t.indexOf(n)!==-1)continue;e[n]=r[n]}return e}var lt=class{constructor(t,e,n){this.line=void 0,this.column=void 0,this.index=void 0,this.line=t,this.column=e,this.index=n}},Ar=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 Oe(r,t){let{line:e,column:n,index:i}=r;return new lt(e,n+t,i+t)}var Su="BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED",Bw={ImportMetaOutsideModule:{message:`import.meta may appear only with 'sourceType: "module"'`,code:Su},ImportOutsideModule:{message:`'import' and 'export' may appear only with 'sourceType: "module"'`,code:Su}},Eu={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"},Hi=r=>r.type==="UpdateExpression"?Eu.UpdateExpression[`${r.prefix}`]:Eu[r.type],Vw={AccessorIsGenerator:({kind:r})=>`A ${r}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.",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:r})=>`Missing initializer in ${r} 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.",DeferImportRequiresNamespace:'Only `import defer * as x from "./module"` is valid.',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:r})=>`\`${r}\` 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:r,exportName:t})=>`A string literal cannot be used as an exported binding without \`from\`.
4
4
  - Did you mean \`export { '${r}' as '${t}' } from 'some-module'\`?`,ExportDefaultFromAsIdentifier:"'from' is not allowed as an identifier after 'export default'.",ForInOfLoopInitializer:({type:r})=>`'${r==="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:r})=>`Unsyntactic ${r==="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 `deprecatedImportAssert` parser plugin to suppress this error.",ImportBindingIsString:({importName:r})=>`A string literal cannot be used as an imported binding.
5
- - Did you mean \`import { "${r}" as foo }\`?`,ImportCallArity:"`import()` requires exactly 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.",InvalidCoverDiscardElement:"'void' must be followed by an expression when not used in a binding position.",InvalidCoverInitializedName:"Invalid shorthand property initializer.",InvalidDecimal:"Invalid decimal.",InvalidDigit:({radix:r})=>`Expected number in radix ${r}.`,InvalidEscapeSequence:"Bad character escape sequence.",InvalidEscapeSequenceTemplate:"Invalid escape sequence in template.",InvalidEscapedReservedWord:({reservedWord:r})=>`Escape sequence in keyword ${r}.`,InvalidIdentifier:({identifierName:r})=>`Invalid identifier ${r}.`,InvalidLhs:({ancestor:r})=>`Invalid left-hand side in ${ji(r)}.`,InvalidLhsBinding:({ancestor:r})=>`Binding invalid left-hand side in ${ji(r)}.`,InvalidLhsOptionalChaining:({ancestor:r})=>`Invalid optional chaining in the left-hand side of ${ji(r)}.`,InvalidNumber:"Invalid number.",InvalidOrMissingExponent:"Floating-point numbers require a valid exponent after the 'e'.",InvalidOrUnexpectedToken:({unexpected:r})=>`Unexpected character '${r}'.`,InvalidParenthesizedAssignment:"Invalid parenthesized assignment pattern.",InvalidPrivateFieldResolution:({identifierName:r})=>`Private name #${r} 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:r})=>`Label '${r}' is already declared.`,LetInLexicalBinding:"'let' is disallowed as a lexically bound name.",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:r})=>`This experimental syntax requires enabling the parser plugin: ${r.map(t=>JSON.stringify(t)).join(", ")}.`,MissingOneOfPlugins:({missingPlugin:r})=>`This experimental syntax requires enabling one of the following parser plugin(s): ${r.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:r})=>`Duplicate key "${r}" is not allowed in module attributes.`,ModuleExportNameHasLoneSurrogate:({surrogateCharCode:r})=>`An export name cannot include a lone surrogate, found '\\u${r.toString(16)}'.`,ModuleExportUndefined:({localName:r})=>`Export '${r}' 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:r})=>`Private names are only allowed in property accesses (\`obj.#${r}\`) or in \`in\` expressions (\`#${r} in obj\`).`,PrivateNameRedeclaration:({identifierName:r})=>`Duplicate private name #${r}.`,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.",SourcePhaseImportRequiresDefault:'Only `import source x from "./module"` is valid.',StaticPrototype:"Classes may not have static property named prototype.",SuperCallNotNewExpression:"Cannot use new with super(...).",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:r})=>`Unexpected keyword '${r}'.`,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:r})=>`Unexpected reserved word '${r}'.`,UnexpectedSuper:"'super' is only allowed in object methods and classes.",UnexpectedToken:({expected:r,unexpected:t})=>`Unexpected token${t?` '${t}'.`:""}${r?`, expected "${r}"`:""}`,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` or in the bare case statement.",UnexpectedVoidPattern:"Unexpected void binding.",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:r,onlyValidPropertyName:t})=>`The only valid meta property for ${r} is ${r}.${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.",UsingDeclarationExport:"Using declaration cannot be exported.",UsingDeclarationHasBindingPattern:"Using declaration cannot have destructuring patterns.",VarRedeclaration:({identifierName:r})=>`Identifier '${r}' has already been declared.`,VoidPatternCatchClauseParam:"A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.",VoidPatternInitializer:"A void binding may not have an initializer.",YieldBindingIdentifier:"Can not use 'yield' as identifier inside a generator.",YieldInParameter:"Yield expression is not allowed in formal parameters.",YieldNotInGeneratorFunction:"'yield' is only allowed within generator functions.",ZeroDigitNumericSeparator:"Numeric separator can not be used after leading 0."},Lw={StrictDelete:"Deleting local variable in strict mode.",StrictEvalArguments:({referenceName:r})=>`Assigning to '${r}' in strict mode.`,StrictEvalArgumentsBinding:({bindingName:r})=>`Binding '${r}' 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."},Mw={ParseExpressionEmptyInput:"Unexpected parseExpression() input: The input is empty or contains only comments.",ParseExpressionExpectsEOF:({unexpected:r})=>`Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(r)}\`.`},$w=new Set(["ArrowFunctionExpression","AssignmentExpression","ConditionalExpression","YieldExpression"]),_w=Object.assign({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:r})=>`Invalid topic token ${r}. In order to use ${r} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${r}" }.`,PipeTopicUnused:"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",PipeUnparenthesizedBody:({type:r})=>`Hack-style pipe body cannot be an unparenthesized ${ji({type:r})}; 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.'}),Fw={UnsupportedBind:"Binding should be performed on object property.",UnsupportedBindRHS:"The right-hand side of binding can not be super or import."},jw=["message"];function Pu(r,t,e){Object.defineProperty(r,t,{enumerable:!1,configurable:!0,value:e})}function Bw({toMessage:r,code:t,reasonCode:e,syntaxPlugin:n}){let i=e==="MissingPlugin"||e==="MissingOneOfPlugins",s={AccessorCannotDeclareThisParameter:"AccesorCannotDeclareThisParameter",AccessorCannotHaveTypeParameters:"AccesorCannotHaveTypeParameters",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference",SetAccessorCannotHaveOptionalParameter:"SetAccesorCannotHaveOptionalParameter",SetAccessorCannotHaveRestParameter:"SetAccesorCannotHaveRestParameter",SetAccessorCannotHaveReturnType:"SetAccesorCannotHaveReturnType"};return s[e]&&(e=s[e]),function a(o,d){let c=new SyntaxError;return c.code=t,c.reasonCode=e,c.loc=o,c.pos=o.index,c.syntaxPlugin=n,i&&(c.missingPlugin=d.missingPlugin),Pu(c,"clone",function(u={}){var p;let{line:f,column:h,index:g}=(p=u.loc)!=null?p:o;return a(new lt(f,h,g),Object.assign({},d,u.details))}),Pu(c,"details",d),Object.defineProperty(c,"message",{configurable:!0,get(){let l=`${r(d)} (${o.line}:${o.column})`;return this.message=l,l},set(l){Object.defineProperty(this,"message",{value:l,writable:!0})}}),c}}function Ye(r,t){if(Array.isArray(r))return n=>Ye(n,r[0]);let e={};for(let n of Object.keys(r)){let i=r[n],s=typeof i=="string"?{message:()=>i}:typeof i=="function"?{message:i}:i,{message:a}=s,o=Nw(s,jw),d=typeof a=="string"?()=>a:a;e[n]=Bw(Object.assign({code:"BABEL_PARSER_SYNTAX_ERROR",reasonCode:n,toMessage:d},t?{syntaxPlugin:t}:{},o))}return e}var b=Object.assign({},Ye(Ow),Ye(Dw),Ye(Lw),Ye(Mw),Ye`pipelineOperator`(_w),Ye`functionBind`(Fw));function Vw(){return{sourceType:"script",sourceFilename:void 0,startIndex:0,startColumn:0,startLine:1,allowAwaitOutsideFunction:!1,allowReturnOutsideFunction:!1,allowNewTargetOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,allowUndeclaredExports:!1,allowYieldOutsideFunction:!1,plugins:[],strictMode:void 0,ranges:!1,tokens:!1,createImportExpressions:!1,createParenthesizedExpressions:!1,errorRecovery:!1,attachComment:!0,annexB:!0}}function zw(r){let t=Vw();if(r==null)return t;if(r.annexB!=null&&r.annexB!==!1)throw new Error("The `annexB` option can only be set to `false`.");for(let e of Object.keys(t))r[e]!=null&&(t[e]=r[e]);if(t.startLine===1)r.startIndex==null&&t.startColumn>0?t.startIndex=t.startColumn:r.startColumn==null&&t.startIndex>0&&(t.startColumn=t.startIndex);else if((r.startColumn==null||r.startIndex==null)&&r.startIndex!=null)throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");if(t.sourceType==="commonjs"){if(r.allowAwaitOutsideFunction!=null)throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.");if(r.allowReturnOutsideFunction!=null)throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.");if(r.allowNewTargetOutsideFunction!=null)throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.")}return t}var{defineProperty:Hw}=Object,Ru=(r,t)=>{r&&Hw(r,t,{enumerable:!1,value:r[t]})};function hn(r){return Ru(r.loc.start,"index"),Ru(r.loc.end,"index"),r}var qw=r=>class extends r{parse(){let e=hn(super.parse());return this.optionFlags&256&&(e.tokens=e.tokens.map(hn)),e}parseRegExpLiteral({pattern:e,flags:n}){let i=null;try{i=new RegExp(e,n)}catch{}let s=this.estreeParseLiteral(i);return s.regex={pattern:e,flags:n},s}parseBigIntLiteral(e){let n;try{n=BigInt(e)}catch{n=null}let i=this.estreeParseLiteral(n);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)}estreeParseChainExpression(e,n){let i=this.startNodeAtNode(e);return i.expression=e,this.finishNodeAt(i,"ChainExpression",n)}directiveToStmt(e){let n=e.value;delete e.value,this.castNodeTo(n,"Literal"),n.raw=n.extra.raw,n.value=n.extra.expressionValue;let i=this.castNodeTo(e,"ExpressionStatement");return i.expression=n,i.directive=n.extra.rawValue,delete n.extra,i}fillOptionalPropertiesForTSESLint(e){}cloneEstreeStringLiteral(e){let{start:n,end:i,loc:s,range:a,raw:o,value:d}=e,c=Object.create(e.constructor.prototype);return c.type="Literal",c.start=n,c.end=i,c.loc=s,c.range=a,c.raw=o,c.value=d,c}initFunction(e,n){super.initFunction(e,n),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 n;return e.type==="ExpressionStatement"&&e.expression.type==="Literal"&&typeof e.expression.value=="string"&&!((n=e.expression.extra)!=null&&n.parenthesized)}parseBlockBody(e,n,i,s,a){super.parseBlockBody(e,n,i,s,a);let o=e.directives.map(d=>this.directiveToStmt(d));e.body=o.concat(e.body),delete e.directives}parsePrivateName(){let e=super.parsePrivateName();return this.getPluginOption("estree","classFeatures")?this.convertPrivateNameToPrivateIdentifier(e):e}convertPrivateNameToPrivateIdentifier(e){let n=super.getPrivateNameSV(e);return delete e.id,e.name=n,this.castNodeTo(e,"PrivateIdentifier")}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,n){let i=super.parseLiteral(e,n);return i.raw=i.extra.raw,delete i.extra,i}parseFunctionBody(e,n,i=!1){super.parseFunctionBody(e,n,i),e.expression=e.body.type!=="BlockStatement"}parseMethod(e,n,i,s,a,o,d=!1){let c=this.startNode();c.kind=e.kind,c=super.parseMethod(c,n,i,s,a,o,d),delete c.kind;let{typeParameters:l}=e;l&&(delete e.typeParameters,c.typeParameters=l,this.resetStartLocationFromNode(c,l));let u=this.castNodeTo(c,"FunctionExpression");return e.value=u,o==="ClassPrivateMethod"&&(e.computed=!1),o==="ObjectMethod"?(e.kind==="method"&&(e.kind="init"),e.shorthand=!1,this.finishNode(e,"Property")):this.finishNode(e,"MethodDefinition")}nameIsConstructor(e){return e.type==="Literal"?e.value==="constructor":super.nameIsConstructor(e)}parseClassProperty(...e){let n=super.parseClassProperty(...e);return this.getPluginOption("estree","classFeatures")&&this.castNodeTo(n,"PropertyDefinition"),n}parseClassPrivateProperty(...e){let n=super.parseClassPrivateProperty(...e);return this.getPluginOption("estree","classFeatures")&&(this.castNodeTo(n,"PropertyDefinition"),n.computed=!1),n}parseClassAccessorProperty(e){let n=super.parseClassAccessorProperty(e);return this.getPluginOption("estree","classFeatures")&&(n.abstract&&this.hasPlugin("typescript")?(delete n.abstract,this.castNodeTo(n,"TSAbstractAccessorProperty")):this.castNodeTo(n,"AccessorProperty")),n}parseObjectProperty(e,n,i,s){let a=super.parseObjectProperty(e,n,i,s);return a&&(a.kind="init",this.castNodeTo(a,"Property")),a}finishObjectProperty(e){return e.kind="init",this.finishNode(e,"Property")}isValidLVal(e,n,i,s){return e==="Property"?"value":super.isValidLVal(e,n,i,s)}isAssignable(e,n){return e!=null&&this.isObjectProperty(e)?this.isAssignable(e.value,n):super.isAssignable(e,n)}toAssignable(e,n=!1){if(e!=null&&this.isObjectProperty(e)){let{key:i,value:s}=e;this.isPrivateName(i)&&this.classScope.usePrivateName(this.getPrivateNameSV(i),i.loc.start),this.toAssignable(s,n)}else super.toAssignable(e,n)}toAssignableObjectExpressionProp(e,n,i){e.type==="Property"&&(e.kind==="get"||e.kind==="set")?this.raise(b.PatternHasAccessor,e.key):e.type==="Property"&&e.method?this.raise(b.PatternHasMethod,e.key):super.toAssignableObjectExpressionProp(e,n,i)}finishCallExpression(e,n){let i=super.finishCallExpression(e,n);if(i.callee.type==="Import"){var s,a;this.castNodeTo(i,"ImportExpression"),i.source=i.arguments[0],i.options=(s=i.arguments[1])!=null?s:null,i.attributes=(a=i.arguments[1])!=null?a:null,delete i.arguments,delete i.callee}else i.type==="OptionalCallExpression"?this.castNodeTo(i,"CallExpression"):i.optional=!1;return i}toReferencedArguments(e){e.type!=="ImportExpression"&&super.toReferencedArguments(e)}parseExport(e,n){let i=this.state.lastTokStartLoc,s=super.parseExport(e,n);switch(s.type){case"ExportAllDeclaration":s.exported=null;break;case"ExportNamedDeclaration":s.specifiers.length===1&&s.specifiers[0].type==="ExportNamespaceSpecifier"&&(this.castNodeTo(s,"ExportAllDeclaration"),s.exported=s.specifiers[0].exported,delete s.specifiers);case"ExportDefaultDeclaration":{var a;let{declaration:o}=s;o?.type==="ClassDeclaration"&&((a=o.decorators)==null?void 0:a.length)>0&&o.start===s.start&&this.resetStartLocation(s,i)}break}return s}stopParseSubscript(e,n){let i=super.stopParseSubscript(e,n);return n.optionalChainMember?this.estreeParseChainExpression(i,e.loc.end):i}parseMember(e,n,i,s,a){let o=super.parseMember(e,n,i,s,a);return o.type==="OptionalMemberExpression"?this.castNodeTo(o,"MemberExpression"):o.optional=!1,o}isOptionalMemberExpression(e){return e.type==="ChainExpression"?e.expression.type==="MemberExpression":super.isOptionalMemberExpression(e)}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.type==="Property"&&(e.method||e.kind==="get"||e.kind==="set")}castNodeTo(e,n){let i=super.castNodeTo(e,n);return this.fillOptionalPropertiesForTSESLint(i),i}cloneIdentifier(e){let n=super.cloneIdentifier(e);return this.fillOptionalPropertiesForTSESLint(n),n}cloneStringLiteral(e){return e.type==="Literal"?this.cloneEstreeStringLiteral(e):super.cloneStringLiteral(e)}finishNodeAt(e,n,i){return hn(super.finishNodeAt(e,n,i))}finishNode(e,n){let i=super.finishNode(e,n);return this.fillOptionalPropertiesForTSESLint(i),i}resetStartLocation(e,n){super.resetStartLocation(e,n),hn(e)}resetEndLocation(e,n=this.state.lastTokEndLoc){super.resetEndLocation(e,n),hn(e)}},Wt=class{constructor(t,e){this.token=void 0,this.preserveSpace=void 0,this.token=t,this.preserveSpace=!!e}},ee={brace:new Wt("{"),j_oTag:new Wt("<tag"),j_cTag:new Wt("</tag"),j_expr:new Wt("<tag>...</tag>",!0)};ee.template=new Wt("`",!0);var U=!0,S=!0,Ya=!0,mn=!0,St=!0,Uw=!0,zi=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}},Ro=new Map;function X(r,t={}){t.keyword=r;let e=F(r,t);return Ro.set(r,e),e}function Ne(r,t){return F(r,{beforeExpr:U,binop:t})}var bn=-1,gt=[],To=[],Ao=[],So=[],Eo=[],Co=[];function F(r,t={}){var e,n,i,s;return++bn,To.push(r),Ao.push((e=t.binop)!=null?e:-1),So.push((n=t.beforeExpr)!=null?n:!1),Eo.push((i=t.startsExpr)!=null?i:!1),Co.push((s=t.prefix)!=null?s:!1),gt.push(new zi(r,t)),bn}function G(r,t={}){var e,n,i,s;return++bn,Ro.set(r,bn),To.push(r),Ao.push((e=t.binop)!=null?e:-1),So.push((n=t.beforeExpr)!=null?n:!1),Eo.push((i=t.startsExpr)!=null?i:!1),Co.push((s=t.prefix)!=null?s:!1),gt.push(new zi("name",t)),bn}var Gw={bracketL:F("[",{beforeExpr:U,startsExpr:S}),bracketHashL:F("#[",{beforeExpr:U,startsExpr:S}),bracketBarL:F("[|",{beforeExpr:U,startsExpr:S}),bracketR:F("]"),bracketBarR:F("|]"),braceL:F("{",{beforeExpr:U,startsExpr:S}),braceBarL:F("{|",{beforeExpr:U,startsExpr:S}),braceHashL:F("#{",{beforeExpr:U,startsExpr:S}),braceR:F("}"),braceBarR:F("|}"),parenL:F("(",{beforeExpr:U,startsExpr:S}),parenR:F(")"),comma:F(",",{beforeExpr:U}),semi:F(";",{beforeExpr:U}),colon:F(":",{beforeExpr:U}),doubleColon:F("::",{beforeExpr:U}),dot:F("."),question:F("?",{beforeExpr:U}),questionDot:F("?."),arrow:F("=>",{beforeExpr:U}),template:F("template"),ellipsis:F("...",{beforeExpr:U}),backQuote:F("`",{startsExpr:S}),dollarBraceL:F("${",{beforeExpr:U,startsExpr:S}),templateTail:F("...`",{startsExpr:S}),templateNonTail:F("...${",{beforeExpr:U,startsExpr:S}),at:F("@"),hash:F("#",{startsExpr:S}),interpreterDirective:F("#!..."),eq:F("=",{beforeExpr:U,isAssign:mn}),assign:F("_=",{beforeExpr:U,isAssign:mn}),slashAssign:F("_=",{beforeExpr:U,isAssign:mn}),xorAssign:F("_=",{beforeExpr:U,isAssign:mn}),moduloAssign:F("_=",{beforeExpr:U,isAssign:mn}),incDec:F("++/--",{prefix:St,postfix:Uw,startsExpr:S}),bang:F("!",{beforeExpr:U,prefix:St,startsExpr:S}),tilde:F("~",{beforeExpr:U,prefix:St,startsExpr:S}),doubleCaret:F("^^",{startsExpr:S}),doubleAt:F("@@",{startsExpr:S}),pipeline:Ne("|>",0),nullishCoalescing:Ne("??",1),logicalOR:Ne("||",1),logicalAND:Ne("&&",2),bitwiseOR:Ne("|",3),bitwiseXOR:Ne("^",4),bitwiseAND:Ne("&",5),equality:Ne("==/!=/===/!==",6),lt:Ne("</>/<=/>=",7),gt:Ne("</>/<=/>=",7),relational:Ne("</>/<=/>=",7),bitShift:Ne("<</>>/>>>",8),bitShiftL:Ne("<</>>/>>>",8),bitShiftR:Ne("<</>>/>>>",8),plusMin:F("+/-",{beforeExpr:U,binop:9,prefix:St,startsExpr:S}),modulo:F("%",{binop:10,startsExpr:S}),star:F("*",{binop:10}),slash:Ne("/",10),exponent:F("**",{beforeExpr:U,binop:11,rightAssociative:!0}),_in:X("in",{beforeExpr:U,binop:7}),_instanceof:X("instanceof",{beforeExpr:U,binop:7}),_break:X("break"),_case:X("case",{beforeExpr:U}),_catch:X("catch"),_continue:X("continue"),_debugger:X("debugger"),_default:X("default",{beforeExpr:U}),_else:X("else",{beforeExpr:U}),_finally:X("finally"),_function:X("function",{startsExpr:S}),_if:X("if"),_return:X("return",{beforeExpr:U}),_switch:X("switch"),_throw:X("throw",{beforeExpr:U,prefix:St,startsExpr:S}),_try:X("try"),_var:X("var"),_const:X("const"),_with:X("with"),_new:X("new",{beforeExpr:U,startsExpr:S}),_this:X("this",{startsExpr:S}),_super:X("super",{startsExpr:S}),_class:X("class",{startsExpr:S}),_extends:X("extends",{beforeExpr:U}),_export:X("export"),_import:X("import",{startsExpr:S}),_null:X("null",{startsExpr:S}),_true:X("true",{startsExpr:S}),_false:X("false",{startsExpr:S}),_typeof:X("typeof",{beforeExpr:U,prefix:St,startsExpr:S}),_void:X("void",{beforeExpr:U,prefix:St,startsExpr:S}),_delete:X("delete",{beforeExpr:U,prefix:St,startsExpr:S}),_do:X("do",{isLoop:Ya,beforeExpr:U}),_for:X("for",{isLoop:Ya}),_while:X("while",{isLoop:Ya}),_as:G("as",{startsExpr:S}),_assert:G("assert",{startsExpr:S}),_async:G("async",{startsExpr:S}),_await:G("await",{startsExpr:S}),_defer:G("defer",{startsExpr:S}),_from:G("from",{startsExpr:S}),_get:G("get",{startsExpr:S}),_let:G("let",{startsExpr:S}),_meta:G("meta",{startsExpr:S}),_of:G("of",{startsExpr:S}),_sent:G("sent",{startsExpr:S}),_set:G("set",{startsExpr:S}),_source:G("source",{startsExpr:S}),_static:G("static",{startsExpr:S}),_using:G("using",{startsExpr:S}),_yield:G("yield",{startsExpr:S}),_asserts:G("asserts",{startsExpr:S}),_checks:G("checks",{startsExpr:S}),_exports:G("exports",{startsExpr:S}),_global:G("global",{startsExpr:S}),_implements:G("implements",{startsExpr:S}),_intrinsic:G("intrinsic",{startsExpr:S}),_infer:G("infer",{startsExpr:S}),_is:G("is",{startsExpr:S}),_mixins:G("mixins",{startsExpr:S}),_proto:G("proto",{startsExpr:S}),_require:G("require",{startsExpr:S}),_satisfies:G("satisfies",{startsExpr:S}),_keyof:G("keyof",{startsExpr:S}),_readonly:G("readonly",{startsExpr:S}),_unique:G("unique",{startsExpr:S}),_abstract:G("abstract",{startsExpr:S}),_declare:G("declare",{startsExpr:S}),_enum:G("enum",{startsExpr:S}),_module:G("module",{startsExpr:S}),_namespace:G("namespace",{startsExpr:S}),_interface:G("interface",{startsExpr:S}),_type:G("type",{startsExpr:S}),_opaque:G("opaque",{startsExpr:S}),name:F("name",{startsExpr:S}),placeholder:F("%%",{startsExpr:S}),string:F("string",{startsExpr:S}),num:F("num",{startsExpr:S}),bigint:F("bigint",{startsExpr:S}),decimal:F("decimal",{startsExpr:S}),regexp:F("regexp",{startsExpr:S}),privateName:F("#name",{startsExpr:S}),eof:F("eof"),jsxName:F("jsxName"),jsxText:F("jsxText",{beforeExpr:U}),jsxTagStart:F("jsxTagStart",{startsExpr:S}),jsxTagEnd:F("jsxTagEnd")};function te(r){return r>=93&&r<=133}function Kw(r){return r<=92}function Qe(r){return r>=58&&r<=133}function _u(r){return r>=58&&r<=137}function Ww(r){return So[r]}function gn(r){return Eo[r]}function Jw(r){return r>=29&&r<=33}function Tu(r){return r>=129&&r<=131}function Xw(r){return r>=90&&r<=92}function No(r){return r>=58&&r<=92}function Yw(r){return r>=39&&r<=59}function Qw(r){return r===34}function Zw(r){return Co[r]}function eb(r){return r>=121&&r<=123}function tb(r){return r>=124&&r<=130}function Ct(r){return To[r]}function Bi(r){return Ao[r]}function rb(r){return r===57}function Hi(r){return r>=24&&r<=25}function yt(r){return gt[r]}gt[8].updateContext=r=>{r.pop()};gt[5].updateContext=gt[7].updateContext=gt[23].updateContext=r=>{r.push(ee.brace)};gt[22].updateContext=r=>{r[r.length-1]===ee.template?r.pop():r.push(ee.template)};gt[143].updateContext=r=>{r.push(ee.j_expr,ee.j_oTag)};var Oo="\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-\u088F\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\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\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-\u1C8A\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-\uA7DC\uA7F1-\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",Fu="\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\u0897-\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-\u1ADD\u1AE0-\u1AEB\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\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\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\uFF65",nb=new RegExp("["+Oo+"]"),ib=new RegExp("["+Oo+Fu+"]");Oo=Fu=null;var ju=[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,4,51,13,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,7,25,39,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,39,27,10,22,251,41,7,1,17,5,57,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,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,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,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,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,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,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,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489],sb=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,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,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,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,199,7,137,9,54,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,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,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,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239];function no(r,t){let e=65536;for(let n=0,i=t.length;n<i;n+=2){if(e+=t[n],e>r)return!1;if(e+=t[n+1],e>=r)return!0}return!1}function ct(r){return r<65?r===36:r<=90?!0:r<97?r===95:r<=122?!0:r<=65535?r>=170&&nb.test(String.fromCharCode(r)):no(r,ju)}function Jt(r){return r<48?r===36:r<58?!0:r<65?!1:r<=90?!0:r<97?r===95:r<=122?!0:r<=65535?r>=170&&ib.test(String.fromCharCode(r)):no(r,ju)||no(r,sb)}var Do={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"]},ab=new Set(Do.keyword),ob=new Set(Do.strict),db=new Set(Do.strictBind);function Bu(r,t){return t&&r==="await"||r==="enum"}function Vu(r,t){return Bu(r,t)||ob.has(r)}function zu(r){return db.has(r)}function Hu(r,t){return Vu(r,t)||zu(r)}function cb(r){return ab.has(r)}function lb(r,t,e){return r===64&&t===64&&ct(e)}var ub=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 pb(r){return ub.has(r)}var xn=class{constructor(t){this.flags=0,this.names=new Map,this.firstLexicalName="",this.flags=t}},vn=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 allowNewTarget(){return(this.currentThisScopeFlags()&512)>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&1731)return!1}}get inNonArrowFunction(){return(this.currentThisScopeFlags()&2)>0}get inBareCaseStatement(){return(this.currentScope().flags&256)>0}get treatFunctionsAsVar(){return this.treatFunctionsAsVarInScope(this.currentScope())}createScope(t){return new xn(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,n){let i=this.currentScope();if(e&8||e&16){this.checkRedeclarationInScope(i,t,e,n);let s=i.names.get(t)||0;e&16?s=s|4:(i.firstLexicalName||(i.firstLexicalName=t),s=s|2),i.names.set(t,s),e&8&&this.maybeExportDefined(i,t)}else if(e&4)for(let s=this.scopeStack.length-1;s>=0&&(i=this.scopeStack[s],this.checkRedeclarationInScope(i,t,e,n),i.names.set(t,(i.names.get(t)||0)|1),this.maybeExportDefined(i,t),!(i.flags&1667));--s);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,n,i){this.isRedeclaredInScope(t,e,n)&&this.parser.raise(b.VarRedeclaration,i,{identifierName:e})}isRedeclaredInScope(t,e,n){if(!(n&1))return!1;if(n&8)return t.names.has(e);let i=t.names.get(e)||0;return n&16?(i&2)>0||!this.treatFunctionsAsVarInScope(t)&&(i&1)>0:(i&2)>0&&!(t.flags&8&&t.firstLexicalName===e)||!this.treatFunctionsAsVarInScope(t)&&(i&4)>0}checkLocalExport(t){let{name:e}=t;this.scopeStack[0].names.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&1667)return e}}currentThisScopeFlags(){for(let t=this.scopeStack.length-1;;t--){let{flags:e}=this.scopeStack[t];if(e&1731&&!(e&4))return e}}},io=class extends xn{constructor(...t){super(...t),this.declareFunctions=new Set}},so=class extends vn{createScope(t){return new io(t)}declareName(t,e,n){let i=this.currentScope();if(e&2048){this.checkRedeclarationInScope(i,t,e,n),this.maybeExportDefined(i,t),i.declareFunctions.add(t);return}super.declareName(t,e,n)}isRedeclaredInScope(t,e,n){if(super.isRedeclaredInScope(t,e,n))return!0;if(n&2048&&!t.declareFunctions.has(e)){let i=t.names.get(e);return(i&4)>0||(i&2)>0}return!1}checkLocalExport(t){this.scopeStack[0].declareFunctions.has(t.name)||super.checkLocalExport(t)}},fb=new Set(["_","any","bool","boolean","empty","extends","false","interface","mixed","null","number","static","string","true","typeof","void"]),z=Ye`flow`({AmbiguousConditionalArrow:"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",AmbiguousDeclareModuleKind:"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",AssignReservedType:({reservedType:r})=>`Cannot overwrite reserved type ${r}.`,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:r,enumName:t})=>`Boolean enum members need to be initialized. Use either \`${r} = true,\` or \`${r} = false,\` in enum \`${t}\`.`,EnumDuplicateMemberName:({memberName:r,enumName:t})=>`Enum member names need to be unique, but the name \`${r}\` has already been used before in enum \`${t}\`.`,EnumInconsistentMemberValues:({enumName:r})=>`Enum \`${r}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,EnumInvalidExplicitType:({invalidEnumType:r,enumName:t})=>`Enum type \`${r}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${t}\`.`,EnumInvalidExplicitTypeUnknownSupplied:({enumName:r})=>`Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${r}\`.`,EnumInvalidMemberInitializerPrimaryType:({enumName:r,memberName:t,explicitType:e})=>`Enum \`${r}\` has type \`${e}\`, so the initializer of \`${t}\` needs to be a ${e} literal.`,EnumInvalidMemberInitializerSymbolType:({enumName:r,memberName:t})=>`Symbol enum members cannot be initialized. Use \`${t},\` in enum \`${r}\`.`,EnumInvalidMemberInitializerUnknownType:({enumName:r,memberName:t})=>`The enum member initializer for \`${t}\` needs to be a literal (either a boolean, number, or string) in enum \`${r}\`.`,EnumInvalidMemberName:({enumName:r,memberName:t,suggestion:e})=>`Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${t}\`, consider using \`${e}\`, in enum \`${r}\`.`,EnumNumberMemberNotInitialized:({enumName:r,memberName:t})=>`Number enum members need to be initialized, e.g. \`${t} = 1\` in enum \`${r}\`.`,EnumStringMemberInconsistentlyInitialized:({enumName:r})=>`String enum members need to consistently either all use initializers, or use no initializers, in enum \`${r}\`.`,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:r})=>`Unexpected reserved type ${r}.`,UnexpectedReservedUnderscore:"`_` is only allowed as a type argument to call or new.",UnexpectedSpaceBetweenModuloChecks:"Spaces between `%` and `checks` are not allowed here.",UnexpectedSpreadType:"Spread operator cannot appear in class or interface definitions.",UnexpectedSubtractionOperand:'Unexpected token, expected "number" or "bigint".',UnexpectedTokenAfterTypeParameter:"Expected an arrow function after this type parameter declaration.",UnexpectedTypeParameterBeforeAsyncArrowFunction:"Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",UnsupportedDeclareExportKind:({unsupportedExportKind:r,suggestion:t})=>`\`declare export ${r}\` is not supported. Use \`${t}\` instead.`,UnsupportedStatementInDeclareModule:"Only declares and type imports are allowed inside declare module.",UnterminatedFlowComment:"Unterminated flow-comment."});function hb(r){return r.type==="DeclareExportAllDeclaration"||r.type==="DeclareExportDeclaration"&&(!r.declaration||r.declaration.type!=="TypeAlias"&&r.declaration.type!=="InterfaceDeclaration")}function Au(r){return r.importKind==="type"||r.importKind==="typeof"}var mb={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"};function yb(r,t){let e=[],n=[];for(let i=0;i<r.length;i++)(t(r[i],i,r)?e:n).push(r[i]);return[e,n]}var gb=/\*?\s*@((?:no)?flow)\b/,wb=r=>class extends r{constructor(...e){super(...e),this.flowPragma=void 0}getScopeHandler(){return so}shouldParseTypes(){return this.getPluginOption("flow","all")||this.flowPragma==="flow"}finishToken(e,n){e!==134&&e!==13&&e!==28&&this.flowPragma===void 0&&(this.flowPragma=null),super.finishToken(e,n)}addComment(e){if(this.flowPragma===void 0){let n=gb.exec(e.value);if(n)if(n[1]==="flow")this.flowPragma="flow";else if(n[1]==="noflow")this.flowPragma="noflow";else throw new Error("Unexpected flow pragma")}super.addComment(e)}flowParseTypeInitialiser(e){let n=this.state.inType;this.state.inType=!0,this.expect(e||14);let i=this.flowParseType();return this.state.inType=n,i}flowParsePredicate(){let e=this.startNode(),n=this.state.startLoc;return this.next(),this.expectContextual(110),this.state.lastTokStartLoc.index>n.index+1&&this.raise(z.UnexpectedSpaceBetweenModuloChecks,n),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 n=null,i=null;return this.match(54)?(this.state.inType=e,i=this.flowParsePredicate()):(n=this.flowParseType(),this.state.inType=e,this.match(54)&&(i=this.flowParsePredicate())),[n,i]}flowParseDeclareClass(e){return this.next(),this.flowParseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")}flowParseDeclareFunction(e){this.next();let n=e.id=this.parseIdentifier(),i=this.startNode(),s=this.startNode();this.match(47)?i.typeParameters=this.flowParseTypeParameterDeclaration():i.typeParameters=null,this.expect(10);let a=this.flowParseFunctionTypeParams();return i.params=a.params,i.rest=a.rest,i.this=a._this,this.expect(11),[i.returnType,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),s.typeAnnotation=this.finishNode(i,"FunctionTypeAnnotation"),n.typeAnnotation=this.finishNode(s,"TypeAnnotation"),this.resetEndLocation(n),this.semicolon(),this.scope.declareName(e.id.name,2048,e.id.loc.start),this.finishNode(e,"DeclareFunction")}flowParseDeclare(e,n){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(127))return this.match(16)?this.flowParseDeclareModuleExports(e):(n&&this.raise(z.NestedDeclareModule,this.state.lastTokStartLoc),this.flowParseDeclareModule(e));if(this.isContextual(130))return this.flowParseDeclareTypeAlias(e);if(this.isContextual(131))return this.flowParseDeclareOpaqueType(e);if(this.isContextual(129))return this.flowParseDeclareInterface(e);if(this.match(82))return this.flowParseDeclareExportDeclaration(e,n);throw this.unexpected()}flowParseDeclareVariable(e){return this.next(),e.id=this.flowParseTypeAnnotatableIdentifier(),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(134)?e.id=super.parseExprAtom():e.id=this.parseIdentifier();let n=e.body=this.startNode(),i=n.body=[];for(this.expect(5);!this.match(8);){let o=this.startNode();this.match(83)?(this.next(),!this.isContextual(130)&&!this.match(87)&&this.raise(z.InvalidNonTypeImportInDeclareModule,this.state.lastTokStartLoc),i.push(super.parseImport(o))):(this.expectContextual(125,z.UnsupportedStatementInDeclareModule),i.push(this.flowParseDeclare(o,!0)))}this.scope.exit(),this.expect(8),this.finishNode(n,"BlockStatement");let s=null,a=!1;return i.forEach(o=>{hb(o)?(s==="CommonJS"&&this.raise(z.AmbiguousDeclareModuleKind,o),s="ES"):o.type==="DeclareModuleExports"&&(a&&this.raise(z.DuplicateDeclareModuleExports,o),s==="ES"&&this.raise(z.AmbiguousDeclareModuleKind,o),s="CommonJS",a=!0)}),e.kind=s||"CommonJS",this.finishNode(e,"DeclareModule")}flowParseDeclareExportDeclaration(e,n){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(130)||this.isContextual(129))&&!n){let i=this.state.value;throw this.raise(z.UnsupportedDeclareExportKind,this.state.startLoc,{unsupportedExportKind:i,suggestion:mb[i]})}if(this.match(74)||this.match(68)||this.match(80)||this.isContextual(131))return e.declaration=this.flowParseDeclare(this.startNode()),e.default=!1,this.finishNode(e,"DeclareExportDeclaration");if(this.match(55)||this.match(5)||this.isContextual(129)||this.isContextual(130)||this.isContextual(131))return e=this.parseExport(e,null),e.type==="ExportNamedDeclaration"?(e.default=!1,delete e.exportKind,this.castNodeTo(e,"DeclareExportDeclaration")):this.castNodeTo(e,"DeclareExportAllDeclaration");throw this.unexpected()}flowParseDeclareModuleExports(e){return this.next(),this.expectContextual(111),e.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(e,"DeclareModuleExports")}flowParseDeclareTypeAlias(e){this.next();let n=this.flowParseTypeAlias(e);return this.castNodeTo(n,"DeclareTypeAlias"),n}flowParseDeclareOpaqueType(e){this.next();let n=this.flowParseOpaqueType(e,!0);return this.castNodeTo(n,"DeclareOpaqueType"),n}flowParseDeclareInterface(e){return this.next(),this.flowParseInterfaceish(e,!1),this.finishNode(e,"DeclareInterface")}flowParseInterfaceish(e,n){if(e.id=this.flowParseRestrictedIdentifier(!n,!0),this.scope.declareName(e.id.name,n?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(!n&&this.eat(12));if(n){if(e.implements=[],e.mixins=[],this.eatContextual(117))do e.mixins.push(this.flowParseInterfaceExtends());while(this.eat(12));if(this.eatContextual(113))do e.implements.push(this.flowParseInterfaceExtends());while(this.eat(12))}e.body=this.flowParseObjectType({allowStatic:n,allowExact:!1,allowSpread:!1,allowProto:n,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(z.UnexpectedReservedUnderscore,this.state.startLoc)}checkReservedType(e,n,i){fb.has(e)&&this.raise(i?z.AssignReservedType:z.UnexpectedReservedType,n,{reservedType:e})}flowParseRestrictedIdentifierName(e,n){return this.checkReservedType(this.state.value,this.state.startLoc,n),this.parseIdentifierName(e)}flowParseRestrictedIdentifier(e,n){let i=this.startNode(),s=this.flowParseRestrictedIdentifierName(e,n);return this.createIdentifier(i,s)}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,n){return this.expectContextual(130),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,n||(e.impltype=this.flowParseTypeInitialiser(29)),this.semicolon(),this.finishNode(e,"OpaqueType")}flowParseTypeParameterBound(){if(this.match(14)||this.isContextual(81)){let e=this.startNode();return this.next(),e.typeAnnotation=this.flowParseType(),this.finishNode(e,"TypeAnnotation")}}flowParseTypeParameter(e=!1){let n=this.state.startLoc,i=this.startNode(),s=this.flowParseVariance();return i.name=this.flowParseRestrictedIdentifierName(),i.variance=s,i.bound=this.flowParseTypeParameterBound(),this.match(29)?(this.eat(29),i.default=this.flowParseType()):e&&this.raise(z.MissingTypeParamDefault,n),this.finishNode(i,"TypeParameter")}flowParseTypeParameterDeclaration(){let e=this.state.inType,n=this.startNode();n.params=[],this.state.inType=!0,this.match(47)||this.match(143)?this.next():this.unexpected();let i=!1;do{let s=this.flowParseTypeParameter(i);n.params.push(s),s.default&&(i=!0),this.match(48)||this.expect(12)}while(!this.match(48));return this.expect(48),this.state.inType=e,this.finishNode(n,"TypeParameterDeclaration")}flowInTopLevelContext(e){if(this.curContext()!==ee.brace){let n=this.state.context;this.state.context=[n[0]];try{return e()}finally{this.state.context=n}}else return e()}flowParseTypeParameterInstantiationInExpression(){if(this.reScan_lt()===47)return this.flowParseTypeParameterInstantiation()}flowParseTypeParameterInstantiation(){let e=this.startNode(),n=this.state.inType;return this.state.inType=!0,e.params=[],this.flowInTopLevelContext(()=>{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);this.state.noAnonFunctionType=i}),this.state.inType=n,!this.state.inType&&this.curContext()===ee.brace&&this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TypeParameterInstantiation")}flowParseTypeParameterInstantiationCallOrNew(){if(this.reScan_lt()!==47)return null;let e=this.startNode(),n=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=n,this.finishNode(e,"TypeParameterInstantiation")}flowParseInterfaceType(){let e=this.startNode();if(this.expectContextual(129),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(135)||this.match(134)?super.parseExprAtom():this.parseIdentifier(!0)}flowParseObjectTypeIndexer(e,n,i){return e.static=n,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,n){return e.static=n,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,n){let i=this.startNode();return e.static=n,e.value=this.flowParseObjectTypeMethodish(i),this.finishNode(e,"ObjectTypeCallProperty")}flowParseObjectType({allowStatic:e,allowExact:n,allowSpread:i,allowProto:s,allowInexact:a}){let o=this.state.inType;this.state.inType=!0;let d=this.startNode();d.callProperties=[],d.properties=[],d.indexers=[],d.internalSlots=[];let c,l,u=!1;for(n&&this.match(6)?(this.expect(6),c=9,l=!0):(this.expect(5),c=8,l=!1),d.exact=l;!this.match(c);){let f=!1,h=null,g=null,m=this.startNode();if(s&&this.isContextual(118)){let w=this.lookahead();w.type!==14&&w.type!==17&&(this.next(),h=this.state.startLoc,e=!1)}if(e&&this.isContextual(106)){let w=this.lookahead();w.type!==14&&w.type!==17&&(this.next(),f=!0)}let y=this.flowParseVariance();if(this.eat(0))h!=null&&this.unexpected(h),this.eat(0)?(y&&this.unexpected(y.loc.start),d.internalSlots.push(this.flowParseObjectTypeInternalSlot(m,f))):d.indexers.push(this.flowParseObjectTypeIndexer(m,f,y));else if(this.match(10)||this.match(47))h!=null&&this.unexpected(h),y&&this.unexpected(y.loc.start),d.callProperties.push(this.flowParseObjectTypeCallProperty(m,f));else{let w="init";if(this.isContextual(99)||this.isContextual(104)){let v=this.lookahead();_u(v.type)&&(w=this.state.value,this.next())}let x=this.flowParseObjectTypeProperty(m,f,h,y,w,i,a??!l);x===null?(u=!0,g=this.state.lastTokStartLoc):d.properties.push(x)}this.flowObjectTypeSemicolon(),g&&!this.match(8)&&!this.match(9)&&this.raise(z.UnexpectedExplicitInexactInObject,g)}this.expect(c),i&&(d.inexact=u);let p=this.finishNode(d,"ObjectTypeAnnotation");return this.state.inType=o,p}flowParseObjectTypeProperty(e,n,i,s,a,o,d){if(this.eat(21))return this.match(12)||this.match(13)||this.match(8)||this.match(9)?(o?d||this.raise(z.InexactInsideExact,this.state.lastTokStartLoc):this.raise(z.InexactInsideNonObject,this.state.lastTokStartLoc),s&&this.raise(z.InexactVariance,s),null):(o||this.raise(z.UnexpectedSpreadType,this.state.lastTokStartLoc),i!=null&&this.unexpected(i),s&&this.raise(z.SpreadVariance,s),e.argument=this.flowParseType(),this.finishNode(e,"ObjectTypeSpreadProperty"));{e.key=this.flowParseObjectPropertyKey(),e.static=n,e.proto=i!=null,e.kind=a;let c=!1;return this.match(47)||this.match(10)?(e.method=!0,i!=null&&this.unexpected(i),s&&this.unexpected(s.loc.start),e.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e.loc.start)),(a==="get"||a==="set")&&this.flowCheckGetterSetterParams(e),!o&&e.key.name==="constructor"&&e.value.this&&this.raise(z.ThisParamBannedInConstructor,e.value.this)):(a!=="init"&&this.unexpected(),e.method=!1,this.eat(17)&&(c=!0),e.value=this.flowParseTypeInitialiser(),e.variance=s),e.optional=c,this.finishNode(e,"ObjectTypeProperty")}}flowCheckGetterSetterParams(e){let n=e.kind==="get"?0:1,i=e.value.params.length+(e.value.rest?1:0);e.value.this&&this.raise(e.kind==="get"?z.GetterMayNotHaveThisParam:z.SetterMayNotHaveThisParam,e.value.this),i!==n&&this.raise(e.kind==="get"?b.BadGetterArity:b.BadSetterArity,e),e.kind==="set"&&e.value.rest&&this.raise(b.BadSetterRestParameter,e)}flowObjectTypeSemicolon(){!this.eat(13)&&!this.eat(12)&&!this.match(8)&&!this.match(9)&&this.unexpected()}flowParseQualifiedTypeIdentifier(e,n){e??(e=this.state.startLoc);let i=n||this.flowParseRestrictedIdentifier(!0);for(;this.eat(16);){let s=this.startNodeAt(e);s.qualification=i,s.id=this.flowParseRestrictedIdentifier(!0),i=this.finishNode(s,"QualifiedTypeIdentifier")}return i}flowParseGenericType(e,n){let i=this.startNodeAt(e);return i.typeParameters=null,i.id=this.flowParseQualifiedTypeIdentifier(e,n),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.pos<this.length&&!this.match(3)&&(e.types.push(this.flowParseType()),!this.match(3));)this.expect(12);return this.expect(3),this.finishNode(e,"TupleTypeAnnotation")}flowParseFunctionTypeParam(e){let n=null,i=!1,s=null,a=this.startNode(),o=this.lookahead(),d=this.state.type===78;return o.type===14||o.type===17?(d&&!e&&this.raise(z.ThisParamMustBeFirst,a),n=this.parseIdentifier(d),this.eat(17)&&(i=!0,d&&this.raise(z.ThisParamMayNotBeOptional,a)),s=this.flowParseTypeInitialiser()):s=this.flowParseType(),a.name=n,a.optional=i,a.typeAnnotation=s,this.finishNode(a,"FunctionTypeParam")}reinterpretTypeAsFunctionTypeParam(e){let n=this.startNodeAt(e.loc.start);return n.name=null,n.optional=!1,n.typeAnnotation=e,this.finishNode(n,"FunctionTypeParam")}flowParseFunctionTypeParams(e=[]){let n=null,i=null;for(this.match(78)&&(i=this.flowParseFunctionTypeParam(!0),i.name=null,this.match(11)||this.expect(12));!this.match(11)&&!this.match(21);)e.push(this.flowParseFunctionTypeParam(!1)),this.match(11)||this.expect(12);return this.eat(21)&&(n=this.flowParseFunctionTypeParam(!1)),{params:e,rest:n,_this:i}}flowIdentToTypeAnnotation(e,n,i){switch(i.name){case"any":return this.finishNode(n,"AnyTypeAnnotation");case"bool":case"boolean":return this.finishNode(n,"BooleanTypeAnnotation");case"mixed":return this.finishNode(n,"MixedTypeAnnotation");case"empty":return this.finishNode(n,"EmptyTypeAnnotation");case"number":return this.finishNode(n,"NumberTypeAnnotation");case"string":return this.finishNode(n,"StringTypeAnnotation");case"symbol":return this.finishNode(n,"SymbolTypeAnnotation");default:return this.checkNotUnderscore(i.name),this.flowParseGenericType(e,i)}}flowParsePrimaryType(){let e=this.state.startLoc,n=this.startNode(),i,s,a=!1,o=this.state.noAnonFunctionType;switch(this.state.type){case 5:return this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!0,allowProto:!1,allowInexact:!0});case 6:return this.flowParseObjectType({allowStatic:!1,allowExact:!0,allowSpread:!0,allowProto:!1,allowInexact:!1});case 0:return this.state.noAnonFunctionType=!1,s=this.flowParseTupleType(),this.state.noAnonFunctionType=o,s;case 47:{let d=this.startNode();return d.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(10),i=this.flowParseFunctionTypeParams(),d.params=i.params,d.rest=i.rest,d.this=i._this,this.expect(11),this.expect(19),d.returnType=this.flowParseType(),this.finishNode(d,"FunctionTypeAnnotation")}case 10:{let d=this.startNode();if(this.next(),!this.match(11)&&!this.match(21))if(te(this.state.type)||this.match(78)){let c=this.lookahead().type;a=c!==17&&c!==14}else a=!0;if(a){if(this.state.noAnonFunctionType=!1,s=this.flowParseType(),this.state.noAnonFunctionType=o,this.state.noAnonFunctionType||!(this.match(12)||this.match(11)&&this.lookahead().type===19))return this.expect(11),s;this.eat(12)}return s?i=this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(s)]):i=this.flowParseFunctionTypeParams(),d.params=i.params,d.rest=i.rest,d.this=i._this,this.expect(11),this.expect(19),d.returnType=this.flowParseType(),d.typeParameters=null,this.finishNode(d,"FunctionTypeAnnotation")}case 134:return this.parseLiteral(this.state.value,"StringLiteralTypeAnnotation");case 85:case 86:return n.value=this.match(85),this.next(),this.finishNode(n,"BooleanLiteralTypeAnnotation");case 53:if(this.state.value==="-"){if(this.next(),this.match(135))return this.parseLiteralAtNode(-this.state.value,"NumberLiteralTypeAnnotation",n);if(this.match(136))return this.parseLiteralAtNode(-this.state.value,"BigIntLiteralTypeAnnotation",n);throw this.raise(z.UnexpectedSubtractionOperand,this.state.startLoc)}throw this.unexpected();case 135:return this.parseLiteral(this.state.value,"NumberLiteralTypeAnnotation");case 136:return this.parseLiteral(this.state.value,"BigIntLiteralTypeAnnotation");case 88:return this.next(),this.finishNode(n,"VoidTypeAnnotation");case 84:return this.next(),this.finishNode(n,"NullLiteralTypeAnnotation");case 78:return this.next(),this.finishNode(n,"ThisTypeAnnotation");case 55:return this.next(),this.finishNode(n,"ExistsTypeAnnotation");case 87:return this.flowParseTypeofType();default:if(No(this.state.type)){let d=Ct(this.state.type);return this.next(),super.createIdentifier(n,d)}else if(te(this.state.type))return this.isContextual(129)?this.flowParseInterfaceType():this.flowIdentToTypeAnnotation(e,n,this.parseIdentifier())}throw this.unexpected()}flowParsePostfixType(){let e=this.state.startLoc,n=this.flowParsePrimaryType(),i=!1;for(;(this.match(0)||this.match(18))&&!this.canInsertSemicolon();){let s=this.startNodeAt(e),a=this.eat(18);i=i||a,this.expect(0),!a&&this.match(3)?(s.elementType=n,this.next(),n=this.finishNode(s,"ArrayTypeAnnotation")):(s.objectType=n,s.indexType=this.flowParseType(),this.expect(3),i?(s.optional=a,n=this.finishNode(s,"OptionalIndexedAccessType")):n=this.finishNode(s,"IndexedAccessType"))}return n}flowParsePrefixType(){let e=this.startNode();return this.eat(17)?(e.typeAnnotation=this.flowParsePrefixType(),this.finishNode(e,"NullableTypeAnnotation")):this.flowParsePostfixType()}flowParseAnonFunctionWithoutParens(){let e=this.flowParsePrefixType();if(!this.state.noAnonFunctionType&&this.eat(19)){let n=this.startNodeAt(e.loc.start);return n.params=[this.reinterpretTypeAsFunctionTypeParam(e)],n.rest=null,n.this=null,n.returnType=this.flowParseType(),n.typeParameters=null,this.finishNode(n,"FunctionTypeAnnotation")}return e}flowParseIntersectionType(){let e=this.startNode();this.eat(45);let n=this.flowParseAnonFunctionWithoutParens();for(e.types=[n];this.eat(45);)e.types.push(this.flowParseAnonFunctionWithoutParens());return e.types.length===1?n:this.finishNode(e,"IntersectionTypeAnnotation")}flowParseUnionType(){let e=this.startNode();this.eat(43);let n=this.flowParseIntersectionType();for(e.types=[n];this.eat(43);)e.types.push(this.flowParseIntersectionType());return e.types.length===1?n:this.finishNode(e,"UnionTypeAnnotation")}flowParseType(){let e=this.state.inType;this.state.inType=!0;let n=this.flowParseUnionType();return this.state.inType=e,n}flowParseTypeOrImplicitInstantiation(){if(this.state.type===132&&this.state.value==="_"){let e=this.state.startLoc,n=this.parseIdentifier();return this.flowParseGenericType(e,n)}else return this.flowParseType()}flowParseTypeAnnotation(){let e=this.startNode();return e.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(e,"TypeAnnotation")}flowParseTypeAnnotatableIdentifier(){let e=this.startNode(),n=this.parseIdentifierName();return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),this.createIdentifier(e,n)}typeCastToParameter(e){return e.expression.typeAnnotation=e.typeAnnotation,this.resetEndLocation(e.expression,e.typeAnnotation.loc.end),e.expression}flowParseVariance(){let e=null;return this.match(53)?(e=this.startNode(),this.state.value==="+"?e.kind="plus":e.kind="minus",this.next(),this.finishNode(e,"Variance")):e}parseFunctionBody(e,n,i=!1){if(n){this.forwardNoArrowParamsConversionAt(e,()=>super.parseFunctionBody(e,!0,i));return}super.parseFunctionBody(e,!1,i)}parseFunctionBodyAndFinish(e,n,i=!1){if(this.match(14)){let s=this.startNode();[s.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),e.returnType=s.typeAnnotation?this.finishNode(s,"TypeAnnotation"):null}return super.parseFunctionBodyAndFinish(e,n,i)}parseStatementLike(e){if(this.state.strict&&this.isContextual(129)){let i=this.lookahead();if(Qe(i.type)){let s=this.startNode();return this.next(),this.flowParseInterface(s)}}else if(this.isContextual(126)){let i=this.startNode();return this.next(),this.flowParseEnumDeclaration(i)}let n=super.parseStatementLike(e);return this.flowPragma===void 0&&!this.isValidDirective(n)&&(this.flowPragma=null),n}parseExpressionStatement(e,n,i){if(n.type==="Identifier"){if(n.name==="declare"){if(this.match(80)||te(this.state.type)||this.match(68)||this.match(74)||this.match(82))return this.flowParseDeclare(e)}else if(te(this.state.type)){if(n.name==="interface")return this.flowParseInterface(e);if(n.name==="type")return this.flowParseTypeAlias(e);if(n.name==="opaque")return this.flowParseOpaqueType(e,!1)}}return super.parseExpressionStatement(e,n,i)}shouldParseExportDeclaration(){let{type:e}=this.state;return e===126||Tu(e)?!this.state.containsEsc:super.shouldParseExportDeclaration()}isExportDefaultSpecifier(){let{type:e}=this.state;return e===126||Tu(e)?this.state.containsEsc:super.isExportDefaultSpecifier()}parseExportDefaultExpression(){if(this.isContextual(126)){let e=this.startNode();return this.next(),this.flowParseEnumDeclaration(e)}return super.parseExportDefaultExpression()}parseConditional(e,n,i){if(!this.match(17))return e;if(this.state.maybeInArrowParameters){let p=this.lookaheadCharCode();if(p===44||p===61||p===58||p===41)return this.setOptionalParametersError(i),e}this.expect(17);let s=this.state.clone(),a=this.state.noArrowAt,o=this.startNodeAt(n),{consequent:d,failed:c}=this.tryParseConditionalConsequent(),[l,u]=this.getArrowLikeExpressions(d);if(c||u.length>0){let p=[...a];if(u.length>0){this.state=s,this.state.noArrowAt=p;for(let f=0;f<u.length;f++)p.push(u[f].start);({consequent:d,failed:c}=this.tryParseConditionalConsequent()),[l,u]=this.getArrowLikeExpressions(d)}c&&l.length>1&&this.raise(z.AmbiguousConditionalArrow,s.startLoc),c&&l.length===1&&(this.state=s,p.push(l[0].start),this.state.noArrowAt=p,{consequent:d,failed:c}=this.tryParseConditionalConsequent())}return this.getArrowLikeExpressions(d,!0),this.state.noArrowAt=a,this.expect(14),o.test=e,o.consequent=d,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(),n=!this.match(14);return this.state.noArrowParamsConversionAt.pop(),{consequent:e,failed:n}}getArrowLikeExpressions(e,n){let i=[e],s=[];for(;i.length!==0;){let a=i.pop();a.type==="ArrowFunctionExpression"?(a.typeParameters||!a.returnType?this.finishArrowValidation(a):s.push(a),a.body.type!=="BlockStatement"&&i.push(a.body)):a.type==="ConditionalExpression"&&(i.push(a.consequent),i.push(a.alternate))}return n?(s.forEach(a=>this.finishArrowValidation(a)),[s,[]]):yb(s,a=>a.params.every(o=>this.isAssignable(o,!0)))}finishArrowValidation(e){var n;this.toAssignableList(e.params,(n=e.extra)==null?void 0:n.trailingCommaLoc,!1),this.scope.enter(518),super.checkParams(e,!1,!0),this.scope.exit()}forwardNoArrowParamsConversionAt(e,n){let i;return this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))?(this.state.noArrowParamsConversionAt.push(this.state.start),i=n(),this.state.noArrowParamsConversionAt.pop()):i=n(),i}parseParenItem(e,n){let i=super.parseParenItem(e,n);if(this.eat(17)&&(i.optional=!0,this.resetEndLocation(e)),this.match(14)){let s=this.startNodeAt(n);return s.expression=i,s.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(s,"TypeCastExpression")}return i}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(130)){e.exportKind="type";let n=this.startNode();return this.next(),this.match(5)?(e.specifiers=this.parseExportSpecifiers(!0),super.parseExportFrom(e),null):this.flowParseTypeAlias(n)}else if(this.isContextual(131)){e.exportKind="type";let n=this.startNode();return this.next(),this.flowParseOpaqueType(n,!1)}else if(this.isContextual(129)){e.exportKind="type";let n=this.startNode();return this.next(),this.flowParseInterface(n)}else if(this.isContextual(126)){e.exportKind="value";let n=this.startNode();return this.next(),this.flowParseEnumDeclaration(n)}else return super.parseExportDeclaration(e)}eatExportStar(e){return super.eatExportStar(e)?!0:this.isContextual(130)&&this.lookahead().type===55?(e.exportKind="type",this.next(),this.next(),!0):!1}maybeParseExportNamespaceSpecifier(e){let{startLoc:n}=this.state,i=super.maybeParseExportNamespaceSpecifier(e);return i&&e.exportKind==="type"&&this.unexpected(n),i}parseClassId(e,n,i){super.parseClassId(e,n,i),this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration())}parseClassMember(e,n,i){let{startLoc:s}=this.state;if(this.isContextual(125)){if(super.parseClassMemberFromModifier(e,n))return;n.declare=!0}super.parseClassMember(e,n,i),n.declare&&(n.type!=="ClassProperty"&&n.type!=="ClassPrivateProperty"&&n.type!=="PropertyDefinition"?this.raise(z.DeclareClassElement,s):n.value&&this.raise(z.DeclareClassFieldInitializer,n.value))}isIterator(e){return e==="iterator"||e==="asyncIterator"}readIterator(){let e=super.readWord1(),n="@@"+e;(!this.isIterator(e)||!this.state.inType)&&this.raise(b.InvalidIdentifier,this.state.curPosition(),{identifierName:n}),this.finishToken(132,n)}getTokenFromCode(e){let n=this.input.charCodeAt(this.state.pos+1);e===123&&n===124?this.finishOp(6,2):this.state.inType&&(e===62||e===60)?this.finishOp(e===62?48:47,1):this.state.inType&&e===63?n===46?this.finishOp(18,2):this.finishOp(17,1):lb(e,n,this.input.charCodeAt(this.state.pos+2))?(this.state.pos+=2,this.readIterator()):super.getTokenFromCode(e)}isAssignable(e,n){return e.type==="TypeCastExpression"?this.isAssignable(e.expression,n):super.isAssignable(e,n)}toAssignable(e,n=!1){!n&&e.type==="AssignmentExpression"&&e.left.type==="TypeCastExpression"&&(e.left=this.typeCastToParameter(e.left)),super.toAssignable(e,n)}toAssignableList(e,n,i){for(let s=0;s<e.length;s++){let a=e[s];a?.type==="TypeCastExpression"&&(e[s]=this.typeCastToParameter(a))}super.toAssignableList(e,n,i)}toReferencedList(e,n){for(let s=0;s<e.length;s++){var i;let a=e[s];a&&a.type==="TypeCastExpression"&&!((i=a.extra)!=null&&i.parenthesized)&&(e.length>1||!n)&&this.raise(z.TypeCastInPattern,a.typeAnnotation)}return e}parseArrayLike(e,n,i){let s=super.parseArrayLike(e,n,i);return i!=null&&!this.state.maybeInArrowParameters&&this.toReferencedList(s.elements),s}isValidLVal(e,n,i,s){return e==="TypeCastExpression"||super.isValidLVal(e,n,i,s)}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,n,i,s,a,o){if(n.variance&&this.unexpected(n.variance.loc.start),delete n.variance,this.match(47)&&(n.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassMethod(e,n,i,s,a,o),n.params&&a){let d=n.params;d.length>0&&this.isThisParam(d[0])&&this.raise(z.ThisParamBannedInConstructor,n)}else if(n.type==="MethodDefinition"&&a&&n.value.params){let d=n.value.params;d.length>0&&this.isThisParam(d[0])&&this.raise(z.ThisParamBannedInConstructor,n)}}pushClassPrivateMethod(e,n,i,s){n.variance&&this.unexpected(n.variance.loc.start),delete n.variance,this.match(47)&&(n.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassPrivateMethod(e,n,i,s)}parseClassSuper(e){if(super.parseClassSuper(e),e.superClass&&(this.match(47)||this.match(51))&&(e.superTypeParameters=this.flowParseTypeParameterInstantiationInExpression()),this.isContextual(113)){this.next();let n=e.implements=[];do{let i=this.startNode();i.id=this.flowParseRestrictedIdentifier(!0),this.match(47)?i.typeParameters=this.flowParseTypeParameterInstantiation():i.typeParameters=null,n.push(this.finishNode(i,"ClassImplements"))}while(this.eat(12))}}checkGetterSetterParams(e){super.checkGetterSetterParams(e);let n=this.getObjectOrClassMethodParams(e);if(n.length>0){let i=n[0];this.isThisParam(i)&&e.kind==="get"?this.raise(z.GetterMayNotHaveThisParam,i):this.isThisParam(i)&&this.raise(z.SetterMayNotHaveThisParam,i)}}parsePropertyNamePrefixOperator(e){e.variance=this.flowParseVariance()}parseObjPropValue(e,n,i,s,a,o,d){e.variance&&this.unexpected(e.variance.loc.start),delete e.variance;let c;this.match(47)&&!o&&(c=this.flowParseTypeParameterDeclaration(),this.match(10)||this.unexpected());let l=super.parseObjPropValue(e,n,i,s,a,o,d);return c&&((l.value||l).typeParameters=c),l}parseFunctionParamType(e){return this.eat(17)&&(e.type!=="Identifier"&&this.raise(z.PatternIsOptional,e),this.isThisParam(e)&&this.raise(z.ThisParamMayNotBeOptional,e),e.optional=!0),this.match(14)?e.typeAnnotation=this.flowParseTypeAnnotation():this.isThisParam(e)&&this.raise(z.ThisParamAnnotationRequired,e),this.match(29)&&this.isThisParam(e)&&this.raise(z.ThisParamNoDefault,e),this.resetEndLocation(e),e}parseMaybeDefault(e,n){let i=super.parseMaybeDefault(e,n);return i.type==="AssignmentPattern"&&i.typeAnnotation&&i.right.start<i.typeAnnotation.start&&this.raise(z.TypeBeforeInitializer,i.typeAnnotation),i}checkImportReflection(e){super.checkImportReflection(e),e.module&&e.importKind!=="value"&&this.raise(z.ImportReflectionHasImportType,e.specifiers[0].loc.start)}parseImportSpecifierLocal(e,n,i){n.local=Au(e)?this.flowParseRestrictedIdentifier(!0,!0):this.parseIdentifier(),e.specifiers.push(this.finishImportSpecifier(n,i))}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return!0;if(this.isContextual(130)){if(!e)return!0;let n=this.lookaheadCharCode();return n===123||n===42}return!e&&this.isContextual(87)}applyImportPhase(e,n,i,s){if(super.applyImportPhase(e,n,i,s),n){if(!i&&this.match(65))return;e.exportKind=i==="type"?i:"value"}else i==="type"&&this.match(55)&&this.unexpected(),e.importKind=i==="type"||i==="typeof"?i:"value"}parseImportSpecifier(e,n,i,s,a){let o=e.imported,d=null;o.type==="Identifier"&&(o.name==="type"?d="type":o.name==="typeof"&&(d="typeof"));let c=!1;if(this.isContextual(93)&&!this.isLookaheadContextual("as")){let u=this.parseIdentifier(!0);d!==null&&!Qe(this.state.type)?(e.imported=u,e.importKind=d,e.local=this.cloneIdentifier(u)):(e.imported=o,e.importKind=null,e.local=this.parseIdentifier())}else{if(d!==null&&Qe(this.state.type))e.imported=this.parseIdentifier(!0),e.importKind=d;else{if(n)throw this.raise(b.ImportBindingIsString,e,{importName:o.value});e.imported=o,e.importKind=null}this.eatContextual(93)?e.local=this.parseIdentifier():(c=!0,e.local=this.cloneIdentifier(e.imported))}let l=Au(e);return i&&l&&this.raise(z.ImportTypeShorthandOnlyInPureImport,e),(i||l)&&this.checkReservedType(e.local.name,e.local.loc.start,!0),c&&!i&&!l&&this.checkReservedWord(e.local.name,e.loc.start,!0,!0),this.finishImportSpecifier(e,"ImportSpecifier")}parseBindingAtom(){return this.state.type===78?this.parseIdentifier(!0):super.parseBindingAtom()}parseFunctionParams(e,n){let i=e.kind;i!=="get"&&i!=="set"&&this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),super.parseFunctionParams(e,n)}parseVarId(e,n){super.parseVarId(e,n),this.match(14)&&(e.id.typeAnnotation=this.flowParseTypeAnnotation(),this.resetEndLocation(e.id))}parseAsyncArrowFromCallExpression(e,n){if(this.match(14)){let i=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0,e.returnType=this.flowParseTypeAnnotation(),this.state.noAnonFunctionType=i}return super.parseAsyncArrowFromCallExpression(e,n)}shouldParseAsyncArrow(){return this.match(14)||super.shouldParseAsyncArrow()}parseMaybeAssign(e,n){var i;let s=null,a;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){if(s=this.state.clone(),a=this.tryParse(()=>super.parseMaybeAssign(e,n),s),!a.error)return a.node;let{context:c}=this.state,l=c[c.length-1];(l===ee.j_oTag||l===ee.j_expr)&&c.pop()}if((i=a)!=null&&i.error||this.match(47)){var o,d;s=s||this.state.clone();let c,l=this.tryParse(p=>{var f;c=this.flowParseTypeParameterDeclaration();let h=this.forwardNoArrowParamsConversionAt(c,()=>{let m=super.parseMaybeAssign(e,n);return this.resetStartLocationFromNode(m,c),m});(f=h.extra)!=null&&f.parenthesized&&p();let g=this.maybeUnwrapTypeCastExpression(h);return g.type!=="ArrowFunctionExpression"&&p(),g.typeParameters=c,this.resetStartLocationFromNode(g,c),h},s),u=null;if(l.node&&this.maybeUnwrapTypeCastExpression(l.node).type==="ArrowFunctionExpression"){if(!l.error&&!l.aborted)return l.node.async&&this.raise(z.UnexpectedTypeParameterBeforeAsyncArrowFunction,c),l.node;u=l.node}if((o=a)!=null&&o.node)return this.state=a.failState,a.node;if(u)return this.state=l.failState,u;throw(d=a)!=null&&d.thrown?a.error:l.thrown?l.error:this.raise(z.UnexpectedTokenAfterTypeParameter,c)}return super.parseMaybeAssign(e,n)}parseArrow(e){if(this.match(14)){let n=this.tryParse(()=>{let i=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0;let s=this.startNode();return[s.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),this.state.noAnonFunctionType=i,this.canInsertSemicolon()&&this.unexpected(),this.match(19)||this.unexpected(),s});if(n.thrown)return null;n.error&&(this.state=n.failState),e.returnType=n.node.typeAnnotation?this.finishNode(n.node,"TypeAnnotation"):null}return super.parseArrow(e)}shouldParseArrow(e){return this.match(14)||super.shouldParseArrow(e)}setArrowFunctionParameters(e,n){this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))?e.params=n:super.setArrowFunctionParameters(e,n)}checkParams(e,n,i,s=!0){if(!(i&&this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start)))){for(let a=0;a<e.params.length;a++)this.isThisParam(e.params[a])&&a>0&&this.raise(z.ThisParamMustBeFirst,e.params[a]);super.checkParams(e,n,i,s)}}parseParenAndDistinguishExpression(e){return super.parseParenAndDistinguishExpression(e&&!this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)))}parseSubscripts(e,n,i){if(e.type==="Identifier"&&e.name==="async"&&this.state.noArrowAt.includes(n.index)){this.next();let s=this.startNodeAt(n);s.callee=e,s.arguments=super.parseCallExpressionArguments(),e=this.finishNode(s,"CallExpression")}else if(e.type==="Identifier"&&e.name==="async"&&this.match(47)){let s=this.state.clone(),a=this.tryParse(d=>this.parseAsyncArrowWithTypeParameters(n)||d(),s);if(!a.error&&!a.aborted)return a.node;let o=this.tryParse(()=>super.parseSubscripts(e,n,i),s);if(o.node&&!o.error)return o.node;if(a.node)return this.state=a.failState,a.node;if(o.node)return this.state=o.failState,o.node;throw a.error||o.error}return super.parseSubscripts(e,n,i)}parseSubscript(e,n,i,s){if(this.match(18)&&this.isLookaheadToken_lt()){if(s.optionalChainMember=!0,i)return s.stop=!0,e;this.next();let a=this.startNodeAt(n);return a.callee=e,a.typeArguments=this.flowParseTypeParameterInstantiationInExpression(),this.expect(10),a.arguments=this.parseCallExpressionArguments(),a.optional=!0,this.finishCallExpression(a,!0)}else if(!i&&this.shouldParseTypes()&&(this.match(47)||this.match(51))){let a=this.startNodeAt(n);a.callee=e;let o=this.tryParse(()=>(a.typeArguments=this.flowParseTypeParameterInstantiationCallOrNew(),this.expect(10),a.arguments=super.parseCallExpressionArguments(),s.optionalChainMember&&(a.optional=!1),this.finishCallExpression(a,s.optionalChainMember)));if(o.node)return o.error&&(this.state=o.failState),o.node}return super.parseSubscript(e,n,i,s)}parseNewCallee(e){super.parseNewCallee(e);let n=null;this.shouldParseTypes()&&this.match(47)&&(n=this.tryParse(()=>this.flowParseTypeParameterInstantiationCallOrNew()).node),e.typeArguments=n}parseAsyncArrowWithTypeParameters(e){let n=this.startNodeAt(e);if(this.parseFunctionParams(n,!1),!!this.parseArrow(n))return super.parseArrowExpression(n,void 0,!0)}readToken_mult_modulo(e){let n=this.input.charCodeAt(this.state.pos+1);if(e===42&&n===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 n=this.input.charCodeAt(this.state.pos+1);if(e===124&&n===125){this.finishOp(9,2);return}super.readToken_pipe_amp(e)}parseTopLevel(e,n){let i=super.parseTopLevel(e,n);return this.state.hasFlowComment&&this.raise(z.UnterminatedFlowComment,this.state.curPosition()),i}skipBlockComment(){if(this.hasPlugin("flowComments")&&this.skipFlowComment()){if(this.state.hasFlowComment)throw this.raise(z.NestedFlowComment,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,n=2;for(;[32,9].includes(this.input.charCodeAt(e+n));)n++;let i=this.input.charCodeAt(n+e),s=this.input.charCodeAt(n+e+1);return i===58&&s===58?n+2:this.input.slice(n+e,n+e+12)==="flow-include"?n+12:i===58&&s!==58?n:!1}hasFlowCommentCompletion(){if(this.input.indexOf("*/",this.state.pos)===-1)throw this.raise(b.UnterminatedComment,this.state.curPosition())}flowEnumErrorBooleanMemberNotInitialized(e,{enumName:n,memberName:i}){this.raise(z.EnumBooleanMemberNotInitialized,e,{memberName:i,enumName:n})}flowEnumErrorInvalidMemberInitializer(e,n){return this.raise(n.explicitType?n.explicitType==="symbol"?z.EnumInvalidMemberInitializerSymbolType:z.EnumInvalidMemberInitializerPrimaryType:z.EnumInvalidMemberInitializerUnknownType,e,n)}flowEnumErrorNumberMemberNotInitialized(e,n){this.raise(z.EnumNumberMemberNotInitialized,e,n)}flowEnumErrorStringMemberInconsistentlyInitialized(e,n){this.raise(z.EnumStringMemberInconsistentlyInitialized,e,n)}flowEnumMemberInit(){let e=this.state.startLoc,n=()=>this.match(12)||this.match(8);switch(this.state.type){case 135:{let i=this.parseNumericLiteral(this.state.value);return n()?{type:"number",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}case 134:{let i=this.parseStringLiteral(this.state.value);return n()?{type:"string",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}case 85:case 86:{let i=this.parseBooleanLiteral(this.match(85));return n()?{type:"boolean",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}default:return{type:"invalid",loc:e}}}flowEnumMemberRaw(){let e=this.state.startLoc,n=this.parseIdentifier(!0),i=this.eat(29)?this.flowEnumMemberInit():{type:"none",loc:e};return{id:n,init:i}}flowEnumCheckExplicitTypeMismatch(e,n,i){let{explicitType:s}=n;s!==null&&s!==i&&this.flowEnumErrorInvalidMemberInitializer(e,n)}flowEnumMembers({enumName:e,explicitType:n}){let i=new Set,s={booleanMembers:[],numberMembers:[],stringMembers:[],defaultedMembers:[]},a=!1;for(;!this.match(8);){if(this.eat(21)){a=!0;break}let o=this.startNode(),{id:d,init:c}=this.flowEnumMemberRaw(),l=d.name;if(l==="")continue;/^[a-z]/.test(l)&&this.raise(z.EnumInvalidMemberName,d,{memberName:l,suggestion:l[0].toUpperCase()+l.slice(1),enumName:e}),i.has(l)&&this.raise(z.EnumDuplicateMemberName,d,{memberName:l,enumName:e}),i.add(l);let u={enumName:e,explicitType:n,memberName:l};switch(o.id=d,c.type){case"boolean":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"boolean"),o.init=c.value,s.booleanMembers.push(this.finishNode(o,"EnumBooleanMember"));break}case"number":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"number"),o.init=c.value,s.numberMembers.push(this.finishNode(o,"EnumNumberMember"));break}case"string":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"string"),o.init=c.value,s.stringMembers.push(this.finishNode(o,"EnumStringMember"));break}case"invalid":throw this.flowEnumErrorInvalidMemberInitializer(c.loc,u);case"none":switch(n){case"boolean":this.flowEnumErrorBooleanMemberNotInitialized(c.loc,u);break;case"number":this.flowEnumErrorNumberMemberNotInitialized(c.loc,u);break;default:s.defaultedMembers.push(this.finishNode(o,"EnumDefaultedMember"))}}this.match(8)||this.expect(12)}return{members:s,hasUnknownMembers:a}}flowEnumStringMembers(e,n,{enumName:i}){if(e.length===0)return n;if(n.length===0)return e;if(n.length>e.length){for(let s of e)this.flowEnumErrorStringMemberInconsistentlyInitialized(s,{enumName:i});return n}else{for(let s of n)this.flowEnumErrorStringMemberInconsistentlyInitialized(s,{enumName:i});return e}}flowEnumParseExplicitType({enumName:e}){if(!this.eatContextual(102))return null;if(!te(this.state.type))throw this.raise(z.EnumInvalidExplicitTypeUnknownSupplied,this.state.startLoc,{enumName:e});let{value:n}=this.state;return this.next(),n!=="boolean"&&n!=="number"&&n!=="string"&&n!=="symbol"&&this.raise(z.EnumInvalidExplicitType,this.state.startLoc,{enumName:e,invalidEnumType:n}),n}flowEnumBody(e,n){let i=n.name,s=n.loc.start,a=this.flowEnumParseExplicitType({enumName:i});this.expect(5);let{members:o,hasUnknownMembers:d}=this.flowEnumMembers({enumName:i,explicitType:a});switch(e.hasUnknownMembers=d,a){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 c=()=>(e.members=[],this.expect(8),this.finishNode(e,"EnumStringBody"));e.explicitType=!1;let l=o.booleanMembers.length,u=o.numberMembers.length,p=o.stringMembers.length,f=o.defaultedMembers.length;if(!l&&!u&&!p&&!f)return c();if(!l&&!u)return e.members=this.flowEnumStringMembers(o.stringMembers,o.defaultedMembers,{enumName:i}),this.expect(8),this.finishNode(e,"EnumStringBody");if(!u&&!p&&l>=f){for(let h of o.defaultedMembers)this.flowEnumErrorBooleanMemberNotInitialized(h.loc.start,{enumName:i,memberName:h.id.name});return e.members=o.booleanMembers,this.expect(8),this.finishNode(e,"EnumBooleanBody")}else if(!l&&!p&&u>=f){for(let h of o.defaultedMembers)this.flowEnumErrorNumberMemberNotInitialized(h.loc.start,{enumName:i,memberName:h.id.name});return e.members=o.numberMembers,this.expect(8),this.finishNode(e,"EnumNumberBody")}else return this.raise(z.EnumInconsistentMemberValues,s,{enumName:i}),c()}}}flowParseEnumDeclaration(e){let n=this.parseIdentifier();return e.id=n,e.body=this.flowEnumBody(this.startNode(),n),this.finishNode(e,"EnumDeclaration")}jsxParseOpeningElementAfterName(e){return this.shouldParseTypes()&&(this.match(47)||this.match(51))&&(e.typeArguments=this.flowParseTypeParameterInstantiationInExpression()),super.jsxParseOpeningElementAfterName(e)}isLookaheadToken_lt(){let e=this.nextTokenStart();if(this.input.charCodeAt(e)===60){let n=this.input.charCodeAt(e+1);return n!==60&&n!==61}return!1}reScan_lt_gt(){let{type:e}=this.state;e===47?(this.state.pos-=1,this.readToken_lt()):e===48&&(this.state.pos-=1,this.readToken_gt())}reScan_lt(){let{type:e}=this.state;return e===51?(this.state.pos-=2,this.finishOp(47,1),47):e}maybeUnwrapTypeCastExpression(e){return e.type==="TypeCastExpression"?e.expression:e}},bb={__proto__:null,quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:"\xA0",iexcl:"\xA1",cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",frac34:"\xBE",iquest:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acirc:"\xC2",Atilde:"\xC3",Auml:"\xC4",Aring:"\xC5",AElig:"\xC6",Ccedil:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecirc:"\xCA",Euml:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icirc:"\xCE",Iuml:"\xCF",ETH:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocirc:"\xD4",Otilde:"\xD5",Ouml:"\xD6",times:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucirc:"\xDB",Uuml:"\xDC",Yacute:"\xDD",THORN:"\xDE",szlig:"\xDF",agrave:"\xE0",aacute:"\xE1",acirc:"\xE2",atilde:"\xE3",auml:"\xE4",aring:"\xE5",aelig:"\xE6",ccedil:"\xE7",egrave:"\xE8",eacute:"\xE9",ecirc:"\xEA",euml:"\xEB",igrave:"\xEC",iacute:"\xED",icirc:"\xEE",iuml:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocirc:"\xF4",otilde:"\xF5",ouml:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucirc:"\xFB",uuml:"\xFC",yacute:"\xFD",thorn:"\xFE",yuml:"\xFF",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",fnof:"\u0192",circ:"\u02C6",tilde:"\u02DC",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039A",Lambda:"\u039B",Mu:"\u039C",Nu:"\u039D",Xi:"\u039E",Omicron:"\u039F",Pi:"\u03A0",Rho:"\u03A1",Sigma:"\u03A3",Tau:"\u03A4",Upsilon:"\u03A5",Phi:"\u03A6",Chi:"\u03A7",Psi:"\u03A8",Omega:"\u03A9",alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",rho:"\u03C1",sigmaf:"\u03C2",sigma:"\u03C3",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",thetasym:"\u03D1",upsih:"\u03D2",piv:"\u03D6",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",bull:"\u2022",hellip:"\u2026",permil:"\u2030",prime:"\u2032",Prime:"\u2033",lsaquo:"\u2039",rsaquo:"\u203A",oline:"\u203E",frasl:"\u2044",euro:"\u20AC",image:"\u2111",weierp:"\u2118",real:"\u211C",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21B5",lArr:"\u21D0",uArr:"\u21D1",rArr:"\u21D2",dArr:"\u21D3",hArr:"\u21D4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220B",prod:"\u220F",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221A",prop:"\u221D",infin:"\u221E",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222A",int:"\u222B",there4:"\u2234",sim:"\u223C",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22A5",sdot:"\u22C5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230A",rfloor:"\u230B",lang:"\u2329",rang:"\u232A",loz:"\u25CA",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666"},xb=/\r\n|[\r\n\u2028\u2029]/,_i=new RegExp(xb.source,"g");function Ir(r){switch(r){case 10:case 13:case 8232:case 8233:return!0;default:return!1}}function Su(r,t,e){for(let n=t;n<e;n++)if(Ir(r.charCodeAt(n)))return!0;return!1}var Qa=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,Za=/(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;function vb(r){switch(r){case 9:case 11:case 12:case 32:case 160:case 5760:case 8192:case 8193:case 8194:case 8195:case 8196:case 8197:case 8198:case 8199:case 8200:case 8201:case 8202:case 8239:case 8287:case 12288:case 65279:return!0;default:return!1}}var Kt=Ye`jsx`({AttributeIsEmpty:"JSX attributes must only be assigned a non-empty expression.",MissingClosingTagElement:({openingTagName:r})=>`Expected corresponding JSX closing tag for <${r}>.`,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:r,HTMLEntity:t})=>`Unexpected token \`${r}\`. Did you mean \`${t}\` or \`{'${r}'}\`?`,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 Et(r){return r?r.type==="JSXOpeningFragment"||r.type==="JSXClosingFragment":!1}function kr(r){if(r.type==="JSXIdentifier")return r.name;if(r.type==="JSXNamespacedName")return r.namespace.name+":"+r.name.name;if(r.type==="JSXMemberExpression")return kr(r.object)+"."+kr(r.property);throw new Error("Node had unexpected type: "+r.type)}var kb=r=>class extends r{jsxReadToken(){let e="",n=this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(Kt.UnterminatedJsxContent,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(143)):super.getTokenFromCode(i);return}e+=this.input.slice(n,this.state.pos),this.finishToken(142,e);return;case 38:e+=this.input.slice(n,this.state.pos),e+=this.jsxReadEntity(),n=this.state.pos;break;default:Ir(i)?(e+=this.input.slice(n,this.state.pos),e+=this.jsxReadNewLine(!0),n=this.state.pos):++this.state.pos}}}jsxReadNewLine(e){let n=this.input.charCodeAt(this.state.pos),i;return++this.state.pos,n===13&&this.input.charCodeAt(this.state.pos)===10?(++this.state.pos,i=e?`
5
+ - Did you mean \`import { "${r}" as foo }\`?`,ImportCallArity:"`import()` requires exactly 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.",InvalidCoverDiscardElement:"'void' must be followed by an expression when not used in a binding position.",InvalidCoverInitializedName:"Invalid shorthand property initializer.",InvalidDecimal:"Invalid decimal.",InvalidDigit:({radix:r})=>`Expected number in radix ${r}.`,InvalidEscapeSequence:"Bad character escape sequence.",InvalidEscapeSequenceTemplate:"Invalid escape sequence in template.",InvalidEscapedReservedWord:({reservedWord:r})=>`Escape sequence in keyword ${r}.`,InvalidIdentifier:({identifierName:r})=>`Invalid identifier ${r}.`,InvalidLhs:({ancestor:r})=>`Invalid left-hand side in ${Hi(r)}.`,InvalidLhsBinding:({ancestor:r})=>`Binding invalid left-hand side in ${Hi(r)}.`,InvalidLhsOptionalChaining:({ancestor:r})=>`Invalid optional chaining in the left-hand side of ${Hi(r)}.`,InvalidNumber:"Invalid number.",InvalidOrMissingExponent:"Floating-point numbers require a valid exponent after the 'e'.",InvalidOrUnexpectedToken:({unexpected:r})=>`Unexpected character '${r}'.`,InvalidParenthesizedAssignment:"Invalid parenthesized assignment pattern.",InvalidPrivateFieldResolution:({identifierName:r})=>`Private name #${r} 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:r})=>`Label '${r}' is already declared.`,LetInLexicalBinding:"'let' is disallowed as a lexically bound name.",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:r})=>`This experimental syntax requires enabling the parser plugin: ${r.map(t=>JSON.stringify(t)).join(", ")}.`,MissingOneOfPlugins:({missingPlugin:r})=>`This experimental syntax requires enabling one of the following parser plugin(s): ${r.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:r})=>`Duplicate key "${r}" is not allowed in module attributes.`,ModuleExportNameHasLoneSurrogate:({surrogateCharCode:r})=>`An export name cannot include a lone surrogate, found '\\u${r.toString(16)}'.`,ModuleExportUndefined:({localName:r})=>`Export '${r}' 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:r})=>`Private names are only allowed in property accesses (\`obj.#${r}\`) or in \`in\` expressions (\`#${r} in obj\`).`,PrivateNameRedeclaration:({identifierName:r})=>`Duplicate private name #${r}.`,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.",SourcePhaseImportRequiresDefault:'Only `import source x from "./module"` is valid.',StaticPrototype:"Classes may not have static property named prototype.",SuperCallNotNewExpression:"Cannot use new with super(...).",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:r})=>`Unexpected keyword '${r}'.`,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:r})=>`Unexpected reserved word '${r}'.`,UnexpectedSuper:"'super' is only allowed in object methods and classes.",UnexpectedToken:({expected:r,unexpected:t})=>`Unexpected token${t?` '${t}'.`:""}${r?`, expected "${r}"`:""}`,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` or in the bare case statement.",UnexpectedVoidPattern:"Unexpected void binding.",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:r,onlyValidPropertyName:t})=>`The only valid meta property for ${r} is ${r}.${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.",UsingDeclarationExport:"Using declaration cannot be exported.",UsingDeclarationHasBindingPattern:"Using declaration cannot have destructuring patterns.",VarRedeclaration:({identifierName:r})=>`Identifier '${r}' has already been declared.`,VoidPatternCatchClauseParam:"A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.",VoidPatternInitializer:"A void binding may not have an initializer.",YieldBindingIdentifier:"Can not use 'yield' as identifier inside a generator.",YieldInParameter:"Yield expression is not allowed in formal parameters.",YieldNotInGeneratorFunction:"'yield' is only allowed within generator functions.",ZeroDigitNumericSeparator:"Numeric separator can not be used after leading 0."},zw={StrictDelete:"Deleting local variable in strict mode.",StrictEvalArguments:({referenceName:r})=>`Assigning to '${r}' in strict mode.`,StrictEvalArgumentsBinding:({bindingName:r})=>`Binding '${r}' 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."},Hw={ParseExpressionEmptyInput:"Unexpected parseExpression() input: The input is empty or contains only comments.",ParseExpressionExpectsEOF:({unexpected:r})=>`Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(r)}\`.`},qw=new Set(["ArrowFunctionExpression","AssignmentExpression","ConditionalExpression","YieldExpression"]),Uw=Object.assign({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:r})=>`Invalid topic token ${r}. In order to use ${r} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${r}" }.`,PipeTopicUnused:"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",PipeUnparenthesizedBody:({type:r})=>`Hack-style pipe body cannot be an unparenthesized ${Hi({type:r})}; 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.'}),Gw={UnsupportedBind:"Binding should be performed on object property.",UnsupportedBindRHS:"The right-hand side of binding can not be super or import."},Kw=["message"];function Cu(r,t,e){Object.defineProperty(r,t,{enumerable:!1,configurable:!0,value:e})}function Ww({toMessage:r,code:t,reasonCode:e,syntaxPlugin:n}){let i=e==="MissingPlugin"||e==="MissingOneOfPlugins",s={AccessorCannotDeclareThisParameter:"AccesorCannotDeclareThisParameter",AccessorCannotHaveTypeParameters:"AccesorCannotHaveTypeParameters",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference",SetAccessorCannotHaveOptionalParameter:"SetAccesorCannotHaveOptionalParameter",SetAccessorCannotHaveRestParameter:"SetAccesorCannotHaveRestParameter",SetAccessorCannotHaveReturnType:"SetAccesorCannotHaveReturnType"};return s[e]&&(e=s[e]),function a(o,d){let c=new SyntaxError;return c.code=t,c.reasonCode=e,c.loc=o,c.pos=o.index,c.syntaxPlugin=n,i&&(c.missingPlugin=d.missingPlugin),Cu(c,"clone",function(u={}){var p;let{line:f,column:h,index:g}=(p=u.loc)!=null?p:o;return a(new lt(f,h,g),Object.assign({},d,u.details))}),Cu(c,"details",d),Object.defineProperty(c,"message",{configurable:!0,get(){let l=`${r(d)} (${o.line}:${o.column})`;return this.message=l,l},set(l){Object.defineProperty(this,"message",{value:l,writable:!0})}}),c}}function Qe(r,t){if(Array.isArray(r))return n=>Qe(n,r[0]);let e={};for(let n of Object.keys(r)){let i=r[n],s=typeof i=="string"?{message:()=>i}:typeof i=="function"?{message:i}:i,{message:a}=s,o=jw(s,Kw),d=typeof a=="string"?()=>a:a;e[n]=Ww(Object.assign({code:"BABEL_PARSER_SYNTAX_ERROR",reasonCode:n,toMessage:d},t?{syntaxPlugin:t}:{},o))}return e}var b=Object.assign({},Qe(Bw),Qe(Vw),Qe(zw),Qe(Hw),Qe`pipelineOperator`(Uw),Qe`functionBind`(Gw));function Jw(){return{sourceType:"script",sourceFilename:void 0,startIndex:0,startColumn:0,startLine:1,allowAwaitOutsideFunction:!1,allowReturnOutsideFunction:!1,allowNewTargetOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,allowUndeclaredExports:!1,allowYieldOutsideFunction:!1,plugins:[],strictMode:void 0,ranges:!1,tokens:!1,createImportExpressions:!1,createParenthesizedExpressions:!1,errorRecovery:!1,attachComment:!0,annexB:!0}}function Xw(r){let t=Jw();if(r==null)return t;if(r.annexB!=null&&r.annexB!==!1)throw new Error("The `annexB` option can only be set to `false`.");for(let e of Object.keys(t))r[e]!=null&&(t[e]=r[e]);if(t.startLine===1)r.startIndex==null&&t.startColumn>0?t.startIndex=t.startColumn:r.startColumn==null&&t.startIndex>0&&(t.startColumn=t.startIndex);else if((r.startColumn==null||r.startIndex==null)&&r.startIndex!=null)throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");if(t.sourceType==="commonjs"){if(r.allowAwaitOutsideFunction!=null)throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.");if(r.allowReturnOutsideFunction!=null)throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.");if(r.allowNewTargetOutsideFunction!=null)throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.")}return t}var{defineProperty:Yw}=Object,Nu=(r,t)=>{r&&Yw(r,t,{enumerable:!1,value:r[t]})};function mn(r){return Nu(r.loc.start,"index"),Nu(r.loc.end,"index"),r}var Qw=r=>class extends r{parse(){let e=mn(super.parse());return this.optionFlags&256&&(e.tokens=e.tokens.map(mn)),e}parseRegExpLiteral({pattern:e,flags:n}){let i=null;try{i=new RegExp(e,n)}catch{}let s=this.estreeParseLiteral(i);return s.regex={pattern:e,flags:n},s}parseBigIntLiteral(e){let n;try{n=BigInt(e)}catch{n=null}let i=this.estreeParseLiteral(n);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)}estreeParseChainExpression(e,n){let i=this.startNodeAtNode(e);return i.expression=e,this.finishNodeAt(i,"ChainExpression",n)}directiveToStmt(e){let n=e.value;delete e.value,this.castNodeTo(n,"Literal"),n.raw=n.extra.raw,n.value=n.extra.expressionValue;let i=this.castNodeTo(e,"ExpressionStatement");return i.expression=n,i.directive=n.extra.rawValue,delete n.extra,i}fillOptionalPropertiesForTSESLint(e){}cloneEstreeStringLiteral(e){let{start:n,end:i,loc:s,range:a,raw:o,value:d}=e,c=Object.create(e.constructor.prototype);return c.type="Literal",c.start=n,c.end=i,c.loc=s,c.range=a,c.raw=o,c.value=d,c}initFunction(e,n){super.initFunction(e,n),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 n;return e.type==="ExpressionStatement"&&e.expression.type==="Literal"&&typeof e.expression.value=="string"&&!((n=e.expression.extra)!=null&&n.parenthesized)}parseBlockBody(e,n,i,s,a){super.parseBlockBody(e,n,i,s,a);let o=e.directives.map(d=>this.directiveToStmt(d));e.body=o.concat(e.body),delete e.directives}parsePrivateName(){let e=super.parsePrivateName();return this.getPluginOption("estree","classFeatures")?this.convertPrivateNameToPrivateIdentifier(e):e}convertPrivateNameToPrivateIdentifier(e){let n=super.getPrivateNameSV(e);return delete e.id,e.name=n,this.castNodeTo(e,"PrivateIdentifier")}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,n){let i=super.parseLiteral(e,n);return i.raw=i.extra.raw,delete i.extra,i}parseFunctionBody(e,n,i=!1){super.parseFunctionBody(e,n,i),e.expression=e.body.type!=="BlockStatement"}parseMethod(e,n,i,s,a,o,d=!1){let c=this.startNode();c.kind=e.kind,c=super.parseMethod(c,n,i,s,a,o,d),delete c.kind;let{typeParameters:l}=e;l&&(delete e.typeParameters,c.typeParameters=l,this.resetStartLocationFromNode(c,l));let u=this.castNodeTo(c,"FunctionExpression");return e.value=u,o==="ClassPrivateMethod"&&(e.computed=!1),o==="ObjectMethod"?(e.kind==="method"&&(e.kind="init"),e.shorthand=!1,this.finishNode(e,"Property")):this.finishNode(e,"MethodDefinition")}nameIsConstructor(e){return e.type==="Literal"?e.value==="constructor":super.nameIsConstructor(e)}parseClassProperty(...e){let n=super.parseClassProperty(...e);return this.getPluginOption("estree","classFeatures")&&this.castNodeTo(n,"PropertyDefinition"),n}parseClassPrivateProperty(...e){let n=super.parseClassPrivateProperty(...e);return this.getPluginOption("estree","classFeatures")&&(this.castNodeTo(n,"PropertyDefinition"),n.computed=!1),n}parseClassAccessorProperty(e){let n=super.parseClassAccessorProperty(e);return this.getPluginOption("estree","classFeatures")&&(n.abstract&&this.hasPlugin("typescript")?(delete n.abstract,this.castNodeTo(n,"TSAbstractAccessorProperty")):this.castNodeTo(n,"AccessorProperty")),n}parseObjectProperty(e,n,i,s){let a=super.parseObjectProperty(e,n,i,s);return a&&(a.kind="init",this.castNodeTo(a,"Property")),a}finishObjectProperty(e){return e.kind="init",this.finishNode(e,"Property")}isValidLVal(e,n,i,s){return e==="Property"?"value":super.isValidLVal(e,n,i,s)}isAssignable(e,n){return e!=null&&this.isObjectProperty(e)?this.isAssignable(e.value,n):super.isAssignable(e,n)}toAssignable(e,n=!1){if(e!=null&&this.isObjectProperty(e)){let{key:i,value:s}=e;this.isPrivateName(i)&&this.classScope.usePrivateName(this.getPrivateNameSV(i),i.loc.start),this.toAssignable(s,n)}else super.toAssignable(e,n)}toAssignableObjectExpressionProp(e,n,i){e.type==="Property"&&(e.kind==="get"||e.kind==="set")?this.raise(b.PatternHasAccessor,e.key):e.type==="Property"&&e.method?this.raise(b.PatternHasMethod,e.key):super.toAssignableObjectExpressionProp(e,n,i)}finishCallExpression(e,n){let i=super.finishCallExpression(e,n);if(i.callee.type==="Import"){var s,a;this.castNodeTo(i,"ImportExpression"),i.source=i.arguments[0],i.options=(s=i.arguments[1])!=null?s:null,i.attributes=(a=i.arguments[1])!=null?a:null,delete i.arguments,delete i.callee}else i.type==="OptionalCallExpression"?this.castNodeTo(i,"CallExpression"):i.optional=!1;return i}toReferencedArguments(e){e.type!=="ImportExpression"&&super.toReferencedArguments(e)}parseExport(e,n){let i=this.state.lastTokStartLoc,s=super.parseExport(e,n);switch(s.type){case"ExportAllDeclaration":s.exported=null;break;case"ExportNamedDeclaration":s.specifiers.length===1&&s.specifiers[0].type==="ExportNamespaceSpecifier"&&(this.castNodeTo(s,"ExportAllDeclaration"),s.exported=s.specifiers[0].exported,delete s.specifiers);case"ExportDefaultDeclaration":{var a;let{declaration:o}=s;o?.type==="ClassDeclaration"&&((a=o.decorators)==null?void 0:a.length)>0&&o.start===s.start&&this.resetStartLocation(s,i)}break}return s}stopParseSubscript(e,n){let i=super.stopParseSubscript(e,n);return n.optionalChainMember?this.estreeParseChainExpression(i,e.loc.end):i}parseMember(e,n,i,s,a){let o=super.parseMember(e,n,i,s,a);return o.type==="OptionalMemberExpression"?this.castNodeTo(o,"MemberExpression"):o.optional=!1,o}isOptionalMemberExpression(e){return e.type==="ChainExpression"?e.expression.type==="MemberExpression":super.isOptionalMemberExpression(e)}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.type==="Property"&&(e.method||e.kind==="get"||e.kind==="set")}castNodeTo(e,n){let i=super.castNodeTo(e,n);return this.fillOptionalPropertiesForTSESLint(i),i}cloneIdentifier(e){let n=super.cloneIdentifier(e);return this.fillOptionalPropertiesForTSESLint(n),n}cloneStringLiteral(e){return e.type==="Literal"?this.cloneEstreeStringLiteral(e):super.cloneStringLiteral(e)}finishNodeAt(e,n,i){return mn(super.finishNodeAt(e,n,i))}finishNode(e,n){let i=super.finishNode(e,n);return this.fillOptionalPropertiesForTSESLint(i),i}resetStartLocation(e,n){super.resetStartLocation(e,n),mn(e)}resetEndLocation(e,n=this.state.lastTokEndLoc){super.resetEndLocation(e,n),mn(e)}},Jt=class{constructor(t,e){this.token=void 0,this.preserveSpace=void 0,this.token=t,this.preserveSpace=!!e}},te={brace:new Jt("{"),j_oTag:new Jt("<tag"),j_cTag:new Jt("</tag"),j_expr:new Jt("<tag>...</tag>",!0)};te.template=new Jt("`",!0);var U=!0,S=!0,ro=!0,yn=!0,Et=!0,Zw=!0,Gi=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}},Co=new Map;function Y(r,t={}){t.keyword=r;let e=F(r,t);return Co.set(r,e),e}function Ne(r,t){return F(r,{beforeExpr:U,binop:t})}var xn=-1,gt=[],No=[],Oo=[],Do=[],Lo=[],Mo=[];function F(r,t={}){var e,n,i,s;return++xn,No.push(r),Oo.push((e=t.binop)!=null?e:-1),Do.push((n=t.beforeExpr)!=null?n:!1),Lo.push((i=t.startsExpr)!=null?i:!1),Mo.push((s=t.prefix)!=null?s:!1),gt.push(new Gi(r,t)),xn}function G(r,t={}){var e,n,i,s;return++xn,Co.set(r,xn),No.push(r),Oo.push((e=t.binop)!=null?e:-1),Do.push((n=t.beforeExpr)!=null?n:!1),Lo.push((i=t.startsExpr)!=null?i:!1),Mo.push((s=t.prefix)!=null?s:!1),gt.push(new Gi("name",t)),xn}var eb={bracketL:F("[",{beforeExpr:U,startsExpr:S}),bracketHashL:F("#[",{beforeExpr:U,startsExpr:S}),bracketBarL:F("[|",{beforeExpr:U,startsExpr:S}),bracketR:F("]"),bracketBarR:F("|]"),braceL:F("{",{beforeExpr:U,startsExpr:S}),braceBarL:F("{|",{beforeExpr:U,startsExpr:S}),braceHashL:F("#{",{beforeExpr:U,startsExpr:S}),braceR:F("}"),braceBarR:F("|}"),parenL:F("(",{beforeExpr:U,startsExpr:S}),parenR:F(")"),comma:F(",",{beforeExpr:U}),semi:F(";",{beforeExpr:U}),colon:F(":",{beforeExpr:U}),doubleColon:F("::",{beforeExpr:U}),dot:F("."),question:F("?",{beforeExpr:U}),questionDot:F("?."),arrow:F("=>",{beforeExpr:U}),template:F("template"),ellipsis:F("...",{beforeExpr:U}),backQuote:F("`",{startsExpr:S}),dollarBraceL:F("${",{beforeExpr:U,startsExpr:S}),templateTail:F("...`",{startsExpr:S}),templateNonTail:F("...${",{beforeExpr:U,startsExpr:S}),at:F("@"),hash:F("#",{startsExpr:S}),interpreterDirective:F("#!..."),eq:F("=",{beforeExpr:U,isAssign:yn}),assign:F("_=",{beforeExpr:U,isAssign:yn}),slashAssign:F("_=",{beforeExpr:U,isAssign:yn}),xorAssign:F("_=",{beforeExpr:U,isAssign:yn}),moduloAssign:F("_=",{beforeExpr:U,isAssign:yn}),incDec:F("++/--",{prefix:Et,postfix:Zw,startsExpr:S}),bang:F("!",{beforeExpr:U,prefix:Et,startsExpr:S}),tilde:F("~",{beforeExpr:U,prefix:Et,startsExpr:S}),doubleCaret:F("^^",{startsExpr:S}),doubleAt:F("@@",{startsExpr:S}),pipeline:Ne("|>",0),nullishCoalescing:Ne("??",1),logicalOR:Ne("||",1),logicalAND:Ne("&&",2),bitwiseOR:Ne("|",3),bitwiseXOR:Ne("^",4),bitwiseAND:Ne("&",5),equality:Ne("==/!=/===/!==",6),lt:Ne("</>/<=/>=",7),gt:Ne("</>/<=/>=",7),relational:Ne("</>/<=/>=",7),bitShift:Ne("<</>>/>>>",8),bitShiftL:Ne("<</>>/>>>",8),bitShiftR:Ne("<</>>/>>>",8),plusMin:F("+/-",{beforeExpr:U,binop:9,prefix:Et,startsExpr:S}),modulo:F("%",{binop:10,startsExpr:S}),star:F("*",{binop:10}),slash:Ne("/",10),exponent:F("**",{beforeExpr:U,binop:11,rightAssociative:!0}),_in:Y("in",{beforeExpr:U,binop:7}),_instanceof:Y("instanceof",{beforeExpr:U,binop:7}),_break:Y("break"),_case:Y("case",{beforeExpr:U}),_catch:Y("catch"),_continue:Y("continue"),_debugger:Y("debugger"),_default:Y("default",{beforeExpr:U}),_else:Y("else",{beforeExpr:U}),_finally:Y("finally"),_function:Y("function",{startsExpr:S}),_if:Y("if"),_return:Y("return",{beforeExpr:U}),_switch:Y("switch"),_throw:Y("throw",{beforeExpr:U,prefix:Et,startsExpr:S}),_try:Y("try"),_var:Y("var"),_const:Y("const"),_with:Y("with"),_new:Y("new",{beforeExpr:U,startsExpr:S}),_this:Y("this",{startsExpr:S}),_super:Y("super",{startsExpr:S}),_class:Y("class",{startsExpr:S}),_extends:Y("extends",{beforeExpr:U}),_export:Y("export"),_import:Y("import",{startsExpr:S}),_null:Y("null",{startsExpr:S}),_true:Y("true",{startsExpr:S}),_false:Y("false",{startsExpr:S}),_typeof:Y("typeof",{beforeExpr:U,prefix:Et,startsExpr:S}),_void:Y("void",{beforeExpr:U,prefix:Et,startsExpr:S}),_delete:Y("delete",{beforeExpr:U,prefix:Et,startsExpr:S}),_do:Y("do",{isLoop:ro,beforeExpr:U}),_for:Y("for",{isLoop:ro}),_while:Y("while",{isLoop:ro}),_as:G("as",{startsExpr:S}),_assert:G("assert",{startsExpr:S}),_async:G("async",{startsExpr:S}),_await:G("await",{startsExpr:S}),_defer:G("defer",{startsExpr:S}),_from:G("from",{startsExpr:S}),_get:G("get",{startsExpr:S}),_let:G("let",{startsExpr:S}),_meta:G("meta",{startsExpr:S}),_of:G("of",{startsExpr:S}),_sent:G("sent",{startsExpr:S}),_set:G("set",{startsExpr:S}),_source:G("source",{startsExpr:S}),_static:G("static",{startsExpr:S}),_using:G("using",{startsExpr:S}),_yield:G("yield",{startsExpr:S}),_asserts:G("asserts",{startsExpr:S}),_checks:G("checks",{startsExpr:S}),_exports:G("exports",{startsExpr:S}),_global:G("global",{startsExpr:S}),_implements:G("implements",{startsExpr:S}),_intrinsic:G("intrinsic",{startsExpr:S}),_infer:G("infer",{startsExpr:S}),_is:G("is",{startsExpr:S}),_mixins:G("mixins",{startsExpr:S}),_proto:G("proto",{startsExpr:S}),_require:G("require",{startsExpr:S}),_satisfies:G("satisfies",{startsExpr:S}),_keyof:G("keyof",{startsExpr:S}),_readonly:G("readonly",{startsExpr:S}),_unique:G("unique",{startsExpr:S}),_abstract:G("abstract",{startsExpr:S}),_declare:G("declare",{startsExpr:S}),_enum:G("enum",{startsExpr:S}),_module:G("module",{startsExpr:S}),_namespace:G("namespace",{startsExpr:S}),_interface:G("interface",{startsExpr:S}),_type:G("type",{startsExpr:S}),_opaque:G("opaque",{startsExpr:S}),name:F("name",{startsExpr:S}),placeholder:F("%%",{startsExpr:S}),string:F("string",{startsExpr:S}),num:F("num",{startsExpr:S}),bigint:F("bigint",{startsExpr:S}),decimal:F("decimal",{startsExpr:S}),regexp:F("regexp",{startsExpr:S}),privateName:F("#name",{startsExpr:S}),eof:F("eof"),jsxName:F("jsxName"),jsxText:F("jsxText",{beforeExpr:U}),jsxTagStart:F("jsxTagStart",{startsExpr:S}),jsxTagEnd:F("jsxTagEnd")};function re(r){return r>=93&&r<=133}function tb(r){return r<=92}function Ze(r){return r>=58&&r<=133}function Hu(r){return r>=58&&r<=137}function rb(r){return Do[r]}function wn(r){return Lo[r]}function nb(r){return r>=29&&r<=33}function Ou(r){return r>=129&&r<=131}function ib(r){return r>=90&&r<=92}function $o(r){return r>=58&&r<=92}function sb(r){return r>=39&&r<=59}function ab(r){return r===34}function ob(r){return Mo[r]}function db(r){return r>=121&&r<=123}function cb(r){return r>=124&&r<=130}function Nt(r){return No[r]}function qi(r){return Oo[r]}function lb(r){return r===57}function Ki(r){return r>=24&&r<=25}function yt(r){return gt[r]}gt[8].updateContext=r=>{r.pop()};gt[5].updateContext=gt[7].updateContext=gt[23].updateContext=r=>{r.push(te.brace)};gt[22].updateContext=r=>{r[r.length-1]===te.template?r.pop():r.push(te.template)};gt[143].updateContext=r=>{r.push(te.j_expr,te.j_oTag)};var _o="\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-\u088F\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\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\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-\u1C8A\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-\uA7DC\uA7F1-\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",qu="\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\u0897-\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-\u1ADD\u1AE0-\u1AEB\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\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\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\uFF65",ub=new RegExp("["+_o+"]"),pb=new RegExp("["+_o+qu+"]");_o=qu=null;var Uu=[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,4,51,13,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,7,25,39,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,39,27,10,22,251,41,7,1,17,5,57,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,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,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,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,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,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,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,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489],fb=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,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,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,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,199,7,137,9,54,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,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,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,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239];function co(r,t){let e=65536;for(let n=0,i=t.length;n<i;n+=2){if(e+=t[n],e>r)return!1;if(e+=t[n+1],e>=r)return!0}return!1}function ct(r){return r<65?r===36:r<=90?!0:r<97?r===95:r<=122?!0:r<=65535?r>=170&&ub.test(String.fromCharCode(r)):co(r,Uu)}function Xt(r){return r<48?r===36:r<58?!0:r<65?!1:r<=90?!0:r<97?r===95:r<=122?!0:r<=65535?r>=170&&pb.test(String.fromCharCode(r)):co(r,Uu)||co(r,fb)}var Fo={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"]},hb=new Set(Fo.keyword),mb=new Set(Fo.strict),yb=new Set(Fo.strictBind);function Gu(r,t){return t&&r==="await"||r==="enum"}function Ku(r,t){return Gu(r,t)||mb.has(r)}function Wu(r){return yb.has(r)}function Ju(r,t){return Ku(r,t)||Wu(r)}function gb(r){return hb.has(r)}function wb(r,t,e){return r===64&&t===64&&ct(e)}var bb=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 xb(r){return bb.has(r)}var vn=class{constructor(t){this.flags=0,this.names=new Map,this.firstLexicalName="",this.flags=t}},kn=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 allowNewTarget(){return(this.currentThisScopeFlags()&512)>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&1731)return!1}}get inNonArrowFunction(){return(this.currentThisScopeFlags()&2)>0}get inBareCaseStatement(){return(this.currentScope().flags&256)>0}get treatFunctionsAsVar(){return this.treatFunctionsAsVarInScope(this.currentScope())}createScope(t){return new vn(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,n){let i=this.currentScope();if(e&8||e&16){this.checkRedeclarationInScope(i,t,e,n);let s=i.names.get(t)||0;e&16?s=s|4:(i.firstLexicalName||(i.firstLexicalName=t),s=s|2),i.names.set(t,s),e&8&&this.maybeExportDefined(i,t)}else if(e&4)for(let s=this.scopeStack.length-1;s>=0&&(i=this.scopeStack[s],this.checkRedeclarationInScope(i,t,e,n),i.names.set(t,(i.names.get(t)||0)|1),this.maybeExportDefined(i,t),!(i.flags&1667));--s);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,n,i){this.isRedeclaredInScope(t,e,n)&&this.parser.raise(b.VarRedeclaration,i,{identifierName:e})}isRedeclaredInScope(t,e,n){if(!(n&1))return!1;if(n&8)return t.names.has(e);let i=t.names.get(e)||0;return n&16?(i&2)>0||!this.treatFunctionsAsVarInScope(t)&&(i&1)>0:(i&2)>0&&!(t.flags&8&&t.firstLexicalName===e)||!this.treatFunctionsAsVarInScope(t)&&(i&4)>0}checkLocalExport(t){let{name:e}=t;this.scopeStack[0].names.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&1667)return e}}currentThisScopeFlags(){for(let t=this.scopeStack.length-1;;t--){let{flags:e}=this.scopeStack[t];if(e&1731&&!(e&4))return e}}},lo=class extends vn{constructor(...t){super(...t),this.declareFunctions=new Set}},uo=class extends kn{createScope(t){return new lo(t)}declareName(t,e,n){let i=this.currentScope();if(e&2048){this.checkRedeclarationInScope(i,t,e,n),this.maybeExportDefined(i,t),i.declareFunctions.add(t);return}super.declareName(t,e,n)}isRedeclaredInScope(t,e,n){if(super.isRedeclaredInScope(t,e,n))return!0;if(n&2048&&!t.declareFunctions.has(e)){let i=t.names.get(e);return(i&4)>0||(i&2)>0}return!1}checkLocalExport(t){this.scopeStack[0].declareFunctions.has(t.name)||super.checkLocalExport(t)}},vb=new Set(["_","any","bool","boolean","empty","extends","false","interface","mixed","null","number","static","string","true","typeof","void"]),B=Qe`flow`({AmbiguousConditionalArrow:"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",AmbiguousDeclareModuleKind:"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",AssignReservedType:({reservedType:r})=>`Cannot overwrite reserved type ${r}.`,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:r,enumName:t})=>`Boolean enum members need to be initialized. Use either \`${r} = true,\` or \`${r} = false,\` in enum \`${t}\`.`,EnumDuplicateMemberName:({memberName:r,enumName:t})=>`Enum member names need to be unique, but the name \`${r}\` has already been used before in enum \`${t}\`.`,EnumInconsistentMemberValues:({enumName:r})=>`Enum \`${r}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,EnumInvalidExplicitType:({invalidEnumType:r,enumName:t})=>`Enum type \`${r}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${t}\`.`,EnumInvalidExplicitTypeUnknownSupplied:({enumName:r})=>`Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${r}\`.`,EnumInvalidMemberInitializerPrimaryType:({enumName:r,memberName:t,explicitType:e})=>`Enum \`${r}\` has type \`${e}\`, so the initializer of \`${t}\` needs to be a ${e} literal.`,EnumInvalidMemberInitializerSymbolType:({enumName:r,memberName:t})=>`Symbol enum members cannot be initialized. Use \`${t},\` in enum \`${r}\`.`,EnumInvalidMemberInitializerUnknownType:({enumName:r,memberName:t})=>`The enum member initializer for \`${t}\` needs to be a literal (either a boolean, number, or string) in enum \`${r}\`.`,EnumInvalidMemberName:({enumName:r,memberName:t,suggestion:e})=>`Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${t}\`, consider using \`${e}\`, in enum \`${r}\`.`,EnumNumberMemberNotInitialized:({enumName:r,memberName:t})=>`Number enum members need to be initialized, e.g. \`${t} = 1\` in enum \`${r}\`.`,EnumStringMemberInconsistentlyInitialized:({enumName:r})=>`String enum members need to consistently either all use initializers, or use no initializers, in enum \`${r}\`.`,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:r})=>`Unexpected reserved type ${r}.`,UnexpectedReservedUnderscore:"`_` is only allowed as a type argument to call or new.",UnexpectedSpaceBetweenModuloChecks:"Spaces between `%` and `checks` are not allowed here.",UnexpectedSpreadType:"Spread operator cannot appear in class or interface definitions.",UnexpectedSubtractionOperand:'Unexpected token, expected "number" or "bigint".',UnexpectedTokenAfterTypeParameter:"Expected an arrow function after this type parameter declaration.",UnexpectedTypeParameterBeforeAsyncArrowFunction:"Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",UnsupportedDeclareExportKind:({unsupportedExportKind:r,suggestion:t})=>`\`declare export ${r}\` is not supported. Use \`${t}\` instead.`,UnsupportedStatementInDeclareModule:"Only declares and type imports are allowed inside declare module.",UnterminatedFlowComment:"Unterminated flow-comment."});function kb(r){return r.type==="DeclareExportAllDeclaration"||r.type==="DeclareExportDeclaration"&&(!r.declaration||r.declaration.type!=="TypeAlias"&&r.declaration.type!=="InterfaceDeclaration")}function Du(r){return r.importKind==="type"||r.importKind==="typeof"}var Ib={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"};function Pb(r,t){let e=[],n=[];for(let i=0;i<r.length;i++)(t(r[i],i,r)?e:n).push(r[i]);return[e,n]}var Rb=/\*?\s*@((?:no)?flow)\b/,Tb=r=>class extends r{constructor(...e){super(...e),this.flowPragma=void 0}getScopeHandler(){return uo}shouldParseTypes(){return this.getPluginOption("flow","all")||this.flowPragma==="flow"}finishToken(e,n){e!==134&&e!==13&&e!==28&&this.flowPragma===void 0&&(this.flowPragma=null),super.finishToken(e,n)}addComment(e){if(this.flowPragma===void 0){let n=Rb.exec(e.value);if(n)if(n[1]==="flow")this.flowPragma="flow";else if(n[1]==="noflow")this.flowPragma="noflow";else throw new Error("Unexpected flow pragma")}super.addComment(e)}flowParseTypeInitialiser(e){let n=this.state.inType;this.state.inType=!0,this.expect(e||14);let i=this.flowParseType();return this.state.inType=n,i}flowParsePredicate(){let e=this.startNode(),n=this.state.startLoc;return this.next(),this.expectContextual(110),this.state.lastTokStartLoc.index>n.index+1&&this.raise(B.UnexpectedSpaceBetweenModuloChecks,n),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 n=null,i=null;return this.match(54)?(this.state.inType=e,i=this.flowParsePredicate()):(n=this.flowParseType(),this.state.inType=e,this.match(54)&&(i=this.flowParsePredicate())),[n,i]}flowParseDeclareClass(e){return this.next(),this.flowParseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")}flowParseDeclareFunction(e){this.next();let n=e.id=this.parseIdentifier(),i=this.startNode(),s=this.startNode();this.match(47)?i.typeParameters=this.flowParseTypeParameterDeclaration():i.typeParameters=null,this.expect(10);let a=this.flowParseFunctionTypeParams();return i.params=a.params,i.rest=a.rest,i.this=a._this,this.expect(11),[i.returnType,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),s.typeAnnotation=this.finishNode(i,"FunctionTypeAnnotation"),n.typeAnnotation=this.finishNode(s,"TypeAnnotation"),this.resetEndLocation(n),this.semicolon(),this.scope.declareName(e.id.name,2048,e.id.loc.start),this.finishNode(e,"DeclareFunction")}flowParseDeclare(e,n){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(127))return this.match(16)?this.flowParseDeclareModuleExports(e):(n&&this.raise(B.NestedDeclareModule,this.state.lastTokStartLoc),this.flowParseDeclareModule(e));if(this.isContextual(130))return this.flowParseDeclareTypeAlias(e);if(this.isContextual(131))return this.flowParseDeclareOpaqueType(e);if(this.isContextual(129))return this.flowParseDeclareInterface(e);if(this.match(82))return this.flowParseDeclareExportDeclaration(e,n);throw this.unexpected()}flowParseDeclareVariable(e){return this.next(),e.id=this.flowParseTypeAnnotatableIdentifier(),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(134)?e.id=super.parseExprAtom():e.id=this.parseIdentifier();let n=e.body=this.startNode(),i=n.body=[];for(this.expect(5);!this.match(8);){let o=this.startNode();this.match(83)?(this.next(),!this.isContextual(130)&&!this.match(87)&&this.raise(B.InvalidNonTypeImportInDeclareModule,this.state.lastTokStartLoc),i.push(super.parseImport(o))):(this.expectContextual(125,B.UnsupportedStatementInDeclareModule),i.push(this.flowParseDeclare(o,!0)))}this.scope.exit(),this.expect(8),this.finishNode(n,"BlockStatement");let s=null,a=!1;return i.forEach(o=>{kb(o)?(s==="CommonJS"&&this.raise(B.AmbiguousDeclareModuleKind,o),s="ES"):o.type==="DeclareModuleExports"&&(a&&this.raise(B.DuplicateDeclareModuleExports,o),s==="ES"&&this.raise(B.AmbiguousDeclareModuleKind,o),s="CommonJS",a=!0)}),e.kind=s||"CommonJS",this.finishNode(e,"DeclareModule")}flowParseDeclareExportDeclaration(e,n){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(130)||this.isContextual(129))&&!n){let i=this.state.value;throw this.raise(B.UnsupportedDeclareExportKind,this.state.startLoc,{unsupportedExportKind:i,suggestion:Ib[i]})}if(this.match(74)||this.match(68)||this.match(80)||this.isContextual(131))return e.declaration=this.flowParseDeclare(this.startNode()),e.default=!1,this.finishNode(e,"DeclareExportDeclaration");if(this.match(55)||this.match(5)||this.isContextual(129)||this.isContextual(130)||this.isContextual(131))return e=this.parseExport(e,null),e.type==="ExportNamedDeclaration"?(e.default=!1,delete e.exportKind,this.castNodeTo(e,"DeclareExportDeclaration")):this.castNodeTo(e,"DeclareExportAllDeclaration");throw this.unexpected()}flowParseDeclareModuleExports(e){return this.next(),this.expectContextual(111),e.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(e,"DeclareModuleExports")}flowParseDeclareTypeAlias(e){this.next();let n=this.flowParseTypeAlias(e);return this.castNodeTo(n,"DeclareTypeAlias"),n}flowParseDeclareOpaqueType(e){this.next();let n=this.flowParseOpaqueType(e,!0);return this.castNodeTo(n,"DeclareOpaqueType"),n}flowParseDeclareInterface(e){return this.next(),this.flowParseInterfaceish(e,!1),this.finishNode(e,"DeclareInterface")}flowParseInterfaceish(e,n){if(e.id=this.flowParseRestrictedIdentifier(!n,!0),this.scope.declareName(e.id.name,n?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(!n&&this.eat(12));if(n){if(e.implements=[],e.mixins=[],this.eatContextual(117))do e.mixins.push(this.flowParseInterfaceExtends());while(this.eat(12));if(this.eatContextual(113))do e.implements.push(this.flowParseInterfaceExtends());while(this.eat(12))}e.body=this.flowParseObjectType({allowStatic:n,allowExact:!1,allowSpread:!1,allowProto:n,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(B.UnexpectedReservedUnderscore,this.state.startLoc)}checkReservedType(e,n,i){vb.has(e)&&this.raise(i?B.AssignReservedType:B.UnexpectedReservedType,n,{reservedType:e})}flowParseRestrictedIdentifierName(e,n){return this.checkReservedType(this.state.value,this.state.startLoc,n),this.parseIdentifierName(e)}flowParseRestrictedIdentifier(e,n){let i=this.startNode(),s=this.flowParseRestrictedIdentifierName(e,n);return this.createIdentifier(i,s)}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,n){return this.expectContextual(130),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,n||(e.impltype=this.flowParseTypeInitialiser(29)),this.semicolon(),this.finishNode(e,"OpaqueType")}flowParseTypeParameterBound(){if(this.match(14)||this.isContextual(81)){let e=this.startNode();return this.next(),e.typeAnnotation=this.flowParseType(),this.finishNode(e,"TypeAnnotation")}}flowParseTypeParameter(e=!1){let n=this.state.startLoc,i=this.startNode(),s=this.flowParseVariance();return i.name=this.flowParseRestrictedIdentifierName(),i.variance=s,i.bound=this.flowParseTypeParameterBound(),this.match(29)?(this.eat(29),i.default=this.flowParseType()):e&&this.raise(B.MissingTypeParamDefault,n),this.finishNode(i,"TypeParameter")}flowParseTypeParameterDeclaration(){let e=this.state.inType,n=this.startNode();n.params=[],this.state.inType=!0,this.match(47)||this.match(143)?this.next():this.unexpected();let i=!1;do{let s=this.flowParseTypeParameter(i);n.params.push(s),s.default&&(i=!0),this.match(48)||this.expect(12)}while(!this.match(48));return this.expect(48),this.state.inType=e,this.finishNode(n,"TypeParameterDeclaration")}flowInTopLevelContext(e){if(this.curContext()!==te.brace){let n=this.state.context;this.state.context=[n[0]];try{return e()}finally{this.state.context=n}}else return e()}flowParseTypeParameterInstantiationInExpression(){if(this.reScan_lt()===47)return this.flowParseTypeParameterInstantiation()}flowParseTypeParameterInstantiation(){let e=this.startNode(),n=this.state.inType;return this.state.inType=!0,e.params=[],this.flowInTopLevelContext(()=>{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);this.state.noAnonFunctionType=i}),this.state.inType=n,!this.state.inType&&this.curContext()===te.brace&&this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TypeParameterInstantiation")}flowParseTypeParameterInstantiationCallOrNew(){if(this.reScan_lt()!==47)return null;let e=this.startNode(),n=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=n,this.finishNode(e,"TypeParameterInstantiation")}flowParseInterfaceType(){let e=this.startNode();if(this.expectContextual(129),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(135)||this.match(134)?super.parseExprAtom():this.parseIdentifier(!0)}flowParseObjectTypeIndexer(e,n,i){return e.static=n,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,n){return e.static=n,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,n){let i=this.startNode();return e.static=n,e.value=this.flowParseObjectTypeMethodish(i),this.finishNode(e,"ObjectTypeCallProperty")}flowParseObjectType({allowStatic:e,allowExact:n,allowSpread:i,allowProto:s,allowInexact:a}){let o=this.state.inType;this.state.inType=!0;let d=this.startNode();d.callProperties=[],d.properties=[],d.indexers=[],d.internalSlots=[];let c,l,u=!1;for(n&&this.match(6)?(this.expect(6),c=9,l=!0):(this.expect(5),c=8,l=!1),d.exact=l;!this.match(c);){let f=!1,h=null,g=null,m=this.startNode();if(s&&this.isContextual(118)){let w=this.lookahead();w.type!==14&&w.type!==17&&(this.next(),h=this.state.startLoc,e=!1)}if(e&&this.isContextual(106)){let w=this.lookahead();w.type!==14&&w.type!==17&&(this.next(),f=!0)}let y=this.flowParseVariance();if(this.eat(0))h!=null&&this.unexpected(h),this.eat(0)?(y&&this.unexpected(y.loc.start),d.internalSlots.push(this.flowParseObjectTypeInternalSlot(m,f))):d.indexers.push(this.flowParseObjectTypeIndexer(m,f,y));else if(this.match(10)||this.match(47))h!=null&&this.unexpected(h),y&&this.unexpected(y.loc.start),d.callProperties.push(this.flowParseObjectTypeCallProperty(m,f));else{let w="init";if(this.isContextual(99)||this.isContextual(104)){let v=this.lookahead();Hu(v.type)&&(w=this.state.value,this.next())}let x=this.flowParseObjectTypeProperty(m,f,h,y,w,i,a??!l);x===null?(u=!0,g=this.state.lastTokStartLoc):d.properties.push(x)}this.flowObjectTypeSemicolon(),g&&!this.match(8)&&!this.match(9)&&this.raise(B.UnexpectedExplicitInexactInObject,g)}this.expect(c),i&&(d.inexact=u);let p=this.finishNode(d,"ObjectTypeAnnotation");return this.state.inType=o,p}flowParseObjectTypeProperty(e,n,i,s,a,o,d){if(this.eat(21))return this.match(12)||this.match(13)||this.match(8)||this.match(9)?(o?d||this.raise(B.InexactInsideExact,this.state.lastTokStartLoc):this.raise(B.InexactInsideNonObject,this.state.lastTokStartLoc),s&&this.raise(B.InexactVariance,s),null):(o||this.raise(B.UnexpectedSpreadType,this.state.lastTokStartLoc),i!=null&&this.unexpected(i),s&&this.raise(B.SpreadVariance,s),e.argument=this.flowParseType(),this.finishNode(e,"ObjectTypeSpreadProperty"));{e.key=this.flowParseObjectPropertyKey(),e.static=n,e.proto=i!=null,e.kind=a;let c=!1;return this.match(47)||this.match(10)?(e.method=!0,i!=null&&this.unexpected(i),s&&this.unexpected(s.loc.start),e.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e.loc.start)),(a==="get"||a==="set")&&this.flowCheckGetterSetterParams(e),!o&&e.key.name==="constructor"&&e.value.this&&this.raise(B.ThisParamBannedInConstructor,e.value.this)):(a!=="init"&&this.unexpected(),e.method=!1,this.eat(17)&&(c=!0),e.value=this.flowParseTypeInitialiser(),e.variance=s),e.optional=c,this.finishNode(e,"ObjectTypeProperty")}}flowCheckGetterSetterParams(e){let n=e.kind==="get"?0:1,i=e.value.params.length+(e.value.rest?1:0);e.value.this&&this.raise(e.kind==="get"?B.GetterMayNotHaveThisParam:B.SetterMayNotHaveThisParam,e.value.this),i!==n&&this.raise(e.kind==="get"?b.BadGetterArity:b.BadSetterArity,e),e.kind==="set"&&e.value.rest&&this.raise(b.BadSetterRestParameter,e)}flowObjectTypeSemicolon(){!this.eat(13)&&!this.eat(12)&&!this.match(8)&&!this.match(9)&&this.unexpected()}flowParseQualifiedTypeIdentifier(e,n){e??(e=this.state.startLoc);let i=n||this.flowParseRestrictedIdentifier(!0);for(;this.eat(16);){let s=this.startNodeAt(e);s.qualification=i,s.id=this.flowParseRestrictedIdentifier(!0),i=this.finishNode(s,"QualifiedTypeIdentifier")}return i}flowParseGenericType(e,n){let i=this.startNodeAt(e);return i.typeParameters=null,i.id=this.flowParseQualifiedTypeIdentifier(e,n),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.pos<this.length&&!this.match(3)&&(e.types.push(this.flowParseType()),!this.match(3));)this.expect(12);return this.expect(3),this.finishNode(e,"TupleTypeAnnotation")}flowParseFunctionTypeParam(e){let n=null,i=!1,s=null,a=this.startNode(),o=this.lookahead(),d=this.state.type===78;return o.type===14||o.type===17?(d&&!e&&this.raise(B.ThisParamMustBeFirst,a),n=this.parseIdentifier(d),this.eat(17)&&(i=!0,d&&this.raise(B.ThisParamMayNotBeOptional,a)),s=this.flowParseTypeInitialiser()):s=this.flowParseType(),a.name=n,a.optional=i,a.typeAnnotation=s,this.finishNode(a,"FunctionTypeParam")}reinterpretTypeAsFunctionTypeParam(e){let n=this.startNodeAt(e.loc.start);return n.name=null,n.optional=!1,n.typeAnnotation=e,this.finishNode(n,"FunctionTypeParam")}flowParseFunctionTypeParams(e=[]){let n=null,i=null;for(this.match(78)&&(i=this.flowParseFunctionTypeParam(!0),i.name=null,this.match(11)||this.expect(12));!this.match(11)&&!this.match(21);)e.push(this.flowParseFunctionTypeParam(!1)),this.match(11)||this.expect(12);return this.eat(21)&&(n=this.flowParseFunctionTypeParam(!1)),{params:e,rest:n,_this:i}}flowIdentToTypeAnnotation(e,n,i){switch(i.name){case"any":return this.finishNode(n,"AnyTypeAnnotation");case"bool":case"boolean":return this.finishNode(n,"BooleanTypeAnnotation");case"mixed":return this.finishNode(n,"MixedTypeAnnotation");case"empty":return this.finishNode(n,"EmptyTypeAnnotation");case"number":return this.finishNode(n,"NumberTypeAnnotation");case"string":return this.finishNode(n,"StringTypeAnnotation");case"symbol":return this.finishNode(n,"SymbolTypeAnnotation");default:return this.checkNotUnderscore(i.name),this.flowParseGenericType(e,i)}}flowParsePrimaryType(){let e=this.state.startLoc,n=this.startNode(),i,s,a=!1,o=this.state.noAnonFunctionType;switch(this.state.type){case 5:return this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!0,allowProto:!1,allowInexact:!0});case 6:return this.flowParseObjectType({allowStatic:!1,allowExact:!0,allowSpread:!0,allowProto:!1,allowInexact:!1});case 0:return this.state.noAnonFunctionType=!1,s=this.flowParseTupleType(),this.state.noAnonFunctionType=o,s;case 47:{let d=this.startNode();return d.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(10),i=this.flowParseFunctionTypeParams(),d.params=i.params,d.rest=i.rest,d.this=i._this,this.expect(11),this.expect(19),d.returnType=this.flowParseType(),this.finishNode(d,"FunctionTypeAnnotation")}case 10:{let d=this.startNode();if(this.next(),!this.match(11)&&!this.match(21))if(re(this.state.type)||this.match(78)){let c=this.lookahead().type;a=c!==17&&c!==14}else a=!0;if(a){if(this.state.noAnonFunctionType=!1,s=this.flowParseType(),this.state.noAnonFunctionType=o,this.state.noAnonFunctionType||!(this.match(12)||this.match(11)&&this.lookahead().type===19))return this.expect(11),s;this.eat(12)}return s?i=this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(s)]):i=this.flowParseFunctionTypeParams(),d.params=i.params,d.rest=i.rest,d.this=i._this,this.expect(11),this.expect(19),d.returnType=this.flowParseType(),d.typeParameters=null,this.finishNode(d,"FunctionTypeAnnotation")}case 134:return this.parseLiteral(this.state.value,"StringLiteralTypeAnnotation");case 85:case 86:return n.value=this.match(85),this.next(),this.finishNode(n,"BooleanLiteralTypeAnnotation");case 53:if(this.state.value==="-"){if(this.next(),this.match(135))return this.parseLiteralAtNode(-this.state.value,"NumberLiteralTypeAnnotation",n);if(this.match(136))return this.parseLiteralAtNode(-this.state.value,"BigIntLiteralTypeAnnotation",n);throw this.raise(B.UnexpectedSubtractionOperand,this.state.startLoc)}throw this.unexpected();case 135:return this.parseLiteral(this.state.value,"NumberLiteralTypeAnnotation");case 136:return this.parseLiteral(this.state.value,"BigIntLiteralTypeAnnotation");case 88:return this.next(),this.finishNode(n,"VoidTypeAnnotation");case 84:return this.next(),this.finishNode(n,"NullLiteralTypeAnnotation");case 78:return this.next(),this.finishNode(n,"ThisTypeAnnotation");case 55:return this.next(),this.finishNode(n,"ExistsTypeAnnotation");case 87:return this.flowParseTypeofType();default:if($o(this.state.type)){let d=Nt(this.state.type);return this.next(),super.createIdentifier(n,d)}else if(re(this.state.type))return this.isContextual(129)?this.flowParseInterfaceType():this.flowIdentToTypeAnnotation(e,n,this.parseIdentifier())}throw this.unexpected()}flowParsePostfixType(){let e=this.state.startLoc,n=this.flowParsePrimaryType(),i=!1;for(;(this.match(0)||this.match(18))&&!this.canInsertSemicolon();){let s=this.startNodeAt(e),a=this.eat(18);i=i||a,this.expect(0),!a&&this.match(3)?(s.elementType=n,this.next(),n=this.finishNode(s,"ArrayTypeAnnotation")):(s.objectType=n,s.indexType=this.flowParseType(),this.expect(3),i?(s.optional=a,n=this.finishNode(s,"OptionalIndexedAccessType")):n=this.finishNode(s,"IndexedAccessType"))}return n}flowParsePrefixType(){let e=this.startNode();return this.eat(17)?(e.typeAnnotation=this.flowParsePrefixType(),this.finishNode(e,"NullableTypeAnnotation")):this.flowParsePostfixType()}flowParseAnonFunctionWithoutParens(){let e=this.flowParsePrefixType();if(!this.state.noAnonFunctionType&&this.eat(19)){let n=this.startNodeAt(e.loc.start);return n.params=[this.reinterpretTypeAsFunctionTypeParam(e)],n.rest=null,n.this=null,n.returnType=this.flowParseType(),n.typeParameters=null,this.finishNode(n,"FunctionTypeAnnotation")}return e}flowParseIntersectionType(){let e=this.startNode();this.eat(45);let n=this.flowParseAnonFunctionWithoutParens();for(e.types=[n];this.eat(45);)e.types.push(this.flowParseAnonFunctionWithoutParens());return e.types.length===1?n:this.finishNode(e,"IntersectionTypeAnnotation")}flowParseUnionType(){let e=this.startNode();this.eat(43);let n=this.flowParseIntersectionType();for(e.types=[n];this.eat(43);)e.types.push(this.flowParseIntersectionType());return e.types.length===1?n:this.finishNode(e,"UnionTypeAnnotation")}flowParseType(){let e=this.state.inType;this.state.inType=!0;let n=this.flowParseUnionType();return this.state.inType=e,n}flowParseTypeOrImplicitInstantiation(){if(this.state.type===132&&this.state.value==="_"){let e=this.state.startLoc,n=this.parseIdentifier();return this.flowParseGenericType(e,n)}else return this.flowParseType()}flowParseTypeAnnotation(){let e=this.startNode();return e.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(e,"TypeAnnotation")}flowParseTypeAnnotatableIdentifier(){let e=this.startNode(),n=this.parseIdentifierName();return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),this.createIdentifier(e,n)}typeCastToParameter(e){return e.expression.typeAnnotation=e.typeAnnotation,this.resetEndLocation(e.expression,e.typeAnnotation.loc.end),e.expression}flowParseVariance(){let e=null;return this.match(53)?(e=this.startNode(),this.state.value==="+"?e.kind="plus":e.kind="minus",this.next(),this.finishNode(e,"Variance")):e}parseFunctionBody(e,n,i=!1){if(n){this.forwardNoArrowParamsConversionAt(e,()=>super.parseFunctionBody(e,!0,i));return}super.parseFunctionBody(e,!1,i)}parseFunctionBodyAndFinish(e,n,i=!1){if(this.match(14)){let s=this.startNode();[s.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),e.returnType=s.typeAnnotation?this.finishNode(s,"TypeAnnotation"):null}return super.parseFunctionBodyAndFinish(e,n,i)}parseStatementLike(e){if(this.state.strict&&this.isContextual(129)){let i=this.lookahead();if(Ze(i.type)){let s=this.startNode();return this.next(),this.flowParseInterface(s)}}else if(this.isContextual(126)){let i=this.startNode();return this.next(),this.flowParseEnumDeclaration(i)}let n=super.parseStatementLike(e);return this.flowPragma===void 0&&!this.isValidDirective(n)&&(this.flowPragma=null),n}parseExpressionStatement(e,n,i){if(n.type==="Identifier"){if(n.name==="declare"){if(this.match(80)||re(this.state.type)||this.match(68)||this.match(74)||this.match(82))return this.flowParseDeclare(e)}else if(re(this.state.type)){if(n.name==="interface")return this.flowParseInterface(e);if(n.name==="type")return this.flowParseTypeAlias(e);if(n.name==="opaque")return this.flowParseOpaqueType(e,!1)}}return super.parseExpressionStatement(e,n,i)}shouldParseExportDeclaration(){let{type:e}=this.state;return e===126||Ou(e)?!this.state.containsEsc:super.shouldParseExportDeclaration()}isExportDefaultSpecifier(){let{type:e}=this.state;return e===126||Ou(e)?this.state.containsEsc:super.isExportDefaultSpecifier()}parseExportDefaultExpression(){if(this.isContextual(126)){let e=this.startNode();return this.next(),this.flowParseEnumDeclaration(e)}return super.parseExportDefaultExpression()}parseConditional(e,n,i){if(!this.match(17))return e;if(this.state.maybeInArrowParameters){let p=this.lookaheadCharCode();if(p===44||p===61||p===58||p===41)return this.setOptionalParametersError(i),e}this.expect(17);let s=this.state.clone(),a=this.state.noArrowAt,o=this.startNodeAt(n),{consequent:d,failed:c}=this.tryParseConditionalConsequent(),[l,u]=this.getArrowLikeExpressions(d);if(c||u.length>0){let p=[...a];if(u.length>0){this.state=s,this.state.noArrowAt=p;for(let f=0;f<u.length;f++)p.push(u[f].start);({consequent:d,failed:c}=this.tryParseConditionalConsequent()),[l,u]=this.getArrowLikeExpressions(d)}c&&l.length>1&&this.raise(B.AmbiguousConditionalArrow,s.startLoc),c&&l.length===1&&(this.state=s,p.push(l[0].start),this.state.noArrowAt=p,{consequent:d,failed:c}=this.tryParseConditionalConsequent())}return this.getArrowLikeExpressions(d,!0),this.state.noArrowAt=a,this.expect(14),o.test=e,o.consequent=d,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(),n=!this.match(14);return this.state.noArrowParamsConversionAt.pop(),{consequent:e,failed:n}}getArrowLikeExpressions(e,n){let i=[e],s=[];for(;i.length!==0;){let a=i.pop();a.type==="ArrowFunctionExpression"?(a.typeParameters||!a.returnType?this.finishArrowValidation(a):s.push(a),a.body.type!=="BlockStatement"&&i.push(a.body)):a.type==="ConditionalExpression"&&(i.push(a.consequent),i.push(a.alternate))}return n?(s.forEach(a=>this.finishArrowValidation(a)),[s,[]]):Pb(s,a=>a.params.every(o=>this.isAssignable(o,!0)))}finishArrowValidation(e){var n;this.toAssignableList(e.params,(n=e.extra)==null?void 0:n.trailingCommaLoc,!1),this.scope.enter(518),super.checkParams(e,!1,!0),this.scope.exit()}forwardNoArrowParamsConversionAt(e,n){let i;return this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))?(this.state.noArrowParamsConversionAt.push(this.state.start),i=n(),this.state.noArrowParamsConversionAt.pop()):i=n(),i}parseParenItem(e,n){let i=super.parseParenItem(e,n);if(this.eat(17)&&(i.optional=!0,this.resetEndLocation(e)),this.match(14)){let s=this.startNodeAt(n);return s.expression=i,s.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(s,"TypeCastExpression")}return i}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(130)){e.exportKind="type";let n=this.startNode();return this.next(),this.match(5)?(e.specifiers=this.parseExportSpecifiers(!0),super.parseExportFrom(e),null):this.flowParseTypeAlias(n)}else if(this.isContextual(131)){e.exportKind="type";let n=this.startNode();return this.next(),this.flowParseOpaqueType(n,!1)}else if(this.isContextual(129)){e.exportKind="type";let n=this.startNode();return this.next(),this.flowParseInterface(n)}else if(this.isContextual(126)){e.exportKind="value";let n=this.startNode();return this.next(),this.flowParseEnumDeclaration(n)}else return super.parseExportDeclaration(e)}eatExportStar(e){return super.eatExportStar(e)?!0:this.isContextual(130)&&this.lookahead().type===55?(e.exportKind="type",this.next(),this.next(),!0):!1}maybeParseExportNamespaceSpecifier(e){let{startLoc:n}=this.state,i=super.maybeParseExportNamespaceSpecifier(e);return i&&e.exportKind==="type"&&this.unexpected(n),i}parseClassId(e,n,i){super.parseClassId(e,n,i),this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration())}parseClassMember(e,n,i){let{startLoc:s}=this.state;if(this.isContextual(125)){if(super.parseClassMemberFromModifier(e,n))return;n.declare=!0}super.parseClassMember(e,n,i),n.declare&&(n.type!=="ClassProperty"&&n.type!=="ClassPrivateProperty"&&n.type!=="PropertyDefinition"?this.raise(B.DeclareClassElement,s):n.value&&this.raise(B.DeclareClassFieldInitializer,n.value))}isIterator(e){return e==="iterator"||e==="asyncIterator"}readIterator(){let e=super.readWord1(),n="@@"+e;(!this.isIterator(e)||!this.state.inType)&&this.raise(b.InvalidIdentifier,this.state.curPosition(),{identifierName:n}),this.finishToken(132,n)}getTokenFromCode(e){let n=this.input.charCodeAt(this.state.pos+1);e===123&&n===124?this.finishOp(6,2):this.state.inType&&(e===62||e===60)?this.finishOp(e===62?48:47,1):this.state.inType&&e===63?n===46?this.finishOp(18,2):this.finishOp(17,1):wb(e,n,this.input.charCodeAt(this.state.pos+2))?(this.state.pos+=2,this.readIterator()):super.getTokenFromCode(e)}isAssignable(e,n){return e.type==="TypeCastExpression"?this.isAssignable(e.expression,n):super.isAssignable(e,n)}toAssignable(e,n=!1){!n&&e.type==="AssignmentExpression"&&e.left.type==="TypeCastExpression"&&(e.left=this.typeCastToParameter(e.left)),super.toAssignable(e,n)}toAssignableList(e,n,i){for(let s=0;s<e.length;s++){let a=e[s];a?.type==="TypeCastExpression"&&(e[s]=this.typeCastToParameter(a))}super.toAssignableList(e,n,i)}toReferencedList(e,n){for(let s=0;s<e.length;s++){var i;let a=e[s];a&&a.type==="TypeCastExpression"&&!((i=a.extra)!=null&&i.parenthesized)&&(e.length>1||!n)&&this.raise(B.TypeCastInPattern,a.typeAnnotation)}return e}parseArrayLike(e,n,i){let s=super.parseArrayLike(e,n,i);return i!=null&&!this.state.maybeInArrowParameters&&this.toReferencedList(s.elements),s}isValidLVal(e,n,i,s){return e==="TypeCastExpression"||super.isValidLVal(e,n,i,s)}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,n,i,s,a,o){if(n.variance&&this.unexpected(n.variance.loc.start),delete n.variance,this.match(47)&&(n.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassMethod(e,n,i,s,a,o),n.params&&a){let d=n.params;d.length>0&&this.isThisParam(d[0])&&this.raise(B.ThisParamBannedInConstructor,n)}else if(n.type==="MethodDefinition"&&a&&n.value.params){let d=n.value.params;d.length>0&&this.isThisParam(d[0])&&this.raise(B.ThisParamBannedInConstructor,n)}}pushClassPrivateMethod(e,n,i,s){n.variance&&this.unexpected(n.variance.loc.start),delete n.variance,this.match(47)&&(n.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassPrivateMethod(e,n,i,s)}parseClassSuper(e){if(super.parseClassSuper(e),e.superClass&&(this.match(47)||this.match(51))&&(e.superTypeParameters=this.flowParseTypeParameterInstantiationInExpression()),this.isContextual(113)){this.next();let n=e.implements=[];do{let i=this.startNode();i.id=this.flowParseRestrictedIdentifier(!0),this.match(47)?i.typeParameters=this.flowParseTypeParameterInstantiation():i.typeParameters=null,n.push(this.finishNode(i,"ClassImplements"))}while(this.eat(12))}}checkGetterSetterParams(e){super.checkGetterSetterParams(e);let n=this.getObjectOrClassMethodParams(e);if(n.length>0){let i=n[0];this.isThisParam(i)&&e.kind==="get"?this.raise(B.GetterMayNotHaveThisParam,i):this.isThisParam(i)&&this.raise(B.SetterMayNotHaveThisParam,i)}}parsePropertyNamePrefixOperator(e){e.variance=this.flowParseVariance()}parseObjPropValue(e,n,i,s,a,o,d){e.variance&&this.unexpected(e.variance.loc.start),delete e.variance;let c;this.match(47)&&!o&&(c=this.flowParseTypeParameterDeclaration(),this.match(10)||this.unexpected());let l=super.parseObjPropValue(e,n,i,s,a,o,d);return c&&((l.value||l).typeParameters=c),l}parseFunctionParamType(e){return this.eat(17)&&(e.type!=="Identifier"&&this.raise(B.PatternIsOptional,e),this.isThisParam(e)&&this.raise(B.ThisParamMayNotBeOptional,e),e.optional=!0),this.match(14)?e.typeAnnotation=this.flowParseTypeAnnotation():this.isThisParam(e)&&this.raise(B.ThisParamAnnotationRequired,e),this.match(29)&&this.isThisParam(e)&&this.raise(B.ThisParamNoDefault,e),this.resetEndLocation(e),e}parseMaybeDefault(e,n){let i=super.parseMaybeDefault(e,n);return i.type==="AssignmentPattern"&&i.typeAnnotation&&i.right.start<i.typeAnnotation.start&&this.raise(B.TypeBeforeInitializer,i.typeAnnotation),i}checkImportReflection(e){super.checkImportReflection(e),e.module&&e.importKind!=="value"&&this.raise(B.ImportReflectionHasImportType,e.specifiers[0].loc.start)}parseImportSpecifierLocal(e,n,i){n.local=Du(e)?this.flowParseRestrictedIdentifier(!0,!0):this.parseIdentifier(),e.specifiers.push(this.finishImportSpecifier(n,i))}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return!0;if(this.isContextual(130)){if(!e)return!0;let n=this.lookaheadCharCode();return n===123||n===42}return!e&&this.isContextual(87)}applyImportPhase(e,n,i,s){if(super.applyImportPhase(e,n,i,s),n){if(!i&&this.match(65))return;e.exportKind=i==="type"?i:"value"}else i==="type"&&this.match(55)&&this.unexpected(),e.importKind=i==="type"||i==="typeof"?i:"value"}parseImportSpecifier(e,n,i,s,a){let o=e.imported,d=null;o.type==="Identifier"&&(o.name==="type"?d="type":o.name==="typeof"&&(d="typeof"));let c=!1;if(this.isContextual(93)&&!this.isLookaheadContextual("as")){let u=this.parseIdentifier(!0);d!==null&&!Ze(this.state.type)?(e.imported=u,e.importKind=d,e.local=this.cloneIdentifier(u)):(e.imported=o,e.importKind=null,e.local=this.parseIdentifier())}else{if(d!==null&&Ze(this.state.type))e.imported=this.parseIdentifier(!0),e.importKind=d;else{if(n)throw this.raise(b.ImportBindingIsString,e,{importName:o.value});e.imported=o,e.importKind=null}this.eatContextual(93)?e.local=this.parseIdentifier():(c=!0,e.local=this.cloneIdentifier(e.imported))}let l=Du(e);return i&&l&&this.raise(B.ImportTypeShorthandOnlyInPureImport,e),(i||l)&&this.checkReservedType(e.local.name,e.local.loc.start,!0),c&&!i&&!l&&this.checkReservedWord(e.local.name,e.loc.start,!0,!0),this.finishImportSpecifier(e,"ImportSpecifier")}parseBindingAtom(){return this.state.type===78?this.parseIdentifier(!0):super.parseBindingAtom()}parseFunctionParams(e,n){let i=e.kind;i!=="get"&&i!=="set"&&this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),super.parseFunctionParams(e,n)}parseVarId(e,n){super.parseVarId(e,n),this.match(14)&&(e.id.typeAnnotation=this.flowParseTypeAnnotation(),this.resetEndLocation(e.id))}parseAsyncArrowFromCallExpression(e,n){if(this.match(14)){let i=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0,e.returnType=this.flowParseTypeAnnotation(),this.state.noAnonFunctionType=i}return super.parseAsyncArrowFromCallExpression(e,n)}shouldParseAsyncArrow(){return this.match(14)||super.shouldParseAsyncArrow()}parseMaybeAssign(e,n){var i;let s=null,a;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){if(s=this.state.clone(),a=this.tryParse(()=>super.parseMaybeAssign(e,n),s),!a.error)return a.node;let{context:c}=this.state,l=c[c.length-1];(l===te.j_oTag||l===te.j_expr)&&c.pop()}if((i=a)!=null&&i.error||this.match(47)){var o,d;s=s||this.state.clone();let c,l=this.tryParse(p=>{var f;c=this.flowParseTypeParameterDeclaration();let h=this.forwardNoArrowParamsConversionAt(c,()=>{let m=super.parseMaybeAssign(e,n);return this.resetStartLocationFromNode(m,c),m});(f=h.extra)!=null&&f.parenthesized&&p();let g=this.maybeUnwrapTypeCastExpression(h);return g.type!=="ArrowFunctionExpression"&&p(),g.typeParameters=c,this.resetStartLocationFromNode(g,c),h},s),u=null;if(l.node&&this.maybeUnwrapTypeCastExpression(l.node).type==="ArrowFunctionExpression"){if(!l.error&&!l.aborted)return l.node.async&&this.raise(B.UnexpectedTypeParameterBeforeAsyncArrowFunction,c),l.node;u=l.node}if((o=a)!=null&&o.node)return this.state=a.failState,a.node;if(u)return this.state=l.failState,u;throw(d=a)!=null&&d.thrown?a.error:l.thrown?l.error:this.raise(B.UnexpectedTokenAfterTypeParameter,c)}return super.parseMaybeAssign(e,n)}parseArrow(e){if(this.match(14)){let n=this.tryParse(()=>{let i=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0;let s=this.startNode();return[s.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),this.state.noAnonFunctionType=i,this.canInsertSemicolon()&&this.unexpected(),this.match(19)||this.unexpected(),s});if(n.thrown)return null;n.error&&(this.state=n.failState),e.returnType=n.node.typeAnnotation?this.finishNode(n.node,"TypeAnnotation"):null}return super.parseArrow(e)}shouldParseArrow(e){return this.match(14)||super.shouldParseArrow(e)}setArrowFunctionParameters(e,n){this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))?e.params=n:super.setArrowFunctionParameters(e,n)}checkParams(e,n,i,s=!0){if(!(i&&this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start)))){for(let a=0;a<e.params.length;a++)this.isThisParam(e.params[a])&&a>0&&this.raise(B.ThisParamMustBeFirst,e.params[a]);super.checkParams(e,n,i,s)}}parseParenAndDistinguishExpression(e){return super.parseParenAndDistinguishExpression(e&&!this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)))}parseSubscripts(e,n,i){if(e.type==="Identifier"&&e.name==="async"&&this.state.noArrowAt.includes(n.index)){this.next();let s=this.startNodeAt(n);s.callee=e,s.arguments=super.parseCallExpressionArguments(),e=this.finishNode(s,"CallExpression")}else if(e.type==="Identifier"&&e.name==="async"&&this.match(47)){let s=this.state.clone(),a=this.tryParse(d=>this.parseAsyncArrowWithTypeParameters(n)||d(),s);if(!a.error&&!a.aborted)return a.node;let o=this.tryParse(()=>super.parseSubscripts(e,n,i),s);if(o.node&&!o.error)return o.node;if(a.node)return this.state=a.failState,a.node;if(o.node)return this.state=o.failState,o.node;throw a.error||o.error}return super.parseSubscripts(e,n,i)}parseSubscript(e,n,i,s){if(this.match(18)&&this.isLookaheadToken_lt()){if(s.optionalChainMember=!0,i)return s.stop=!0,e;this.next();let a=this.startNodeAt(n);return a.callee=e,a.typeArguments=this.flowParseTypeParameterInstantiationInExpression(),this.expect(10),a.arguments=this.parseCallExpressionArguments(),a.optional=!0,this.finishCallExpression(a,!0)}else if(!i&&this.shouldParseTypes()&&(this.match(47)||this.match(51))){let a=this.startNodeAt(n);a.callee=e;let o=this.tryParse(()=>(a.typeArguments=this.flowParseTypeParameterInstantiationCallOrNew(),this.expect(10),a.arguments=super.parseCallExpressionArguments(),s.optionalChainMember&&(a.optional=!1),this.finishCallExpression(a,s.optionalChainMember)));if(o.node)return o.error&&(this.state=o.failState),o.node}return super.parseSubscript(e,n,i,s)}parseNewCallee(e){super.parseNewCallee(e);let n=null;this.shouldParseTypes()&&this.match(47)&&(n=this.tryParse(()=>this.flowParseTypeParameterInstantiationCallOrNew()).node),e.typeArguments=n}parseAsyncArrowWithTypeParameters(e){let n=this.startNodeAt(e);if(this.parseFunctionParams(n,!1),!!this.parseArrow(n))return super.parseArrowExpression(n,void 0,!0)}readToken_mult_modulo(e){let n=this.input.charCodeAt(this.state.pos+1);if(e===42&&n===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 n=this.input.charCodeAt(this.state.pos+1);if(e===124&&n===125){this.finishOp(9,2);return}super.readToken_pipe_amp(e)}parseTopLevel(e,n){let i=super.parseTopLevel(e,n);return this.state.hasFlowComment&&this.raise(B.UnterminatedFlowComment,this.state.curPosition()),i}skipBlockComment(){if(this.hasPlugin("flowComments")&&this.skipFlowComment()){if(this.state.hasFlowComment)throw this.raise(B.NestedFlowComment,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,n=2;for(;[32,9].includes(this.input.charCodeAt(e+n));)n++;let i=this.input.charCodeAt(n+e),s=this.input.charCodeAt(n+e+1);return i===58&&s===58?n+2:this.input.slice(n+e,n+e+12)==="flow-include"?n+12:i===58&&s!==58?n:!1}hasFlowCommentCompletion(){if(this.input.indexOf("*/",this.state.pos)===-1)throw this.raise(b.UnterminatedComment,this.state.curPosition())}flowEnumErrorBooleanMemberNotInitialized(e,{enumName:n,memberName:i}){this.raise(B.EnumBooleanMemberNotInitialized,e,{memberName:i,enumName:n})}flowEnumErrorInvalidMemberInitializer(e,n){return this.raise(n.explicitType?n.explicitType==="symbol"?B.EnumInvalidMemberInitializerSymbolType:B.EnumInvalidMemberInitializerPrimaryType:B.EnumInvalidMemberInitializerUnknownType,e,n)}flowEnumErrorNumberMemberNotInitialized(e,n){this.raise(B.EnumNumberMemberNotInitialized,e,n)}flowEnumErrorStringMemberInconsistentlyInitialized(e,n){this.raise(B.EnumStringMemberInconsistentlyInitialized,e,n)}flowEnumMemberInit(){let e=this.state.startLoc,n=()=>this.match(12)||this.match(8);switch(this.state.type){case 135:{let i=this.parseNumericLiteral(this.state.value);return n()?{type:"number",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}case 134:{let i=this.parseStringLiteral(this.state.value);return n()?{type:"string",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}case 85:case 86:{let i=this.parseBooleanLiteral(this.match(85));return n()?{type:"boolean",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}default:return{type:"invalid",loc:e}}}flowEnumMemberRaw(){let e=this.state.startLoc,n=this.parseIdentifier(!0),i=this.eat(29)?this.flowEnumMemberInit():{type:"none",loc:e};return{id:n,init:i}}flowEnumCheckExplicitTypeMismatch(e,n,i){let{explicitType:s}=n;s!==null&&s!==i&&this.flowEnumErrorInvalidMemberInitializer(e,n)}flowEnumMembers({enumName:e,explicitType:n}){let i=new Set,s={booleanMembers:[],numberMembers:[],stringMembers:[],defaultedMembers:[]},a=!1;for(;!this.match(8);){if(this.eat(21)){a=!0;break}let o=this.startNode(),{id:d,init:c}=this.flowEnumMemberRaw(),l=d.name;if(l==="")continue;/^[a-z]/.test(l)&&this.raise(B.EnumInvalidMemberName,d,{memberName:l,suggestion:l[0].toUpperCase()+l.slice(1),enumName:e}),i.has(l)&&this.raise(B.EnumDuplicateMemberName,d,{memberName:l,enumName:e}),i.add(l);let u={enumName:e,explicitType:n,memberName:l};switch(o.id=d,c.type){case"boolean":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"boolean"),o.init=c.value,s.booleanMembers.push(this.finishNode(o,"EnumBooleanMember"));break}case"number":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"number"),o.init=c.value,s.numberMembers.push(this.finishNode(o,"EnumNumberMember"));break}case"string":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"string"),o.init=c.value,s.stringMembers.push(this.finishNode(o,"EnumStringMember"));break}case"invalid":throw this.flowEnumErrorInvalidMemberInitializer(c.loc,u);case"none":switch(n){case"boolean":this.flowEnumErrorBooleanMemberNotInitialized(c.loc,u);break;case"number":this.flowEnumErrorNumberMemberNotInitialized(c.loc,u);break;default:s.defaultedMembers.push(this.finishNode(o,"EnumDefaultedMember"))}}this.match(8)||this.expect(12)}return{members:s,hasUnknownMembers:a}}flowEnumStringMembers(e,n,{enumName:i}){if(e.length===0)return n;if(n.length===0)return e;if(n.length>e.length){for(let s of e)this.flowEnumErrorStringMemberInconsistentlyInitialized(s,{enumName:i});return n}else{for(let s of n)this.flowEnumErrorStringMemberInconsistentlyInitialized(s,{enumName:i});return e}}flowEnumParseExplicitType({enumName:e}){if(!this.eatContextual(102))return null;if(!re(this.state.type))throw this.raise(B.EnumInvalidExplicitTypeUnknownSupplied,this.state.startLoc,{enumName:e});let{value:n}=this.state;return this.next(),n!=="boolean"&&n!=="number"&&n!=="string"&&n!=="symbol"&&this.raise(B.EnumInvalidExplicitType,this.state.startLoc,{enumName:e,invalidEnumType:n}),n}flowEnumBody(e,n){let i=n.name,s=n.loc.start,a=this.flowEnumParseExplicitType({enumName:i});this.expect(5);let{members:o,hasUnknownMembers:d}=this.flowEnumMembers({enumName:i,explicitType:a});switch(e.hasUnknownMembers=d,a){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 c=()=>(e.members=[],this.expect(8),this.finishNode(e,"EnumStringBody"));e.explicitType=!1;let l=o.booleanMembers.length,u=o.numberMembers.length,p=o.stringMembers.length,f=o.defaultedMembers.length;if(!l&&!u&&!p&&!f)return c();if(!l&&!u)return e.members=this.flowEnumStringMembers(o.stringMembers,o.defaultedMembers,{enumName:i}),this.expect(8),this.finishNode(e,"EnumStringBody");if(!u&&!p&&l>=f){for(let h of o.defaultedMembers)this.flowEnumErrorBooleanMemberNotInitialized(h.loc.start,{enumName:i,memberName:h.id.name});return e.members=o.booleanMembers,this.expect(8),this.finishNode(e,"EnumBooleanBody")}else if(!l&&!p&&u>=f){for(let h of o.defaultedMembers)this.flowEnumErrorNumberMemberNotInitialized(h.loc.start,{enumName:i,memberName:h.id.name});return e.members=o.numberMembers,this.expect(8),this.finishNode(e,"EnumNumberBody")}else return this.raise(B.EnumInconsistentMemberValues,s,{enumName:i}),c()}}}flowParseEnumDeclaration(e){let n=this.parseIdentifier();return e.id=n,e.body=this.flowEnumBody(this.startNode(),n),this.finishNode(e,"EnumDeclaration")}jsxParseOpeningElementAfterName(e){return this.shouldParseTypes()&&(this.match(47)||this.match(51))&&(e.typeArguments=this.flowParseTypeParameterInstantiationInExpression()),super.jsxParseOpeningElementAfterName(e)}isLookaheadToken_lt(){let e=this.nextTokenStart();if(this.input.charCodeAt(e)===60){let n=this.input.charCodeAt(e+1);return n!==60&&n!==61}return!1}reScan_lt_gt(){let{type:e}=this.state;e===47?(this.state.pos-=1,this.readToken_lt()):e===48&&(this.state.pos-=1,this.readToken_gt())}reScan_lt(){let{type:e}=this.state;return e===51?(this.state.pos-=2,this.finishOp(47,1),47):e}maybeUnwrapTypeCastExpression(e){return e.type==="TypeCastExpression"?e.expression:e}},Ab={__proto__:null,quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:"\xA0",iexcl:"\xA1",cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",frac34:"\xBE",iquest:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acirc:"\xC2",Atilde:"\xC3",Auml:"\xC4",Aring:"\xC5",AElig:"\xC6",Ccedil:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecirc:"\xCA",Euml:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icirc:"\xCE",Iuml:"\xCF",ETH:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocirc:"\xD4",Otilde:"\xD5",Ouml:"\xD6",times:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucirc:"\xDB",Uuml:"\xDC",Yacute:"\xDD",THORN:"\xDE",szlig:"\xDF",agrave:"\xE0",aacute:"\xE1",acirc:"\xE2",atilde:"\xE3",auml:"\xE4",aring:"\xE5",aelig:"\xE6",ccedil:"\xE7",egrave:"\xE8",eacute:"\xE9",ecirc:"\xEA",euml:"\xEB",igrave:"\xEC",iacute:"\xED",icirc:"\xEE",iuml:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocirc:"\xF4",otilde:"\xF5",ouml:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucirc:"\xFB",uuml:"\xFC",yacute:"\xFD",thorn:"\xFE",yuml:"\xFF",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",fnof:"\u0192",circ:"\u02C6",tilde:"\u02DC",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039A",Lambda:"\u039B",Mu:"\u039C",Nu:"\u039D",Xi:"\u039E",Omicron:"\u039F",Pi:"\u03A0",Rho:"\u03A1",Sigma:"\u03A3",Tau:"\u03A4",Upsilon:"\u03A5",Phi:"\u03A6",Chi:"\u03A7",Psi:"\u03A8",Omega:"\u03A9",alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",rho:"\u03C1",sigmaf:"\u03C2",sigma:"\u03C3",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",thetasym:"\u03D1",upsih:"\u03D2",piv:"\u03D6",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",bull:"\u2022",hellip:"\u2026",permil:"\u2030",prime:"\u2032",Prime:"\u2033",lsaquo:"\u2039",rsaquo:"\u203A",oline:"\u203E",frasl:"\u2044",euro:"\u20AC",image:"\u2111",weierp:"\u2118",real:"\u211C",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21B5",lArr:"\u21D0",uArr:"\u21D1",rArr:"\u21D2",dArr:"\u21D3",hArr:"\u21D4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220B",prod:"\u220F",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221A",prop:"\u221D",infin:"\u221E",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222A",int:"\u222B",there4:"\u2234",sim:"\u223C",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22A5",sdot:"\u22C5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230A",rfloor:"\u230B",lang:"\u2329",rang:"\u232A",loz:"\u25CA",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666"},Sb=/\r\n|[\r\n\u2028\u2029]/,Vi=new RegExp(Sb.source,"g");function Rr(r){switch(r){case 10:case 13:case 8232:case 8233:return!0;default:return!1}}function Lu(r,t,e){for(let n=t;n<e;n++)if(Rr(r.charCodeAt(n)))return!0;return!1}var no=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,io=/(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;function Eb(r){switch(r){case 9:case 11:case 12:case 32:case 160:case 5760:case 8192:case 8193:case 8194:case 8195:case 8196:case 8197:case 8198:case 8199:case 8200:case 8201:case 8202:case 8239:case 8287:case 12288:case 65279:return!0;default:return!1}}var Wt=Qe`jsx`({AttributeIsEmpty:"JSX attributes must only be assigned a non-empty expression.",MissingClosingTagElement:({openingTagName:r})=>`Expected corresponding JSX closing tag for <${r}>.`,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:r,HTMLEntity:t})=>`Unexpected token \`${r}\`. Did you mean \`${t}\` or \`{'${r}'}\`?`,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 Ct(r){return r?r.type==="JSXOpeningFragment"||r.type==="JSXClosingFragment":!1}function Pr(r){if(r.type==="JSXIdentifier")return r.name;if(r.type==="JSXNamespacedName")return r.namespace.name+":"+r.name.name;if(r.type==="JSXMemberExpression")return Pr(r.object)+"."+Pr(r.property);throw new Error("Node had unexpected type: "+r.type)}var Cb=r=>class extends r{jsxReadToken(){let e="",n=this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(Wt.UnterminatedJsxContent,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(143)):super.getTokenFromCode(i);return}e+=this.input.slice(n,this.state.pos),this.finishToken(142,e);return;case 38:e+=this.input.slice(n,this.state.pos),e+=this.jsxReadEntity(),n=this.state.pos;break;default:Rr(i)?(e+=this.input.slice(n,this.state.pos),e+=this.jsxReadNewLine(!0),n=this.state.pos):++this.state.pos}}}jsxReadNewLine(e){let n=this.input.charCodeAt(this.state.pos),i;return++this.state.pos,n===13&&this.input.charCodeAt(this.state.pos)===10?(++this.state.pos,i=e?`
6
6
  `:`\r
7
- `):i=String.fromCharCode(n),++this.state.curLine,this.state.lineStart=this.state.pos,i}jsxReadString(e){let n="",i=++this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(b.UnterminatedString,this.state.startLoc);let s=this.input.charCodeAt(this.state.pos);if(s===e)break;s===38?(n+=this.input.slice(i,this.state.pos),n+=this.jsxReadEntity(),i=this.state.pos):Ir(s)?(n+=this.input.slice(i,this.state.pos),n+=this.jsxReadNewLine(!1),i=this.state.pos):++this.state.pos}n+=this.input.slice(i,this.state.pos++),this.finishToken(134,n)}jsxReadEntity(){let e=++this.state.pos;if(this.codePointAtPos(this.state.pos)===35){++this.state.pos;let n=10;this.codePointAtPos(this.state.pos)===120&&(n=16,++this.state.pos);let i=this.readInt(n,void 0,!1,"bail");if(i!==null&&this.codePointAtPos(this.state.pos)===59)return++this.state.pos,String.fromCodePoint(i)}else{let n=0,i=!1;for(;n++<10&&this.state.pos<this.length&&!(i=this.codePointAtPos(this.state.pos)===59);)++this.state.pos;if(i){let s=this.input.slice(e,this.state.pos),a=bb[s];if(++this.state.pos,a)return a}}return this.state.pos=e,"&"}jsxReadWord(){let e,n=this.state.pos;do e=this.input.charCodeAt(++this.state.pos);while(Jt(e)||e===45);this.finishToken(141,this.input.slice(n,this.state.pos))}jsxParseIdentifier(){let e=this.startNode();return this.match(141)?e.name=this.state.value:No(this.state.type)?e.name=Ct(this.state.type):this.unexpected(),this.next(),this.finishNode(e,"JSXIdentifier")}jsxParseNamespacedName(){let e=this.state.startLoc,n=this.jsxParseIdentifier();if(!this.eat(14))return n;let i=this.startNodeAt(e);return i.namespace=n,i.name=this.jsxParseIdentifier(),this.finishNode(i,"JSXNamespacedName")}jsxParseElementName(){let e=this.state.startLoc,n=this.jsxParseNamespacedName();if(n.type==="JSXNamespacedName")return n;for(;this.eat(16);){let i=this.startNodeAt(e);i.object=n,i.property=this.jsxParseIdentifier(),n=this.finishNode(i,"JSXMemberExpression")}return n}jsxParseAttributeValue(){let e;switch(this.state.type){case 5:return e=this.startNode(),this.setContext(ee.brace),this.next(),e=this.jsxParseExpressionContainer(e,ee.j_oTag),e.expression.type==="JSXEmptyExpression"&&this.raise(Kt.AttributeIsEmpty,e),e;case 143:case 134:return this.parseExprAtom();default:throw this.raise(Kt.UnsupportedJsxValue,this.state.startLoc)}}jsxParseEmptyExpression(){let e=this.startNodeAt(this.state.lastTokEndLoc);return this.finishNodeAt(e,"JSXEmptyExpression",this.state.startLoc)}jsxParseSpreadChild(e){return this.next(),e.expression=this.parseExpression(),this.setContext(ee.j_expr),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXSpreadChild")}jsxParseExpressionContainer(e,n){if(this.match(8))e.expression=this.jsxParseEmptyExpression();else{let i=this.parseExpression();e.expression=i}return this.setContext(n),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXExpressionContainer")}jsxParseAttribute(){let e=this.startNode();return this.match(5)?(this.setContext(ee.brace),this.next(),this.expect(21),e.argument=this.parseMaybeAssignAllowIn(),this.setContext(ee.j_oTag),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXSpreadAttribute")):(e.name=this.jsxParseNamespacedName(),e.value=this.eat(29)?this.jsxParseAttributeValue():null,this.finishNode(e,"JSXAttribute"))}jsxParseOpeningElementAt(e){let n=this.startNodeAt(e);return this.eat(144)?this.finishNode(n,"JSXOpeningFragment"):(n.name=this.jsxParseElementName(),this.jsxParseOpeningElementAfterName(n))}jsxParseOpeningElementAfterName(e){let n=[];for(;!this.match(56)&&!this.match(144);)n.push(this.jsxParseAttribute());return e.attributes=n,e.selfClosing=this.eat(56),this.expect(144),this.finishNode(e,"JSXOpeningElement")}jsxParseClosingElementAt(e){let n=this.startNodeAt(e);return this.eat(144)?this.finishNode(n,"JSXClosingFragment"):(n.name=this.jsxParseElementName(),this.expect(144),this.finishNode(n,"JSXClosingElement"))}jsxParseElementAt(e){let n=this.startNodeAt(e),i=[],s=this.jsxParseOpeningElementAt(e),a=null;if(!s.selfClosing){e:for(;;)switch(this.state.type){case 143:if(e=this.state.startLoc,this.next(),this.eat(56)){a=this.jsxParseClosingElementAt(e);break e}i.push(this.jsxParseElementAt(e));break;case 142:i.push(this.parseLiteral(this.state.value,"JSXText"));break;case 5:{let o=this.startNode();this.setContext(ee.brace),this.next(),this.match(21)?i.push(this.jsxParseSpreadChild(o)):i.push(this.jsxParseExpressionContainer(o,ee.j_expr));break}default:this.unexpected()}Et(s)&&!Et(a)&&a!==null?this.raise(Kt.MissingClosingTagFragment,a):!Et(s)&&Et(a)?this.raise(Kt.MissingClosingTagElement,a,{openingTagName:kr(s.name)}):!Et(s)&&!Et(a)&&kr(a.name)!==kr(s.name)&&this.raise(Kt.MissingClosingTagElement,a,{openingTagName:kr(s.name)})}if(Et(s)?(n.openingFragment=s,n.closingFragment=a):(n.openingElement=s,n.closingElement=a),n.children=i,this.match(47))throw this.raise(Kt.UnwrappedAdjacentJSXElements,this.state.startLoc);return Et(s)?this.finishNode(n,"JSXFragment"):this.finishNode(n,"JSXElement")}jsxParseElement(){let e=this.state.startLoc;return this.next(),this.jsxParseElementAt(e)}setContext(e){let{context:n}=this.state;n[n.length-1]=e}parseExprAtom(e){return this.match(143)?this.jsxParseElement():this.match(47)&&this.input.charCodeAt(this.state.pos)!==33?(this.replaceToken(143),this.jsxParseElement()):super.parseExprAtom(e)}skipSpace(){this.curContext().preserveSpace||super.skipSpace()}getTokenFromCode(e){let n=this.curContext();if(n===ee.j_expr){this.jsxReadToken();return}if(n===ee.j_oTag||n===ee.j_cTag){if(ct(e)){this.jsxReadWord();return}if(e===62){++this.state.pos,this.finishToken(144);return}if((e===34||e===39)&&n===ee.j_oTag){this.jsxReadString(e);return}}if(e===60&&this.state.canStartJSXElement&&this.input.charCodeAt(this.state.pos+1)!==33){++this.state.pos,this.finishToken(143);return}super.getTokenFromCode(e)}updateContext(e){let{context:n,type:i}=this.state;if(i===56&&e===143)n.splice(-2,2,ee.j_cTag),this.state.canStartJSXElement=!1;else if(i===143)n.push(ee.j_oTag);else if(i===144){let s=n[n.length-1];s===ee.j_oTag&&e===56||s===ee.j_cTag?(n.pop(),this.state.canStartJSXElement=n[n.length-1]===ee.j_expr):(this.setContext(ee.j_expr),this.state.canStartJSXElement=!0)}else this.state.canStartJSXElement=Ww(i)}},ao=class extends xn{constructor(...t){super(...t),this.tsNames=new Map}},oo=class extends vn{constructor(...t){super(...t),this.importsStack=[]}createScope(t){return this.importsStack.push(new Set),new ao(t)}enter(t){t===1024&&this.importsStack.push(new Set),super.enter(t)}exit(){let t=super.exit();return t===1024&&this.importsStack.pop(),t}hasImport(t,e){let n=this.importsStack.length;if(this.importsStack[n-1].has(t))return!0;if(!e&&n>1){for(let i=0;i<n-1;i++)if(this.importsStack[i].has(t))return!0}return!1}declareName(t,e,n){if(e&4096){this.hasImport(t,!0)&&this.parser.raise(b.VarRedeclaration,n,{identifierName:t}),this.importsStack[this.importsStack.length-1].add(t);return}let i=this.currentScope(),s=i.tsNames.get(t)||0;if(e&1024){this.maybeExportDefined(i,t),i.tsNames.set(t,s|16);return}super.declareName(t,e,n),e&2&&(e&1||(this.checkRedeclarationInScope(i,t,e,n),this.maybeExportDefined(i,t)),s=s|1),e&256&&(s=s|2),e&512&&(s=s|4),e&128&&(s=s|8),s&&i.tsNames.set(t,s)}isRedeclaredInScope(t,e,n){let i=t.tsNames.get(e);if((i&2)>0){if(n&256){let s=!!(n&512),a=(i&4)>0;return s!==a}return!0}return n&128&&(i&8)>0?t.names.get(e)&2?!!(n&1):!1:n&2&&(i&1)>0?!0:super.isRedeclaredInScope(t,e,n)}checkLocalExport(t){let{name:e}=t;if(this.hasImport(e))return;let n=this.scopeStack.length;for(let i=n-1;i>=0;i--){let a=this.scopeStack[i].tsNames.get(e);if((a&1)>0||(a&16)>0)return}super.checkLocalExport(t)}},co=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()&2)>0}get hasYield(){return(this.currentFlags()&1)>0}get hasReturn(){return(this.currentFlags()&4)>0}get hasIn(){return(this.currentFlags()&8)>0}};function Vi(r,t){return(r?2:0)|(t?1:0)}var lo=class{constructor(){this.sawUnambiguousESM=!1,this.ambiguousScriptDifferentAst=!1}sourceToOffsetPos(t){return t+this.startIndex}offsetToSourcePos(t){return t-this.startIndex}hasPlugin(t){if(typeof t=="string")return this.plugins.has(t);{let[e,n]=t;if(!this.hasPlugin(e))return!1;let i=this.plugins.get(e);for(let s of Object.keys(n))if(i?.[s]!==n[s])return!1;return!0}}getPluginOption(t,e){var n;return(n=this.plugins.get(t))==null?void 0:n[e]}};function qu(r,t){r.trailingComments===void 0?r.trailingComments=t:r.trailingComments.unshift(...t)}function Ib(r,t){r.leadingComments===void 0?r.leadingComments=t:r.leadingComments.unshift(...t)}function kn(r,t){r.innerComments===void 0?r.innerComments=t:r.innerComments.unshift(...t)}function Xe(r,t,e){let n=null,i=t.length;for(;n===null&&i>0;)n=t[--i];n===null||n.start>e.start?kn(r,e.comments):qu(n,e.comments)}var uo=class extends lo{addComment(t){this.filename&&(t.loc.filename=this.filename);let{commentsLen:e}=this.state;this.comments.length!==e&&(this.comments.length=e),this.comments.push(t),this.state.commentsLen++}processComment(t){let{commentStack:e}=this.state,n=e.length;if(n===0)return;let i=n-1,s=e[i];s.start===t.end&&(s.leadingNode=t,i--);let{start:a}=t;for(;i>=0;i--){let o=e[i],d=o.end;if(d>a)o.containingNode=t,this.finalizeComment(o),e.splice(i,1);else{d===a&&(o.trailingNode=t);break}}}finalizeComment(t){var e;let{comments:n}=t;if(t.leadingNode!==null||t.trailingNode!==null)t.leadingNode!==null&&qu(t.leadingNode,n),t.trailingNode!==null&&Ib(t.trailingNode,n);else{let i=t.containingNode,s=t.start;if(this.input.charCodeAt(this.offsetToSourcePos(s)-1)===44)switch(i.type){case"ObjectExpression":case"ObjectPattern":Xe(i,i.properties,t);break;case"CallExpression":case"NewExpression":case"OptionalCallExpression":Xe(i,i.arguments,t);break;case"ImportExpression":Xe(i,[i.source,(e=i.options)!=null?e:null],t);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":case"ObjectMethod":case"ClassMethod":case"ClassPrivateMethod":case"TSTypeParameterDeclaration":Xe(i,i.params,t);break;case"ArrayExpression":case"ArrayPattern":Xe(i,i.elements,t);break;case"ExportNamedDeclaration":case"ImportDeclaration":Xe(i,i.specifiers,t);break;case"TSEnumDeclaration":Xe(i,i.members,t);break;case"TSEnumBody":Xe(i,i.members,t);break;case"TSInterfaceBody":Xe(i,i.body,t);break;default:{if(i.type==="RecordExpression"){Xe(i,i.properties,t);break}if(i.type==="TupleExpression"){Xe(i,i.elements,t);break}kn(i,n)}}else kn(i,n)}}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:n}=e;if(n===0)return;let i=e[n-1];i.leadingNode===t&&(i.leadingNode=null)}takeSurroundingComments(t,e,n){let{commentStack:i}=this.state,s=i.length;if(s===0)return;let a=s-1;for(;a>=0;a--){let o=i[a],d=o.end;if(o.start===n)o.leadingNode=t;else if(d===e)o.trailingNode=t;else if(d<e)break}}},po=class r{constructor(){this.flags=1024,this.startIndex=void 0,this.curLine=void 0,this.lineStart=void 0,this.startLoc=void 0,this.endLoc=void 0,this.errors=[],this.potentialArrowAt=-1,this.noArrowAt=[],this.noArrowParamsConversionAt=[],this.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null},this.labels=[],this.commentsLen=0,this.commentStack=[],this.pos=0,this.type=140,this.value=null,this.start=0,this.end=0,this.lastTokEndLoc=null,this.lastTokStartLoc=null,this.context=[ee.brace],this.firstInvalidTemplateEscapePos=null,this.strictErrors=new Map,this.tokensLength=0}get strict(){return(this.flags&1)>0}set strict(t){t?this.flags|=1:this.flags&=-2}init({strictMode:t,sourceType:e,startIndex:n,startLine:i,startColumn:s}){this.strict=t===!1?!1:t===!0?!0:e==="module",this.startIndex=n,this.curLine=i,this.lineStart=-s,this.startLoc=this.endLoc=new lt(i,s,n)}get maybeInArrowParameters(){return(this.flags&2)>0}set maybeInArrowParameters(t){t?this.flags|=2:this.flags&=-3}get inType(){return(this.flags&4)>0}set inType(t){t?this.flags|=4:this.flags&=-5}get noAnonFunctionType(){return(this.flags&8)>0}set noAnonFunctionType(t){t?this.flags|=8:this.flags&=-9}get hasFlowComment(){return(this.flags&16)>0}set hasFlowComment(t){t?this.flags|=16:this.flags&=-17}get isAmbientContext(){return(this.flags&32)>0}set isAmbientContext(t){t?this.flags|=32:this.flags&=-33}get inAbstractClass(){return(this.flags&64)>0}set inAbstractClass(t){t?this.flags|=64:this.flags&=-65}get inDisallowConditionalTypesContext(){return(this.flags&128)>0}set inDisallowConditionalTypesContext(t){t?this.flags|=128:this.flags&=-129}get soloAwait(){return(this.flags&256)>0}set soloAwait(t){t?this.flags|=256:this.flags&=-257}get inFSharpPipelineDirectBody(){return(this.flags&512)>0}set inFSharpPipelineDirectBody(t){t?this.flags|=512:this.flags&=-513}get canStartJSXElement(){return(this.flags&1024)>0}set canStartJSXElement(t){t?this.flags|=1024:this.flags&=-1025}get containsEsc(){return(this.flags&2048)>0}set containsEsc(t){t?this.flags|=2048:this.flags&=-2049}get hasTopLevelAwait(){return(this.flags&4096)>0}set hasTopLevelAwait(t){t?this.flags|=4096:this.flags&=-4097}curPosition(){return new lt(this.curLine,this.pos-this.lineStart,this.pos+this.startIndex)}clone(){let t=new r;return t.flags=this.flags,t.startIndex=this.startIndex,t.curLine=this.curLine,t.lineStart=this.lineStart,t.startLoc=this.startLoc,t.endLoc=this.endLoc,t.errors=this.errors.slice(),t.potentialArrowAt=this.potentialArrowAt,t.noArrowAt=this.noArrowAt.slice(),t.noArrowParamsConversionAt=this.noArrowParamsConversionAt.slice(),t.topicContext=this.topicContext,t.labels=this.labels.slice(),t.commentsLen=this.commentsLen,t.commentStack=this.commentStack.slice(),t.pos=this.pos,t.type=this.type,t.value=this.value,t.start=this.start,t.end=this.end,t.lastTokEndLoc=this.lastTokEndLoc,t.lastTokStartLoc=this.lastTokStartLoc,t.context=this.context.slice(),t.firstInvalidTemplateEscapePos=this.firstInvalidTemplateEscapePos,t.strictErrors=this.strictErrors,t.tokensLength=this.tokensLength,t}},Pb=function(t){return t>=48&&t<=57},Eu={decBinOct:new Set([46,66,69,79,95,98,101,111]),hex:new Set([46,88,95,120])},Fi={bin:r=>r===48||r===49,oct:r=>r>=48&&r<=55,dec:r=>r>=48&&r<=57,hex:r=>r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102};function Cu(r,t,e,n,i,s){let a=e,o=n,d=i,c="",l=null,u=e,{length:p}=t;for(;;){if(e>=p){s.unterminated(a,o,d),c+=t.slice(u,e);break}let f=t.charCodeAt(e);if(Rb(r,f,t,e)){c+=t.slice(u,e);break}if(f===92){c+=t.slice(u,e);let h=Tb(t,e,n,i,r==="template",s);h.ch===null&&!l?l={pos:e,lineStart:n,curLine:i}:c+=h.ch,{pos:e,lineStart:n,curLine:i}=h,u=e}else f===8232||f===8233?(++e,++i,n=e):f===10||f===13?r==="template"?(c+=t.slice(u,e)+`
8
- `,++e,f===13&&t.charCodeAt(e)===10&&++e,++i,u=n=e):s.unterminated(a,o,d):++e}return{pos:e,str:c,firstInvalidLoc:l,lineStart:n,curLine:i,containsInvalid:!!l}}function Rb(r,t,e,n){return r==="template"?t===96||t===36&&e.charCodeAt(n+1)===123:t===(r==="double"?34:39)}function Tb(r,t,e,n,i,s){let a=!i;t++;let o=c=>({pos:t,ch:c,lineStart:e,curLine:n}),d=r.charCodeAt(t++);switch(d){case 110:return o(`
9
- `);case 114:return o("\r");case 120:{let c;return{code:c,pos:t}=fo(r,t,e,n,2,!1,a,s),o(c===null?null:String.fromCharCode(c))}case 117:{let c;return{code:c,pos:t}=Gu(r,t,e,n,a,s),o(c===null?null:String.fromCodePoint(c))}case 116:return o(" ");case 98:return o("\b");case 118:return o("\v");case 102:return o("\f");case 13:r.charCodeAt(t)===10&&++t;case 10:e=t,++n;case 8232:case 8233:return o("");case 56:case 57:if(i)return o(null);s.strictNumericEscape(t-1,e,n);default:if(d>=48&&d<=55){let c=t-1,u=/^[0-7]+/.exec(r.slice(c,t+2))[0],p=parseInt(u,8);p>255&&(u=u.slice(0,-1),p=parseInt(u,8)),t+=u.length-1;let f=r.charCodeAt(t);if(u!=="0"||f===56||f===57){if(i)return o(null);s.strictNumericEscape(c,e,n)}return o(String.fromCharCode(p))}return o(String.fromCharCode(d))}}function fo(r,t,e,n,i,s,a,o){let d=t,c;return{n:c,pos:t}=Uu(r,t,e,n,16,i,s,!1,o,!a),c===null&&(a?o.invalidEscapeSequence(d,e,n):t=d-1),{code:c,pos:t}}function Uu(r,t,e,n,i,s,a,o,d,c){let l=t,u=i===16?Eu.hex:Eu.decBinOct,p=i===16?Fi.hex:i===10?Fi.dec:i===8?Fi.oct:Fi.bin,f=!1,h=0;for(let g=0,m=s??1/0;g<m;++g){let y=r.charCodeAt(t),w;if(y===95&&o!=="bail"){let x=r.charCodeAt(t-1),v=r.charCodeAt(t+1);if(o){if(Number.isNaN(v)||!p(v)||u.has(x)||u.has(v)){if(c)return{n:null,pos:t};d.unexpectedNumericSeparator(t,e,n)}}else{if(c)return{n:null,pos:t};d.numericSeparatorInEscapeSequence(t,e,n)}++t;continue}if(y>=97?w=y-97+10:y>=65?w=y-65+10:Pb(y)?w=y-48:w=1/0,w>=i){if(w<=9&&c)return{n:null,pos:t};if(w<=9&&d.invalidDigit(t,e,n,i))w=0;else if(a)w=0,f=!0;else break}++t,h=h*i+w}return t===l||s!=null&&t-l!==s||f?{n:null,pos:t}:{n:h,pos:t}}function Gu(r,t,e,n,i,s){let a=r.charCodeAt(t),o;if(a===123){if(++t,{code:o,pos:t}=fo(r,t,e,n,r.indexOf("}",t)-t,!0,i,s),++t,o!==null&&o>1114111)if(i)s.invalidCodePoint(t,e,n);else return{code:null,pos:t}}else({code:o,pos:t}=fo(r,t,e,n,4,!1,i,s));return{code:o,pos:t}}function yn(r,t,e){return new lt(e,r-t,r)}var Ab=new Set([103,109,115,105,121,117,100,118]),dt=class{constructor(t){let e=t.startIndex||0;this.type=t.type,this.value=t.value,this.start=e+t.start,this.end=e+t.end,this.loc=new Rr(t.startLoc,t.endLoc)}},ho=class extends uo{constructor(t,e){super(),this.isLookahead=void 0,this.tokens=[],this.errorHandlers_readInt={invalidDigit:(n,i,s,a)=>this.optionFlags&2048?(this.raise(b.InvalidDigit,yn(n,i,s),{radix:a}),!0):!1,numericSeparatorInEscapeSequence:this.errorBuilder(b.NumericSeparatorInEscapeSequence),unexpectedNumericSeparator:this.errorBuilder(b.UnexpectedNumericSeparator)},this.errorHandlers_readCodePoint=Object.assign({},this.errorHandlers_readInt,{invalidEscapeSequence:this.errorBuilder(b.InvalidEscapeSequence),invalidCodePoint:this.errorBuilder(b.InvalidCodePoint)}),this.errorHandlers_readStringContents_string=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:(n,i,s)=>{this.recordStrictModeErrors(b.StrictNumericEscape,yn(n,i,s))},unterminated:(n,i,s)=>{throw this.raise(b.UnterminatedString,yn(n-1,i,s))}}),this.errorHandlers_readStringContents_template=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:this.errorBuilder(b.StrictNumericEscape),unterminated:(n,i,s)=>{throw this.raise(b.UnterminatedTemplate,yn(n,i,s))}}),this.state=new po,this.state.init(t),this.input=e,this.length=e.length,this.comments=[],this.isLookahead=!1}pushToken(t){this.tokens.length=this.state.tokensLength,this.tokens.push(t),++this.state.tokensLength}next(){this.checkKeywordEscapes(),this.optionFlags&256&&this.pushToken(new dt(this.state)),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 Qa.lastIndex=t,Qa.test(this.input)?Qa.lastIndex:t}lookaheadCharCode(){return this.lookaheadCharCodeSince(this.state.pos)}lookaheadCharCodeSince(t){return this.input.charCodeAt(this.nextTokenStartSince(t))}nextTokenInLineStart(){return this.nextTokenInLineStartSince(this.state.pos)}nextTokenInLineStartSince(t){return Za.lastIndex=t,Za.test(this.input)?Za.lastIndex:t}lookaheadInLineCharCode(){return this.input.charCodeAt(this.nextTokenInLineStart())}codePointAtPos(t){let e=this.input.charCodeAt(t);if((e&64512)===55296&&++t<this.input.length){let n=this.input.charCodeAt(t);(n&64512)===56320&&(e=65536+((e&1023)<<10)+(n&1023))}return e}setStrict(t){this.state.strict=t,t&&(this.state.strictErrors.forEach(([e,n])=>this.raise(e,n)),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(140);return}this.getTokenFromCode(this.codePointAtPos(this.state.pos))}skipBlockComment(t){let e;this.isLookahead||(e=this.state.curPosition());let n=this.state.pos,i=this.input.indexOf(t,n+2);if(i===-1)throw this.raise(b.UnterminatedComment,this.state.curPosition());for(this.state.pos=i+t.length,_i.lastIndex=n+2;_i.test(this.input)&&_i.lastIndex<=i;)++this.state.curLine,this.state.lineStart=_i.lastIndex;if(this.isLookahead)return;let s={type:"CommentBlock",value:this.input.slice(n+2,i),start:this.sourceToOffsetPos(n),end:this.sourceToOffsetPos(i+t.length),loc:new Rr(e,this.state.curPosition())};return this.optionFlags&256&&this.pushToken(s),s}skipLineComment(t){let e=this.state.pos,n;this.isLookahead||(n=this.state.curPosition());let i=this.input.charCodeAt(this.state.pos+=t);if(this.state.pos<this.length)for(;!Ir(i)&&++this.state.pos<this.length;)i=this.input.charCodeAt(this.state.pos);if(this.isLookahead)return;let s=this.state.pos,o={type:"CommentLine",value:this.input.slice(e+t,s),start:this.sourceToOffsetPos(e),end:this.sourceToOffsetPos(s),loc:new Rr(n,this.state.curPosition())};return this.optionFlags&256&&this.pushToken(o),o}skipSpace(){let t=this.state.pos,e=this.optionFlags&4096?[]:null;e:for(;this.state.pos<this.length;){let n=this.input.charCodeAt(this.state.pos);switch(n){case 32:case 160:case 9:++this.state.pos;break;case 13:this.input.charCodeAt(this.state.pos+1)===10&&++this.state.pos;case 10:case 8232:case 8233:++this.state.pos,++this.state.curLine,this.state.lineStart=this.state.pos;break;case 47:switch(this.input.charCodeAt(this.state.pos+1)){case 42:{let i=this.skipBlockComment("*/");i!==void 0&&(this.addComment(i),e?.push(i));break}case 47:{let i=this.skipLineComment(2);i!==void 0&&(this.addComment(i),e?.push(i));break}default:break e}break;default:if(vb(n))++this.state.pos;else if(n===45&&!this.inModule&&this.optionFlags&8192){let i=this.state.pos;if(this.input.charCodeAt(i+1)===45&&this.input.charCodeAt(i+2)===62&&(t===0||this.state.lineStart>t)){let s=this.skipLineComment(3);s!==void 0&&(this.addComment(s),e?.push(s))}else break e}else if(n===60&&!this.inModule&&this.optionFlags&8192){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 s=this.skipLineComment(4);s!==void 0&&(this.addComment(s),e?.push(s))}else break e}else break e}}if(e?.length>0){let n=this.state.pos,i={start:this.sourceToOffsetPos(t),end:this.sourceToOffsetPos(n),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 n=this.state.type;this.state.type=t,this.state.value=e,this.isLookahead||this.updateContext(n)}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(b.UnexpectedDigitAfterHash,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?b.RecordExpressionHashIncorrectStartSyntaxType:b.TupleExpressionHashIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,e===123?this.finishToken(7):this.finishToken(1)}else ct(e)?(++this.state.pos,this.finishToken(139,this.readWord1(e))):e===92?(++this.state.pos,this.finishToken(139,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;!Ir(t)&&++this.state.pos<this.length;)t=this.input.charCodeAt(this.state.pos);let n=this.input.slice(e+2,this.state.pos);return this.finishToken(28,n),!0}readToken_mult_modulo(t){let e=t===42?55:54,n=1,i=this.input.charCodeAt(this.state.pos+1);t===42&&i===42&&(n++,i=this.input.charCodeAt(this.state.pos+2),e=57),i===61&&!this.state.inType&&(n++,e=t===37?33:30),this.finishOp(e,n)}readToken_pipe_amp(t){let e=this.input.charCodeAt(this.state.pos+1);if(e===t){this.input.charCodeAt(this.state.pos+2)===61?this.finishOp(30,3):this.finishOp(t===124?41:42,2);return}if(t===124){if(e===62){this.finishOp(39,2);return}if(this.hasPlugin("recordAndTuple")&&e===125){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(b.RecordExpressionBarIncorrectEndSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(9);return}if(this.hasPlugin("recordAndTuple")&&e===93){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(b.TupleExpressionBarIncorrectEndSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(4);return}}if(e===61){this.finishOp(30,2);return}this.finishOp(t===124?43:45,1)}readToken_caret(){let t=this.input.charCodeAt(this.state.pos+1);t===61&&!this.state.inType?this.finishOp(32,2):t===94&&this.hasPlugin(["pipelineOperator",{proposal:"hack",topicToken:"^^"}])?(this.finishOp(37,2),this.input.codePointAt(this.state.pos)===94&&this.unexpected()):this.finishOp(44,1)}readToken_atSign(){this.input.charCodeAt(this.state.pos+1)===64&&this.hasPlugin(["pipelineOperator",{proposal:"hack",topicToken:"@@"}])?this.finishOp(38,2):this.finishOp(26,1)}readToken_plus_min(t){let e=this.input.charCodeAt(this.state.pos+1);if(e===t){this.finishOp(34,2);return}e===61?this.finishOp(30,2):this.finishOp(53,1)}readToken_lt(){let{pos:t}=this.state,e=this.input.charCodeAt(t+1);if(e===60){if(this.input.charCodeAt(t+2)===61){this.finishOp(30,3);return}this.finishOp(51,2);return}if(e===61){this.finishOp(49,2);return}this.finishOp(47,1)}readToken_gt(){let{pos:t}=this.state,e=this.input.charCodeAt(t+1);if(e===62){let n=this.input.charCodeAt(t+2)===62?3:2;if(this.input.charCodeAt(t+n)===61){this.finishOp(30,n+1);return}this.finishOp(52,n);return}if(e===61){this.finishOp(49,2);return}this.finishOp(48,1)}readToken_eq_excl(t){let e=this.input.charCodeAt(this.state.pos+1);if(e===61){this.finishOp(46,this.input.charCodeAt(this.state.pos+2)===61?3:2);return}if(t===61&&e===62){this.state.pos+=2,this.finishToken(19);return}this.finishOp(t===61?29:35,1)}readToken_question(){let t=this.input.charCodeAt(this.state.pos+1),e=this.input.charCodeAt(this.state.pos+2);t===63?e===61?this.finishOp(30,3):this.finishOp(40,2):t===46&&!(e>=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(b.TupleExpressionBarIncorrectStartSyntaxType,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(b.RecordExpressionBarIncorrectStartSyntaxType,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(ct(t)){this.readWord(t);return}}throw this.raise(b.InvalidOrUnexpectedToken,this.state.curPosition(),{unexpected:String.fromCodePoint(t)})}finishOp(t,e){let n=this.input.slice(this.state.pos,this.state.pos+e);this.state.pos+=e,this.finishToken(t,n)}readRegexp(){let t=this.state.startLoc,e=this.state.start+1,n,i,{pos:s}=this.state;for(;;++s){if(s>=this.length)throw this.raise(b.UnterminatedRegExp,Oe(t,1));let c=this.input.charCodeAt(s);if(Ir(c))throw this.raise(b.UnterminatedRegExp,Oe(t,1));if(n)n=!1;else{if(c===91)i=!0;else if(c===93&&i)i=!1;else if(c===47&&!i)break;n=c===92}}let a=this.input.slice(e,s);++s;let o="",d=()=>Oe(t,s+2-e);for(;s<this.length;){let c=this.codePointAtPos(s),l=String.fromCharCode(c);if(Ab.has(c))c===118?o.includes("u")&&this.raise(b.IncompatibleRegExpUVFlags,d()):c===117&&o.includes("v")&&this.raise(b.IncompatibleRegExpUVFlags,d()),o.includes(l)&&this.raise(b.DuplicateRegExpFlags,d());else if(Jt(c)||c===92)this.raise(b.MalformedRegExpFlags,d());else break;++s,o+=l}this.state.pos=s,this.finishToken(138,{pattern:a,flags:o})}readInt(t,e,n=!1,i=!0){let{n:s,pos:a}=Uu(this.input,this.state.pos,this.state.lineStart,this.state.curLine,t,e,n,i,this.errorHandlers_readInt,!1);return this.state.pos=a,s}readRadixNumber(t){let e=this.state.pos,n=this.state.curPosition(),i=!1;this.state.pos+=2;let s=this.readInt(t);s==null&&this.raise(b.InvalidDigit,Oe(n,2),{radix:t});let a=this.input.charCodeAt(this.state.pos);if(a===110)++this.state.pos,i=!0;else if(a===109)throw this.raise(b.InvalidDecimal,n);if(ct(this.codePointAtPos(this.state.pos)))throw this.raise(b.NumberIdentifier,this.state.curPosition());if(i){let o=this.input.slice(e,this.state.pos).replace(/[_n]/g,"");this.finishToken(136,o);return}this.finishToken(135,s)}readNumber(t){let e=this.state.pos,n=this.state.curPosition(),i=!1,s=!1,a=!1,o=!1;!t&&this.readInt(10)===null&&this.raise(b.InvalidNumber,this.state.curPosition());let d=this.state.pos-e>=2&&this.input.charCodeAt(e)===48;if(d){let f=this.input.slice(e,this.state.pos);if(this.recordStrictModeErrors(b.StrictOctalLiteral,n),!this.state.strict){let h=f.indexOf("_");h>0&&this.raise(b.ZeroDigitNumericSeparator,Oe(n,h))}o=d&&!/[89]/.test(f)}let c=this.input.charCodeAt(this.state.pos);if(c===46&&!o&&(++this.state.pos,this.readInt(10),i=!0,c=this.input.charCodeAt(this.state.pos)),(c===69||c===101)&&!o&&(c=this.input.charCodeAt(++this.state.pos),(c===43||c===45)&&++this.state.pos,this.readInt(10)===null&&this.raise(b.InvalidOrMissingExponent,n),i=!0,a=!0,c=this.input.charCodeAt(this.state.pos)),c===110&&((i||d)&&this.raise(b.InvalidBigIntLiteral,n),++this.state.pos,s=!0),c===109){this.expectPlugin("decimal",this.state.curPosition()),(a||d)&&this.raise(b.InvalidDecimal,n),++this.state.pos;var l=!0}if(ct(this.codePointAtPos(this.state.pos)))throw this.raise(b.NumberIdentifier,this.state.curPosition());let u=this.input.slice(e,this.state.pos).replace(/[_mn]/g,"");if(s){this.finishToken(136,u);return}if(l){this.finishToken(137,u);return}let p=o?parseInt(u,8):parseFloat(u);this.finishToken(135,p)}readCodePoint(t){let{code:e,pos:n}=Gu(this.input,this.state.pos,this.state.lineStart,this.state.curLine,t,this.errorHandlers_readCodePoint);return this.state.pos=n,e}readString(t){let{str:e,pos:n,curLine:i,lineStart:s}=Cu(t===34?"double":"single",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_string);this.state.pos=n+1,this.state.lineStart=s,this.state.curLine=i,this.finishToken(134,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:n,pos:i,curLine:s,lineStart:a}=Cu("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=a,this.state.curLine=s,n&&(this.state.firstInvalidTemplateEscapePos=new lt(n.curLine,n.pos-n.lineStart,this.sourceToOffsetPos(n.pos))),this.input.codePointAt(i)===96?this.finishToken(24,n?null:t+e+"`"):(this.state.pos++,this.finishToken(25,n?null:t+e+"${"))}recordStrictModeErrors(t,e){let n=e.index;this.state.strict&&!this.state.strictErrors.has(n)?this.raise(t,e):this.state.strictErrors.set(n,[t,e])}readWord1(t){this.state.containsEsc=!1;let e="",n=this.state.pos,i=this.state.pos;for(t!==void 0&&(this.state.pos+=t<=65535?1:2);this.state.pos<this.length;){let s=this.codePointAtPos(this.state.pos);if(Jt(s))this.state.pos+=s<=65535?1:2;else if(s===92){this.state.containsEsc=!0,e+=this.input.slice(i,this.state.pos);let a=this.state.curPosition(),o=this.state.pos===n?ct:Jt;if(this.input.charCodeAt(++this.state.pos)!==117){this.raise(b.MissingUnicodeEscape,this.state.curPosition()),i=this.state.pos-1;continue}++this.state.pos;let d=this.readCodePoint(!0);d!==null&&(o(d)||this.raise(b.EscapedCharNotAnIdentifier,a),e+=String.fromCodePoint(d)),i=this.state.pos}else break}return e+this.input.slice(i,this.state.pos)}readWord(t){let e=this.readWord1(t),n=Ro.get(e);n!==void 0?this.finishToken(n,Ct(n)):this.finishToken(132,e)}checkKeywordEscapes(){let{type:t}=this.state;No(t)&&this.state.containsEsc&&this.raise(b.InvalidEscapedReservedWord,this.state.startLoc,{reservedWord:Ct(t)})}raise(t,e,n={}){let i=e instanceof lt?e:e.loc.start,s=t(i,n);if(!(this.optionFlags&2048))throw s;return this.isLookahead||this.state.errors.push(s),s}raiseOverwrite(t,e,n={}){let i=e instanceof lt?e:e.loc.start,s=i.index,a=this.state.errors;for(let o=a.length-1;o>=0;o--){let d=a[o];if(d.loc.index===s)return a[o]=t(i,n);if(d.loc.index<s)break}return this.raise(t,e,n)}updateContext(t){}unexpected(t,e){throw this.raise(b.UnexpectedToken,t??this.state.startLoc,{expected:e?Ct(e):null})}expectPlugin(t,e){if(this.hasPlugin(t))return!0;throw this.raise(b.MissingPlugin,e??this.state.startLoc,{missingPlugin:[t]})}expectOnePlugin(t){if(!t.some(e=>this.hasPlugin(e)))throw this.raise(b.MissingOneOfPlugins,this.state.startLoc,{missingPlugin:t})}errorBuilder(t){return(e,n,i)=>{this.raise(t,yn(e,n,i))}}},mo=class{constructor(){this.privateNames=new Set,this.loneAccessors=new Map,this.undefinedPrivateNames=new Map}},yo=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 mo)}exit(){let t=this.stack.pop(),e=this.current();for(let[n,i]of Array.from(t.undefinedPrivateNames))e?e.undefinedPrivateNames.has(n)||e.undefinedPrivateNames.set(n,i):this.parser.raise(b.InvalidPrivateFieldResolution,i,{identifierName:n})}declarePrivateName(t,e,n){let{privateNames:i,loneAccessors:s,undefinedPrivateNames:a}=this.current(),o=i.has(t);if(e&3){let d=o&&s.get(t);if(d){let c=d&4,l=e&4,u=d&3,p=e&3;o=u===p||c!==l,o||s.delete(t)}else o||s.set(t,e)}o&&this.parser.raise(b.PrivateNameRedeclaration,n,{identifierName:t}),i.add(t),a.delete(t)}usePrivateName(t,e){let n;for(n of this.stack)if(n.privateNames.has(t))return;n?n.undefinedPrivateNames.set(t,e):this.parser.raise(b.InvalidPrivateFieldResolution,e,{identifierName:t})}},Tr=class{constructor(t=0){this.type=t}canBeArrowParameterDeclaration(){return this.type===2||this.type===1}isCertainlyParameterDeclaration(){return this.type===3}},qi=class extends Tr{constructor(t){super(t),this.declarationErrors=new Map}recordDeclarationError(t,e){let n=e.index;this.declarationErrors.set(n,[t,e])}clearDeclarationError(t){this.declarationErrors.delete(t)}iterateErrors(t){this.declarationErrors.forEach(t)}},go=class{constructor(t){this.parser=void 0,this.stack=[new Tr],this.parser=t}enter(t){this.stack.push(t)}exit(){this.stack.pop()}recordParameterInitializerError(t,e){let n=e.loc.start,{stack:i}=this,s=i.length-1,a=i[s];for(;!a.isCertainlyParameterDeclaration();){if(a.canBeArrowParameterDeclaration())a.recordDeclarationError(t,n);else return;a=i[--s]}this.parser.raise(t,n)}recordArrowParameterBindingError(t,e){let{stack:n}=this,i=n[n.length-1],s=e.loc.start;if(i.isCertainlyParameterDeclaration())this.parser.raise(t,s);else if(i.canBeArrowParameterDeclaration())i.recordDeclarationError(t,s);else return}recordAsyncArrowParametersError(t){let{stack:e}=this,n=e.length-1,i=e[n];for(;i.canBeArrowParameterDeclaration();)i.type===2&&i.recordDeclarationError(b.AwaitBindingIdentifier,t),i=e[--n]}validateAsPattern(){let{stack:t}=this,e=t[t.length-1];e.canBeArrowParameterDeclaration()&&e.iterateErrors(([n,i])=>{this.parser.raise(n,i);let s=t.length-2,a=t[s];for(;a.canBeArrowParameterDeclaration();)a.clearDeclarationError(i.index),a=t[--s]})}};function Sb(){return new Tr(3)}function Eb(){return new qi(1)}function Cb(){return new qi(2)}function Ku(){return new Tr}var wo=class extends ho{addExtra(t,e,n,i=!0){if(!t)return;let{extra:s}=t;s==null&&(s={},t.extra=s),i?s[e]=n:Object.defineProperty(s,e,{enumerable:i,value:n})}isContextual(t){return this.state.type===t&&!this.state.containsEsc}isUnparsedContextual(t,e){if(this.input.startsWith(e,t)){let n=this.input.charCodeAt(t+e.length);return!(Jt(n)||(n&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,this.state.startLoc);this.unexpected(null,t)}}canInsertSemicolon(){return this.match(140)||this.match(8)||this.hasPrecedingLineBreak()}hasPrecedingLineBreak(){return Su(this.input,this.offsetToSourcePos(this.state.lastTokEndLoc.index),this.state.start)}hasFollowingLineBreak(){return Su(this.input,this.state.end,this.nextTokenStart())}isLineTerminator(){return this.eat(13)||this.canInsertSemicolon()}semicolon(t=!0){(t?this.isLineTerminator():this.eat(13))||this.raise(b.MissingSemicolon,this.state.lastTokEndLoc)}expect(t,e){this.eat(t)||this.unexpected(e,t)}tryParse(t,e=this.state.clone()){let n={node:null};try{let i=t((s=null)=>{throw n.node=s,n});if(this.state.errors.length>e.errors.length){let s=this.state;return this.state=e,this.state.tokensLength=s.tokensLength,{node:i,error:s.errors[e.errors.length],thrown:!1,aborted:!1,failState:s}}return{node:i,error:null,thrown:!1,aborted:!1,failState:null}}catch(i){let s=this.state;if(this.state=e,i instanceof SyntaxError)return{node:null,error:i,thrown:!0,aborted:!1,failState:s};if(i===n)return{node:n.node,error:null,thrown:!1,aborted:!0,failState:s};throw i}}checkExpressionErrors(t,e){if(!t)return!1;let{shorthandAssignLoc:n,doubleProtoLoc:i,privateKeyLoc:s,optionalParametersLoc:a,voidPatternLoc:o}=t,d=!!n||!!i||!!a||!!s||!!o;if(!e)return d;n!=null&&this.raise(b.InvalidCoverInitializedName,n),i!=null&&this.raise(b.DuplicateProto,i),s!=null&&this.raise(b.UnexpectedPrivateField,s),a!=null&&this.unexpected(a),o!=null&&this.raise(b.InvalidCoverDiscardElement,o)}isLiteralPropertyName(){return _u(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 n=this.exportedIdentifiers;this.exportedIdentifiers=new Set;let i=this.inModule;this.inModule=t;let s=this.scope,a=this.getScopeHandler();this.scope=new a(this,t);let o=this.prodParam;this.prodParam=new co;let d=this.classScope;this.classScope=new yo(this);let c=this.expressionScope;return this.expressionScope=new go(this),()=>{this.state.labels=e,this.exportedIdentifiers=n,this.inModule=i,this.scope=s,this.prodParam=o,this.classScope=d,this.expressionScope=c}}enterInitialScopes(){let t=0;(this.inModule||this.optionFlags&1)&&(t|=2),this.optionFlags&32&&(t|=1);let e=!this.inModule&&this.options.sourceType==="commonjs";(e||this.optionFlags&2)&&(t|=4),this.prodParam.enter(t);let n=e?514:1;this.optionFlags&4&&(n|=512),this.scope.enter(n)}checkDestructuringPrivate(t){let{privateKeyLoc:e}=t;e!==null&&this.expectPlugin("destructuringPrivate",e)}},Pr=class{constructor(){this.shorthandAssignLoc=null,this.doubleProtoLoc=null,this.privateKeyLoc=null,this.optionalParametersLoc=null,this.voidPatternLoc=null}},Ar=class{constructor(t,e,n){this.type="",this.start=e,this.end=0,this.loc=new Rr(n),t?.optionFlags&128&&(this.range=[e,0]),t!=null&&t.filename&&(this.loc.filename=t.filename)}},bo=Ar.prototype;bo.__clone=function(){let r=new Ar(void 0,this.start,this.loc.start),t=Object.keys(this);for(let e=0,n=t.length;e<n;e++){let i=t[e];i!=="leadingComments"&&i!=="trailingComments"&&i!=="innerComments"&&(r[i]=this[i])}return r};var xo=class extends wo{startNode(){let t=this.state.startLoc;return new Ar(this,t.index,t)}startNodeAt(t){return new Ar(this,t.index,t)}startNodeAtNode(t){return this.startNodeAt(t.loc.start)}finishNode(t,e){return this.finishNodeAt(t,e,this.state.lastTokEndLoc)}finishNodeAt(t,e,n){return t.type=e,t.end=n.index,t.loc.end=n,this.optionFlags&128&&(t.range[1]=n.index),this.optionFlags&4096&&this.processComment(t),t}resetStartLocation(t,e){t.start=e.index,t.loc.start=e,this.optionFlags&128&&(t.range[0]=e.index)}resetEndLocation(t,e=this.state.lastTokEndLoc){t.end=e.index,t.loc.end=e,this.optionFlags&128&&(t.range[1]=e.index)}resetStartLocationFromNode(t,e){this.resetStartLocation(t,e.loc.start)}castNodeTo(t,e){return t.type=e,t}cloneIdentifier(t){let{type:e,start:n,end:i,loc:s,range:a,name:o}=t,d=Object.create(bo);return d.type=e,d.start=n,d.end=i,d.loc=s,d.range=a,d.name=o,t.extra&&(d.extra=t.extra),d}cloneStringLiteral(t){let{type:e,start:n,end:i,loc:s,range:a,extra:o}=t,d=Object.create(bo);return d.type=e,d.start=n,d.end=i,d.loc=s,d.range=a,d.extra=o,d.value=t.value,d}},vo=r=>r.type==="ParenthesizedExpression"?vo(r.expression):r,ko=class extends xo{toAssignable(t,e=!1){var n,i;let s;switch((t.type==="ParenthesizedExpression"||(n=t.extra)!=null&&n.parenthesized)&&(s=vo(t),e?s.type==="Identifier"?this.expressionScope.recordArrowParameterBindingError(b.InvalidParenthesizedAssignment,t):s.type!=="CallExpression"&&s.type!=="MemberExpression"&&!this.isOptionalMemberExpression(s)&&this.raise(b.InvalidParenthesizedAssignment,t):this.raise(b.InvalidParenthesizedAssignment,t)),t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":break;case"ObjectExpression":this.castNodeTo(t,"ObjectPattern");for(let o=0,d=t.properties.length,c=d-1;o<d;o++){var a;let l=t.properties[o],u=o===c;this.toAssignableObjectExpressionProp(l,u,e),u&&l.type==="RestElement"&&(a=t.extra)!=null&&a.trailingCommaLoc&&this.raise(b.RestTrailingComma,t.extra.trailingCommaLoc)}break;case"ObjectProperty":{let{key:o,value:d}=t;this.isPrivateName(o)&&this.classScope.usePrivateName(this.getPrivateNameSV(o),o.loc.start),this.toAssignable(d,e);break}case"SpreadElement":throw new Error("Internal @babel/parser error (this is a bug, please report it). SpreadElement should be converted by .toAssignable's caller.");case"ArrayExpression":this.castNodeTo(t,"ArrayPattern"),this.toAssignableList(t.elements,(i=t.extra)==null?void 0:i.trailingCommaLoc,e);break;case"AssignmentExpression":t.operator!=="="&&this.raise(b.MissingEqInAssignment,t.left.loc.end),this.castNodeTo(t,"AssignmentPattern"),delete t.operator,t.left.type==="VoidPattern"&&this.raise(b.VoidPatternInitializer,t.left),this.toAssignable(t.left,e);break;case"ParenthesizedExpression":this.toAssignable(s,e);break}}toAssignableObjectExpressionProp(t,e,n){if(t.type==="ObjectMethod")this.raise(t.kind==="get"||t.kind==="set"?b.PatternHasAccessor:b.PatternHasMethod,t.key);else if(t.type==="SpreadElement"){this.castNodeTo(t,"RestElement");let i=t.argument;this.checkToRestConversion(i,!1),this.toAssignable(i,n),e||this.raise(b.RestTrailingComma,t)}else this.toAssignable(t,n)}toAssignableList(t,e,n){let i=t.length-1;for(let s=0;s<=i;s++){let a=t[s];a&&(this.toAssignableListItem(t,s,n),a.type==="RestElement"&&(s<i?this.raise(b.RestTrailingComma,a):e&&this.raise(b.RestTrailingComma,e)))}}toAssignableListItem(t,e,n){let i=t[e];if(i.type==="SpreadElement"){this.castNodeTo(i,"RestElement");let s=i.argument;this.checkToRestConversion(s,!0),this.toAssignable(s,n)}else this.toAssignable(i,n)}isAssignable(t,e){switch(t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":return!0;case"ObjectExpression":{let n=t.properties.length-1;return t.properties.every((i,s)=>i.type!=="ObjectMethod"&&(s===n||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(n=>n===null||this.isAssignable(n));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 n of t)n?.type==="ArrayExpression"&&this.toReferencedListDeep(n.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();this.next();let e=this.parseBindingAtom();return e.type==="VoidPattern"&&this.raise(b.UnexpectedVoidPattern,e),t.argument=e,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);case 88:return this.parseVoidPattern(null)}return this.parseIdentifier()}parseBindingList(t,e,n){let i=n&1,s=[],a=!0;for(;!this.eat(t);)if(a?a=!1:this.expect(12),i&&this.match(12))s.push(null);else{if(this.eat(t))break;if(this.match(21)){let o=this.parseRestBinding();if((this.hasPlugin("flow")||n&2)&&(o=this.parseFunctionParamType(o)),s.push(o),!this.checkCommaAfterRest(e)){this.expect(t);break}}else{let o=[];if(n&2)for(this.match(26)&&this.hasPlugin("decorators")&&this.raise(b.UnsupportedParameterDecorator,this.state.startLoc);this.match(26);)o.push(this.parseDecorator());s.push(this.parseBindingElement(n,o))}}return s}parseBindingRestProperty(t){return this.next(),this.hasPlugin("discardBinding")&&this.match(88)?(t.argument=this.parseVoidPattern(null),this.raise(b.UnexpectedVoidPattern,t.argument)):t.argument=this.parseIdentifier(),this.checkCommaAfterRest(125),this.finishNode(t,"RestElement")}parseBindingProperty(){let{type:t,startLoc:e}=this.state;if(t===21)return this.parseBindingRestProperty(this.startNode());let n=this.startNode();return t===139?(this.expectPlugin("destructuringPrivate",e),this.classScope.usePrivateName(this.state.value,e),n.key=this.parsePrivateName()):this.parsePropertyName(n),n.method=!1,this.parseObjPropValue(n,e,!1,!1,!0,!1)}parseBindingElement(t,e){let n=this.parseMaybeDefault();return(this.hasPlugin("flow")||t&2)&&this.parseFunctionParamType(n),e.length&&(n.decorators=e,this.resetStartLocationFromNode(n,e[0])),this.parseMaybeDefault(n.loc.start,n)}parseFunctionParamType(t){return t}parseMaybeDefault(t,e){if(t??(t=this.state.startLoc),e=e??this.parseBindingAtom(),!this.eat(29))return e;let n=this.startNodeAt(t);return e.type==="VoidPattern"&&this.raise(b.VoidPatternInitializer,e),n.left=e,n.right=this.parseMaybeAssignAllowIn(),this.finishNode(n,"AssignmentPattern")}isValidLVal(t,e,n,i){switch(t){case"AssignmentPattern":return"left";case"RestElement":return"argument";case"ObjectProperty":return"value";case"ParenthesizedExpression":return"expression";case"ArrayPattern":return"elements";case"ObjectPattern":return"properties";case"VoidPattern":return!0;case"CallExpression":if(!e&&!this.state.strict&&this.optionFlags&8192)return!0}return!1}isOptionalMemberExpression(t){return t.type==="OptionalMemberExpression"}checkLVal(t,e,n=64,i=!1,s=!1,a=!1,o=!1){var d;let c=t.type;if(this.isObjectMethod(t))return;let l=this.isOptionalMemberExpression(t);if(l||c==="MemberExpression"){l&&(this.expectPlugin("optionalChainingAssign",t.loc.start),e.type!=="AssignmentExpression"&&this.raise(b.InvalidLhsOptionalChaining,t,{ancestor:e})),n!==64&&this.raise(b.InvalidPropertyBindingPattern,t);return}if(c==="Identifier"){this.checkIdentifier(t,n,s);let{name:y}=t;i&&(i.has(y)?this.raise(b.ParamDupe,t):i.add(y));return}else c==="VoidPattern"&&e.type==="CatchClause"&&this.raise(b.VoidPatternCatchClauseParam,t);let u=vo(t);o||(o=u.type==="CallExpression"&&(u.callee.type==="Import"||u.callee.type==="Super"));let p=this.isValidLVal(c,o,!(a||(d=t.extra)!=null&&d.parenthesized)&&e.type==="AssignmentExpression",n);if(p===!0)return;if(p===!1){let y=n===64?b.InvalidLhs:b.InvalidLhsBinding;this.raise(y,t,{ancestor:e});return}let f,h;typeof p=="string"?(f=p,h=c==="ParenthesizedExpression"):[f,h]=p;let g=c==="ArrayPattern"||c==="ObjectPattern"?{type:c}:e,m=t[f];if(Array.isArray(m))for(let y of m)y&&this.checkLVal(y,g,n,i,s,h,!0);else m&&this.checkLVal(m,g,n,i,s,h,o)}checkIdentifier(t,e,n=!1){this.state.strict&&(n?Hu(t.name,this.inModule):zu(t.name))&&(e===64?this.raise(b.StrictEvalArguments,t,{referenceName:t.name}):this.raise(b.StrictEvalArgumentsBinding,t,{bindingName:t.name})),e&8192&&t.name==="let"&&this.raise(b.LetInLexicalBinding,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(b.InvalidRestAssignmentPattern,t)}}checkCommaAfterRest(t){return this.match(12)?(this.raise(this.lookaheadCharCode()===t?b.RestTrailingComma:b.ElementAfterRest,this.state.startLoc),!0):!1}},eo=/in(?:stanceof)?|as|satisfies/y;function Nb(r){if(r==null)throw new Error(`Unexpected ${r} value.`);return r}function Nu(r){if(!r)throw new Error("Assert fail")}var D=Ye`typescript`({AbstractMethodHasImplementation:({methodName:r})=>`Method '${r}' cannot have an implementation because it is marked abstract.`,AbstractPropertyHasInitializer:({propertyName:r})=>`Property '${r}' cannot have an initializer because it is marked abstract.`,AccessorCannotBeOptional:"An 'accessor' property cannot be declared optional.",AccessorCannotDeclareThisParameter:"'get' and 'set' accessors cannot declare 'this' parameters.",AccessorCannotHaveTypeParameters:"An accessor cannot have type parameters.",ClassMethodHasDeclare:"Class methods cannot have the 'declare' modifier.",ClassMethodHasReadonly:"Class methods cannot have the 'readonly' modifier.",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"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:r})=>`'declare' is not allowed in ${r}ters.`,DeclareClassFieldHasInitializer:"Initializers are not allowed in ambient contexts.",DeclareFunctionHasImplementation:"An implementation cannot be declared in ambient contexts.",DuplicateAccessibilityModifier:({modifier:r})=>`Accessibility modifier already seen: '${r}'.`,DuplicateModifier:({modifier:r})=>`Duplicate modifier: '${r}'.`,EmptyHeritageClauseType:({token:r})=>`'${r}' 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:r})=>`'${r[0]}' modifier cannot be used with '${r[1]}' modifier.`,IndexSignatureHasAbstract:"Index signatures cannot have the 'abstract' modifier.",IndexSignatureHasAccessibility:({modifier:r})=>`Index signatures cannot have an accessibility modifier ('${r}').`,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.",InvalidHeritageClauseType:({token:r})=>`'${r}' list can only include identifiers or qualified-names with optional type arguments.`,InvalidModifierOnAwaitUsingDeclaration:r=>`'${r}' modifier cannot appear on an await using declaration.`,InvalidModifierOnTypeMember:({modifier:r})=>`'${r}' modifier cannot appear on a type member.`,InvalidModifierOnTypeParameter:({modifier:r})=>`'${r}' modifier cannot appear on a type parameter.`,InvalidModifierOnTypeParameterPositions:({modifier:r})=>`'${r}' modifier can only appear on a type parameter of a class, interface or type alias.`,InvalidModifierOnUsingDeclaration:r=>`'${r}' modifier cannot appear on a using declaration.`,InvalidModifiersOrder:({orderedModifiers:r})=>`'${r[0]}' modifier must precede '${r[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.",NonAbstractClassHasAbstractMethod:"Abstract methods can only appear within an abstract class.",NonClassMethodPropertyHasAbstractModifier:"'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:r})=>`Private elements cannot have an accessibility modifier ('${r}').`,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 `<T,>() => ...`.",ReservedTypeAssertion:"This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",SetAccessorCannotHaveOptionalParameter:"A 'set' accessor cannot have an optional parameter.",SetAccessorCannotHaveRestParameter:"A 'set' accessor cannot have rest parameter.",SetAccessorCannotHaveReturnType:"A 'set' accessor cannot have a return type annotation.",SingleTypeParameterWithoutTrailingComma:({typeParameterName:r})=>`Single type parameter ${r} should have a trailing comma. Example usage: <${r},>.`,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:r})=>`Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${r}.`,UsingDeclarationInAmbientContext:r=>`'${r}' declarations are not allowed in ambient contexts.`});function Ob(r){switch(r){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 Ou(r){return r==="private"||r==="public"||r==="protected"}function Db(r){return r==="in"||r==="out"}var Lb=r=>class extends r{constructor(...e){super(...e),this.tsParseInOutModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out"],disallowedModifiers:["const","public","private","protected","readonly","declare","abstract","override"],errorTemplate:D.InvalidModifierOnTypeParameter}),this.tsParseConstModifier=this.tsParseModifiers.bind(this,{allowedModifiers:["const"],disallowedModifiers:["in","out"],errorTemplate:D.InvalidModifierOnTypeParameterPositions}),this.tsParseInOutConstModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out","const"],disallowedModifiers:["public","private","protected","readonly","declare","abstract","override"],errorTemplate:D.InvalidModifierOnTypeParameter})}getScopeHandler(){return oo}tsIsIdentifier(){return te(this.state.type)}tsTokenCanFollowModifier(){return this.match(0)||this.match(5)||this.match(55)||this.match(21)||this.match(139)||this.isLiteralPropertyName()}tsNextTokenOnSameLineAndCanFollowModifier(){return this.next(),this.hasPrecedingLineBreak()?!1:this.tsTokenCanFollowModifier()}tsNextTokenCanFollowModifier(){return this.match(106)?(this.next(),this.tsTokenCanFollowModifier()):this.tsNextTokenOnSameLineAndCanFollowModifier()}tsParseModifier(e,n,i){if(!te(this.state.type)&&this.state.type!==58&&this.state.type!==75)return;let s=this.state.value;if(e.includes(s)){if(i&&this.match(106)||n&&this.tsIsStartOfStaticBlocks())return;if(this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this)))return s}}tsParseModifiers({allowedModifiers:e,disallowedModifiers:n,stopOnStartOfClassStaticBlock:i,errorTemplate:s=D.InvalidModifierOnTypeMember},a){let o=(c,l,u,p)=>{l===u&&a[p]&&this.raise(D.InvalidModifiersOrder,c,{orderedModifiers:[u,p]})},d=(c,l,u,p)=>{(a[u]&&l===p||a[p]&&l===u)&&this.raise(D.IncompatibleModifiers,c,{modifiers:[u,p]})};for(;;){let{startLoc:c}=this.state,l=this.tsParseModifier(e.concat(n??[]),i,a.static);if(!l)break;Ou(l)?a.accessibility?this.raise(D.DuplicateAccessibilityModifier,c,{modifier:l}):(o(c,l,l,"override"),o(c,l,l,"static"),o(c,l,l,"readonly"),a.accessibility=l):Db(l)?(a[l]&&this.raise(D.DuplicateModifier,c,{modifier:l}),a[l]=!0,o(c,l,"in","out")):(hasOwnProperty.call(a,l)?this.raise(D.DuplicateModifier,c,{modifier:l}):(o(c,l,"static","readonly"),o(c,l,"static","override"),o(c,l,"override","readonly"),o(c,l,"abstract","override"),d(c,l,"declare","override"),d(c,l,"static","abstract")),a[l]=!0),n!=null&&n.includes(l)&&this.raise(s,c,{modifier:l})}}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,n){let i=[];for(;!this.tsIsListTerminator(e);)i.push(n());return i}tsParseDelimitedList(e,n,i){return Nb(this.tsParseDelimitedListWorker(e,n,!0,i))}tsParseDelimitedListWorker(e,n,i,s){let a=[],o=-1;for(;!this.tsIsListTerminator(e);){o=-1;let d=n();if(d==null)return;if(a.push(d),this.eat(12)){o=this.state.lastTokStartLoc.index;continue}if(this.tsIsListTerminator(e))break;i&&this.expect(12);return}return s&&(s.value=o),a}tsParseBracketedList(e,n,i,s,a){s||(i?this.expect(0):this.expect(47));let o=this.tsParseDelimitedList(e,n,a);return i?this.expect(3):this.expect(48),o}tsParseImportType(){let e=this.startNode();return this.expect(83),this.expect(10),this.match(134)?e.argument=this.parseStringLiteral(this.state.value):(this.raise(D.UnsupportedImportTypeArgument,this.state.startLoc),e.argument=super.parseExprAtom()),this.eat(12)?e.options=this.tsParseImportTypeOptions():e.options=null,this.expect(11),this.eat(16)&&(e.qualifier=this.tsParseEntityName(3)),this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSImportType")}tsParseImportTypeOptions(){let e=this.startNode();this.expect(5);let n=this.startNode();return this.isContextual(76)?(n.method=!1,n.key=this.parseIdentifier(!0),n.computed=!1,n.shorthand=!1):this.unexpected(null,76),this.expect(14),n.value=this.tsParseImportTypeWithPropertyValue(),e.properties=[this.finishObjectProperty(n)],this.eat(12),this.expect(8),this.finishNode(e,"ObjectExpression")}tsParseImportTypeWithPropertyValue(){let e=this.startNode(),n=[];for(this.expect(5);!this.match(8);){let i=this.state.type;te(i)||i===134?n.push(super.parsePropertyDefinition(null)):this.unexpected(),this.eat(12)}return e.properties=n,this.next(),this.finishNode(e,"ObjectExpression")}tsParseEntityName(e){let n;if(e&1&&this.match(78))if(e&2)n=this.parseIdentifier(!0);else{let i=this.startNode();this.next(),n=this.finishNode(i,"ThisExpression")}else n=this.parseIdentifier(!!(e&1));for(;this.eat(16);){let i=this.startNodeAtNode(n);i.left=n,i.right=this.parseIdentifier(!!(e&1)),n=this.finishNode(i,"TSQualifiedName")}return n}tsParseTypeReference(){let e=this.startNode();return e.typeName=this.tsParseEntityName(1),!this.hasPrecedingLineBreak()&&this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSTypeReference")}tsParseThisTypePredicate(e){this.next();let n=this.startNodeAtNode(e);return n.parameterName=e,n.typeAnnotation=this.tsParseTypeAnnotation(!1),n.asserts=!1,this.finishNode(n,"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(3),!this.hasPrecedingLineBreak()&&this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSTypeQuery")}tsParseTypeParameter(e){let n=this.startNode();return e(n),n.name=this.tsParseTypeParameterName(),n.constraint=this.tsEatThenParseType(81),n.default=this.tsEatThenParseType(29),this.finishNode(n,"TSTypeParameter")}tsTryParseTypeParameters(e){if(this.match(47))return this.tsParseTypeParameters(e)}tsParseTypeParameters(e){let n=this.startNode();this.match(47)||this.match(143)?this.next():this.unexpected();let i={value:-1};return n.params=this.tsParseBracketedList("TypeParametersOrArguments",this.tsParseTypeParameter.bind(this,e),!1,!0,i),n.params.length===0&&this.raise(D.EmptyTypeParameters,n),i.value!==-1&&this.addExtra(n,"trailingComma",i.value),this.finishNode(n,"TSTypeParameterDeclaration")}tsFillSignature(e,n){let i=e===19,s="parameters",a="typeAnnotation";n.typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier),this.expect(10),n[s]=this.tsParseBindingListForSignature(),i?n[a]=this.tsParseTypeOrTypePredicateAnnotation(e):this.match(e)&&(n[a]=this.tsParseTypeOrTypePredicateAnnotation(e))}tsParseBindingListForSignature(){let e=super.parseBindingList(11,41,2);for(let n of e){let{type:i}=n;(i==="AssignmentPattern"||i==="TSParameterProperty")&&this.raise(D.UnsupportedSignatureParameterKind,n,{type:i})}return e}tsParseTypeMemberSemicolon(){!this.eat(12)&&!this.isLineTerminator()&&this.expect(13)}tsParseSignatureMember(e,n){return this.tsFillSignature(14,n),this.tsParseTypeMemberSemicolon(),this.finishNode(n,e)}tsIsUnambiguouslyIndexSignature(){return this.next(),te(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 n=this.parseIdentifier();n.typeAnnotation=this.tsParseTypeAnnotation(),this.resetEndLocation(n),this.expect(3),e.parameters=[n];let i=this.tsTryParseTypeAnnotation();return i&&(e.typeAnnotation=i),this.tsParseTypeMemberSemicolon(),this.finishNode(e,"TSIndexSignature")}tsParsePropertyOrMethodSignature(e,n){if(this.eat(17)&&(e.optional=!0),this.match(10)||this.match(47)){n&&this.raise(D.ReadonlyForMethodSignature,e);let i=e;i.kind&&this.match(47)&&this.raise(D.AccessorCannotHaveTypeParameters,this.state.curPosition()),this.tsFillSignature(14,i),this.tsParseTypeMemberSemicolon();let s="parameters",a="typeAnnotation";if(i.kind==="get")i[s].length>0&&(this.raise(b.BadGetterArity,this.state.curPosition()),this.isThisParam(i[s][0])&&this.raise(D.AccessorCannotDeclareThisParameter,this.state.curPosition()));else if(i.kind==="set"){if(i[s].length!==1)this.raise(b.BadSetterArity,this.state.curPosition());else{let o=i[s][0];this.isThisParam(o)&&this.raise(D.AccessorCannotDeclareThisParameter,this.state.curPosition()),o.type==="Identifier"&&o.optional&&this.raise(D.SetAccessorCannotHaveOptionalParameter,this.state.curPosition()),o.type==="RestElement"&&this.raise(D.SetAccessorCannotHaveRestParameter,this.state.curPosition())}i[a]&&this.raise(D.SetAccessorCannotHaveReturnType,i[a])}else i.kind="method";return this.finishNode(i,"TSMethodSignature")}else{let i=e;n&&(i.readonly=!0);let s=this.tsTryParseTypeAnnotation();return s&&(i.typeAnnotation=s),this.tsParseTypeMemberSemicolon(),this.finishNode(i,"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 n=this.tsTryParseIndexSignature(e);return n||(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.match(10)&&!this.match(47)&&this.unexpected(null,10)),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(122):(this.isContextual(122)&&this.next(),!this.match(0)||(this.next(),!this.tsIsIdentifier())?!1:(this.next(),this.match(58)))}tsParseMappedType(){let e=this.startNode();this.expect(5),this.match(53)?(e.readonly=this.state.value,this.next(),this.expectContextual(122)):this.eatContextual(122)&&(e.readonly=!0),this.expect(0);let n=this.startNode();return n.name=this.tsParseTypeParameterName(),n.constraint=this.tsExpectThenParseType(58),e.typeParameter=this.finishNode(n,"TSTypeParameter"),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 n=!1;return e.elementTypes.forEach(i=>{let{type:s}=i;n&&s!=="TSRestType"&&s!=="TSOptionalType"&&!(s==="TSNamedTupleMember"&&i.optional)&&this.raise(D.OptionalTypeBeforeRequired,i),n||(n=s==="TSNamedTupleMember"&&i.optional||s==="TSOptionalType")}),this.finishNode(e,"TSTupleType")}tsParseTupleElementType(){let e=this.state.startLoc,n=this.eat(21),{startLoc:i}=this.state,s,a,o,d,l=Qe(this.state.type)?this.lookaheadCharCode():null;if(l===58)s=!0,o=!1,a=this.parseIdentifier(!0),this.expect(14),d=this.tsParseType();else if(l===63){o=!0;let u=this.state.value,p=this.tsParseNonArrayType();this.lookaheadCharCode()===58?(s=!0,a=this.createIdentifier(this.startNodeAt(i),u),this.expect(17),this.expect(14),d=this.tsParseType()):(s=!1,d=p,this.expect(17))}else d=this.tsParseType(),o=this.eat(17),s=this.eat(14);if(s){let u;a?(u=this.startNodeAt(i),u.optional=o,u.label=a,u.elementType=d,this.eat(17)&&(u.optional=!0,this.raise(D.TupleOptionalAfterType,this.state.lastTokStartLoc))):(u=this.startNodeAt(i),u.optional=o,this.raise(D.InvalidTupleMemberLabel,d),u.label=d,u.elementType=this.tsParseType()),d=this.finishNode(u,"TSNamedTupleMember")}else if(o){let u=this.startNodeAt(i);u.typeAnnotation=d,d=this.finishNode(u,"TSOptionalType")}if(n){let u=this.startNodeAt(e);u.typeAnnotation=d,d=this.finishNode(u,"TSRestType")}return d}tsParseParenthesizedType(){let e=this.startNode();return this.expect(10),e.typeAnnotation=this.tsParseType(),this.expect(11),this.finishNode(e,"TSParenthesizedType")}tsParseFunctionOrConstructorType(e,n){let i=this.startNode();return e==="TSConstructorType"&&(i.abstract=!!n,n&&this.next(),this.next()),this.tsInAllowConditionalTypesContext(()=>this.tsFillSignature(19,i)),this.finishNode(i,e)}tsParseLiteralTypeNode(){let e=this.startNode();switch(this.state.type){case 135:case 136:case 134: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(116)&&!this.hasPrecedingLineBreak()?this.tsParseThisTypePredicate(e):e}tsParseNonArrayType(){switch(this.state.type){case 134:case 135:case 136:case 85:case 86:return this.tsParseLiteralTypeNode();case 53:if(this.state.value==="-"){let e=this.startNode(),n=this.lookahead();return n.type!==135&&n.type!==136&&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(te(e)||e===88||e===84){let n=e===88?"TSVoidKeyword":e===84?"TSNullKeyword":Ob(this.state.value);if(n!==void 0&&this.lookaheadCharCode()!==46){let i=this.startNode();return this.next(),this.finishNode(i,n)}return this.tsParseTypeReference()}}}throw this.unexpected()}tsParseArrayTypeOrHigher(){let{startLoc:e}=this.state,n=this.tsParseNonArrayType();for(;!this.hasPrecedingLineBreak()&&this.eat(0);)if(this.match(3)){let i=this.startNodeAt(e);i.elementType=n,this.expect(3),n=this.finishNode(i,"TSArrayType")}else{let i=this.startNodeAt(e);i.objectType=n,i.indexType=this.tsParseType(),this.expect(3),n=this.finishNode(i,"TSIndexedAccessType")}return n}tsParseTypeOperator(){let e=this.startNode(),n=this.state.value;return this.next(),e.operator=n,e.typeAnnotation=this.tsParseTypeOperatorOrHigher(),n==="readonly"&&this.tsCheckTypeAnnotationForReadOnly(e),this.finishNode(e,"TSTypeOperator")}tsCheckTypeAnnotationForReadOnly(e){switch(e.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(D.UnexpectedReadonly,e)}}tsParseInferType(){let e=this.startNode();this.expectContextual(115);let n=this.startNode();return n.name=this.tsParseTypeParameterName(),n.constraint=this.tsTryParse(()=>this.tsParseConstraintForInferType()),e.typeParameter=this.finishNode(n,"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 eb(this.state.type)&&!this.state.containsEsc?this.tsParseTypeOperator():this.isContextual(115)?this.tsParseInferType():this.tsInAllowConditionalTypesContext(()=>this.tsParseArrayTypeOrHigher())}tsParseUnionOrIntersectionType(e,n,i){let s=this.startNode(),a=this.eat(i),o=[];do o.push(n());while(this.eat(i));return o.length===1&&!a?o[0]:(s.types=o,this.finishNode(s,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(te(this.state.type)||this.match(78))return this.next(),!0;if(this.match(5)){let{errors:e}=this.state,n=e.length;try{return this.parseObjectLike(8,!0),e.length===n}catch{return!1}}if(this.match(0)){this.next();let{errors:e}=this.state,n=e.length;try{return super.parseBindingList(3,93,1),e.length===n}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 n=this.startNode();this.expect(e);let i=this.startNode(),s=!!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));if(s&&this.match(78)){let d=this.tsParseThisTypeOrThisTypePredicate();return d.type==="TSThisType"?(i.parameterName=d,i.asserts=!0,i.typeAnnotation=null,d=this.finishNode(i,"TSTypePredicate")):(this.resetStartLocationFromNode(d,i),d.asserts=!0),n.typeAnnotation=d,this.finishNode(n,"TSTypeAnnotation")}let a=this.tsIsIdentifier()&&this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));if(!a)return s?(i.parameterName=this.parseIdentifier(),i.asserts=s,i.typeAnnotation=null,n.typeAnnotation=this.finishNode(i,"TSTypePredicate"),this.finishNode(n,"TSTypeAnnotation")):this.tsParseTypeAnnotation(!1,n);let o=this.tsParseTypeAnnotation(!1);return i.parameterName=a,i.typeAnnotation=o,i.asserts=s,n.typeAnnotation=this.finishNode(i,"TSTypePredicate"),this.finishNode(n,"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(116)&&!this.hasPrecedingLineBreak())return this.next(),e}tsParseTypePredicateAsserts(){if(this.state.type!==109)return!1;let e=this.state.containsEsc;return this.next(),!te(this.state.type)&&!this.match(78)?!1:(e&&this.raise(b.InvalidEscapedReservedWord,this.state.lastTokStartLoc,{reservedWord:"asserts"}),!0)}tsParseTypeAnnotation(e=!0,n=this.startNode()){return this.tsInType(()=>{e&&this.expect(14),n.typeAnnotation=this.tsParseType()}),this.finishNode(n,"TSTypeAnnotation")}tsParseType(){Nu(this.state.inType);let e=this.tsParseNonConditionalType();if(this.state.inDisallowConditionalTypesContext||this.hasPrecedingLineBreak()||!this.eat(81))return e;let n=this.startNodeAtNode(e);return n.checkType=e,n.extendsType=this.tsInDisallowConditionalTypesContext(()=>this.tsParseNonConditionalType()),this.expect(17),n.trueType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.expect(14),n.falseType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.finishNode(n,"TSConditionalType")}isAbstractConstructorSignature(){return this.isContextual(124)&&this.isLookaheadContextual("new")}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(D.ReservedTypeAssertion,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 n=this.state.startLoc,i=this.tsParseDelimitedList("HeritageClauseElement",()=>{let s=this.startNode();return s.expression=this.tsParseEntityName(3),this.match(47)&&(s.typeParameters=this.tsParseTypeArguments()),this.finishNode(s,"TSExpressionWithTypeArguments")});return i.length||this.raise(D.EmptyHeritageClauseType,n,{token:e}),i}tsParseInterfaceDeclaration(e,n={}){if(this.hasFollowingLineBreak())return null;this.expectContextual(129),n.declare&&(e.declare=!0),te(this.state.type)?(e.id=this.parseIdentifier(),this.checkIdentifier(e.id,130)):(e.id=null,this.raise(D.MissingInterfaceName,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(114)&&this.lookaheadCharCode()!==46){let n=this.startNode();return this.next(),this.finishNode(n,"TSIntrinsicKeyword")}return this.tsParseType()}),this.semicolon(),this.finishNode(e,"TSTypeAliasDeclaration")}tsInTopLevelContext(e){if(this.curContext()!==ee.brace){let n=this.state.context;this.state.context=[n[0]];try{return e()}finally{this.state.context=n}}else return e()}tsInType(e){let n=this.state.inType;this.state.inType=!0;try{return e()}finally{this.state.inType=n}}tsInDisallowConditionalTypesContext(e){let n=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!0;try{return e()}finally{this.state.inDisallowConditionalTypesContext=n}}tsInAllowConditionalTypesContext(e){let n=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!1;try{return e()}finally{this.state.inDisallowConditionalTypesContext=n}}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(134)?super.parseStringLiteral(this.state.value):this.parseIdentifier(!0),this.eat(29)&&(e.initializer=super.parseMaybeAssignAllowIn()),this.finishNode(e,"TSEnumMember")}tsParseEnumDeclaration(e,n={}){return n.const&&(e.const=!0),n.declare&&(e.declare=!0),this.expectContextual(126),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")}tsParseEnumBody(){let e=this.startNode();return this.expect(5),e.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(8),this.finishNode(e,"TSEnumBody")}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,n=!1){if(e.id=this.parseIdentifier(),n||this.checkIdentifier(e.id,1024),this.eat(16)){let i=this.startNode();this.tsParseModuleOrNamespaceDeclaration(i,!0),e.body=i}else this.scope.enter(1024),this.prodParam.enter(0),e.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit();return this.finishNode(e,"TSModuleDeclaration")}tsParseAmbientExternalModuleDeclaration(e){return this.isContextual(112)?(e.kind="global",e.global=!0,e.id=this.parseIdentifier()):this.match(134)?(e.kind="module",e.id=super.parseStringLiteral(this.state.value)):this.unexpected(),this.match(5)?(this.scope.enter(1024),this.prodParam.enter(0),e.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit()):this.semicolon(),this.finishNode(e,"TSModuleDeclaration")}tsParseImportEqualsDeclaration(e,n,i){e.isExport=i||!1,e.id=n||this.parseIdentifier(),this.checkIdentifier(e.id,4096),this.expect(29);let s=this.tsParseModuleReference();return e.importKind==="type"&&s.type!=="TSExternalModuleReference"&&this.raise(D.ImportAliasHasImportType,s),e.moduleReference=s,this.semicolon(),this.finishNode(e,"TSImportEqualsDeclaration")}tsIsExternalModuleReference(){return this.isContextual(119)&&this.lookaheadCharCode()===40}tsParseModuleReference(){return this.tsIsExternalModuleReference()?this.tsParseExternalModuleReference():this.tsParseEntityName(0)}tsParseExternalModuleReference(){let e=this.startNode();return this.expectContextual(119),this.expect(10),this.match(134)||this.unexpected(),e.expression=super.parseExprAtom(),this.expect(11),this.sawUnambiguousESM=!0,this.finishNode(e,"TSExternalModuleReference")}tsLookAhead(e){let n=this.state.clone(),i=e();return this.state=n,i}tsTryParseAndCatch(e){let n=this.tryParse(i=>e()||i());if(!(n.aborted||!n.node))return n.error&&(this.state=n.failState),n.node}tsTryParse(e){let n=this.state.clone(),i=e();if(i!==void 0&&i!==!1)return i;this.state=n}tsTryParseDeclare(e){if(this.isLineTerminator())return;let n=this.state.type;return this.tsInAmbientContext(()=>{switch(n){case 68:return e.declare=!0,super.parseFunctionStatement(e,!1,!1);case 80:return e.declare=!0,this.parseClass(e,!0,!1);case 126:return this.tsParseEnumDeclaration(e,{declare:!0});case 112:return this.tsParseAmbientExternalModuleDeclaration(e);case 100:if(this.state.containsEsc)return;case 75:case 74:return!this.match(75)||!this.isLookaheadContextual("enum")?(e.declare=!0,this.parseVarStatement(e,this.state.value,!0)):(this.expect(75),this.tsParseEnumDeclaration(e,{const:!0,declare:!0}));case 107:if(this.isUsing())return this.raise(D.InvalidModifierOnUsingDeclaration,this.state.startLoc,"declare"),e.declare=!0,this.parseVarStatement(e,"using",!0);break;case 96:if(this.isAwaitUsing())return this.raise(D.InvalidModifierOnAwaitUsingDeclaration,this.state.startLoc,"declare"),e.declare=!0,this.next(),this.parseVarStatement(e,"await using",!0);break;case 129:{let i=this.tsParseInterfaceDeclaration(e,{declare:!0});if(i)return i}default:if(te(n))return this.tsParseDeclaration(e,this.state.type,!0,null)}})}tsTryParseExportDeclaration(){return this.tsParseDeclaration(this.startNode(),this.state.type,!0,null)}tsParseDeclaration(e,n,i,s){switch(n){case 124:if(this.tsCheckLineTerminator(i)&&(this.match(80)||te(this.state.type)))return this.tsParseAbstractDeclaration(e,s);break;case 127:if(this.tsCheckLineTerminator(i)){if(this.match(134))return this.tsParseAmbientExternalModuleDeclaration(e);if(te(this.state.type))return e.kind="module",this.tsParseModuleOrNamespaceDeclaration(e)}break;case 128:if(this.tsCheckLineTerminator(i)&&te(this.state.type))return e.kind="namespace",this.tsParseModuleOrNamespaceDeclaration(e);break;case 130:if(this.tsCheckLineTerminator(i)&&te(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 n=this.state.maybeInArrowParameters;this.state.maybeInArrowParameters=!0;let i=this.tsTryParseAndCatch(()=>{let s=this.startNodeAt(e);return s.typeParameters=this.tsParseTypeParameters(this.tsParseConstModifier),super.parseFunctionParams(s),s.returnType=this.tsTryParseTypeOrTypePredicateAnnotation(),this.expect(19),s});if(this.state.maybeInArrowParameters=n,!!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.tsInTopLevelContext(()=>(this.expect(47),this.tsParseDelimitedList("TypeParametersOrArguments",this.tsParseType.bind(this))))),e.params.length===0?this.raise(D.EmptyTypeArguments,e):!this.state.inType&&this.curContext()===ee.brace&&this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TSTypeParameterInstantiation")}tsIsDeclarationStart(){return tb(this.state.type)}isExportDefaultSpecifier(){return this.tsIsDeclarationStart()?!1:super.isExportDefaultSpecifier()}parseBindingElement(e,n){let i=n.length?n[0].loc.start:this.state.startLoc,s={};this.tsParseModifiers({allowedModifiers:["public","private","protected","override","readonly"]},s);let a=s.accessibility,o=s.override,d=s.readonly;!(e&4)&&(a||d||o)&&this.raise(D.UnexpectedParameterModifier,i);let c=this.parseMaybeDefault();e&2&&this.parseFunctionParamType(c);let l=this.parseMaybeDefault(c.loc.start,c);if(a||d||o){let u=this.startNodeAt(i);return n.length&&(u.decorators=n),a&&(u.accessibility=a),d&&(u.readonly=d),o&&(u.override=o),l.type!=="Identifier"&&l.type!=="AssignmentPattern"&&this.raise(D.UnsupportedParameterPropertyKind,u),u.parameter=l,this.finishNode(u,"TSParameterProperty")}return n.length&&(c.decorators=n),l}isSimpleParameter(e){return e.type==="TSParameterProperty"&&super.isSimpleParameter(e.parameter)||super.isSimpleParameter(e)}tsDisallowOptionalPattern(e){for(let n of e.params)n.type!=="Identifier"&&n.optional&&!this.state.isAmbientContext&&this.raise(D.PatternIsOptional,n)}setArrowFunctionParameters(e,n,i){super.setArrowFunctionParameters(e,n,i),this.tsDisallowOptionalPattern(e)}parseFunctionBodyAndFinish(e,n,i=!1){this.match(14)&&(e.returnType=this.tsParseTypeOrTypePredicateAnnotation(14));let s=n==="FunctionDeclaration"?"TSDeclareFunction":n==="ClassMethod"||n==="ClassPrivateMethod"?"TSDeclareMethod":void 0;return s&&!this.match(5)&&this.isLineTerminator()?this.finishNode(e,s):s==="TSDeclareFunction"&&this.state.isAmbientContext&&(this.raise(D.DeclareFunctionHasImplementation,e),e.declare)?super.parseFunctionBodyAndFinish(e,s,i):(this.tsDisallowOptionalPattern(e),super.parseFunctionBodyAndFinish(e,n,i))}registerFunctionStatementId(e){!e.body&&e.id?this.checkIdentifier(e.id,1024):super.registerFunctionStatementId(e)}tsCheckForInvalidTypeCasts(e){e.forEach(n=>{n?.type==="TSTypeCastExpression"&&this.raise(D.UnexpectedTypeAnnotation,n.typeAnnotation)})}toReferencedList(e,n){return this.tsCheckForInvalidTypeCasts(e),e}parseArrayLike(e,n,i){let s=super.parseArrayLike(e,n,i);return s.type==="ArrayExpression"&&this.tsCheckForInvalidTypeCasts(s.elements),s}parseSubscript(e,n,i,s){if(!this.hasPrecedingLineBreak()&&this.match(35)){this.state.canStartJSXElement=!1,this.next();let o=this.startNodeAt(n);return o.expression=e,this.finishNode(o,"TSNonNullExpression")}let a=!1;if(this.match(18)&&this.lookaheadCharCode()===60){if(i)return s.stop=!0,e;s.optionalChainMember=a=!0,this.next()}if(this.match(47)||this.match(51)){let o,d=this.tsTryParseAndCatch(()=>{if(!i&&this.atPossibleAsyncArrow(e)){let p=this.tsTryParseGenericAsyncArrowFunction(n);if(p)return s.stop=!0,p}let c=this.tsParseTypeArgumentsInExpression();if(!c)return;if(a&&!this.match(10)){o=this.state.curPosition();return}if(Hi(this.state.type)){let p=super.parseTaggedTemplateExpression(e,n,s);return p.typeParameters=c,p}if(!i&&this.eat(10)){let p=this.startNodeAt(n);return p.callee=e,p.arguments=this.parseCallExpressionArguments(),this.tsCheckForInvalidTypeCasts(p.arguments),p.typeParameters=c,s.optionalChainMember&&(p.optional=a),this.finishCallExpression(p,s.optionalChainMember)}let l=this.state.type;if(l===48||l===52||l!==10&&l!==93&&l!==120&&gn(l)&&!this.hasPrecedingLineBreak())return;let u=this.startNodeAt(n);return u.expression=e,u.typeParameters=c,this.finishNode(u,"TSInstantiationExpression")});if(o&&this.unexpected(o,10),d)return d.type==="TSInstantiationExpression"&&((this.match(16)||this.match(18)&&this.lookaheadCharCode()!==40)&&this.raise(D.InvalidPropertyAccessAfterInstantiationExpression,this.state.startLoc),!this.match(16)&&!this.match(18)&&(d.expression=super.stopParseSubscript(e,s))),d}return super.parseSubscript(e,n,i,s)}parseNewCallee(e){var n;super.parseNewCallee(e);let{callee:i}=e;i.type==="TSInstantiationExpression"&&!((n=i.extra)!=null&&n.parenthesized)&&(e.typeParameters=i.typeParameters,e.callee=i.expression)}parseExprOp(e,n,i){let s;if(Bi(58)>i&&!this.hasPrecedingLineBreak()&&(this.isContextual(93)||(s=this.isContextual(120)))){let a=this.startNodeAt(n);return a.expression=e,a.typeAnnotation=this.tsInType(()=>(this.next(),this.match(75)?(s&&this.raise(b.UnexpectedKeyword,this.state.startLoc,{keyword:"const"}),this.tsParseTypeReference()):this.tsParseType())),this.finishNode(a,s?"TSSatisfiesExpression":"TSAsExpression"),this.reScan_lt_gt(),this.parseExprOp(a,n,i)}return super.parseExprOp(e,n,i)}checkReservedWord(e,n,i,s){this.state.isAmbientContext||super.checkReservedWord(e,n,i,s)}checkImportReflection(e){super.checkImportReflection(e),e.module&&e.importKind!=="value"&&this.raise(D.ImportReflectionHasImportType,e.specifiers[0].loc.start)}checkDuplicateExports(){}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return!0;if(this.isContextual(130)){let n=this.lookaheadCharCode();return e?n===123||n===42:n!==61}return!e&&this.isContextual(87)}applyImportPhase(e,n,i,s){super.applyImportPhase(e,n,i,s),n?e.exportKind=i==="type"?"type":"value":e.importKind=i==="type"||i==="typeof"?i:"value"}parseImport(e){if(this.match(134))return e.importKind="value",super.parseImport(e);let n;if(te(this.state.type)&&this.lookaheadCharCode()===61)return e.importKind="value",this.tsParseImportEqualsDeclaration(e);if(this.isContextual(130)){let i=this.parseMaybeImportPhase(e,!1);if(this.lookaheadCharCode()===61)return this.tsParseImportEqualsDeclaration(e,i);n=super.parseImportSpecifiersAndAfter(e,i)}else n=super.parseImport(e);return n.importKind==="type"&&n.specifiers.length>1&&n.specifiers[0].type==="ImportDefaultSpecifier"&&this.raise(D.TypeImportCannotSpecifyDefaultAndNamed,n),n}parseExport(e,n){if(this.match(83)){let i=e;this.next();let s=null;return this.isContextual(130)&&this.isPotentialImportPhase(!1)?s=this.parseMaybeImportPhase(i,!1):i.importKind="value",this.tsParseImportEqualsDeclaration(i,s,!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(128),i.id=this.parseIdentifier(),this.semicolon(),this.finishNode(i,"TSNamespaceExportDeclaration")}else return super.parseExport(e,n)}isAbstractClass(){return this.isContextual(124)&&this.isLookaheadContextual("class")}parseExportDefaultExpression(){if(this.isAbstractClass()){let e=this.startNode();return this.next(),e.abstract=!0,this.parseClass(e,!0,!0)}if(this.match(129)){let e=this.tsParseInterfaceDeclaration(this.startNode());if(e)return e}return super.parseExportDefaultExpression()}parseVarStatement(e,n,i=!1){let{isAmbientContext:s}=this.state,a=super.parseVarStatement(e,n,i||s);if(!s)return a;if(!e.declare&&(n==="using"||n==="await using"))return this.raiseOverwrite(D.UsingDeclarationInAmbientContext,e,n),a;for(let{id:o,init:d}of a.declarations)d&&(n==="var"||n==="let"||o.typeAnnotation?this.raise(D.InitializerNotAllowedInAmbientContext,d):$b(d,this.hasPlugin("estree"))||this.raise(D.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference,d));return a}parseStatementContent(e,n){if(!this.state.containsEsc)switch(this.state.type){case 75:{if(this.isLookaheadContextual("enum")){let i=this.startNode();return this.expect(75),this.tsParseEnumDeclaration(i,{const:!0})}break}case 124:case 125:{if(this.nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine()){let i=this.state.type,s=this.startNode();this.next();let a=i===125?this.tsTryParseDeclare(s):this.tsParseAbstractDeclaration(s,n);return a?(i===125&&(a.declare=!0),a):(s.expression=this.createIdentifier(this.startNodeAt(s.loc.start),i===125?"declare":"abstract"),this.semicolon(!1),this.finishNode(s,"ExpressionStatement"))}break}case 126:return this.tsParseEnumDeclaration(this.startNode());case 112:{if(this.lookaheadCharCode()===123){let s=this.startNode();return this.tsParseAmbientExternalModuleDeclaration(s)}break}case 129:{let i=this.tsParseInterfaceDeclaration(this.startNode());if(i)return i;break}case 127:{if(this.nextTokenIsIdentifierOrStringLiteralOnSameLine()){let i=this.startNode();return this.next(),this.tsParseDeclaration(i,127,!1,n)}break}case 128:{if(this.nextTokenIsIdentifierOnSameLine()){let i=this.startNode();return this.next(),this.tsParseDeclaration(i,128,!1,n)}break}case 130:{if(this.nextTokenIsIdentifierOnSameLine()){let i=this.startNode();return this.next(),this.tsParseTypeAliasDeclaration(i)}break}}return super.parseStatementContent(e,n)}parseAccessModifier(){return this.tsParseModifier(["public","protected","private"])}tsHasSomeModifiers(e,n){return n.some(i=>Ou(i)?e.accessibility===i:!!e[i])}tsIsStartOfStaticBlocks(){return this.isContextual(106)&&this.lookaheadCharCode()===123}parseClassMember(e,n,i){let s=["declare","private","public","protected","override","abstract","readonly","static"];this.tsParseModifiers({allowedModifiers:s,disallowedModifiers:["in","out"],stopOnStartOfClassStaticBlock:!0,errorTemplate:D.InvalidModifierOnTypeParameterPositions},n);let a=()=>{this.tsIsStartOfStaticBlocks()?(this.next(),this.next(),this.tsHasSomeModifiers(n,s)&&this.raise(D.StaticBlockCannotHaveModifier,this.state.curPosition()),super.parseClassStaticBlock(e,n)):this.parseClassMemberWithIsStatic(e,n,i,!!n.static)};n.declare?this.tsInAmbientContext(a):a()}parseClassMemberWithIsStatic(e,n,i,s){let a=this.tsTryParseIndexSignature(n);if(a){e.body.push(a),n.abstract&&this.raise(D.IndexSignatureHasAbstract,n),n.accessibility&&this.raise(D.IndexSignatureHasAccessibility,n,{modifier:n.accessibility}),n.declare&&this.raise(D.IndexSignatureHasDeclare,n),n.override&&this.raise(D.IndexSignatureHasOverride,n);return}!this.state.inAbstractClass&&n.abstract&&this.raise(D.NonAbstractClassHasAbstractMethod,n),n.override&&(i.hadSuperClass||this.raise(D.OverrideNotInSubClass,n)),super.parseClassMemberWithIsStatic(e,n,i,s)}parsePostMemberNameModifiers(e){this.eat(17)&&(e.optional=!0),e.readonly&&this.match(10)&&this.raise(D.ClassMethodHasReadonly,e),e.declare&&this.match(10)&&this.raise(D.ClassMethodHasDeclare,e)}shouldParseExportDeclaration(){return this.tsIsDeclarationStart()?!0:super.shouldParseExportDeclaration()}parseConditional(e,n,i){if(!this.match(17))return e;if(this.state.maybeInArrowParameters){let s=this.lookaheadCharCode();if(s===44||s===61||s===58||s===41)return this.setOptionalParametersError(i),e}return super.parseConditional(e,n,i)}parseParenItem(e,n){let i=super.parseParenItem(e,n);if(this.eat(17)&&(i.optional=!0,this.resetEndLocation(e)),this.match(14)){let s=this.startNodeAt(n);return s.expression=e,s.typeAnnotation=this.tsParseTypeAnnotation(),this.finishNode(s,"TSTypeCastExpression")}return e}parseExportDeclaration(e){if(!this.state.isAmbientContext&&this.isContextual(125))return this.tsInAmbientContext(()=>this.parseExportDeclaration(e));let n=this.state.startLoc,i=this.eatContextual(125);if(i&&(this.isContextual(125)||!this.shouldParseExportDeclaration()))throw this.raise(D.ExpectedAmbientAfterExportDeclare,this.state.startLoc);let a=te(this.state.type)&&this.tsTryParseExportDeclaration()||super.parseExportDeclaration(e);return a?((a.type==="TSInterfaceDeclaration"||a.type==="TSTypeAliasDeclaration"||i)&&(e.exportKind="type"),i&&a.type!=="TSImportEqualsDeclaration"&&(this.resetStartLocation(a,n),a.declare=!0),a):null}parseClassId(e,n,i,s){if((!n||i)&&this.isContextual(113))return;super.parseClassId(e,n,i,e.declare?1024:8331);let a=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);a&&(e.typeParameters=a)}parseClassPropertyAnnotation(e){e.optional||(this.eat(35)?e.definite=!0:this.eat(17)&&(e.optional=!0));let n=this.tsTryParseTypeAnnotation();n&&(e.typeAnnotation=n)}parseClassProperty(e){if(this.parseClassPropertyAnnotation(e),this.state.isAmbientContext&&!(e.readonly&&!e.typeAnnotation)&&this.match(29)&&this.raise(D.DeclareClassFieldHasInitializer,this.state.startLoc),e.abstract&&this.match(29)){let{key:n}=e;this.raise(D.AbstractPropertyHasInitializer,this.state.startLoc,{propertyName:n.type==="Identifier"&&!e.computed?n.name:`[${this.input.slice(this.offsetToSourcePos(n.start),this.offsetToSourcePos(n.end))}]`})}return super.parseClassProperty(e)}parseClassPrivateProperty(e){return e.abstract&&this.raise(D.PrivateElementHasAbstract,e),e.accessibility&&this.raise(D.PrivateElementHasAccessibility,e,{modifier:e.accessibility}),this.parseClassPropertyAnnotation(e),super.parseClassPrivateProperty(e)}parseClassAccessorProperty(e){return this.parseClassPropertyAnnotation(e),e.optional&&this.raise(D.AccessorCannotBeOptional,e),super.parseClassAccessorProperty(e)}pushClassMethod(e,n,i,s,a,o){let d=this.tsTryParseTypeParameters(this.tsParseConstModifier);d&&a&&this.raise(D.ConstructorHasTypeParameters,d);let{declare:c=!1,kind:l}=n;c&&(l==="get"||l==="set")&&this.raise(D.DeclareAccessor,n,{kind:l}),d&&(n.typeParameters=d),super.pushClassMethod(e,n,i,s,a,o)}pushClassPrivateMethod(e,n,i,s){let a=this.tsTryParseTypeParameters(this.tsParseConstModifier);a&&(n.typeParameters=a),super.pushClassPrivateMethod(e,n,i,s)}declareClassPrivateMethodInScope(e,n){e.type!=="TSDeclareMethod"&&(e.type==="MethodDefinition"&&e.value.body==null||super.declareClassPrivateMethodInScope(e,n))}parseClassSuper(e){if(super.parseClassSuper(e),e.superClass)if(e.superClass.type==="TSInstantiationExpression"){let n=e.superClass,i=n.expression;this.takeSurroundingComments(i,i.start,i.end);let s=n.typeParameters;this.takeSurroundingComments(s,s.start,s.end),e.superClass=i,e.superTypeParameters=s}else(this.match(47)||this.match(51))&&(e.superTypeParameters=this.tsParseTypeArgumentsInExpression());this.eatContextual(113)&&(e.implements=this.tsParseHeritageClause("implements"))}parseObjPropValue(e,n,i,s,a,o,d){let c=this.tsTryParseTypeParameters(this.tsParseConstModifier);return c&&(e.typeParameters=c),super.parseObjPropValue(e,n,i,s,a,o,d)}parseFunctionParams(e,n){let i=this.tsTryParseTypeParameters(this.tsParseConstModifier);i&&(e.typeParameters=i),super.parseFunctionParams(e,n)}parseVarId(e,n){super.parseVarId(e,n),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,n){return this.match(14)&&(e.returnType=this.tsParseTypeAnnotation()),super.parseAsyncArrowFromCallExpression(e,n)}parseMaybeAssign(e,n){var i,s,a,o,d;let c,l,u;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){if(c=this.state.clone(),l=this.tryParse(()=>super.parseMaybeAssign(e,n),c),!l.error)return l.node;let{context:h}=this.state,g=h[h.length-1];(g===ee.j_oTag||g===ee.j_expr)&&h.pop()}if(!((i=l)!=null&&i.error)&&!this.match(47))return super.parseMaybeAssign(e,n);(!c||c===this.state)&&(c=this.state.clone());let p,f=this.tryParse(h=>{var g,m;p=this.tsParseTypeParameters(this.tsParseConstModifier);let y=super.parseMaybeAssign(e,n);return(y.type!=="ArrowFunctionExpression"||(g=y.extra)!=null&&g.parenthesized)&&h(),((m=p)==null?void 0:m.params.length)!==0&&this.resetStartLocationFromNode(y,p),y.typeParameters=p,y},c);if(!f.error&&!f.aborted)return p&&this.reportReservedArrowTypeParam(p),f.node;if(!l&&(Nu(!this.hasPlugin("jsx")),u=this.tryParse(()=>super.parseMaybeAssign(e,n),c),!u.error))return u.node;if((s=l)!=null&&s.node)return this.state=l.failState,l.node;if(f.node)return this.state=f.failState,p&&this.reportReservedArrowTypeParam(p),f.node;if((a=u)!=null&&a.node)return this.state=u.failState,u.node;throw((o=l)==null?void 0:o.error)||f.error||((d=u)==null?void 0:d.error)}reportReservedArrowTypeParam(e){var n;e.params.length===1&&!e.params[0].constraint&&!((n=e.extra)!=null&&n.trailingComma)&&this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(D.ReservedArrowTypeParam,e)}parseMaybeUnary(e,n){return!this.hasPlugin("jsx")&&this.match(47)?this.tsParseTypeAssertion():super.parseMaybeUnary(e,n)}parseArrow(e){if(this.match(14)){let n=this.tryParse(i=>{let s=this.tsParseTypeOrTypePredicateAnnotation(14);return(this.canInsertSemicolon()||!this.match(19))&&i(),s});if(n.aborted)return;n.thrown||(n.error&&(this.state=n.failState),e.returnType=n.node)}return super.parseArrow(e)}parseFunctionParamType(e){this.eat(17)&&(e.optional=!0);let n=this.tsTryParseTypeAnnotation();return n&&(e.typeAnnotation=n),this.resetEndLocation(e),e}isAssignable(e,n){switch(e.type){case"TSTypeCastExpression":return this.isAssignable(e.expression,n);case"TSParameterProperty":return!0;default:return super.isAssignable(e,n)}}toAssignable(e,n=!1){switch(e.type){case"ParenthesizedExpression":this.toAssignableParenthesizedExpression(e,n);break;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":n?this.expressionScope.recordArrowParameterBindingError(D.UnexpectedTypeCastInParameter,e):this.raise(D.UnexpectedTypeCastInParameter,e),this.toAssignable(e.expression,n);break;case"AssignmentExpression":!n&&e.left.type==="TSTypeCastExpression"&&(e.left=this.typeCastToParameter(e.left));default:super.toAssignable(e,n)}}toAssignableParenthesizedExpression(e,n){switch(e.expression.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":case"ParenthesizedExpression":this.toAssignable(e.expression,n);break;default:super.toAssignable(e,n)}}checkToRestConversion(e,n){switch(e.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":this.checkToRestConversion(e.expression,!1);break;default:super.checkToRestConversion(e,n)}}isValidLVal(e,n,i,s){switch(e){case"TSTypeCastExpression":return!0;case"TSParameterProperty":return"parameter";case"TSNonNullExpression":return"expression";case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":return(s!==64||!i)&&["expression",!0];default:return super.isValidLVal(e,n,i,s)}}parseBindingAtom(){return this.state.type===78?this.parseIdentifier(!0):super.parseBindingAtom()}parseMaybeDecoratorArguments(e,n){if(this.match(47)||this.match(51)){let i=this.tsParseTypeArgumentsInExpression();if(this.match(10)){let s=super.parseMaybeDecoratorArguments(e,n);return s.typeParameters=i,s}this.unexpected(null,10)}return super.parseMaybeDecoratorArguments(e,n)}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,n){let i=super.parseMaybeDefault(e,n);return i.type==="AssignmentPattern"&&i.typeAnnotation&&i.right.start<i.typeAnnotation.start&&this.raise(D.TypeAnnotationAfterAssign,i.typeAnnotation),i}getTokenFromCode(e){if(this.state.inType){if(e===62){this.finishOp(48,1);return}if(e===60){this.finishOp(47,1);return}}super.getTokenFromCode(e)}reScan_lt_gt(){let{type:e}=this.state;e===47?(this.state.pos-=1,this.readToken_lt()):e===48&&(this.state.pos-=1,this.readToken_gt())}reScan_lt(){let{type:e}=this.state;return e===51?(this.state.pos-=2,this.finishOp(47,1),47):e}toAssignableListItem(e,n,i){let s=e[n];s.type==="TSTypeCastExpression"&&(e[n]=this.typeCastToParameter(s)),super.toAssignableListItem(e,n,i)}typeCastToParameter(e){return e.expression.typeAnnotation=e.typeAnnotation,this.resetEndLocation(e.expression,e.typeAnnotation.loc.end),e.expression}shouldParseArrow(e){return this.match(14)?e.every(n=>this.isAssignable(n,!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 n=this.tsTryParseAndCatch(()=>this.tsParseTypeArgumentsInExpression());n&&(e.typeParameters=n)}return super.jsxParseOpeningElementAfterName(e)}getGetterSetterExpectedParamCount(e){let n=super.getGetterSetterExpectedParamCount(e),s=this.getObjectOrClassMethodParams(e)[0];return s&&this.isThisParam(s)?n+1:n}parseCatchClauseParam(){let e=super.parseCatchClauseParam(),n=this.tsTryParseTypeAnnotation();return n&&(e.typeAnnotation=n,this.resetEndLocation(e)),e}tsInAmbientContext(e){let{isAmbientContext:n,strict:i}=this.state;this.state.isAmbientContext=!0,this.state.strict=!1;try{return e()}finally{this.state.isAmbientContext=n,this.state.strict=i}}parseClass(e,n,i){let s=this.state.inAbstractClass;this.state.inAbstractClass=!!e.abstract;try{return super.parseClass(e,n,i)}finally{this.state.inAbstractClass=s}}tsParseAbstractDeclaration(e,n){if(this.match(80))return e.abstract=!0,this.maybeTakeDecorators(n,this.parseClass(e,!0,!1));if(this.isContextual(129))return this.hasFollowingLineBreak()?null:(e.abstract=!0,this.raise(D.NonClassMethodPropertyHasAbstractModifier,e),this.tsParseInterfaceDeclaration(e));throw this.unexpected(null,80)}parseMethod(e,n,i,s,a,o,d){let c=super.parseMethod(e,n,i,s,a,o,d);if((c.abstract||c.type==="TSAbstractMethodDefinition")&&(this.hasPlugin("estree")?c.value:c).body){let{key:p}=c;this.raise(D.AbstractMethodHasImplementation,c,{methodName:p.type==="Identifier"&&!c.computed?p.name:`[${this.input.slice(this.offsetToSourcePos(p.start),this.offsetToSourcePos(p.end))}]`})}return c}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,n,i,s){return!n&&s?(this.parseTypeOnlyImportExportSpecifier(e,!1,i),this.finishNode(e,"ExportSpecifier")):(e.exportKind="value",super.parseExportSpecifier(e,n,i,s))}parseImportSpecifier(e,n,i,s,a){return!n&&s?(this.parseTypeOnlyImportExportSpecifier(e,!0,i),this.finishNode(e,"ImportSpecifier")):(e.importKind="value",super.parseImportSpecifier(e,n,i,s,i?4098:4096))}parseTypeOnlyImportExportSpecifier(e,n,i){let s=n?"imported":"local",a=n?"local":"exported",o=e[s],d,c=!1,l=!0,u=o.loc.start;if(this.isContextual(93)){let f=this.parseIdentifier();if(this.isContextual(93)){let h=this.parseIdentifier();Qe(this.state.type)?(c=!0,o=f,d=n?this.parseIdentifier():this.parseModuleExportName(),l=!1):(d=h,l=!1)}else Qe(this.state.type)?(l=!1,d=n?this.parseIdentifier():this.parseModuleExportName()):(c=!0,o=f)}else Qe(this.state.type)&&(c=!0,n?(o=this.parseIdentifier(!0),this.isContextual(93)||this.checkReservedWord(o.name,o.loc.start,!0,!0)):o=this.parseModuleExportName());c&&i&&this.raise(n?D.TypeModifierIsUsedInTypeImports:D.TypeModifierIsUsedInTypeExports,u),e[s]=o,e[a]=d;let p=n?"importKind":"exportKind";e[p]=c?"type":"value",l&&this.eatContextual(93)&&(e[a]=n?this.parseIdentifier():this.parseModuleExportName()),e[a]||(e[a]=this.cloneIdentifier(e[s])),n&&this.checkIdentifier(e[a],c?4098:4096)}fillOptionalPropertiesForTSESLint(e){var n,i,s,a,o,d,c,l,u,p,f,h,g,m,y,w,x,v,I,R,E,A,N,B,V,P,O,M,H,k,T,L,j,se,fe,ue,Y,ve,Re,mt,At,nn,sn,wi,an,on,dn,Rl,Tl;switch(e.type){case"ImportDeclaration":(n=e.phase)!=null||(e.phase=null);return;case"ExpressionStatement":(i=e.directive)!=null||(e.directive=void 0);return;case"RestElement":e.value=void 0;case"Identifier":case"ArrayPattern":case"AssignmentPattern":case"ObjectPattern":(s=e.decorators)!=null||(e.decorators=[]),(a=e.optional)!=null||(e.optional=!1),(o=e.typeAnnotation)!=null||(e.typeAnnotation=void 0);return;case"TSParameterProperty":(d=e.accessibility)!=null||(e.accessibility=void 0),(c=e.decorators)!=null||(e.decorators=[]),(l=e.override)!=null||(e.override=!1),(u=e.readonly)!=null||(e.readonly=!1),(p=e.static)!=null||(e.static=!1);return;case"TSEmptyBodyFunctionExpression":e.body=null;case"TSDeclareFunction":case"FunctionDeclaration":case"FunctionExpression":case"ClassMethod":case"ClassPrivateMethod":(f=e.declare)!=null||(e.declare=!1),(h=e.returnType)!=null||(e.returnType=void 0),(g=e.typeParameters)!=null||(e.typeParameters=void 0);return;case"Property":(m=e.optional)!=null||(e.optional=!1);return;case"TSMethodSignature":case"TSPropertySignature":(y=e.optional)!=null||(e.optional=!1);case"TSIndexSignature":(w=e.accessibility)!=null||(e.accessibility=void 0),(x=e.readonly)!=null||(e.readonly=!1),(v=e.static)!=null||(e.static=!1);return;case"TSAbstractPropertyDefinition":case"PropertyDefinition":case"TSAbstractAccessorProperty":case"AccessorProperty":(I=e.declare)!=null||(e.declare=!1),(R=e.definite)!=null||(e.definite=!1),(E=e.readonly)!=null||(e.readonly=!1),(A=e.typeAnnotation)!=null||(e.typeAnnotation=void 0);case"TSAbstractMethodDefinition":case"MethodDefinition":(N=e.accessibility)!=null||(e.accessibility=void 0),(B=e.decorators)!=null||(e.decorators=[]),(V=e.override)!=null||(e.override=!1),(P=e.optional)!=null||(e.optional=!1);return;case"ClassExpression":(O=e.id)!=null||(e.id=null);case"ClassDeclaration":(M=e.abstract)!=null||(e.abstract=!1),(H=e.declare)!=null||(e.declare=!1),(k=e.decorators)!=null||(e.decorators=[]),(T=e.implements)!=null||(e.implements=[]),(L=e.superTypeArguments)!=null||(e.superTypeArguments=void 0),(j=e.typeParameters)!=null||(e.typeParameters=void 0);return;case"TSTypeAliasDeclaration":case"VariableDeclaration":(se=e.declare)!=null||(e.declare=!1);return;case"VariableDeclarator":(fe=e.definite)!=null||(e.definite=!1);return;case"TSEnumDeclaration":(ue=e.const)!=null||(e.const=!1),(Y=e.declare)!=null||(e.declare=!1);return;case"TSEnumMember":(ve=e.computed)!=null||(e.computed=!1);return;case"TSImportType":(Re=e.qualifier)!=null||(e.qualifier=null),(mt=e.options)!=null||(e.options=null);return;case"TSInterfaceDeclaration":(At=e.declare)!=null||(e.declare=!1),(nn=e.extends)!=null||(e.extends=[]);return;case"TSMappedType":(sn=e.optional)!=null||(e.optional=!1),(wi=e.readonly)!=null||(e.readonly=void 0);return;case"TSModuleDeclaration":(an=e.declare)!=null||(e.declare=!1),(on=e.global)!=null||(e.global=e.kind==="global");return;case"TSTypeParameter":(dn=e.const)!=null||(e.const=!1),(Rl=e.in)!=null||(e.in=!1),(Tl=e.out)!=null||(e.out=!1);return}}chStartsBindingIdentifierAndNotRelationalOperator(e,n){if(ct(e)){if(eo.lastIndex=n,eo.test(this.input)){let i=this.codePointAtPos(eo.lastIndex);if(!Jt(i)&&i!==92)return!1}return!0}else return e===92}nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine(){let e=this.nextTokenInLineStart(),n=this.codePointAtPos(e);return this.chStartsBindingIdentifierAndNotRelationalOperator(n,e)}nextTokenIsIdentifierOrStringLiteralOnSameLine(){let e=this.nextTokenInLineStart(),n=this.codePointAtPos(e);return this.chStartsBindingIdentifier(n,e)||n===34||n===39}};function Mb(r){if(r.type!=="MemberExpression")return!1;let{computed:t,property:e}=r;return t&&e.type!=="StringLiteral"&&(e.type!=="TemplateLiteral"||e.expressions.length>0)?!1:Ju(r.object)}function $b(r,t){var e;let{type:n}=r;if((e=r.extra)!=null&&e.parenthesized)return!1;if(t){if(n==="Literal"){let{value:i}=r;if(typeof i=="string"||typeof i=="boolean")return!0}}else if(n==="StringLiteral"||n==="BooleanLiteral")return!0;return!!(Wu(r,t)||_b(r,t)||n==="TemplateLiteral"&&r.expressions.length===0||Mb(r))}function Wu(r,t){return t?r.type==="Literal"&&(typeof r.value=="number"||"bigint"in r):r.type==="NumericLiteral"||r.type==="BigIntLiteral"}function _b(r,t){if(r.type==="UnaryExpression"){let{operator:e,argument:n}=r;if(e==="-"&&Wu(n,t))return!0}return!1}function Ju(r){return r.type==="Identifier"?!0:r.type!=="MemberExpression"||r.computed?!1:Ju(r.object)}var Du=Ye`placeholders`({ClassNameIsRequired:"A class name is required.",UnexpectedSpace:"Unexpected space in placeholder."}),Fb=r=>class extends r{parsePlaceholder(e){if(this.match(133)){let n=this.startNode();return this.next(),this.assertNoSpace(),n.name=super.parseIdentifier(!0),this.assertNoSpace(),this.expect(133),this.finishPlaceholder(n,e)}}finishPlaceholder(e,n){let i=e;return(!i.expectedNode||!i.type)&&(i=this.finishNode(i,"Placeholder")),i.expectedNode=n,i}getTokenFromCode(e){e===37&&this.input.charCodeAt(this.state.pos+1)===37?this.finishOp(133,2):super.getTokenFromCode(e)}parseExprAtom(e){return this.parsePlaceholder("Expression")||super.parseExprAtom(e)}parseIdentifier(e){return this.parsePlaceholder("Identifier")||super.parseIdentifier(e)}checkReservedWord(e,n,i,s){e!==void 0&&super.checkReservedWord(e,n,i,s)}cloneIdentifier(e){let n=super.cloneIdentifier(e);return n.type==="Placeholder"&&(n.expectedNode=e.expectedNode),n}cloneStringLiteral(e){return e.type==="Placeholder"?this.cloneIdentifier(e):super.cloneStringLiteral(e)}parseBindingAtom(){return this.parsePlaceholder("Pattern")||super.parseBindingAtom()}isValidLVal(e,n,i,s){return e==="Placeholder"||super.isValidLVal(e,n,i,s)}toAssignable(e,n){e&&e.type==="Placeholder"&&e.expectedNode==="Expression"?e.expectedNode="Pattern":super.toAssignable(e,n)}chStartsBindingIdentifier(e,n){if(super.chStartsBindingIdentifier(e,n))return!0;let i=this.nextTokenStart();return this.input.charCodeAt(i)===37&&this.input.charCodeAt(i+1)===37}verifyBreakContinue(e,n){var i;((i=e.label)==null?void 0:i.type)!=="Placeholder"&&super.verifyBreakContinue(e,n)}parseExpressionStatement(e,n){var i;if(n.type!=="Placeholder"||(i=n.extra)!=null&&i.parenthesized)return super.parseExpressionStatement(e,n);if(this.match(14)){let a=e;return a.label=this.finishPlaceholder(n,"Identifier"),this.next(),a.body=super.parseStatementOrSloppyAnnexBFunctionDeclaration(),this.finishNode(a,"LabeledStatement")}this.semicolon();let s=e;return s.name=n.name,this.finishPlaceholder(s,"Statement")}parseBlock(e,n,i){return this.parsePlaceholder("BlockStatement")||super.parseBlock(e,n,i)}parseFunctionId(e){return this.parsePlaceholder("Identifier")||super.parseFunctionId(e)}parseClass(e,n,i){let s=n?"ClassDeclaration":"ClassExpression";this.next();let a=this.state.strict,o=this.parsePlaceholder("Identifier");if(o)if(this.match(81)||this.match(133)||this.match(5))e.id=o;else{if(i||!n)return e.id=null,e.body=this.finishPlaceholder(o,"ClassBody"),this.finishNode(e,s);throw this.raise(Du.ClassNameIsRequired,this.state.startLoc)}else this.parseClassId(e,n,i);return super.parseClassSuper(e),e.body=this.parsePlaceholder("ClassBody")||super.parseClassBody(!!e.superClass,a),this.finishNode(e,s)}parseExport(e,n){let i=this.parsePlaceholder("Identifier");if(!i)return super.parseExport(e,n);let s=e;if(!this.isContextual(98)&&!this.match(12))return s.specifiers=[],s.source=null,s.declaration=this.finishPlaceholder(i,"Declaration"),this.finishNode(s,"ExportNamedDeclaration");this.expectPlugin("exportDefaultFrom");let a=this.startNode();return a.exported=i,s.specifiers=[this.finishNode(a,"ExportDefaultSpecifier")],super.parseExport(s,n)}isExportDefaultSpecifier(){if(this.match(65)){let e=this.nextTokenStart();if(this.isUnparsedContextual(e,"from")&&this.input.startsWith(Ct(133),this.nextTokenStartSince(e+4)))return!0}return super.isExportDefaultSpecifier()}maybeParseExportDefaultSpecifier(e,n){var i;return(i=e.specifiers)!=null&&i.length?!0:super.maybeParseExportDefaultSpecifier(e,n)}checkExport(e){let{specifiers:n}=e;n!=null&&n.length&&(e.specifiers=n.filter(i=>i.exported.type==="Placeholder")),super.checkExport(e),e.specifiers=n}parseImport(e){let n=this.parsePlaceholder("Identifier");if(!n)return super.parseImport(e);if(e.specifiers=[],!this.isContextual(98)&&!this.match(12))return e.source=this.finishPlaceholder(n,"StringLiteral"),this.semicolon(),this.finishNode(e,"ImportDeclaration");let i=this.startNodeAtNode(n);return i.local=n,e.specifiers.push(this.finishNode(i,"ImportDefaultSpecifier")),this.eat(12)&&(this.maybeParseStarImportSpecifier(e)||this.parseNamedImportSpecifiers(e)),this.expectContextual(98),e.source=this.parseImportSource(),this.semicolon(),this.finishNode(e,"ImportDeclaration")}parseImportSource(){return this.parsePlaceholder("StringLiteral")||super.parseImportSource()}assertNoSpace(){this.state.start>this.offsetToSourcePos(this.state.lastTokEndLoc.index)&&this.raise(Du.UnexpectedSpace,this.state.lastTokEndLoc)}},jb=r=>class extends r{parseV8Intrinsic(){if(this.match(54)){let e=this.state.startLoc,n=this.startNode();if(this.next(),te(this.state.type)){let i=this.parseIdentifierName(),s=this.createIdentifier(n,i);if(this.castNodeTo(s,"V8IntrinsicIdentifier"),this.match(10))return s}this.unexpected(e)}}parseExprAtom(e){return this.parseV8Intrinsic()||super.parseExprAtom(e)}},Lu=["minimal","fsharp","hack","smart"],Mu=["^^","@@","^","%","#"];function Bb(r){if(r.has("decorators")){if(r.has("decorators-legacy"))throw new Error("Cannot use the decorators and decorators-legacy plugin together");let n=r.get("decorators").decoratorsBeforeExport;if(n!=null&&typeof n!="boolean")throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");let i=r.get("decorators").allowCallParenthesized;if(i!=null&&typeof i!="boolean")throw new Error("'allowCallParenthesized' must be a boolean.")}if(r.has("flow")&&r.has("typescript"))throw new Error("Cannot combine flow and typescript plugins.");if(r.has("placeholders")&&r.has("v8intrinsic"))throw new Error("Cannot combine placeholders and v8intrinsic plugins.");if(r.has("pipelineOperator")){var t;let n=r.get("pipelineOperator").proposal;if(!Lu.includes(n)){let i=Lu.map(s=>`"${s}"`).join(", ");throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${i}.`)}if(n==="hack"){var e;if(r.has("placeholders"))throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");if(r.has("v8intrinsic"))throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");let i=r.get("pipelineOperator").topicToken;if(!Mu.includes(i)){let s=Mu.map(a=>`"${a}"`).join(", ");throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${s}.`)}if(i==="#"&&((e=r.get("recordAndTuple"))==null?void 0:e.syntaxType)==="hash")throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple",r.get("recordAndTuple")])}\`.`)}else if(n==="smart"&&((t=r.get("recordAndTuple"))==null?void 0:t.syntaxType)==="hash")throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple",r.get("recordAndTuple")])}\`.`)}if(r.has("moduleAttributes")){if(r.has("deprecatedImportAssert")||r.has("importAssertions"))throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.");if(r.get("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(r.has("importAssertions")&&r.has("deprecatedImportAssert"))throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins.");if(r.has("deprecatedImportAssert")||r.has("importAttributes")&&r.get("importAttributes").deprecatedAssertSyntax&&r.set("deprecatedImportAssert",{}),r.has("recordAndTuple")){let n=r.get("recordAndTuple").syntaxType;if(n!=null){let i=["hash","bar"];if(!i.includes(n))throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: "+i.map(s=>`'${s}'`).join(", "))}}if(r.has("asyncDoExpressions")&&!r.has("doExpressions")){let n=new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");throw n.missingPlugins="doExpressions",n}if(r.has("optionalChainingAssign")&&r.get("optionalChainingAssign").version!=="2023-07")throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option, representing the last proposal update. Currently, the only supported value is '2023-07'.");if(r.has("discardBinding")&&r.get("discardBinding").syntaxType!=="void")throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'.")}var Xu={estree:qw,jsx:kb,flow:wb,typescript:Lb,v8intrinsic:jb,placeholders:Fb},Vb=Object.keys(Xu),Io=class extends ko{checkProto(t,e,n,i){if(t.type==="SpreadElement"||this.isObjectMethod(t)||t.computed||t.shorthand)return n;let s=t.key;return(s.type==="Identifier"?s.name:s.value)==="__proto__"?e?(this.raise(b.RecordNoProto,s),!0):(n&&(i?i.doubleProtoLoc===null&&(i.doubleProtoLoc=s.loc.start):this.raise(b.DuplicateProto,s)),!0):n}shouldExitDescending(t,e){return t.type==="ArrowFunctionExpression"&&this.offsetToSourcePos(t.start)===e}getExpression(){if(this.enterInitialScopes(),this.nextToken(),this.match(140))throw this.raise(b.ParseExpressionEmptyInput,this.state.startLoc);let t=this.parseExpression();if(!this.match(140))throw this.raise(b.ParseExpressionExpectsEOF,this.state.startLoc,{unexpected:this.input.codePointAt(this.state.start)});return this.finalizeRemainingComments(),t.comments=this.comments,t.errors=this.state.errors,this.optionFlags&256&&(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,n=this.parseMaybeAssign(t);if(this.match(12)){let i=this.startNodeAt(e);for(i.expressions=[n];this.eat(12);)i.expressions.push(this.parseMaybeAssign(t));return this.toReferencedList(i.expressions),this.finishNode(i,"SequenceExpression")}return n}parseMaybeAssignDisallowIn(t,e){return this.disallowInAnd(()=>this.parseMaybeAssign(t,e))}parseMaybeAssignAllowIn(t,e){return this.allowInAnd(()=>this.parseMaybeAssign(t,e))}setOptionalParametersError(t){t.optionalParametersLoc=this.state.startLoc}parseMaybeAssign(t,e){let n=this.state.startLoc,i=this.isContextual(108);if(i&&this.prodParam.hasYield){this.next();let d=this.parseYield(n);return e&&(d=e.call(this,d,n)),d}let s;t?s=!1:(t=new Pr,s=!0);let{type:a}=this.state;(a===10||te(a))&&(this.state.potentialArrowAt=this.state.start);let o=this.parseMaybeConditional(t);if(e&&(o=e.call(this,o,n)),Jw(this.state.type)){let d=this.startNodeAt(n),c=this.state.value;if(d.operator=c,this.match(29)){this.toAssignable(o,!0),d.left=o;let l=n.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),t.voidPatternLoc!=null&&t.voidPatternLoc.index>=l&&(t.voidPatternLoc=null)}else d.left=o;return this.next(),d.right=this.parseMaybeAssign(),this.checkLVal(o,this.finishNode(d,"AssignmentExpression"),void 0,void 0,void 0,void 0,c==="||="||c==="&&="||c==="??="),d}else s&&this.checkExpressionErrors(t,!0);if(i){let{type:d}=this.state;if((this.hasPlugin("v8intrinsic")?gn(d):gn(d)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(b.YieldNotInGeneratorFunction,n),this.parseYield(n)}return o}parseMaybeConditional(t){let e=this.state.startLoc,n=this.state.potentialArrowAt,i=this.parseExprOps(t);return this.shouldExitDescending(i,n)?i:this.parseConditional(i,e,t)}parseConditional(t,e,n){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(139)?this.parsePrivateName():this.parseMaybeUnary(t)}parseExprOps(t){let e=this.state.startLoc,n=this.state.potentialArrowAt,i=this.parseMaybeUnaryOrPrivate(t);return this.shouldExitDescending(i,n)?i:this.parseExprOp(i,e,-1)}parseExprOp(t,e,n){if(this.isPrivateName(t)){let s=this.getPrivateNameSV(t);(n>=Bi(58)||!this.prodParam.hasIn||!this.match(58))&&this.raise(b.PrivateInExpectedIn,t,{identifierName:s}),this.classScope.usePrivateName(s,t.loc.start)}let i=this.state.type;if(Yw(i)&&(this.prodParam.hasIn||!this.match(58))){let s=Bi(i);if(s>n){if(i===39){if(this.expectPlugin("pipelineOperator"),this.state.inFSharpPipelineDirectBody)return t;this.checkPipelineAtInfixOperator(t,e)}let a=this.startNodeAt(e);a.left=t,a.operator=this.state.value;let o=i===41||i===42,d=i===40;if(d&&(s=Bi(42)),this.next(),i===39&&this.hasPlugin(["pipelineOperator",{proposal:"minimal"}])&&this.state.type===96&&this.prodParam.hasAwait)throw this.raise(b.UnexpectedAwaitAfterPipelineBody,this.state.startLoc);a.right=this.parseExprOpRightExpr(i,s);let c=this.finishNode(a,o||d?"LogicalExpression":"BinaryExpression"),l=this.state.type;if(d&&(l===41||l===42)||o&&l===40)throw this.raise(b.MixingCoalesceWithLogical,this.state.startLoc);return this.parseExprOp(c,e,n)}}return t}parseExprOpRightExpr(t,e){let n=this.state.startLoc;switch(t){case 39:switch(this.getPluginOption("pipelineOperator","proposal")){case"hack":return this.withTopicBindingContext(()=>this.parseHackPipeBody());case"fsharp":return this.withSoloAwaitPermittingContext(()=>this.parseFSharpPipelineBody(e))}if(this.getPluginOption("pipelineOperator","proposal")==="smart")return this.withTopicBindingContext(()=>{if(this.prodParam.hasYield&&this.isContextual(108))throw this.raise(b.PipeBodyIsTighter,this.state.startLoc);return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(t,e),n)});default:return this.parseExprOpBaseRightExpr(t,e)}}parseExprOpBaseRightExpr(t,e){let n=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnaryOrPrivate(),n,rb(t)?e-1:e)}parseHackPipeBody(){var t;let{startLoc:e}=this.state,n=this.parseMaybeAssign();return $w.has(n.type)&&!((t=n.extra)!=null&&t.parenthesized)&&this.raise(b.PipeUnparenthesizedBody,e,{type:n.type}),this.topicReferenceWasUsedInCurrentContext()||this.raise(b.PipeTopicUnused,e),n}checkExponentialAfterUnary(t){this.match(57)&&this.raise(b.UnexpectedTokenUnaryExponentiation,t.argument)}parseMaybeUnary(t,e){let n=this.state.startLoc,i=this.isContextual(96);if(i&&this.recordAwaitIfAllowed()){this.next();let d=this.parseAwait(n);return e||this.checkExponentialAfterUnary(d),d}let s=this.match(34),a=this.startNode();if(Zw(this.state.type)){a.operator=this.state.value,a.prefix=!0,this.match(72)&&this.expectPlugin("throwExpressions");let d=this.match(89);if(this.next(),a.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(t,!0),this.state.strict&&d){let c=a.argument;c.type==="Identifier"?this.raise(b.StrictDelete,a):this.hasPropertyAsPrivateName(c)&&this.raise(b.DeletePrivateField,a)}if(!s)return e||this.checkExponentialAfterUnary(a),this.finishNode(a,"UnaryExpression")}let o=this.parseUpdate(a,s,t);if(i){let{type:d}=this.state;if((this.hasPlugin("v8intrinsic")?gn(d):gn(d)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(b.AwaitNotInAsyncContext,n),this.parseAwait(n)}return o}parseUpdate(t,e,n){if(e){let a=t;return this.checkLVal(a.argument,this.finishNode(a,"UpdateExpression")),t}let i=this.state.startLoc,s=this.parseExprSubscripts(n);if(this.checkExpressionErrors(n,!1))return s;for(;Qw(this.state.type)&&!this.canInsertSemicolon();){let a=this.startNodeAt(i);a.operator=this.state.value,a.prefix=!1,a.argument=s,this.next(),this.checkLVal(s,s=this.finishNode(a,"UpdateExpression"))}return s}parseExprSubscripts(t){let e=this.state.startLoc,n=this.state.potentialArrowAt,i=this.parseExprAtom(t);return this.shouldExitDescending(i,n)?i:this.parseSubscripts(i,e)}parseSubscripts(t,e,n){let i={optionalChainMember:!1,maybeAsyncArrow:this.atPossibleAsyncArrow(t),stop:!1};do t=this.parseSubscript(t,e,n,i),i.maybeAsyncArrow=!1;while(!i.stop);return t}parseSubscript(t,e,n,i){let{type:s}=this.state;if(!n&&s===15)return this.parseBind(t,e,i);if(Hi(s))return this.parseTaggedTemplateExpression(t,e,i);let a=!1;if(s===18){if(n&&(this.raise(b.OptionalChainingNoNew,this.state.startLoc),this.lookaheadCharCode()===40))return this.stopParseSubscript(t,i);i.optionalChainMember=a=!0,this.next()}if(!n&&this.match(10))return this.parseCoverCallAndAsyncArrowHead(t,e,i,a);{let o=this.eat(0);return o||a||this.eat(16)?this.parseMember(t,e,i,o,a):this.stopParseSubscript(t,i)}}stopParseSubscript(t,e){return e.stop=!0,t}parseMember(t,e,n,i,s){let a=this.startNodeAt(e);return a.object=t,a.computed=i,i?(a.property=this.parseExpression(),this.expect(3)):this.match(139)?(t.type==="Super"&&this.raise(b.SuperPrivateField,e),this.classScope.usePrivateName(this.state.value,this.state.startLoc),a.property=this.parsePrivateName()):a.property=this.parseIdentifier(!0),n.optionalChainMember?(a.optional=s,this.finishNode(a,"OptionalMemberExpression")):this.finishNode(a,"MemberExpression")}parseBind(t,e,n){let i=this.startNodeAt(e);i.object=t,this.next();let s=this.match(83),a=this.parseNoCallExpr();if(a.type==="Super"||s&&a.type==="ImportExpression"||a.type==="Import")throw this.raise(b.UnsupportedBindRHS,a);return i.callee=a,n.stop=!0,this.parseSubscripts(this.finishNode(i,"BindExpression"),e,!1)}parseCoverCallAndAsyncArrowHead(t,e,n,i){let s=this.state.maybeInArrowParameters,a=null;this.state.maybeInArrowParameters=!0,this.next();let o=this.startNodeAt(e);o.callee=t;let{maybeAsyncArrow:d,optionalChainMember:c}=n;d&&(this.expressionScope.enter(Cb()),a=new Pr),c&&(o.optional=i),i?o.arguments=this.parseCallExpressionArguments():o.arguments=this.parseCallExpressionArguments(t.type!=="Super",o,a);let l=this.finishCallExpression(o,c);return d&&this.shouldParseAsyncArrow()&&!i?(n.stop=!0,this.checkDestructuringPrivate(a),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),l=this.parseAsyncArrowFromCallExpression(this.startNodeAt(e),l)):(d&&(this.checkExpressionErrors(a,!0),this.expressionScope.exit()),this.toReferencedArguments(l)),this.state.maybeInArrowParameters=s,l}toReferencedArguments(t,e){this.toReferencedListDeep(t.arguments,e)}parseTaggedTemplateExpression(t,e,n){let i=this.startNodeAt(e);return i.tag=t,i.quasi=this.parseTemplate(!0),n.optionalChainMember&&this.raise(b.OptionalChainingNoTemplate,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&&this.offsetToSourcePos(t.start)===this.state.potentialArrowAt}finishCallExpression(t,e){if(t.callee.type==="Import")if(t.arguments.length===0||t.arguments.length>2)this.raise(b.ImportCallArity,t);else for(let n of t.arguments)n.type==="SpreadElement"&&this.raise(b.ImportCallSpreadArgument,n);return this.finishNode(t,e?"OptionalCallExpression":"CallExpression")}parseCallExpressionArguments(t,e,n){let i=[],s=!0,a=this.state.inFSharpPipelineDirectBody;for(this.state.inFSharpPipelineDirectBody=!1;!this.eat(11);){if(s)s=!1;else if(this.expect(12),this.match(11)){e&&this.addTrailingCommaExtraToNode(e),this.next();break}i.push(this.parseExprListItem(11,!1,n,t))}return this.state.inFSharpPipelineDirectBody=a,i}shouldParseAsyncArrow(){return this.match(19)&&!this.canInsertSemicolon()}parseAsyncArrowFromCallExpression(t,e){var n;return this.resetPreviousNodeTrailingComments(e),this.expect(19),this.parseArrowExpression(t,e.arguments,!0,(n=e.extra)==null?void 0:n.trailingCommaLoc),e.innerComments&&kn(t,e.innerComments),e.callee.trailingComments&&kn(t,e.callee.trailingComments),t}parseNoCallExpr(){let t=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),t,!0)}parseExprAtom(t){let e,n=null,{type:i}=this.state;switch(i){case 79:return this.parseSuper();case 83:return e=this.startNode(),this.next(),this.match(16)?this.parseImportMetaPropertyOrPhaseCall(e):this.match(10)?this.optionFlags&512?this.parseImportCall(e):this.finishNode(e,"Import"):(this.raise(b.UnsupportedImport,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 135:return this.parseNumericLiteral(this.state.value);case 136:return this.parseBigIntLiteral(this.state.value);case 134: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 s=this.state.potentialArrowAt===this.state.start;return this.parseParenAndDistinguishExpression(s)}case 0:return this.parseArrayLike(3,!1,t);case 5:return this.parseObjectLike(8,!1,!1,t);case 68:return this.parseFunctionOrFunctionSent();case 26:n=this.parseDecorators();case 80:return this.parseClass(this.maybeTakeDecorators(n,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 s=e.callee=this.parseNoCallExpr();if(s.type==="MemberExpression")return this.finishNode(e,"BindExpression");throw this.raise(b.UnsupportedBind,s)}case 139:return this.raise(b.PrivateInExpectedIn,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 s=this.getPluginOption("pipelineOperator","proposal");if(s)return this.parseTopicReference(s);throw this.unexpected()}case 47:{let s=this.input.codePointAt(this.nextTokenStart());throw ct(s)||s===62?this.expectOnePlugin(["jsx","flow","typescript"]):this.unexpected()}default:if(i===137)return this.parseDecimalLiteral(this.state.value);if(i===2||i===1)return this.parseArrayLike(this.state.type===2?4:3,!0);if(i===6||i===7)return this.parseObjectLike(this.state.type===6?9:8,!1,!0);if(te(i)){if(this.isContextual(127)&&this.lookaheadInLineCharCode()===123)return this.parseModuleExpression();let s=this.state.potentialArrowAt===this.state.start,a=this.state.containsEsc,o=this.parseIdentifier();if(!a&&o.name==="async"&&!this.canInsertSemicolon()){let{type:d}=this.state;if(d===68)return this.resetPreviousNodeTrailingComments(o),this.next(),this.parseAsyncFunctionExpression(this.startNodeAtNode(o));if(te(d))return s&&this.lookaheadCharCode()===61?this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(o)):o;if(d===90)return this.resetPreviousNodeTrailingComments(o),this.parseDo(this.startNodeAtNode(o),!0)}return s&&this.match(19)&&!this.canInsertSemicolon()?(this.next(),this.parseArrowExpression(this.startNodeAtNode(o),[o],!1)):o}else throw this.unexpected()}}parseTopicReferenceThenEqualsSign(t,e){let n=this.getPluginOption("pipelineOperator","proposal");if(n)return this.state.type=t,this.state.value=e,this.state.pos--,this.state.end--,this.state.endLoc=Oe(this.state.endLoc,-1),this.parseTopicReference(n);throw this.unexpected()}parseTopicReference(t){let e=this.startNode(),n=this.state.startLoc,i=this.state.type;return this.next(),this.finishTopicReference(e,n,t,i)}finishTopicReference(t,e,n,i){if(this.testTopicReferenceConfiguration(n,e,i))return n==="hack"?(this.topicReferenceIsAllowedInCurrentContext()||this.raise(b.PipeTopicUnbound,e),this.registerTopicReference(),this.finishNode(t,"TopicReference")):(this.topicReferenceIsAllowedInCurrentContext()||this.raise(b.PrimaryTopicNotAllowed,e),this.registerTopicReference(),this.finishNode(t,"PipelinePrimaryTopicReference"));throw this.raise(b.PipeTopicUnconfiguredToken,e,{token:Ct(i)})}testTopicReferenceConfiguration(t,e,n){switch(t){case"hack":return this.hasPlugin(["pipelineOperator",{topicToken:Ct(n)}]);case"smart":return n===27;default:throw this.raise(b.PipeTopicRequiresHackPipes,e)}}parseAsyncArrowUnaryFunction(t){this.prodParam.enter(Vi(!0,this.prodParam.hasYield));let e=[this.parseIdentifier()];return this.prodParam.exit(),this.hasPrecedingLineBreak()&&this.raise(b.LineTerminatorBeforeArrow,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 n=this.state.labels;return this.state.labels=[],e?(this.prodParam.enter(2),t.body=this.parseBlock(),this.prodParam.exit()):t.body=this.parseBlock(),this.state.labels=n,this.finishNode(t,"DoExpression")}parseSuper(){let t=this.startNode();return this.next(),this.match(10)&&!this.scope.allowDirectSuper?this.optionFlags&16||this.raise(b.SuperNotAllowed,t):this.scope.allowSuper||this.optionFlags&16||this.raise(b.UnexpectedSuper,t),!this.match(10)&&!this.match(0)&&!this.match(16)&&this.raise(b.UnsupportedSuper,t),this.finishNode(t,"Super")}parsePrivateName(){let t=this.startNode(),e=this.startNodeAt(Oe(this.state.startLoc,1)),n=this.state.value;return this.next(),t.id=this.createIdentifier(e,n),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(103)?this.expectPlugin("functionSent"):this.hasPlugin("functionSent")||this.unexpected(),this.parseMetaProperty(t,e,"sent")}return this.parseFunction(t)}parseMetaProperty(t,e,n){t.meta=e;let i=this.state.containsEsc;return t.property=this.parseIdentifier(!0),(t.property.name!==n||i)&&this.raise(b.UnsupportedMetaProperty,t.property,{target:e.name,onlyValidPropertyName:n}),this.finishNode(t,"MetaProperty")}parseImportMetaPropertyOrPhaseCall(t){if(this.next(),this.isContextual(105)||this.isContextual(97)){let e=this.isContextual(105);return this.expectPlugin(e?"sourcePhaseImports":"deferredImportEvaluation"),this.next(),t.phase=e?"source":"defer",this.parseImportCall(t)}else{let e=this.createIdentifierAt(this.startNodeAtNode(t),"import",this.state.lastTokStartLoc);return this.isContextual(101)&&(this.inModule||this.raise(b.ImportMetaOutsideModule,e),this.sawUnambiguousESM=!0),this.parseMetaProperty(t,e,"meta")}}parseLiteralAtNode(t,e,n){return this.addExtra(n,"rawValue",t),this.addExtra(n,"raw",this.input.slice(this.offsetToSourcePos(n.start),this.state.end)),n.value=t,this.next(),this.finishNode(n,e)}parseLiteral(t,e){let n=this.startNode();return this.parseLiteralAtNode(t,e,n)}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.startNode();return this.addExtra(e,"raw",this.input.slice(this.offsetToSourcePos(e.start),this.state.end)),e.pattern=t.pattern,e.flags=t.flags,this.next(),this.finishNode(e,"RegExpLiteral")}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,n;this.next(),this.expressionScope.enter(Eb());let i=this.state.maybeInArrowParameters,s=this.state.inFSharpPipelineDirectBody;this.state.maybeInArrowParameters=!0,this.state.inFSharpPipelineDirectBody=!1;let a=this.state.startLoc,o=[],d=new Pr,c=!0,l,u;for(;!this.match(11);){if(c)c=!1;else if(this.expect(12,d.optionalParametersLoc===null?null:d.optionalParametersLoc),this.match(11)){u=this.state.startLoc;break}if(this.match(21)){let h=this.state.startLoc;if(l=this.state.startLoc,o.push(this.parseParenItem(this.parseRestBinding(),h)),!this.checkCommaAfterRest(41))break}else o.push(this.parseMaybeAssignAllowInOrVoidPattern(11,d,this.parseParenItem))}let p=this.state.lastTokEndLoc;this.expect(11),this.state.maybeInArrowParameters=i,this.state.inFSharpPipelineDirectBody=s;let f=this.startNodeAt(e);return t&&this.shouldParseArrow(o)&&(f=this.parseArrow(f))?(this.checkDestructuringPrivate(d),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),this.parseArrowExpression(f,o,!1),f):(this.expressionScope.exit(),o.length||this.unexpected(this.state.lastTokStartLoc),u&&this.unexpected(u),l&&this.unexpected(l),this.checkExpressionErrors(d,!0),this.toReferencedListDeep(o,!0),o.length>1?(n=this.startNodeAt(a),n.expressions=o,this.finishNode(n,"SequenceExpression"),this.resetEndLocation(n,p)):n=o[0],this.wrapParenthesis(e,n))}wrapParenthesis(t,e){if(!(this.optionFlags&1024))return this.addExtra(e,"parenthesized",!0),this.addExtra(e,"parenStart",t.index),this.takeSurroundingComments(e,t.index,this.state.lastTokEndLoc.index),e;let n=this.startNodeAt(t);return n.expression=e,this.finishNode(n,"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 n=this.parseMetaProperty(t,e,"target");return this.scope.allowNewTarget||this.raise(b.UnexpectedNewTarget,n),n}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){let e=this.match(83),n=this.parseNoCallExpr();t.callee=n,(e&&n.type==="ImportExpression"||n.type==="Import")&&this.raise(b.ImportCallNotNewExpression,n),n.type==="Super"&&this.raise(b.SuperCallNotNewExpression,n)}parseTemplateElement(t){let{start:e,startLoc:n,end:i,value:s}=this.state,a=e+1,o=this.startNodeAt(Oe(n,1));s===null&&(t||this.raise(b.InvalidEscapeSequenceTemplate,Oe(this.state.firstInvalidTemplateEscapePos,1)));let d=this.match(24),c=d?-1:-2,l=i+c;o.value={raw:this.input.slice(a,l).replace(/\r\n?/g,`
10
- `),cooked:s===null?null:s.slice(1,c)},o.tail=d,this.next();let u=this.finishNode(o,"TemplateElement");return this.resetEndLocation(u,Oe(this.state.lastTokEndLoc,c)),u}parseTemplate(t){let e=this.startNode(),n=this.parseTemplateElement(t),i=[n],s=[];for(;!n.tail;)s.push(this.parseTemplateSubstitution()),this.readTemplateContinuation(),i.push(n=this.parseTemplateElement(t));return e.expressions=s,e.quasis=i,this.finishNode(e,"TemplateLiteral")}parseTemplateSubstitution(){return this.parseExpression()}parseObjectLike(t,e,n,i){n&&this.expectPlugin("recordAndTuple");let s=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let a=!1,o=!0,d=this.startNode();for(d.properties=[],this.next();!this.match(t);){if(o)o=!1;else if(this.expect(12),this.match(t)){this.addTrailingCommaExtraToNode(d);break}let l;e?l=this.parseBindingProperty():(l=this.parsePropertyDefinition(i),a=this.checkProto(l,n,a,i)),n&&!this.isObjectProperty(l)&&l.type!=="SpreadElement"&&this.raise(b.InvalidRecordProperty,l),l.shorthand&&this.addExtra(l,"shorthand",!0),d.properties.push(l)}this.next(),this.state.inFSharpPipelineDirectBody=s;let c="ObjectExpression";return e?c="ObjectPattern":n&&(c="RecordExpression"),this.finishNode(d,c)}addTrailingCommaExtraToNode(t){this.addExtra(t,"trailingComma",this.state.lastTokStartLoc.index),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(b.UnsupportedPropertyDecorator,this.state.startLoc);this.match(26);)e.push(this.parseDecorator());let n=this.startNode(),i=!1,s=!1,a;if(this.match(21))return e.length&&this.unexpected(),this.parseSpread();e.length&&(n.decorators=e,e=[]),n.method=!1,t&&(a=this.state.startLoc);let o=this.eat(55);this.parsePropertyNamePrefixOperator(n);let d=this.state.containsEsc;if(this.parsePropertyName(n,t),!o&&!d&&this.maybeAsyncOrAccessorProp(n)){let{key:c}=n,l=c.name;l==="async"&&!this.hasPrecedingLineBreak()&&(i=!0,this.resetPreviousNodeTrailingComments(c),o=this.eat(55),this.parsePropertyName(n)),(l==="get"||l==="set")&&(s=!0,this.resetPreviousNodeTrailingComments(c),n.kind=l,this.match(55)&&(o=!0,this.raise(b.AccessorIsGenerator,this.state.curPosition(),{kind:l}),this.next()),this.parsePropertyName(n))}return this.parseObjPropValue(n,a,o,i,!1,s,t)}getGetterSetterExpectedParamCount(t){return t.kind==="get"?0:1}getObjectOrClassMethodParams(t){return t.params}checkGetterSetterParams(t){var e;let n=this.getGetterSetterExpectedParamCount(t),i=this.getObjectOrClassMethodParams(t);i.length!==n&&this.raise(t.kind==="get"?b.BadGetterArity:b.BadSetterArity,t),t.kind==="set"&&((e=i[i.length-1])==null?void 0:e.type)==="RestElement"&&this.raise(b.BadSetterRestParameter,t)}parseObjectMethod(t,e,n,i,s){if(s){let a=this.parseMethod(t,e,!1,!1,!1,"ObjectMethod");return this.checkGetterSetterParams(a),a}if(n||e||this.match(10))return i&&this.unexpected(),t.kind="method",t.method=!0,this.parseMethod(t,e,n,!1,!1,"ObjectMethod")}parseObjectProperty(t,e,n,i){if(t.shorthand=!1,this.eat(14))return t.value=n?this.parseMaybeDefault(this.state.startLoc):this.parseMaybeAssignAllowInOrVoidPattern(8,i),this.finishObjectProperty(t);if(!t.computed&&t.key.type==="Identifier"){if(this.checkReservedWord(t.key.name,t.key.loc.start,!0,!1),n)t.value=this.parseMaybeDefault(e,this.cloneIdentifier(t.key));else if(this.match(29)){let s=this.state.startLoc;i!=null?i.shorthandAssignLoc===null&&(i.shorthandAssignLoc=s):this.raise(b.InvalidCoverInitializedName,s),t.value=this.parseMaybeDefault(e,this.cloneIdentifier(t.key))}else t.value=this.cloneIdentifier(t.key);return t.shorthand=!0,this.finishObjectProperty(t)}}finishObjectProperty(t){return this.finishNode(t,"ObjectProperty")}parseObjPropValue(t,e,n,i,s,a,o){let d=this.parseObjectMethod(t,n,i,s,a)||this.parseObjectProperty(t,e,s,o);return d||this.unexpected(),d}parsePropertyName(t,e){if(this.eat(0))t.computed=!0,t.key=this.parseMaybeAssignAllowIn(),this.expect(3);else{let{type:n,value:i}=this.state,s;if(Qe(n))s=this.parseIdentifier(!0);else switch(n){case 135:s=this.parseNumericLiteral(i);break;case 134:s=this.parseStringLiteral(i);break;case 136:s=this.parseBigIntLiteral(i);break;case 139:{let a=this.state.startLoc;e!=null?e.privateKeyLoc===null&&(e.privateKeyLoc=a):this.raise(b.UnexpectedPrivateField,a),s=this.parsePrivateName();break}default:if(n===137){s=this.parseDecimalLiteral(i);break}this.unexpected()}t.key=s,n!==139&&(t.computed=!1)}}initFunction(t,e){t.id=null,t.generator=!1,t.async=e}parseMethod(t,e,n,i,s,a,o=!1){this.initFunction(t,n),t.generator=e,this.scope.enter(530|(o?576:0)|(s?32:0)),this.prodParam.enter(Vi(n,t.generator)),this.parseFunctionParams(t,i);let d=this.parseFunctionBodyAndFinish(t,a,!0);return this.prodParam.exit(),this.scope.exit(),d}parseArrayLike(t,e,n){e&&this.expectPlugin("recordAndTuple");let i=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let s=this.startNode();return this.next(),s.elements=this.parseExprList(t,!e,n,s),this.state.inFSharpPipelineDirectBody=i,this.finishNode(s,e?"TupleExpression":"ArrayExpression")}parseArrowExpression(t,e,n,i){this.scope.enter(518);let s=Vi(n,!1);!this.match(5)&&this.prodParam.hasIn&&(s|=8),this.prodParam.enter(s),this.initFunction(t,n);let a=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=a,this.finishNode(t,"ArrowFunctionExpression")}setArrowFunctionParameters(t,e,n){this.toAssignableList(e,n,!1),t.params=e}parseFunctionBodyAndFinish(t,e,n=!1){return this.parseFunctionBody(t,!1,n),this.finishNode(t,e)}parseFunctionBody(t,e,n=!1){let i=e&&!this.match(5);if(this.expressionScope.enter(Ku()),i)t.body=this.parseMaybeAssign(),this.checkParams(t,!1,e,!1);else{let s=this.state.strict,a=this.state.labels;this.state.labels=[],this.prodParam.enter(this.prodParam.currentFlags()|4),t.body=this.parseBlock(!0,!1,o=>{let d=!this.isSimpleParamList(t.params);o&&d&&this.raise(b.IllegalLanguageModeDirective,(t.kind==="method"||t.kind==="constructor")&&t.key?t.key.loc.end:t);let c=!s&&this.state.strict;this.checkParams(t,!this.state.strict&&!e&&!n&&!d,e,c),this.state.strict&&t.id&&this.checkIdentifier(t.id,65,c)}),this.prodParam.exit(),this.state.labels=a}this.expressionScope.exit()}isSimpleParameter(t){return t.type==="Identifier"}isSimpleParamList(t){for(let e=0,n=t.length;e<n;e++)if(!this.isSimpleParameter(t[e]))return!1;return!0}checkParams(t,e,n,i=!0){let s=!e&&new Set,a={type:"FormalParameters"};for(let o of t.params)this.checkLVal(o,a,5,s,i)}parseExprList(t,e,n,i){let s=[],a=!0;for(;!this.eat(t);){if(a)a=!1;else if(this.expect(12),this.match(t)){i&&this.addTrailingCommaExtraToNode(i),this.next();break}s.push(this.parseExprListItem(t,e,n))}return s}parseExprListItem(t,e,n,i){let s;if(this.match(12))e||this.raise(b.UnexpectedToken,this.state.curPosition(),{unexpected:","}),s=null;else if(this.match(21)){let a=this.state.startLoc;s=this.parseParenItem(this.parseSpread(n),a)}else if(this.match(17)){this.expectPlugin("partialApplication"),i||this.raise(b.UnexpectedArgumentPlaceholder,this.state.startLoc);let a=this.startNode();this.next(),s=this.finishNode(a,"ArgumentPlaceholder")}else s=this.parseMaybeAssignAllowInOrVoidPattern(t,n,this.parseParenItem);return s}parseIdentifier(t){let e=this.startNode(),n=this.parseIdentifierName(t);return this.createIdentifier(e,n)}createIdentifier(t,e){return t.name=e,t.loc.identifierName=e,this.finishNode(t,"Identifier")}createIdentifierAt(t,e,n){return t.name=e,t.loc.identifierName=e,this.finishNodeAt(t,"Identifier",n)}parseIdentifierName(t){let e,{startLoc:n,type:i}=this.state;Qe(i)?e=this.state.value:this.unexpected();let s=Kw(i);return t?s&&this.replaceToken(132):this.checkReservedWord(e,n,s,!1),this.next(),e}checkReservedWord(t,e,n,i){if(t.length>10||!pb(t))return;if(n&&cb(t)){this.raise(b.UnexpectedKeyword,e,{keyword:t});return}if((this.state.strict?i?Hu:Vu:Bu)(t,this.inModule)){this.raise(b.UnexpectedReservedWord,e,{reservedWord:t});return}else if(t==="yield"){if(this.prodParam.hasYield){this.raise(b.YieldBindingIdentifier,e);return}}else if(t==="await"){if(this.prodParam.hasAwait){this.raise(b.AwaitBindingIdentifier,e);return}if(this.scope.inStaticBlock){this.raise(b.AwaitBindingIdentifierInStaticBlock,e);return}this.expressionScope.recordAsyncArrowParametersError(e)}else if(t==="arguments"&&this.scope.inClassAndNotInNonArrowFunction){this.raise(b.ArgumentsInClass,e);return}}recordAwaitIfAllowed(){let t=this.prodParam.hasAwait;return t&&!this.scope.inFunction&&(this.state.hasTopLevelAwait=!0),t}parseAwait(t){let e=this.startNodeAt(t);return this.expressionScope.recordParameterInitializerError(b.AwaitExpressionFormalParameter,e),this.eat(55)&&this.raise(b.ObsoleteAwaitStar,e),!this.scope.inFunction&&!(this.optionFlags&1)&&(this.isAmbiguousPrefixOrIdentifier()?this.ambiguousScriptDifferentAst=!0:this.sawUnambiguousESM=!0),this.state.soloAwait||(e.argument=this.parseMaybeUnary(null,!0)),this.finishNode(e,"AwaitExpression")}isAmbiguousPrefixOrIdentifier(){if(this.hasPrecedingLineBreak())return!0;let{type:t}=this.state;return t===53||t===10||t===0||Hi(t)||t===102&&!this.state.containsEsc||t===138||t===56||this.hasPlugin("v8intrinsic")&&t===54}parseYield(t){let e=this.startNodeAt(t);this.expressionScope.recordParameterInitializerError(b.YieldInParameter,e);let n=!1,i=null;if(!this.hasPrecedingLineBreak())switch(n=this.eat(55),this.state.type){case 13:case 140:case 8:case 11:case 3:case 9:case 14:case 12:if(!n)break;default:i=this.parseMaybeAssign()}return e.delegate=n,e.argument=i,this.finishNode(e,"YieldExpression")}parseImportCall(t){if(this.next(),t.source=this.parseMaybeAssignAllowIn(),t.options=null,this.eat(12)){if(this.match(11))this.addTrailingCommaExtraToNode(t.source);else if(t.options=this.parseMaybeAssignAllowIn(),this.eat(12)&&(this.addTrailingCommaExtraToNode(t.options),!this.match(11))){do this.parseMaybeAssignAllowIn();while(this.eat(12)&&!this.match(11));this.raise(b.ImportCallArity,t)}}return this.expect(11),this.finishNode(t,"ImportExpression")}checkPipelineAtInfixOperator(t,e){this.hasPlugin(["pipelineOperator",{proposal:"smart"}])&&t.type==="SequenceExpression"&&this.raise(b.PipelineHeadSequenceExpression,e)}parseSmartPipelineBodyInStyle(t,e){if(this.isSimpleReference(t)){let n=this.startNodeAt(e);return n.callee=t,this.finishNode(n,"PipelineBareFunction")}else{let n=this.startNodeAt(e);return this.checkSmartPipeTopicBodyEarlyErrors(e),n.expression=t,this.finishNode(n,"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(b.PipelineBodyNoArrow,this.state.startLoc);this.topicReferenceWasUsedInCurrentContext()||this.raise(b.PipelineTopicUnused,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(8&~e){this.prodParam.enter(e|8);try{return t()}finally{this.prodParam.exit()}}return t()}disallowInAnd(t){let e=this.prodParam.currentFlags();if(8&e){this.prodParam.enter(e&-9);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 n=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!0;let i=this.parseExprOp(this.parseMaybeUnaryOrPrivate(),e,t);return this.state.inFSharpPipelineDirectBody=n,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 n=this.initializeScopes(!0);this.enterInitialScopes();try{t.body=this.parseProgram(e,8,"module")}finally{n()}return this.finishNode(t,"ModuleExpression")}parseVoidPattern(t){this.expectPlugin("discardBinding");let e=this.startNode();return t!=null&&(t.voidPatternLoc=this.state.startLoc),this.next(),this.finishNode(e,"VoidPattern")}parseMaybeAssignAllowInOrVoidPattern(t,e,n){if(e!=null&&this.match(88)){let i=this.lookaheadCharCode();if(i===44||i===(t===3?93:t===8?125:41)||i===61)return this.parseMaybeDefault(this.state.startLoc,this.parseVoidPattern(e))}return this.parseMaybeAssignAllowIn(e,n)}parsePropertyNamePrefixOperator(t){}},to={kind:1},zb={kind:2},Hb=/[\uD800-\uDFFF]/u,ro=/in(?:stanceof)?/y;function qb(r,t,e){for(let n=0;n<r.length;n++){let i=r[n],{type:s}=i;if(typeof s=="number"){if(s===139){let{loc:a,start:o,value:d,end:c}=i,l=o+1,u=Oe(a.start,1);r.splice(n,1,new dt({type:yt(27),value:"#",start:o,end:l,startLoc:a.start,endLoc:u}),new dt({type:yt(132),value:d,start:l,end:c,startLoc:u,endLoc:a.end})),n++;continue}if(Hi(s)){let{loc:a,start:o,value:d,end:c}=i,l=o+1,u=Oe(a.start,1),p;t.charCodeAt(o-e)===96?p=new dt({type:yt(22),value:"`",start:o,end:l,startLoc:a.start,endLoc:u}):p=new dt({type:yt(8),value:"}",start:o,end:l,startLoc:a.start,endLoc:u});let f,h,g,m;s===24?(h=c-1,g=Oe(a.end,-1),f=d===null?null:d.slice(1,-1),m=new dt({type:yt(22),value:"`",start:h,end:c,startLoc:g,endLoc:a.end})):(h=c-2,g=Oe(a.end,-2),f=d===null?null:d.slice(1,-2),m=new dt({type:yt(23),value:"${",start:h,end:c,startLoc:g,endLoc:a.end})),r.splice(n,1,p,new dt({type:yt(20),value:f,start:l,end:h,startLoc:u,endLoc:g}),m),n+=2;continue}i.type=yt(s)}}return r}var Po=class extends Io{parseTopLevel(t,e){return t.program=this.parseProgram(e,140,this.options.sourceType==="module"?"module":"script"),t.comments=this.comments,this.optionFlags&256&&(t.tokens=qb(this.tokens,this.input,this.startIndex)),this.finishNode(t,"File")}parseProgram(t,e,n){if(t.sourceType=n,t.interpreter=this.parseInterpreterDirective(),this.parseBlockBody(t,!0,!0,e),this.inModule){if(!(this.optionFlags&64)&&this.scope.undefinedExports.size>0)for(let[s,a]of Array.from(this.scope.undefinedExports))this.raise(b.ModuleExportUndefined,a,{localName:s});this.addExtra(t,"topLevelAwait",this.state.hasTopLevelAwait)}let i;return e===140?i=this.finishNode(t,"Program"):i=this.finishNodeAt(t,"Program",Oe(this.state.startLoc,-1)),i}stmtToDirective(t){let e=this.castNodeTo(t,"Directive"),n=this.castNodeTo(t.expression,"DirectiveLiteral"),i=n.value,s=this.input.slice(this.offsetToSourcePos(n.start),this.offsetToSourcePos(n.end)),a=n.value=s.slice(1,-1);return this.addExtra(n,"raw",s),this.addExtra(n,"rawValue",a),this.addExtra(n,"expressionValue",i),e.value=n,delete t.expression,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(100)?this.hasFollowingBindingAtom():!1}isUsing(){return this.isContextual(107)?this.nextTokenIsIdentifierOnSameLine():!1}isForUsing(){if(!this.isContextual(107))return!1;let t=this.nextTokenInLineStart(),e=this.codePointAtPos(t);if(this.isUnparsedContextual(t,"of")){let n=this.lookaheadCharCodeSince(t+2);if(n!==61&&n!==58&&n!==59)return!1}return!!(this.chStartsBindingIdentifier(e,t)||this.isUnparsedContextual(t,"void"))}nextTokenIsIdentifierOnSameLine(){let t=this.nextTokenInLineStart(),e=this.codePointAtPos(t);return this.chStartsBindingIdentifier(e,t)}isAwaitUsing(){if(!this.isContextual(96))return!1;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!0}return!1}chStartsBindingIdentifier(t,e){if(ct(t)){if(ro.lastIndex=e,ro.test(this.input)){let n=this.codePointAtPos(ro.lastIndex);if(!Jt(n)&&n!==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)}hasInLineFollowingBindingIdentifierOrBrace(){let t=this.nextTokenInLineStart(),e=this.codePointAtPos(t);return e===123||this.chStartsBindingIdentifier(e,t)}allowsUsing(){return(this.scope.inModule||!this.scope.inTopLevel)&&!this.scope.inBareCaseStatement}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 n=this.state.type,i=this.startNode(),s=!!(t&2),a=!!(t&4),o=t&1;switch(n){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 a||this.raise(this.state.strict?b.StrictFunction:this.options.annexB?b.SloppyFunctionAnnexB:b.SloppyFunction,this.state.startLoc),this.parseFunctionStatement(i,!1,!s&&a);case 80:return s||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.isAwaitUsing())return this.allowsUsing()?s?this.recordAwaitIfAllowed()||this.raise(b.AwaitUsingNotInAsyncContext,i):this.raise(b.UnexpectedLexicalDeclaration,i):this.raise(b.UnexpectedUsingDeclaration,i),this.next(),this.parseVarStatement(i,"await using");break;case 107:if(this.state.containsEsc||!this.hasInLineFollowingBindingIdentifierOrBrace())break;return this.allowsUsing()?s||this.raise(b.UnexpectedLexicalDeclaration,this.state.startLoc):this.raise(b.UnexpectedUsingDeclaration,this.state.startLoc),this.parseVarStatement(i,"using");case 100:{if(this.state.containsEsc)break;let l=this.nextTokenStart(),u=this.codePointAtPos(l);if(u!==91&&(!s&&this.hasFollowingLineBreak()||!this.chStartsBindingIdentifier(u,l)&&u!==123))break}case 75:s||this.raise(b.UnexpectedLexicalDeclaration,this.state.startLoc);case 74:{let l=this.state.value;return this.parseVarStatement(i,l)}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 l=this.lookaheadCharCode();if(l===40||l===46)break}case 82:{!(this.optionFlags&8)&&!o&&this.raise(b.UnexpectedImportExport,this.state.startLoc),this.next();let l;return n===83?l=this.parseImport(i):l=this.parseExport(i,e),this.assertModuleNodeAllowed(l),l}default:if(this.isAsyncFunction())return s||this.raise(b.AsyncFunctionInSingleStatementContext,this.state.startLoc),this.next(),this.parseFunctionStatement(i,!0,!s&&a)}let d=this.state.value,c=this.parseExpression();return te(n)&&c.type==="Identifier"&&this.eat(14)?this.parseLabeledStatement(i,d,c,t):this.parseExpressionStatement(i,c,e)}assertModuleNodeAllowed(t){!(this.optionFlags&8)&&!this.inModule&&this.raise(b.ImportOutsideModule,t)}decoratorsEnabledBeforeExport(){return this.hasPlugin("decorators-legacy")?!0:this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")!==!1}maybeTakeDecorators(t,e,n){if(t){var i;(i=e.decorators)!=null&&i.length?(typeof this.getPluginOption("decorators","decoratorsBeforeExport")!="boolean"&&this.raise(b.DecoratorsBeforeAfterExport,e.decorators[0]),e.decorators.unshift(...t)):e.decorators=t,this.resetStartLocationFromNode(e,t[0]),n&&this.resetStartLocationFromNode(n,e)}return 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(b.DecoratorExportClass,this.state.startLoc);else if(!this.canHaveLeadingDecorator())throw this.raise(b.UnexpectedLeadingDecorator,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,n;if(this.match(10)){let i=this.state.startLoc;this.next(),n=this.parseExpression(),this.expect(11),n=this.wrapParenthesis(i,n);let s=this.state.startLoc;t.expression=this.parseMaybeDecoratorArguments(n,i),this.getPluginOption("decorators","allowCallParenthesized")===!1&&t.expression!==n&&this.raise(b.DecoratorArgumentsOutsideParentheses,s)}else{for(n=this.parseIdentifier(!1);this.eat(16);){let i=this.startNodeAt(e);i.object=n,this.match(139)?(this.classScope.usePrivateName(this.state.value,this.state.startLoc),i.property=this.parsePrivateName()):i.property=this.parseIdentifier(!0),i.computed=!1,n=this.finishNode(i,"MemberExpression")}t.expression=this.parseMaybeDecoratorArguments(n,e)}}else t.expression=this.parseExprSubscripts();return this.finishNode(t,"Decorator")}parseMaybeDecoratorArguments(t,e){if(this.eat(10)){let n=this.startNodeAt(e);return n.callee=t,n.arguments=this.parseCallExpressionArguments(),this.toReferencedList(n.arguments),this.finishNode(n,"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 n;for(n=0;n<this.state.labels.length;++n){let i=this.state.labels[n];if((t.label==null||i.name===t.label.name)&&(i.kind!=null&&(e||i.kind===1)||t.label&&e))break}if(n===this.state.labels.length){let i=e?"BreakStatement":"ContinueStatement";this.raise(b.IllegalBreakContinue,t,{type:i})}}parseDebuggerStatement(t){return this.next(),this.semicolon(),this.finishNode(t,"DebuggerStatement")}parseHeaderExpression(){this.expect(10);let t=this.parseExpression();return this.expect(11),t}parseDoWhileStatement(t){return this.next(),this.state.labels.push(to),t.body=this.withSmartMixTopicForbiddingContext(()=>this.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(to);let e=null;if(this.isContextual(96)&&this.recordAwaitIfAllowed()&&(e=this.state.startLoc,this.next()),this.scope.enter(0),this.expect(10),this.match(13))return e!==null&&this.unexpected(e),this.parseFor(t,null);let n=this.isContextual(100);{let d=this.isAwaitUsing(),c=d||this.isForUsing(),l=n&&this.hasFollowingBindingAtom()||c;if(this.match(74)||this.match(75)||l){let u=this.startNode(),p;d?(p="await using",this.recordAwaitIfAllowed()||this.raise(b.AwaitUsingNotInAsyncContext,this.state.startLoc),this.next()):p=this.state.value,this.next(),this.parseVar(u,!0,p);let f=this.finishNode(u,"VariableDeclaration"),h=this.match(58);return h&&c&&this.raise(b.ForInUsing,f),(h||this.isContextual(102))&&f.declarations.length===1?this.parseForIn(t,f,e):(e!==null&&this.unexpected(e),this.parseFor(t,f))}}let i=this.isContextual(95),s=new Pr,a=this.parseExpression(!0,s),o=this.isContextual(102);if(o&&(n&&this.raise(b.ForOfLet,a),e===null&&i&&a.type==="Identifier"&&this.raise(b.ForOfAsync,a)),o||this.match(58)){this.checkDestructuringPrivate(s),this.toAssignable(a,!0);let d=o?"ForOfStatement":"ForInStatement";return this.checkLVal(a,{type:d}),this.parseForIn(t,a,e)}else this.checkExpressionErrors(s,!0);return e!==null&&this.unexpected(e),this.parseFor(t,a)}parseFunctionStatement(t,e,n){return this.next(),this.parseFunction(t,1|(n?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.raise(b.IllegalReturn,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(zb),this.scope.enter(256);let n;for(let i;!this.match(8);)if(this.match(61)||this.match(65)){let s=this.match(61);n&&this.finishNode(n,"SwitchCase"),e.push(n=this.startNode()),n.consequent=[],this.next(),s?n.test=this.parseExpression():(i&&this.raise(b.MultipleDefaultsInSwitch,this.state.lastTokStartLoc),i=!0,n.test=null),this.expect(14)}else n?n.consequent.push(this.parseStatementListItem()):this.unexpected();return this.scope.exit(),n&&this.finishNode(n,"SwitchCase"),this.next(),this.state.labels.pop(),this.finishNode(t,"SwitchStatement")}parseThrowStatement(t){return this.next(),this.hasPrecedingLineBreak()&&this.raise(b.NewlineAfterThrow,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,{type:"CatchClause"},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(b.NoCatchOrFinally,t),this.finishNode(t,"TryStatement")}parseVarStatement(t,e,n=!1){return this.next(),this.parseVar(t,!1,e,n),this.semicolon(),this.finishNode(t,"VariableDeclaration")}parseWhileStatement(t){return this.next(),t.test=this.parseHeaderExpression(),this.state.labels.push(to),t.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.state.labels.pop(),this.finishNode(t,"WhileStatement")}parseWithStatement(t){return this.state.strict&&this.raise(b.StrictWith,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,n,i){for(let a of this.state.labels)a.name===e&&this.raise(b.LabelRedeclaration,n,{labelName:e});let s=Xw(this.state.type)?1:this.match(71)?2:null;for(let a=this.state.labels.length-1;a>=0;a--){let o=this.state.labels[a];if(o.statementStart===t.start)o.statementStart=this.sourceToOffsetPos(this.state.start),o.kind=s;else break}return this.state.labels.push({name:e,kind:s,statementStart:this.sourceToOffsetPos(this.state.start)}),t.body=i&8?this.parseStatementOrSloppyAnnexBFunctionDeclaration(!0):this.parseStatement(),this.state.labels.pop(),t.label=n,this.finishNode(t,"LabeledStatement")}parseExpressionStatement(t,e,n){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")}parseBlock(t=!1,e=!0,n){let i=this.startNode();return t&&this.state.strictErrors.clear(),this.expect(5),e&&this.scope.enter(0),this.parseBlockBody(i,t,!1,8,n),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,n,i,s){let a=t.body=[],o=t.directives=[];this.parseBlockOrModuleBlockBody(a,e?o:void 0,n,i,s)}parseBlockOrModuleBlockBody(t,e,n,i,s){let a=this.state.strict,o=!1,d=!1;for(;!this.match(i);){let c=n?this.parseModuleItem():this.parseStatementListItem();if(e&&!d){if(this.isValidDirective(c)){let l=this.stmtToDirective(c);e.push(l),!o&&l.value.value==="use strict"&&(o=!0,this.setStrict(!0));continue}d=!0,this.state.strictErrors.clear()}t.push(c)}s?.call(this,o),a||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,n){let i=this.match(58);return this.next(),i?n!==null&&this.unexpected(n):t.await=n!==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(b.ForInOfLoopInitializer,e,{type:i?"ForInStatement":"ForOfStatement"}),e.type==="AssignmentPattern"&&this.raise(b.InvalidLhs,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,n,i=!1){let s=t.declarations=[];for(t.kind=n;;){let a=this.startNode();if(this.parseVarId(a,n),a.init=this.eat(29)?e?this.parseMaybeAssignDisallowIn():this.parseMaybeAssignAllowIn():null,a.init===null&&!i&&(a.id.type!=="Identifier"&&!(e&&(this.match(58)||this.isContextual(102)))?this.raise(b.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:"destructuring"}):(n==="const"||n==="using"||n==="await using")&&!(this.match(58)||this.isContextual(102))&&this.raise(b.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:n})),s.push(this.finishNode(a,"VariableDeclarator")),!this.eat(12))break}return t}parseVarId(t,e){let n=this.parseBindingAtom();e==="using"||e==="await using"?(n.type==="ArrayPattern"||n.type==="ObjectPattern")&&this.raise(b.UsingDeclarationHasBindingPattern,n.loc.start):n.type==="VoidPattern"&&this.raise(b.UnexpectedVoidPattern,n.loc.start),this.checkLVal(n,{type:"VariableDeclarator"},e==="var"?5:8201),t.id=n}parseAsyncFunctionExpression(t){return this.parseFunction(t,8)}parseFunction(t,e=0){let n=e&2,i=!!(e&1),s=i&&!(e&4),a=!!(e&8);this.initFunction(t,a),this.match(55)&&(n&&this.raise(b.GeneratorInSingleStatementContext,this.state.startLoc),this.next(),t.generator=!0),i&&(t.id=this.parseFunctionId(s));let o=this.state.maybeInArrowParameters;return this.state.maybeInArrowParameters=!1,this.scope.enter(514),this.prodParam.enter(Vi(a,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&&!n&&this.registerFunctionStatementId(t),this.state.maybeInArrowParameters=o,t}parseFunctionId(t){return t||te(this.state.type)?this.parseIdentifier():null}parseFunctionParams(t,e){this.expect(10),this.expressionScope.enter(Sb()),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,n){this.next();let i=this.state.strict;return this.state.strict=!0,this.parseClassId(t,e,n),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)}nameIsConstructor(t){return t.type==="Identifier"&&t.name==="constructor"||t.type==="StringLiteral"&&t.value==="constructor"}isNonstaticConstructor(t){return!t.computed&&!t.static&&this.nameIsConstructor(t.key)}parseClassBody(t,e){this.classScope.enter();let n={hadConstructor:!1,hadSuperClass:t},i=[],s=this.startNode();if(s.body=[],this.expect(5),this.withSmartMixTopicForbiddingContext(()=>{for(;!this.match(8);){if(this.eat(13)){if(i.length>0)throw this.raise(b.DecoratorSemicolon,this.state.lastTokEndLoc);continue}if(this.match(26)){i.push(this.parseDecorator());continue}let a=this.startNode();i.length&&(a.decorators=i,this.resetStartLocationFromNode(a,i[0]),i=[]),this.parseClassMember(s,a,n),a.kind==="constructor"&&a.decorators&&a.decorators.length>0&&this.raise(b.DecoratorConstructor,a)}}),this.state.strict=e,this.next(),i.length)throw this.raise(b.TrailingDecorator,this.state.startLoc);return this.classScope.exit(),this.finishNode(s,"ClassBody")}parseClassMemberFromModifier(t,e){let n=this.parseIdentifier(!0);if(this.isClassMethod()){let i=e;return i.kind="method",i.computed=!1,i.key=n,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=n,i.static=!1,t.body.push(this.parseClassProperty(i)),!0}return this.resetPreviousNodeTrailingComments(n),!1}parseClassMember(t,e,n){let i=this.isContextual(106);if(i){if(this.parseClassMemberFromModifier(t,e))return;if(this.eat(5)){this.parseClassStaticBlock(t,e);return}}this.parseClassMemberWithIsStatic(t,e,n,i)}parseClassMemberWithIsStatic(t,e,n,i){let s=e,a=e,o=e,d=e,c=e,l=s,u=s;if(e.static=i,this.parsePropertyNamePrefixOperator(e),this.eat(55)){l.kind="method";let y=this.match(139);if(this.parseClassElementName(l),this.parsePostMemberNameModifiers(l),y){this.pushClassPrivateMethod(t,a,!0,!1);return}this.isNonstaticConstructor(s)&&this.raise(b.ConstructorIsGenerator,s.key),this.pushClassMethod(t,s,!0,!1,!1,!1);return}let p=!this.state.containsEsc&&te(this.state.type),f=this.parseClassElementName(e),h=p?f.name:null,g=this.isPrivateName(f),m=this.state.startLoc;if(this.parsePostMemberNameModifiers(u),this.isClassMethod()){if(l.kind="method",g){this.pushClassPrivateMethod(t,a,!1,!1);return}let y=this.isNonstaticConstructor(s),w=!1;y&&(s.kind="constructor",n.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(b.DuplicateConstructor,f),y&&this.hasPlugin("typescript")&&e.override&&this.raise(b.OverrideOnConstructor,f),n.hadConstructor=!0,w=n.hadSuperClass),this.pushClassMethod(t,s,!1,!1,y,w)}else if(this.isClassProperty())g?this.pushClassPrivateProperty(t,d):this.pushClassProperty(t,o);else if(h==="async"&&!this.isLineTerminator()){this.resetPreviousNodeTrailingComments(f);let y=this.eat(55);u.optional&&this.unexpected(m),l.kind="method";let w=this.match(139);this.parseClassElementName(l),this.parsePostMemberNameModifiers(u),w?this.pushClassPrivateMethod(t,a,y,!0):(this.isNonstaticConstructor(s)&&this.raise(b.ConstructorIsAsync,s.key),this.pushClassMethod(t,s,y,!0,!1,!1))}else if((h==="get"||h==="set")&&!(this.match(55)&&this.isLineTerminator())){this.resetPreviousNodeTrailingComments(f),l.kind=h;let y=this.match(139);this.parseClassElementName(s),y?this.pushClassPrivateMethod(t,a,!1,!1):(this.isNonstaticConstructor(s)&&this.raise(b.ConstructorIsAccessor,s.key),this.pushClassMethod(t,s,!1,!1,!1,!1)),this.checkGetterSetterParams(s)}else if(h==="accessor"&&!this.isLineTerminator()){this.expectPlugin("decoratorAutoAccessors"),this.resetPreviousNodeTrailingComments(f);let y=this.match(139);this.parseClassElementName(o),this.pushClassAccessorProperty(t,c,y)}else this.isLineTerminator()?g?this.pushClassPrivateProperty(t,d):this.pushClassProperty(t,o):this.unexpected()}parseClassElementName(t){let{type:e,value:n}=this.state;if((e===132||e===134)&&t.static&&n==="prototype"&&this.raise(b.StaticPrototype,this.state.startLoc),e===139){n==="constructor"&&this.raise(b.ConstructorClassPrivateField,this.state.startLoc);let i=this.parsePrivateName();return t.key=i,i}return this.parsePropertyName(t),t.key}parseClassStaticBlock(t,e){var n;this.scope.enter(720);let i=this.state.labels;this.state.labels=[],this.prodParam.enter(0);let s=e.body=[];this.parseBlockOrModuleBlockBody(s,void 0,!1,8),this.prodParam.exit(),this.scope.exit(),this.state.labels=i,t.body.push(this.finishNode(e,"StaticBlock")),(n=e.decorators)!=null&&n.length&&this.raise(b.DecoratorStaticBlock,e)}pushClassProperty(t,e){!e.computed&&this.nameIsConstructor(e.key)&&this.raise(b.ConstructorClassField,e.key),t.body.push(this.parseClassProperty(e))}pushClassPrivateProperty(t,e){let n=this.parseClassPrivateProperty(e);t.body.push(n),this.classScope.declarePrivateName(this.getPrivateNameSV(n.key),0,n.key.loc.start)}pushClassAccessorProperty(t,e,n){!n&&!e.computed&&this.nameIsConstructor(e.key)&&this.raise(b.ConstructorClassField,e.key);let i=this.parseClassAccessorProperty(e);t.body.push(i),n&&this.classScope.declarePrivateName(this.getPrivateNameSV(i.key),0,i.key.loc.start)}pushClassMethod(t,e,n,i,s,a){t.body.push(this.parseMethod(e,n,i,s,a,"ClassMethod",!0))}pushClassPrivateMethod(t,e,n,i){let s=this.parseMethod(e,n,i,!1,!1,"ClassPrivateMethod",!0);t.body.push(s);let a=s.kind==="get"?s.static?6:2:s.kind==="set"?s.static?5:1:0;this.declareClassPrivateMethodInScope(s,a)}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(592),this.expressionScope.enter(Ku()),this.prodParam.enter(0),t.value=this.eat(29)?this.parseMaybeAssignAllowIn():null,this.expressionScope.exit(),this.prodParam.exit(),this.scope.exit()}parseClassId(t,e,n,i=8331){if(te(this.state.type))t.id=this.parseIdentifier(),e&&this.declareNameFromIdentifier(t.id,i);else if(n||!e)t.id=null;else throw this.raise(b.MissingClassName,this.state.startLoc)}parseClassSuper(t){t.superClass=this.eat(81)?this.parseExprSubscripts():null}parseExport(t,e){let n=this.parseMaybeImportPhase(t,!0),i=this.maybeParseExportDefaultSpecifier(t,n),s=!i||this.eat(12),a=s&&this.eatExportStar(t),o=a&&this.maybeParseExportNamespaceSpecifier(t),d=s&&(!o||this.eat(12)),c=i||a;if(a&&!o){if(i&&this.unexpected(),e)throw this.raise(b.UnsupportedDecoratorExport,t);return this.parseExportFrom(t,!0),this.sawUnambiguousESM=!0,this.finishNode(t,"ExportAllDeclaration")}let l=this.maybeParseExportNamedSpecifiers(t);i&&s&&!a&&!l&&this.unexpected(null,5),o&&d&&this.unexpected(null,98);let u;if(c||l){if(u=!1,e)throw this.raise(b.UnsupportedDecoratorExport,t);this.parseExportFrom(t,c)}else u=this.maybeParseExportDeclaration(t);if(c||l||u){var p;let f=t;if(this.checkExport(f,!0,!1,!!f.source),((p=f.declaration)==null?void 0:p.type)==="ClassDeclaration")this.maybeTakeDecorators(e,f.declaration,f);else if(e)throw this.raise(b.UnsupportedDecoratorExport,t);return this.sawUnambiguousESM=!0,this.finishNode(f,"ExportNamedDeclaration")}if(this.eat(65)){let f=t,h=this.parseExportDefaultExpression();if(f.declaration=h,h.type==="ClassDeclaration")this.maybeTakeDecorators(e,h,f);else if(e)throw this.raise(b.UnsupportedDecoratorExport,t);return this.checkExport(f,!0,!0),this.sawUnambiguousESM=!0,this.finishNode(f,"ExportDefaultDeclaration")}throw this.unexpected(null,5)}eatExportStar(t){return this.eat(55)}maybeParseExportDefaultSpecifier(t,e){if(e||this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom",e?.loc.start);let n=e||this.parseIdentifier(!0),i=this.startNodeAtNode(n);return i.exported=n,t.specifiers=[this.finishNode(i,"ExportDefaultSpecifier")],!0}return!1}maybeParseExportNamespaceSpecifier(t){if(this.isContextual(93)){var e,n;(n=(e=t).specifiers)!=null||(e.specifiers=[]);let i=this.startNodeAt(this.state.lastTokStartLoc);return this.next(),i.exported=this.parseModuleExportName(),t.specifiers.push(this.finishNode(i,"ExportNamespaceSpecifier")),!0}return!1}maybeParseExportNamedSpecifiers(t){if(this.match(5)){let e=t;e.specifiers||(e.specifiers=[]);let n=e.exportKind==="type";return e.specifiers.push(...this.parseExportSpecifiers(n)),e.source=null,this.hasPlugin("importAssertions")?e.assertions=[]:e.attributes=[],e.declaration=null,!0}return!1}maybeParseExportDeclaration(t){return this.shouldParseExportDeclaration()?(t.specifiers=[],t.source=null,this.hasPlugin("importAssertions")?t.assertions=[]:t.attributes=[],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(b.DecoratorBeforeExport,this.state.startLoc),this.parseClass(this.maybeTakeDecorators(this.parseDecorators(!1),this.startNode()),!0,!0);if(this.match(75)||this.match(74)||this.isLet()||this.isUsing()||this.isAwaitUsing())throw this.raise(b.UnsupportedDefaultExport,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(te(t)){if(t===95&&!this.state.containsEsc||t===100)return!1;if((t===130||t===129)&&!this.state.containsEsc){let i=this.nextTokenStart(),s=this.input.charCodeAt(i);if(s===123||this.chStartsBindingIdentifier(s,i)&&!this.input.startsWith("from",i))return this.expectOnePlugin(["flow","typescript"]),!1}}else if(!this.match(65))return!1;let e=this.nextTokenStart(),n=this.isUnparsedContextual(e,"from");if(this.input.charCodeAt(e)===44||te(this.state.type)&&n)return!0;if(this.match(65)&&n){let i=this.input.charCodeAt(this.nextTokenStartSince(e+4));return i===34||i===39}return!1}parseExportFrom(t,e){this.eatContextual(98)?(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(b.DecoratorBeforeExport,this.state.startLoc),!0):this.isUsing()?(this.raise(b.UsingDeclarationExport,this.state.startLoc),!0):this.isAwaitUsing()?(this.raise(b.UsingDeclarationExport,this.state.startLoc),!0):t===74||t===75||t===68||t===80||this.isLet()||this.isAsyncFunction()}checkExport(t,e,n,i){if(e){var s;if(n){if(this.checkDuplicateExports(t,"default"),this.hasPlugin("exportDefaultFrom")){var a;let o=t.declaration;o.type==="Identifier"&&o.name==="from"&&o.end-o.start===4&&!((a=o.extra)!=null&&a.parenthesized)&&this.raise(b.ExportDefaultFromAsIdentifier,o)}}else if((s=t.specifiers)!=null&&s.length)for(let o of t.specifiers){let{exported:d}=o,c=d.type==="Identifier"?d.name:d.value;if(this.checkDuplicateExports(o,c),!i&&o.local){let{local:l}=o;l.type!=="Identifier"?this.raise(b.ExportBindingIsString,o,{localName:l.value,exportName:c}):(this.checkReservedWord(l.name,l.loc.start,!0,!1),this.scope.checkLocalExport(l))}}else if(t.declaration){let o=t.declaration;if(o.type==="FunctionDeclaration"||o.type==="ClassDeclaration"){let{id:d}=o;if(!d)throw new Error("Assertion failure");this.checkDuplicateExports(t,d.name)}else if(o.type==="VariableDeclaration")for(let d of o.declarations)this.checkDeclaration(d.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(b.DuplicateDefaultExport,t):this.raise(b.DuplicateExport,t,{exportName:e})),this.exportedIdentifiers.add(e)}parseExportSpecifiers(t){let e=[],n=!0;for(this.expect(5);!this.eat(8);){if(n)n=!1;else if(this.expect(12),this.eat(8))break;let i=this.isContextual(130),s=this.match(134),a=this.startNode();a.local=this.parseModuleExportName(),e.push(this.parseExportSpecifier(a,s,t,i))}return e}parseExportSpecifier(t,e,n,i){return this.eatContextual(93)?t.exported=this.parseModuleExportName():e?t.exported=this.cloneStringLiteral(t.local):t.exported||(t.exported=this.cloneIdentifier(t.local)),this.finishNode(t,"ExportSpecifier")}parseModuleExportName(){if(this.match(134)){let t=this.parseStringLiteral(this.state.value),e=Hb.exec(t.value);return e&&this.raise(b.ModuleExportNameHasLoneSurrogate,t,{surrogateCharCode:e[0].charCodeAt(0)}),t}return this.parseIdentifier(!0)}isJSONModuleImport(t){return t.assertions!=null?t.assertions.some(({key:e,value:n})=>n.value==="json"&&(e.type==="Identifier"?e.name==="type":e.value==="type")):!1}checkImportReflection(t){let{specifiers:e}=t,n=e.length===1?e[0].type:null;if(t.phase==="source")n!=="ImportDefaultSpecifier"&&this.raise(b.SourcePhaseImportRequiresDefault,e[0].loc.start);else if(t.phase==="defer")n!=="ImportNamespaceSpecifier"&&this.raise(b.DeferImportRequiresNamespace,e[0].loc.start);else if(t.module){var i;n!=="ImportDefaultSpecifier"&&this.raise(b.ImportReflectionNotBinding,e[0].loc.start),((i=t.assertions)==null?void 0:i.length)>0&&this.raise(b.ImportReflectionHasAssertion,e[0].loc.start)}}checkJSONModuleImport(t){if(this.isJSONModuleImport(t)&&t.type!=="ExportAllDeclaration"){let{specifiers:e}=t;if(e!=null){let n=e.find(i=>{let s;if(i.type==="ExportSpecifier"?s=i.local:i.type==="ImportSpecifier"&&(s=i.imported),s!==void 0)return s.type==="Identifier"?s.name!=="default":s.value!=="default"});n!==void 0&&this.raise(b.ImportJSONBindingNotDefault,n.loc.start)}}}isPotentialImportPhase(t){return t?!1:this.isContextual(105)||this.isContextual(97)||this.isContextual(127)}applyImportPhase(t,e,n,i){e||(n==="module"?(this.expectPlugin("importReflection",i),t.module=!0):this.hasPlugin("importReflection")&&(t.module=!1),n==="source"?(this.expectPlugin("sourcePhaseImports",i),t.phase="source"):n==="defer"?(this.expectPlugin("deferredImportEvaluation",i),t.phase="defer"):this.hasPlugin("sourcePhaseImports")&&(t.phase=null))}parseMaybeImportPhase(t,e){if(!this.isPotentialImportPhase(e))return this.applyImportPhase(t,e,null),null;let n=this.startNode(),i=this.parseIdentifierName(!0),{type:s}=this.state;return(Qe(s)?s!==98||this.lookaheadCharCode()===102:s!==12)?(this.applyImportPhase(t,e,i,n.loc.start),null):(this.applyImportPhase(t,e,null),this.createIdentifier(n,i))}isPrecedingIdImportPhase(t){let{type:e}=this.state;return te(e)?e!==98||this.lookaheadCharCode()===102:e!==12}parseImport(t){return this.match(134)?this.parseImportSourceAndAttributes(t):this.parseImportSpecifiersAndAfter(t,this.parseMaybeImportPhase(t,!1))}parseImportSpecifiersAndAfter(t,e){t.specifiers=[];let i=!this.maybeParseDefaultImportSpecifier(t,e)||this.eat(12),s=i&&this.maybeParseStarImportSpecifier(t);return i&&!s&&this.parseNamedImportSpecifiers(t),this.expectContextual(98),this.parseImportSourceAndAttributes(t)}parseImportSourceAndAttributes(t){var e;return(e=t.specifiers)!=null||(t.specifiers=[]),t.source=this.parseImportSource(),this.maybeParseImportAttributes(t),this.checkImportReflection(t),this.checkJSONModuleImport(t),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(t,"ImportDeclaration")}parseImportSource(){return this.match(134)||this.unexpected(),this.parseExprAtom()}parseImportSpecifierLocal(t,e,n){e.local=this.parseIdentifier(),t.specifiers.push(this.finishImportSpecifier(e,n))}finishImportSpecifier(t,e,n=8201){return this.checkLVal(t.local,{type:e},n),this.finishNode(t,e)}parseImportAttributes(){this.expect(5);let t=[],e=new Set;do{if(this.match(8))break;let n=this.startNode(),i=this.state.value;if(e.has(i)&&this.raise(b.ModuleAttributesWithDuplicateKeys,this.state.startLoc,{key:i}),e.add(i),this.match(134)?n.key=this.parseStringLiteral(i):n.key=this.parseIdentifier(!0),this.expect(14),!this.match(134))throw this.raise(b.ModuleAttributeInvalidValue,this.state.startLoc);n.value=this.parseStringLiteral(this.state.value),t.push(this.finishNode(n,"ImportAttribute"))}while(this.eat(12));return this.expect(8),t}parseModuleAttributes(){let t=[],e=new Set;do{let n=this.startNode();if(n.key=this.parseIdentifier(!0),n.key.name!=="type"&&this.raise(b.ModuleAttributeDifferentFromType,n.key),e.has(n.key.name)&&this.raise(b.ModuleAttributesWithDuplicateKeys,n.key,{key:n.key.name}),e.add(n.key.name),this.expect(14),!this.match(134))throw this.raise(b.ModuleAttributeInvalidValue,this.state.startLoc);n.value=this.parseStringLiteral(this.state.value),t.push(this.finishNode(n,"ImportAttribute"))}while(this.eat(12));return t}maybeParseImportAttributes(t){let e;var n=!1;if(this.match(76)){if(this.hasPrecedingLineBreak()&&this.lookaheadCharCode()===40)return;this.next(),this.hasPlugin("moduleAttributes")?(e=this.parseModuleAttributes(),this.addExtra(t,"deprecatedWithLegacySyntax",!0)):e=this.parseImportAttributes(),n=!0}else this.isContextual(94)&&!this.hasPrecedingLineBreak()?(!this.hasPlugin("deprecatedImportAssert")&&!this.hasPlugin("importAssertions")&&this.raise(b.ImportAttributesUseAssert,this.state.startLoc),this.hasPlugin("importAssertions")||this.addExtra(t,"deprecatedAssertSyntax",!0),this.next(),e=this.parseImportAttributes()):e=[];!n&&this.hasPlugin("importAssertions")?t.assertions=e:t.attributes=e}maybeParseDefaultImportSpecifier(t,e){if(e){let n=this.startNodeAtNode(e);return n.local=e,t.specifiers.push(this.finishImportSpecifier(n,"ImportDefaultSpecifier")),!0}else if(Qe(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(b.DestructureNamedImport,this.state.startLoc);if(this.expect(12),this.eat(8))break}let n=this.startNode(),i=this.match(134),s=this.isContextual(130);n.imported=this.parseModuleExportName();let a=this.parseImportSpecifier(n,i,t.importKind==="type"||t.importKind==="typeof",s,void 0);t.specifiers.push(a)}}parseImportSpecifier(t,e,n,i,s){if(this.eatContextual(93))t.local=this.parseIdentifier();else{let{imported:a}=t;if(e)throw this.raise(b.ImportBindingIsString,t,{importName:a.value});this.checkReservedWord(a.name,t.loc.start,!0,!0),t.local||(t.local=this.cloneIdentifier(a))}return this.finishImportSpecifier(t,"ImportSpecifier",s)}isThisParam(t){return t.type==="Identifier"&&t.name==="this"}},Ui=class extends Po{constructor(t,e,n){let i=zw(t);super(i,e),this.options=i,this.initializeScopes(),this.plugins=n,this.filename=i.sourceFilename,this.startIndex=i.startIndex;let s=0;i.allowAwaitOutsideFunction&&(s|=1),i.allowReturnOutsideFunction&&(s|=2),i.allowImportExportEverywhere&&(s|=8),i.allowSuperOutsideMethod&&(s|=16),i.allowUndeclaredExports&&(s|=64),i.allowNewTargetOutsideFunction&&(s|=4),i.allowYieldOutsideFunction&&(s|=32),i.ranges&&(s|=128),i.tokens&&(s|=256),i.createImportExpressions&&(s|=512),i.createParenthesizedExpressions&&(s|=1024),i.errorRecovery&&(s|=2048),i.attachComment&&(s|=4096),i.annexB&&(s|=8192),this.optionFlags=s}getScopeHandler(){return vn}parse(){this.enterInitialScopes();let t=this.startNode(),e=this.startNode();this.nextToken(),t.errors=null;let n=this.parseTopLevel(t,e);return n.errors=this.state.errors,n.comments.length=this.state.commentsLen,n}};function Ub(r,t){var e;if(((e=t)==null?void 0:e.sourceType)==="unambiguous"){t=Object.assign({},t);try{t.sourceType="module";let n=wn(t,r),i=n.parse();if(n.sawUnambiguousESM)return i;if(n.ambiguousScriptDifferentAst)try{return t.sourceType="script",wn(t,r).parse()}catch{}else i.program.sourceType="script";return i}catch(n){try{return t.sourceType="script",wn(t,r).parse()}catch{}throw n}}else return wn(t,r).parse()}function Gb(r,t){let e=wn(t,r);return e.options.strictMode&&(e.state.strict=!0),e.getExpression()}function Kb(r){let t={};for(let e of Object.keys(r))t[e]=yt(r[e]);return t}var Wb=Kb(Gw);function wn(r,t){let e=Ui,n=new Map;if(r!=null&&r.plugins){for(let i of r.plugins){let s,a;typeof i=="string"?s=i:[s,a]=i,n.has(s)||n.set(s,a||{})}Bb(n),e=Jb(n)}return new e(r,t,n)}var $u=new Map;function Jb(r){let t=[];for(let i of Vb)r.has(i)&&t.push(i);let e=t.join("|"),n=$u.get(e);if(!n){n=Ui;for(let i of t)n=Xu[i](n);$u.set(e,n)}return n}In.parse=Ub;In.parseExpression=Gb;In.tokTypes=Wb});import{parseArgs as Q0}from"node:util";import{createHash as tg}from"node:crypto";import{access as _0,appendFile as F0,mkdir as j0,readdir as B0,readFile as Ma,realpath as $a,stat as rg,writeFile as og}from"node:fs/promises";import{isAbsolute as ng,join as je,relative as xl,resolve as ig}from"node:path";import{mkdir as mT,writeFile as yT}from"node:fs/promises";import{join as om}from"node:path";import{lstat as Mg,readFile as Sl,realpath as Ba}from"node:fs/promises";import{dirname as _a,isAbsolute as $g,join as vi,relative as ki,resolve as xi,sep as El}from"node:path";var Cl=["ts","mts","cts","js","mjs","cjs"],Nl={playwright:"playwright.config",cypress:"cypress.config",webdriverio:"wdio.conf"},_g={playwright:["@playwright/test"],cypress:["cypress"],webdriverio:["@wdio/cli","webdriverio"]},Pi={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"};function Fa(r,t){let e=ki(r,t);return e===""||!$g(e)&&e!==".."&&!e.startsWith(`..${El}`)}async function Ii(r){return(await Mg(r).catch(()=>{}))?.isFile()===!0}function ja(r){return r.split(El).join("/")}async function Ol(r){let t=await Ba(r),e={};try{let i=JSON.parse(await Sl(vi(t,"package.json"),"utf8"));e={...i.dependencies,...i.devDependencies}}catch{e={}}let n=[];for(let i of["playwright","cypress","webdriverio"]){let s=_g[i].find(o=>o in e),a;for(let o of Cl){let d=`${Nl[i]}.${o}`;if(await Ii(vi(t,d))){a=d;break}}(s!==void 0||a!==void 0)&&n.push({framework:i,...a===void 0?{}:{configFile:a},...s===void 0?{}:{packageName:s}})}return n}async function Ri(r,t,e){let n=await Ba(r),i=_a(xi(n,e));for(Fa(n,i)||(i=n);;){for(let a of Cl){let o=vi(i,`${Nl[t]}.${a}`);if(await Ii(o))return ja(ki(n,o))}if(i===n)return;let s=_a(i);if(!Fa(n,s))return;i=s}}async function Ti(r,t){let e=await Ba(r),n=t===void 0?e:_a(xi(e,t));if(t!==void 0){let i=await Sl(xi(e,t),"utf8").catch(()=>"");if(/\bsupportFile\s*:\s*false\b/.test(i))return null;let s=/\bsupportFile\s*:\s*["'`]([^"'`]+)["'`]/.exec(i)?.[1];if(s!==void 0){let a=xi(n,s);return Fa(e,a)&&await Ii(a)?ja(ki(e,a)):void 0}}for(let i of["ts","js","tsx","jsx"]){let s=vi(n,"cypress","support",`e2e.${i}`);if(await Ii(s))return ja(ki(e,s))}}import{createHash as Dl}from"node:crypto";function Fg(r){return`${Buffer.byteLength(r,"utf8")}:${r}`}function Te(r){return Dl("sha256").update(r).digest("hex")}function $(r,t){let e=t.map(Fg).join("|"),n=Dl("sha256").update(e,"utf8").digest("hex");return`${r}_${n.slice(0,24)}`}import{isAbsolute as Ll,relative as jg,sep as Ml}from"node:path";var Ai=["1.55.0","1.64.1"],wr=["playwright","cypress","webdriverio"];var Va={playwright:Ai,cypress:["16.2.0"],webdriverio:["10.1.0"]};function Ha(r){return{...r}}function Si(r,t,e){return{errorId:$("err",[t,e]),source:e,...r.message===void 0?{}:{message:r.message},...r.name===void 0?{}:{name:r.name},...r.stack===void 0?{}:{stack:r.stack},...r.snippet===void 0?{}:{snippet:r.snippet},...r.value===void 0?{}:{value:r.value},...r.location===void 0?{}:{location:Ha(r.location)}}}function Fl(r){return{type:r.type,...r.description===void 0?{}:{description:r.description},...r.location===void 0?{}:{location:Ha(r.location)}}}function $l(r){return"text"in r?{kind:"text",text:r.text}:{kind:"base64",base64:r.buffer}}function Bg(r,t,e){return{attachmentId:$("att",[t,String(e)]),name:r.name,contentType:r.contentType,sourceIndex:e,...r.path===void 0?{}:{path:r.path},...r.body===void 0?{}:{bodyBase64:r.body}}}function jl(r,t,e){return{title:r.title,duration:r.duration,...r.error===void 0?{}:{error:Si(r.error,t,`${e}.error`)},steps:r.steps.map((n,i)=>jl(n,t,`${e}.steps[${i}]`))}}function Vg(r){let t=[],e=(n,i,s)=>{n.forEach((a,o)=>{let d=`${s}[${o}]`,c=a.title.length===0?i:[...i,a.title];a.specs.forEach((l,u)=>{l.tests.forEach((p,f)=>{t.push({titlePath:[...c,l.title],spec:l,test:p,sourcePath:`${d}.specs[${u}].tests[${f}]`})})}),e(a.suites,c,`${d}.suites`)})};return e(r.suites,[],"$report.suites"),t}function za(r,t){if(!Ll(t))return;let e=jg(r,t);if(!(Ll(e)||e===".."||e.startsWith(`..${Ml}`)))return e.split(Ml).join("/")}function zg(r,t){return r.config.projects.map(e=>{let n=e.testDir===void 0?void 0:za(t,e.testDir);return{projectId:$("prj",[e.id,e.name]),frameworkProjectId:e.id,name:e.name,repeatEach:e.repeatEach,retries:e.retries,...n===void 0?{}:{testDir:n}}}).sort((e,n)=>e.projectId.localeCompare(n.projectId))}function Hg(r,t,e,n){let i=$("atm",[t,String(r.retry),"repeat:unknown",String(e)]),s=[];return r.error!==void 0&&s.push(Si(r.error,i,`${n}.error`)),r.errors.forEach((a,o)=>{s.push(Si(a,i,`${n}.errors[${o}]`))}),{attemptId:i,sourceIndex:e,retry:r.retry,repeat:{state:"unknown",reason:"not-serialized-by-playwright-json-reporter"},status:r.status,duration:r.duration,startTime:new Date(r.startTime).toISOString(),workerIndex:r.workerIndex,parallelIndex:r.parallelIndex,errors:s,stdout:r.stdout.map($l),stderr:r.stderr.map($l),steps:r.steps.map((a,o)=>jl(a,i,`${n}.steps[${o}]`)),attachments:r.attachments.map((a,o)=>Bg(a,i,o)),annotations:r.annotations.map(Fl),...r.errorLocation===void 0?{}:{errorLocation:Ha(r.errorLocation)}}}function qg(r,t){return r.length===0?"zero-tests":r.some(e=>e.attempts.some(n=>n.status==="interrupted"))?"interrupted":t.length>0?"report-errors":"analysis-ready"}function Bl(r){let{report:t,reportHash:e,artifact:n,options:i}=r,s=i.workspaceRoot,a=zg(t,s),o=t.config.rootDir===void 0?void 0:za(s,t.config.rootDir),d=y=>{let w=y.replaceAll("\\","/");return o===void 0||o===""?w:`${o}/${w}`},c=t.config.configFile===void 0?void 0:za(s,t.config.configFile),l=new Map(a.map(y=>[y.frameworkProjectId,y.projectId])),p=Vg(t).map(({spec:y,test:w,titlePath:x,sourcePath:v})=>{let I=l.get(w.projectId);if(I===void 0)throw new Error(`Validated test references unknown project ID: ${w.projectId}`);let R=d(y.file),E=$("tst",[s,I,R,...x]);return{logicalTestId:E,projectId:I,title:y.title,titlePath:x,tags:[...y.tags].sort(),location:{file:R,line:y.line,column:y.column},timeout:w.timeout,expectedStatus:w.expectedStatus,status:w.status,annotations:w.annotations.map(Fl),attempts:w.results.map((A,N)=>Hg(A,E,N,`${v}.results[${N}]`))}});p.sort((y,w)=>y.logicalTestId.localeCompare(w.logicalTestId));let f=t.errors.map((y,w)=>Si(y,n.artifactId,`$report.errors[${w}]`)),h=p.reduce((y,w)=>y+w.attempts.reduce((x,v)=>x+v.attachments.length,0),0),g=new Date(t.stats.startTime).toISOString(),m=$("run",[e,s,i.gitRoot??"","1.2","1"]);return{schemaVersion:"1.2",runId:m,framework:"playwright",createdAt:g,workspace:{root:s,...i.gitRoot===void 0?{}:{gitRoot:i.gitRoot}},sourceHashes:{report:e},artifact:n,usability:qg(p,f),projects:a,...c===void 0?{}:{configFile:c},logicalTests:p,reportErrors:f,collections:{tests:p.length===0?"empty":"present",errors:f.length===0?"empty":"present",attachments:h===0?"empty":"present"},warnings:[...r.warnings].sort(),stats:{...t.stats,startTime:g}}}var xr=class extends Error{constructor(t){super(t),this.name="ReportValidationError"}};function Se(r,t){throw new xr(`${r} must be ${t}`)}function Q(r,t){return typeof r!="object"||r===null||Array.isArray(r)?Se(t,"an object"):r}function qt(r,t){return Array.isArray(r)?r:Se(t,"an array")}function q(r,t){return typeof r!="string"?Se(t,"a string"):r}function ce(r,t){return r===void 0?void 0:q(r,t)}function ze(r,t){return typeof r!="number"||!Number.isFinite(r)?Se(t,"a finite number"):r}function Ei(r,t){let e=ze(r,t);return Number.isInteger(e)?e:Se(t,"an integer")}function ye(r,t){let e=Ei(r,t);return e<0?Se(t,"a non-negative integer"):e}function qa(r,t){let e=q(r,t);return!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(e)||new Date(e).toISOString()!==e?Se(t,"an ISO 8601 UTC timestamp with millisecond precision"):e}function Vl(r,t){return typeof r!="boolean"?Se(t,"a boolean"):r}function oe(r,t,e,n){let i=r[t];return i===void 0?void 0:e(i,`${n}.${t}`)}function J(r,t,e){return qt(r,t).map((n,i)=>e(n,`${t}[${i}]`))}function Ug(r){return r.length===0?!0:r.length%4!==0?!1:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(r)}function Ua(r,t){let e=q(r,t);return Ug(e)?e:Se(t,"canonical base64")}function Ut(r,t,e){let n=q(r,t);return e.has(n)?n:Se(t,`one of ${[...e].join(", ")}`)}function Ci(r,t){return t===void 0?{}:{[r]:t}}function Ga(r,t){let e=Q(r,t),n=oe(e,"line",ye,t),i=oe(e,"column",ye,t);return{file:q(e.file,`${t}.file`),...n===void 0?{}:{line:n},...i===void 0?{}:{column:i}}}function Ni(r,t){let e=Q(r,t),n=oe(e,"message",q,t),i=oe(e,"name",q,t),s=oe(e,"stack",q,t),a=oe(e,"snippet",q,t),o=oe(e,"value",q,t),d=oe(e,"location",Ga,t);return{...n===void 0?{}:{message:n},...i===void 0?{}:{name:i},...s===void 0?{}:{stack:s},...a===void 0?{}:{snippet:a},...o===void 0?{}:{value:o},...d===void 0?{}:{location:d}}}function Hl(r,t){let e=Q(r,t),n=oe(e,"description",q,t),i=oe(e,"location",Ga,t);return{type:q(e.type,`${t}.type`),...n===void 0?{}:{description:n},...i===void 0?{}:{location:i}}}function zl(r,t){let e=Q(r,t),n=typeof e.text=="string",i=typeof e.buffer=="string";return n===i?Se(t,"exactly one of text or buffer"):n?{text:q(e.text,`${t}.text`)}:{buffer:Ua(e.buffer,`${t}.buffer`)}}function Gg(r,t){let e=Q(r,t),n=oe(e,"path",q,t),i=oe(e,"body",Ua,t);return{name:q(e.name,`${t}.name`),contentType:q(e.contentType,`${t}.contentType`),...n===void 0?{}:{path:n},...i===void 0?{}:{body:i}}}function ql(r,t){let e=Q(r,t),n=oe(e,"error",Ni,t);return{title:q(e.title,`${t}.title`),duration:ze(e.duration,`${t}.duration`),...n===void 0?{}:{error:n},steps:J(e.steps??[],`${t}.steps`,ql)}}var Ul=new Set(["passed","failed","timedOut","skipped","interrupted"]),Kg=new Set(["expected","unexpected","flaky","skipped"]);function Wg(r,t){let e=Q(r,t),n=oe(e,"error",Ni,t),i=oe(e,"errorLocation",Ga,t);return{workerIndex:Ei(e.workerIndex,`${t}.workerIndex`),parallelIndex:Ei(e.parallelIndex,`${t}.parallelIndex`),status:Ut(e.status,`${t}.status`,Ul),duration:ze(e.duration,`${t}.duration`),startTime:qa(e.startTime,`${t}.startTime`),retry:ye(e.retry,`${t}.retry`),...n===void 0?{}:{error:n},errors:J(e.errors??[],`${t}.errors`,Ni),stdout:J(e.stdout??[],`${t}.stdout`,zl),stderr:J(e.stderr??[],`${t}.stderr`,zl),steps:J(e.steps??[],`${t}.steps`,ql),attachments:J(e.attachments??[],`${t}.attachments`,Gg),annotations:J(e.annotations??[],`${t}.annotations`,Hl),...i===void 0?{}:{errorLocation:i}}}function Jg(r,t){let e=Q(r,t);return{timeout:ze(e.timeout,`${t}.timeout`),annotations:J(e.annotations??[],`${t}.annotations`,Hl),expectedStatus:Ut(e.expectedStatus,`${t}.expectedStatus`,Ul),projectName:q(e.projectName,`${t}.projectName`),projectId:q(e.projectId,`${t}.projectId`),results:J(e.results,`${t}.results`,Wg),status:Ut(e.status,`${t}.status`,Kg)}}function Xg(r,t){let e=Q(r,t);return{title:q(e.title,`${t}.title`),ok:Vl(e.ok,`${t}.ok`),tags:J(e.tags??[],`${t}.tags`,q),tests:J(e.tests,`${t}.tests`,Jg),file:q(e.file,`${t}.file`),line:ye(e.line,`${t}.line`),column:ye(e.column,`${t}.column`)}}function Gl(r,t){let e=Q(r,t),n=oe(e,"file",q,t),i=oe(e,"line",ye,t),s=oe(e,"column",ye,t);return{title:q(e.title,`${t}.title`),...n===void 0?{}:{file:n},...i===void 0?{}:{line:i},...s===void 0?{}:{column:s},suites:J(e.suites??[],`${t}.suites`,Gl),specs:J(e.specs??[],`${t}.specs`,Xg)}}function Yg(r,t){let e=Q(r,t);return{id:q(e.id,`${t}.id`),name:q(e.name,`${t}.name`),repeatEach:ye(e.repeatEach,`${t}.repeatEach`),retries:ye(e.retries,`${t}.retries`),...Ci("testDir",ce(e.testDir,`${t}.testDir`))}}function Kl(r){let t=Q(r,"$report"),e=Q(t.config,"$report.config"),n=Q(t.stats,"$report.stats");return{config:{version:q(e.version,"$report.config.version"),projects:J(e.projects,"$report.config.projects",Yg),...Ci("rootDir",ce(e.rootDir,"$report.config.rootDir")),...Ci("configFile",ce(e.configFile,"$report.config.configFile"))},suites:J(t.suites,"$report.suites",Gl),errors:J(t.errors??[],"$report.errors",Ni),stats:{startTime:qa(n.startTime,"$report.stats.startTime"),duration:ze(n.duration,"$report.stats.duration"),expected:ye(n.expected,"$report.stats.expected"),skipped:ye(n.skipped,"$report.stats.skipped"),unexpected:ye(n.unexpected,"$report.stats.unexpected"),flaky:ye(n.flaky,"$report.stats.flaky")}}}var Qg=new TextDecoder("utf-8",{fatal:!0});function Gt(r,t,e){return{kind:"unreadable",artifact:{artifactId:$("art",[r??"unavailable",t??"bytes"]),kind:"report",availability:"unreadable",...t===void 0?{}:{path:t},...r===void 0?{}:{sha256:r},warnings:[]},diagnostic:e}}function Zg(r){return new Set(r??Ai)}function vr(r,t){let e=Te(r);if(r.byteLength===0)return Gt(e,t.reportPath,{reasonCode:"empty-input",message:"The Playwright JSON report is empty.",...t.reportPath===void 0?{}:{path:t.reportPath}});let n;try{n=Qg.decode(r)}catch{return Gt(e,t.reportPath,{reasonCode:"invalid-utf8",message:"The Playwright JSON report is not valid UTF-8.",...t.reportPath===void 0?{}:{path:t.reportPath}})}let i;try{i=JSON.parse(n)}catch(p){return Gt(e,t.reportPath,{reasonCode:"invalid-json",message:p instanceof Error?p.message:"The report is not valid JSON.",...t.reportPath===void 0?{}:{path:t.reportPath}})}let s;try{s=Kl(i)}catch(p){return Gt(e,t.reportPath,{reasonCode:"invalid-report-shape",message:p instanceof xr?p.message:"The JSON value is not a supported Playwright report.",...t.reportPath===void 0?{}:{path:t.reportPath}})}let a=new Set;for(let p of s.config.projects){if(a.has(p.id))return Gt(e,t.reportPath,{reasonCode:"invalid-report-shape",message:`$report.config.projects contains duplicate project ID: ${p.id}`,...t.reportPath===void 0?{}:{path:t.reportPath}});a.add(p.id)}if(new Set(t.incompatiblePlaywrightVersions??[]).has(s.config.version))return Gt(e,t.reportPath,{reasonCode:"incompatible-playwright-version",message:`Playwright ${s.config.version} is configured as incompatible.`,...t.reportPath===void 0?{}:{path:t.reportPath}});let c=Zg(t.testedPlaywrightVersions).has(s.config.version),l=[];c||l.push(`unverified-producer-version:${s.config.version}`),s.config.projects.some(p=>p.repeatEach>1)&&l.push("repeat-index-unavailable");let u={artifactId:$("art",[e]),kind:"report",availability:"present",...t.reportPath===void 0?{}:{path:t.reportPath},sha256:e,format:"playwright-json",formatVersion:s.config.version,versionConfidence:c?"verified":"unverified",warnings:[...l].sort()};try{return{kind:"parsed",run:Bl({report:s,reportHash:e,artifact:u,options:t,warnings:l})}}catch(p){return Gt(e,t.reportPath,{reasonCode:"invalid-report-shape",message:p instanceof Error?p.message:"The report could not be normalized.",...t.reportPath===void 0?{}:{path:t.reportPath}})}}import{createHash as ux}from"node:crypto";import{readdir as px,readFile as fx,stat as hx}from"node:fs/promises";import{basename as mx,join as yx}from"node:path";import{join as tw}from"node:path";var ew=/(?:\(|\bat\s+|^)((?:webpack:\/\/[^\s()]*|file:\/\/[^\s()]*|(?:[A-Za-z]:)?[^():\s][^():]*?)):(\d+):(\d+)\)?\s*$/;function Jl(r){let t=r,e=/^webpack:\/\/[^/]*\/(.*)$/.exec(t);return e!==null&&(t=e[1]??""),t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7)).replaceAll("\\","/"),/^\/[A-Za-z]:\//.test(t)&&(t=t.slice(1))),t.replace(/^(?:\.\/)+/,"")}function Wl(r){return/^https?:\/\//.test(r)||r.includes("/__cypress/")||r.includes("node_modules/")||r.startsWith("node:")||r.startsWith("internal/")}function Xl(r){let t=[];for(let e of r.split(/\r?\n/)){let n=ew.exec(e.trim());if(n===null)continue;let[,i,s,a]=n;if(i===void 0||s===void 0||a===void 0||Wl(i))continue;let o=Jl(i);o===""||Wl(o)||t.push({file:o,line:Number.parseInt(s,10),column:Number.parseInt(a,10)})}return t}function at(r,t){if(r===void 0)return;let e=Xl(r);if(t!==void 0){let n=t.replaceAll("\\","/").replace(/^(?:\.\/)+/,""),i=e.find(s=>{let a=s.file.replaceAll("\\","/");return a===n||a.endsWith(`/${n}`)||n.endsWith(`/${a}`)});if(i!==void 0)return i}return e[0]}var Oi="kwikqa-test-report",Ka="1.0",rw="1",nw=new Set(["cypress","webdriverio"]),iw=new Set(["passed","failed","timedOut","skipped","interrupted"]);function Yl(r,t){let e=t.replaceAll("\\","/");return/^(?:[A-Za-z]:\/|\/|file:\/\/)/.test(e)?t:tw(r,e.replace(/^(?:\.\/)+/,""))}function sw(r){let t=r.rootDir;return t===void 0?r:{...r,tests:r.tests.map(e=>({...e,file:Yl(t,e.file),attempts:e.attempts.map(n=>({...n,attachments:n.attachments.map(i=>i.path===void 0?i:{...i,path:Yl(t,i.path)})}))}))}}function Ql(r){return typeof r=="object"&&r!==null&&r.schema===Oi}function aw(r,t){let e=Q(r,t),n=oe(e,"line",ye,t),i=oe(e,"column",ye,t);return{file:q(e.file,`${t}.file`),...n===void 0?{}:{line:n},...i===void 0?{}:{column:i}}}function Zl(r,t,e){let n=Q(r,t),i=ce(n.message,`${t}.message`),s=ce(n.name,`${t}.name`),a=ce(n.stack,`${t}.stack`),o=ce(n.snippet,`${t}.snippet`),d=ce(n.expected,`${t}.expected`),c=ce(n.actual,`${t}.actual`),u=oe(n,"location",aw,t)??at(a,e);return{...i===void 0?{}:{message:i},...s===void 0?{}:{name:s},...a===void 0?{}:{stack:a},...o===void 0?{}:{snippet:o},...d===void 0&&c===void 0?{}:{value:`Expected: ${d??"(not recorded)"}
11
- Received: ${c??"(not recorded)"}`},...u===void 0?{}:{location:u}}}function ow(r,t,e){let n=Q(r,t),i=ce(n.startTime,`${t}.startTime`);return{status:Ut(n.status,`${t}.status`,iw),retry:ye(n.retry,`${t}.retry`),...i===void 0?{}:{startTime:i},duration:ze(n.duration??0,`${t}.duration`),errors:J(n.errors??[],`${t}.errors`,(s,a)=>Zl(s,a,e)),attachments:J(n.attachments??[],`${t}.attachments`,(s,a)=>{let o=Q(s,a),d=ce(o.path,`${a}.path`);return{name:q(o.name,`${a}.name`),contentType:q(o.contentType,`${a}.contentType`),...d===void 0?{}:{path:d}}}),stdout:J(n.stdout??[],`${t}.stdout`,q),stderr:J(n.stderr??[],`${t}.stderr`,q),steps:[]}}function dw(r,t){let e=Q(r,t),n=q(e.file,`${t}.file`),i=J(e.titlePath,`${t}.titlePath`,q);i.length===0&&Se(`${t}.titlePath`,"a non-empty array");let s=oe(e,"line",ye,t),a=oe(e,"column",ye,t),o=oe(e,"timeout",ze,t);return{file:n,titlePath:i,...s===void 0?{}:{line:s},...a===void 0?{}:{column:a},projectId:q(e.project,`${t}.project`),...o===void 0?{}:{timeout:o},tags:J(e.tags??[],`${t}.tags`,q),attempts:J(e.attempts,`${t}.attempts`,(d,c)=>ow(d,c,n))}}function eu(r){let t=Q(r,"$report");t.schema!==Oi&&Se("$report.schema",Oi),String(t.schemaVersion??"").split(".")[0]!==Ka.split(".")[0]&&Se("$report.schemaVersion",`a ${Ka.split(".")[0]}.x version`);let n=Ut(t.framework,"$report.framework",nw),i=ce(t.frameworkVersion,"$report.frameworkVersion"),s=ce(t.rootDir,"$report.rootDir"),a=ce(t.configFile,"$report.configFile"),o=ce(t.startTime,"$report.startTime"),d=oe(t,"duration",ze,"$report"),c=J(t.projects,"$report.projects",(l,u)=>{let p=Q(l,u);return{id:q(p.id,`${u}.id`),name:q(p.name,`${u}.name`),retries:ye(p.retries??0,`${u}.retries`)}});return qt(t.tests,"$report.tests"),{framework:n,format:"kwikqa-json",adapterVersion:rw,...i===void 0?{}:{frameworkVersion:i},...s===void 0?{}:{rootDir:s},...a===void 0?{}:{configFile:a},...o===void 0?{}:{startTime:o},...d===void 0?{}:{duration:d},projects:c,tests:J(t.tests,"$report.tests",dw),errors:J(t.errors??[],"$report.errors",(l,u)=>Zl(l,u,void 0)),interrupted:t.interrupted===!0,warnings:[]}}function tu(r){let t=r.map(sw),e=t[0];if(e===void 0)throw new Error("No report parts to merge.");let n=e.framework;if(t.some(l=>l.framework!==n))throw new Error("Report parts come from different frameworks.");let i=[...new Set(t.map(l=>l.frameworkVersion).filter(Boolean))],s=new Map;for(let l of t)for(let u of l.projects){let p=s.get(u.id);(p===void 0||u.retries>p.retries)&&s.set(u.id,u)}let a=t.map(l=>l.startTime).filter(l=>l!==void 0).sort(),o=[...new Set(t.map(l=>l.rootDir).filter(Boolean))],d=[...new Set(t.map(l=>l.configFile).filter(Boolean))],c=t.flatMap(l=>l.warnings);return i.length>1&&c.push(`mixed-framework-versions:${i.join(",")}`),o.length>1&&c.push("mixed-report-roots"),{framework:n,format:e.format,adapterVersion:e.adapterVersion,...i.length===1&&i[0]!==void 0?{frameworkVersion:i[0]}:{},...o.length===1&&o[0]!==void 0?{rootDir:o[0]}:{},...d.length===1&&d[0]!==void 0?{configFile:d[0]}:{},...a[0]===void 0?{}:{startTime:a[0]},duration:t.reduce((l,u)=>Math.max(l,u.duration??0),0),projects:[...s.values()],tests:t.flatMap(l=>l.tests),errors:t.flatMap(l=>l.errors),interrupted:t.some(l=>l.interrupted),warnings:c}}var Di=class extends Error{constructor(t){super(t),this.name="XmlError"}},cw=64,lw=5e5,uw=/^[A-Za-z_:][\w.:-]*/,pw={lt:"<",gt:">",amp:"&",quot:'"',apos:"'"};function ru(r){return r.replace(/&(#x[0-9A-Fa-f]+|#\d+|[A-Za-z]+);/g,(t,e)=>{if(e.startsWith("#x")){let i=Number.parseInt(e.slice(2),16);return i<=1114111?String.fromCodePoint(i):t}if(e.startsWith("#")){let i=Number.parseInt(e.slice(1),10);return i<=1114111?String.fromCodePoint(i):t}let n=pw[e];if(n===void 0)throw new Di(`Unknown XML entity: &${e};`);return n})}function nu(r){let t=0,e=0,n=r.charCodeAt(0)===65279?r.slice(1):r,i=c=>{throw new Di(`${c} at offset ${t}`)},s=()=>{for(;;){for(;t<n.length&&/\s/.test(n[t]??"");)t+=1;if(n.startsWith("<?",t)){let c=n.indexOf("?>",t);c<0&&i("Unterminated processing instruction"),t=c+2}else if(n.startsWith("<!--",t)){let c=n.indexOf("-->",t);c<0&&i("Unterminated comment"),t=c+3}else if(n.startsWith("<!DOCTYPE",t)||n.startsWith("<!doctype",t))i("Document type declarations are not accepted");else return}},a=()=>{let c=uw.exec(n.slice(t,t+256));return c===null?i("Expected a name"):(t+=c[0].length,c[0])},o=c=>{c>cw&&i("XML nests too deeply"),e+=1,e>lw&&i("XML has too many nodes"),n[t]!=="<"&&i("Expected an element"),t+=1;let l=a(),u={};for(;;){for(;/\s/.test(n[t]??"");)t+=1;if(n.startsWith("/>",t))return t+=2,{name:l,attributes:u,children:[]};if(n[t]===">"){t+=1;break}let g=a();for(;/\s/.test(n[t]??"");)t+=1;for(n[t]!=="="&&i(`Expected = after attribute ${g}`),t+=1;/\s/.test(n[t]??"");)t+=1;let m=n[t];if(m!=='"'&&m!=="'")return i("Expected a quoted attribute value");let y=n.indexOf(m,t+1);y<0&&i("Unterminated attribute value");let w=n.slice(t+1,y);w.includes("<")&&i("Attribute values must not contain <"),u[g]=ru(w),t=y+1}let p=[],f="",h=()=>{f.length>0&&(p.push(f),e+=1,f="")};for(;;){if(t>=n.length&&i(`Unterminated element <${l}>`),n.startsWith("</",t)){t+=2;let y=a();for(y!==l&&i(`Expected </${l}> but found </${y}>`);/\s/.test(n[t]??"");)t+=1;return n[t]!==">"&&i("Expected >"),t+=1,h(),{name:l,attributes:u,children:p}}if(n.startsWith("<![CDATA[",t)){let y=n.indexOf("]]>",t);y<0&&i("Unterminated CDATA section"),f+=n.slice(t+9,y),t=y+3;continue}if(n.startsWith("<!--",t)){let y=n.indexOf("-->",t);y<0&&i("Unterminated comment"),t=y+3;continue}if(n.startsWith("<?",t)){let y=n.indexOf("?>",t);y<0&&i("Unterminated processing instruction"),t=y+2;continue}if(n[t]==="<"){h(),p.push(o(c+1));continue}let g=n.indexOf("<",t),m=g<0?n.length:g;f+=ru(n.slice(t,m)),t=m}};s();let d=o(0);return s(),t<n.length&&i("Unexpected content after the root element"),d}function ot(r,t){return r.children.filter(e=>typeof e!="string"&&(t===void 0||e.name===t))}function cn(r){return r.children.map(t=>typeof t=="string"?t:cn(t)).join("")}var iu="1",ln=class extends Error{constructor(){super("This JUnit report does not say which framework wrote it. Pass --framework cypress or --framework webdriverio."),this.name="JunitFrameworkUnknownError"}};function su(r){let t=r.slice(0,4096).replace(/^/,"");return/^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<testsuites?\b/.test(t)}function Wa(r){if(r.name==="testsuite")return[r];if(r.name!=="testsuites")throw new Error("A JUnit report's root must be testsuites.");let t=[],e=n=>{for(let i of ot(n,"testsuite"))t.push(i),e(i)};return e(r),t}function au(r){let t=new Map;for(let e of ot(r,"properties"))for(let n of ot(e,"property")){let i=n.attributes.name;i!==void 0&&t.set(i,n.attributes.value??cn(n))}return t}function fw(r,t){let e=Wa(r);if(e.some(n=>au(n).has("capabilities")))return"webdriverio";if(e.some(n=>n.attributes.name==="Root Suite")||/webpack:\/\/|__cypress|CypressError/.test(t))return"cypress"}function ou(r){let t=Number.parseFloat(r??"");return Number.isFinite(t)&&t>=0?Math.round(t*1e3):0}function du(r,t){let e=ot(r,"failure")[0]??ot(r,"error")[0]??void 0,n=ot(r,"system-err").map(i=>cn(i).trim()).filter(i=>i!=="").join(`
12
- `);if(e!==void 0){let i=cn(e).trim(),s=i!==""?i:n!==""?n:void 0,a=e.attributes.message,o=at(s,t);return{status:"failed",errors:[{...a===void 0?{}:{message:a},...e.attributes.type===void 0?{}:{name:e.attributes.type},...s===void 0?{}:{stack:s},...o===void 0?{}:{location:o}}]}}if(ot(r,"skipped").length>0){if(n!==""){let i=at(n,t),s=n.split(`
13
- `)[0]?.replace(/^\w*Error:\s*/,"");return{status:"failed",errors:[{...s===void 0?{}:{message:s},stack:n,...i===void 0?{}:{location:i}}]}}return{status:"skipped",errors:[]}}return{status:"passed",errors:[]}}function hw(r,t,e){if(e===""||r===e||!r.endsWith(` ${e}`))return[r];let n=r.slice(0,-(e.length+1));return t===""||t==="Root Suite"?[n,e]:n===t?[t,e]:n.endsWith(` ${t}`)?[n.slice(0,-(t.length+1)),t,e]:[n,e]}function cu(r,t,e,n){return{status:r,retry:e,duration:n,errors:t,attachments:[],stdout:[],stderr:[],steps:[]}}function mw(r){let t=[],e="";for(let n of Wa(r)){n.attributes.file!==void 0&&n.attributes.file!==""&&(e=n.attributes.file);let i=n.attributes.name??"";for(let s of ot(n,"testcase")){let a=s.attributes.name??"",o=s.attributes.classname??a,d=du(s,e);t.push({file:e,titlePath:hw(a,i,o),projectId:"",attempts:[cu(d.status,d.errors,0,ou(s.attributes.time))]})}}return{framework:"cypress",format:"junit-xml",adapterVersion:iu,projects:[{id:"",name:""}].map(n=>({...n,retries:0})),tests:t,errors:[],interrupted:!1,warnings:["final-attempt-only"]}}function yw(r){let t=[],e=new Set;for(let n of Wa(r)){let i=au(n),s=i.get("file")??n.attributes.file??"",a=(i.get("capabilities")??"").split(".")[0]??"";e.add(a);let o=i.get("suiteName")??n.attributes.name??"",d=new Map,c=[];for(let l of ot(n,"testcase")){let u=l.attributes.name??"",p=du(l,s),f=d.get(u);f===void 0&&(f=[],d.set(u,f),c.push(u)),f.push(cu(p.status,p.errors,f.length,ou(l.attributes.time)))}for(let l of c)t.push({file:s,titlePath:o===""?[l]:[o,l],projectId:a,attempts:d.get(l)??[]})}return{framework:"webdriverio",format:"junit-xml",adapterVersion:iu,projects:[...e].map(n=>({id:n,name:n,retries:0})),tests:t,errors:[],interrupted:!1,warnings:[]}}function lu(r,t){let e=nu(r);switch(fw(e,r)??t.framework){case"cypress":return mw(e);case"webdriverio":return yw(e);default:throw new ln}}import{dirname as vw,isAbsolute as kw,join as Iw}from"node:path";import{isAbsolute as Mi,relative as gw,sep as un}from"node:path";var Li="1970-01-01T00:00:00.000Z";function pn(r,t){switch(r){case"playwright":return t;case"cypress":return[t.filter(e=>e!=="").join(" ")];case"webdriverio":return t.filter(e=>e!=="").slice(-2)}}function uu(r,t,e,n,i){return $("tst",[t,e,n,...r==="playwright"?[]:[`framework:${r}`],...pn(r,i)])}function $i(r,t){if(!Mi(t))return;let e=gw(r,t);if(!(Mi(e)||e===".."||e.startsWith(`..${un}`)))return e.split(un).join("/")}function fn(r){let t=r.trim();return t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7)).replaceAll("\\","/"),/^\/[A-Za-z]:\//.test(t)&&(t=t.slice(1))),t.replaceAll("\\","/")}function pu(r,t,e){let n=fn(e),i=un==="\\"?n.replaceAll("/","\\"):n;if(Mi(i)||/^[A-Za-z]:\//.test(n))return $i(r,i)??n;let s=n.replace(/^(?:\.\/)+/,"");if(t===void 0)return s;let a=$i(r,t);return a===void 0||a===""?s:`${a}/${s}`}function Xa(r,t,e,n,i){let s=r.location===void 0?void 0:{...r.location,file:pu(n,i,r.location.file)};return{errorId:$("err",[t,e]),source:e,...r.message===void 0?{}:{message:r.message},...r.name===void 0?{}:{name:r.name},...r.stack===void 0?{}:{stack:r.stack},...r.snippet===void 0?{}:{snippet:r.snippet},...r.value===void 0?{}:{value:r.value},...s===void 0?{}:{location:s}}}function fu(r,t,e,n,i){return{title:r.title,duration:r.duration,...r.error===void 0?{}:{error:Xa(r.error,t,`${e}.error`,n,i)},steps:r.steps.map((s,a)=>fu(s,t,`${e}.steps[${a}]`,n,i))}}function ww(r,t){let e=fn(t),n=un==="\\"?e.replaceAll("/","\\"):e;return Mi(n)||r===void 0?n:`${r}${un}${n.replace(/^(?:\.[/\\])+/,"")}`}function bw(r){let t=r.filter(n=>n.status!=="skipped");return t.length===0?"skipped":t.at(-1)?.status==="passed"?t.some(n=>n.status!=="passed")?"flaky":"expected":"unexpected"}function xw(r,t,e){return r.length===0?"zero-tests":e||r.some(n=>n.attempts.some(i=>i.status==="interrupted"))?"interrupted":t.length>0?"report-errors":"analysis-ready"}function Ja(r){if(r===void 0)return;let t=new Date(r);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function hu(r){let{report:t,reportHash:e,artifact:n,options:i}=r,s=i.workspaceRoot,a=new Set(r.warnings),o=t.projects.map(w=>{let x=w.testDir===void 0?void 0:$i(s,w.testDir);return{projectId:$("prj",[`framework:${t.framework}`,w.id,w.name]),frameworkProjectId:w.id,name:w.name,repeatEach:1,retries:w.retries,...x===void 0?{}:{testDir:x}}}).sort((w,x)=>w.projectId.localeCompare(x.projectId)),d=new Map(o.map(w=>[w.frameworkProjectId,w.projectId])),c=new Set,l=[];t.tests.forEach((w,x)=>{let v=d.get(w.projectId);if(v===void 0)throw new Error(`Test ${x} references unknown project: ${w.projectId}`);let I=pu(s,t.rootDir,w.file),R=uu(t.framework,s,v,I,w.titlePath);if(c.has(R)){a.add(`duplicate-test-identity:${I}`);return}c.add(R);let E=`$tests[${x}]`,A=w.attempts.map((B,V)=>{let P=$("atm",[R,String(B.retry),"repeat:unknown",String(V)]),O=`${E}.attempts[${V}]`,M=B.errors.map((k,T)=>Xa(k,P,`${O}.errors[${T}]`,s,t.rootDir)),H=M.find(k=>k.location!==void 0)?.location;return{attemptId:P,sourceIndex:V,retry:B.retry,repeat:{state:"unknown",reason:"not-serialized-by-report"},status:B.status,duration:B.duration,startTime:Ja(B.startTime)??Ja(t.startTime)??Li,workerIndex:0,parallelIndex:0,errors:M,stdout:B.stdout.map(k=>({kind:"text",text:k})),stderr:B.stderr.map(k=>({kind:"text",text:k})),steps:B.steps.map((k,T)=>fu(k,P,`${O}.steps[${T}]`,s,t.rootDir)),attachments:B.attachments.map((k,T)=>({attachmentId:$("att",[P,String(T)]),name:k.name,contentType:k.contentType,sourceIndex:T,...k.path===void 0?{}:{path:ww(t.rootDir,k.path)}})),annotations:[],...H===void 0?{}:{errorLocation:H}}}),N=bw(w.attempts);l.push({logicalTestId:R,projectId:v,title:w.titlePath.at(-1)??"",titlePath:w.titlePath,tags:[...w.tags??[]].sort(),location:{file:I,...w.line===void 0?{}:{line:w.line},...w.column===void 0?{}:{column:w.column}},timeout:w.timeout??0,expectedStatus:N==="skipped"?"skipped":"passed",status:N,annotations:[],attempts:A})}),l.sort((w,x)=>w.logicalTestId.localeCompare(x.logicalTestId));let u=t.errors.map((w,x)=>Xa(w,n.artifactId,`$errors[${x}]`,s,t.rootDir)),p=l.reduce((w,x)=>w+x.attempts.reduce((v,I)=>v+I.attachments.length,0),0),f=l.flatMap(w=>w.attempts.map(x=>x.startTime)).filter(w=>w!==Li).sort()[0],h=Ja(t.startTime)??f??Li;h===Li&&a.add("start-time-unavailable");let g={expected:0,unexpected:0,flaky:0,skipped:0};for(let w of l)g[w.status]+=1;let m=t.configFile===void 0?void 0:$i(s,fn(t.configFile)),y=$("run",[e,s,i.gitRoot??"","1.2",`${t.format}:${t.adapterVersion}`]);return{schemaVersion:"1.2",runId:y,framework:t.framework,createdAt:h,workspace:{root:s,...i.gitRoot===void 0?{}:{gitRoot:i.gitRoot}},sourceHashes:{report:e},artifact:n,usability:xw(l,u,t.interrupted),projects:o,...m===void 0?{}:{configFile:m},logicalTests:l,reportErrors:u,collections:{tests:l.length===0?"empty":"present",errors:u.length===0?"empty":"present",attachments:p===0?"empty":"present"},warnings:[...a].sort(),stats:{startTime:h,duration:t.duration??0,...g}}}var Pw="1",Rw=/\.(?:png|jpe?g|webp|gif|mp4|webm)$/i;function yu(r){if(typeof r!="object"||r===null||Array.isArray(r))return!1;let t=r;if(!Array.isArray(t.results)||typeof t.stats!="object")return!1;let e=t.results[0];return e===void 0||typeof e=="object"&&e!==null&&"uuid"in e&&Array.isArray(e.suites)&&Array.isArray(e.tests)}function Tw(r,t){let e=[],n=i=>{if(typeof i=="string"){let s;try{s=JSON.parse(i)}catch{s=void 0}if(s!==void 0&&typeof s!="string"){n(s);return}let a=typeof s=="string"?s:i;Rw.test(a)&&!/^https?:/i.test(a)&&e.push(a);return}if(Array.isArray(i)){for(let s of i)n(s);return}typeof i=="object"&&i!==null&&n(i.value)};return n(r),e.map(i=>{let s=fn(i);return kw(s)||t===void 0?s:Iw(t,s)})}function Aw(r){let t=JSON.stringify(r.results??[]).slice(0,2e5);return/webpack:\/\/|__cypress|\bcy\.|Cypress/.test(t)?"cypress":/\bbrowser\.|\$\(|webdriverio|wdio/.test(t)?"webdriverio":"cypress"}function mu(r){return r.pending===!0||r.skipped===!0?"skipped":r.state==="passed"||r.pass===!0?"passed":r.timedOut===!0?"timedOut":r.state==="failed"||r.fail===!0?"failed":"skipped"}function Sw(r,t,e){let n=r.err;if(typeof n!="object"||n===null)return[];let i=n,s=ce(i.message,`${t}.err.message`),a=ce(i.estack,`${t}.err.estack`),o=ce(i.diff??void 0,`${t}.err.diff`);if(s===void 0&&a===void 0)return[];let d=at(a,e);return[{...s===void 0?{}:{message:s},...a===void 0?{}:{stack:a},...o===void 0||o===""?{}:{value:o},...d===void 0?{}:{location:d}}]}function gu(r,t){let e=Q(r,"$report"),n=qt(e.results,"$report.results"),i=Q(e.stats,"$report.stats"),s=t.reportPath===void 0?void 0:vw(t.reportPath),a=t.framework??Aw(e),o=[],d=[],c=(u,p,f,h)=>{let g=Q(u,p),m=typeof g.title=="string"?g.title:"",y=(typeof g.file=="string"&&g.file!==""?g.file:void 0)??(typeof g.fullFile=="string"&&g.fullFile!==""?g.fullFile:void 0)??h,w=m===""?f:[...f,m];J(g.tests??[],`${p}.tests`,(x,v)=>{let I=Q(x,v),R=q(I.title,`${v}.title`),E=Sw(I,v,y);if(I.isHook===!0){mu(I)!=="passed"&&d.push(...E);return}let A=Tw(I.context,s).map(N=>({name:/\.(?:mp4|webm)$/i.test(N)?"video":"screenshot",contentType:/\.(?:mp4|webm)$/i.test(N)?"video/mp4":/\.png$/i.test(N)?"image/png":"image/jpeg",path:N}));o.push({file:y,titlePath:[...w,R],projectId:"",attempts:[{status:mu(I),retry:0,duration:typeof I.duration=="number"?I.duration:0,errors:E,attachments:A,stdout:[],stderr:[],steps:[]}]})}),J(g.suites??[],`${p}.suites`,(x,v)=>c(x,v,w,y))};n.forEach((u,p)=>{c(u,`$report.results[${p}]`,[],"")});let l=ce(i.start,"$report.stats.start");return{framework:a,format:"mochawesome-json",adapterVersion:Pw,...l===void 0?{}:{startTime:l},...typeof i.duration=="number"?{duration:ze(i.duration,"$report.stats.duration")}:{},projects:[{id:"",name:"",retries:0}],tests:o,errors:d,interrupted:!1,warnings:["final-attempt-only"]}}var Ew="1";function bu(r){if(typeof r!="object"||r===null||Array.isArray(r))return!1;let t=r;return Array.isArray(t.suites)&&Array.isArray(t.specs)&&typeof t.capabilities=="object"&&t.capabilities!==null}function xu(r){if(typeof r!="object"||r===null)return"";let t=r;if(typeof t.browserName=="string")return t.browserName;let e=Object.values(t);return e.length>0&&e.every(n=>typeof n=="object"&&n!==null)?"multiremote":""}function Cw(r){switch(r){case"passed":return"passed";case"failed":return"failed";default:return"skipped"}}function wu(r,t,e){if(typeof r!="object"||r===null)return;let n=Q(r,t),i=ce(n.message,`${t}.message`),s=ce(n.name,`${t}.name`),a=ce(n.stack,`${t}.stack`),o=at(a,e);return{...i===void 0?{}:{message:i},...s===void 0?{}:{name:s},...a===void 0?{}:{stack:a},...o===void 0?{}:{location:o}}}function vu(r){let t=Q(r,"$report"),e=J(t.specs,"$report.specs",q),n=[];e.length!==1&&n.push("ambiguous-spec-file");let i=e[0]??"",s=xu(t.capabilities),a=t.capabilities,o=typeof a.browserVersion=="string"?a.browserVersion:void 0,d=[];return qt(t.suites,"$report.suites").forEach((c,l)=>{let u=`$report.suites[${l}]`,p=Q(c,u),f=typeof p.name=="string"?p.name:"",h=new Map,g=[];J(p.tests??[],`${u}.tests`,(m,y)=>{let w=Q(m,y),x=q(w.name,`${y}.name`),v=wu(w.error,`${y}.error`,i),I=h.get(x);I===void 0&&(I=[],h.set(x,I),g.push(x)),I.push({status:Cw(w.state),retry:I.length,...typeof w.start=="string"?{startTime:w.start}:{},duration:typeof w.duration=="number"?w.duration:0,errors:v===void 0?[]:[v],attachments:[],stdout:[],stderr:[],steps:[]})}),J(p.hooks??[],`${u}.hooks`,(m,y)=>{let w=Q(m,y);if(w.state!=="failed")return;let x=wu(w.error,`${y}.error`,i),v=typeof w.title=="string"?w.title:"hook",I=typeof w.associatedTest=="string"&&w.associatedTest!==""?w.associatedTest:v,R={...x??{},message:`${v}: ${x?.message??"failed"}`},E=h.get(I),A=E?.at(-1);if(E!==void 0&&A!==void 0){A.status!=="failed"&&(E[E.length-1]={...A,status:"failed",errors:[R]});return}h.set(I,[{status:"failed",retry:0,...typeof w.start=="string"?{startTime:w.start}:{},duration:typeof w.duration=="number"?w.duration:0,errors:[R],attachments:[],stdout:[],stderr:[],steps:[]}]),g.push(I)});for(let m of g)d.push({file:i,titlePath:f===""?[m]:[f,m],projectId:s,attempts:h.get(m)??[]})}),{framework:"webdriverio",format:"wdio-json",adapterVersion:Ew,...typeof t.start=="string"?{startTime:t.start}:{},...typeof t.start=="string"&&typeof t.end=="string"?{duration:Math.max(0,Date.parse(t.end)-Date.parse(t.start))||0}:{},projects:[{id:s,name:s,retries:0}],tests:d,errors:[],interrupted:!1,warnings:[...n,...o===void 0?[]:[`browser-version:${s}@${o}`]]}}var Zu=bi(Pn(),1);import{lstat as Xb,readFile as Yb,realpath as Yu}from"node:fs/promises";import{isAbsolute as Qu,relative as Qb,resolve as Zb,sep as ex}from"node:path";var tx=2*1024*1024,rx=new Set(["it","test","specify","xit","fit","xtest","xspecify"]),nx=new Set(["describe","context","suite","xdescribe","fdescribe","xcontext"]),ix=new Set(["only","skip","fixme","serial","parallel","fail","slow"]);function Rn(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof r.type=="string"}function sx(r){let t=[],e=r;for(;Rn(e)&&e.type==="MemberExpression";){let s=e.property;Rn(s)&&s.type==="Identifier"&&t.unshift(String(s.name)),e=e.object}if(!Rn(e)||e.type!=="Identifier")return;t.unshift(String(e.name));let i=t.filter(s=>!ix.has(s)).at(-1);if(i!==void 0){if(nx.has(i))return"suite";if(rx.has(i))return"test"}}function ax(r){if(Rn(r)){if(r.type==="StringLiteral")return String(r.value);if(r.type==="TemplateLiteral"){let t=r.expressions,e=r.quasis;if(t.length===0&&e.length===1)return e[0]?.value.cooked}}}function ox(r,t){let e=[],n=/\.([cm]?[jt]sx?)$/i.exec(t)?.[1]?.toLowerCase()??"ts";n.includes("t")&&e.push("typescript"),(n.endsWith("x")||!n.includes("t"))&&e.push("jsx");let i;try{i=(0,Zu.parse)(r,{sourceType:"unambiguous",errorRecovery:!0,plugins:e})}catch{return[]}let s=[],a=(o,d)=>{if(Array.isArray(o)){for(let c of o)a(c,d);return}if(Rn(o)){if(o.type==="CallExpression"){let c=sx(o.callee),l=o.arguments,u=ax(l[0]);if(c!==void 0&&u!==void 0){if(c==="test"){let p=o.loc;p!==void 0&&s.push({titlePath:[...d,u],line:p.start.line,column:p.start.column+1});return}for(let p of l.slice(1))a(p,[...d,u]);return}}for(let[c,l]of Object.entries(o))c==="loc"||c==="start"||c==="end"||c==="extra"||typeof l=="object"&&l!==null&&a(l,d)}};return a(i,[]),s}function dx(r,t){let e=Qb(r,t);return e===""||!Qu(e)&&e!==".."&&!e.startsWith(`..${ex}`)}async function cx(r,t){if(!(Qu(t)||t.split("/").includes("..")))try{let e=await Yu(r),n=await Yu(Zb(e,t));if(!dx(e,n))return;let i=await Xb(n);return!i.isFile()||i.size>tx?void 0:await Yb(n,"utf8")}catch{return}}function lx(r,t,e){let n=pn(r,t),i=pn(r,e);return n.length===i.length&&n.every((s,a)=>s===i[a])}async function Lo(r){let t=r.logicalTests.filter(i=>i.location.line===void 0);if(t.length===0)return r;let e=new Map;for(let i of new Set(t.map(s=>s.location.file))){let s=await cx(r.workspace.root,i);e.set(i,s===void 0?[]:ox(s,i))}let n=r.logicalTests.map(i=>{if(i.location.line!==void 0)return i;let s=(e.get(i.location.file)??[]).filter(o=>lx(r.framework,o.titlePath,i.titlePath)),a=s.length===1?s[0]:void 0;return a===void 0?i:{...i,location:{...i.location,line:a.line,column:a.column}}});return{...r,logicalTests:n}}var gx=2e3,ep=256*1024*1024,wx=["kwikqa-json","playwright-json","mochawesome-json","wdio-json","junit-xml"],bx=new TextDecoder("utf-8",{fatal:!0});function xx(r){if(typeof r!="object"||r===null||Array.isArray(r))return!1;let t=r,e=t.config;return typeof e=="object"&&e!==null&&"version"in e&&Array.isArray(t.suites)}function vx(r){if(r.bytes.byteLength===0)return{kind:"unreadable",diagnostic:{reasonCode:"empty-input",message:"The report is empty."}};let t;try{t=bx.decode(r.bytes)}catch{return{kind:"unreadable",diagnostic:{reasonCode:"invalid-utf8",message:"The report is not valid UTF-8."}}}if(su(t))return{kind:"classified",value:{file:r,format:"junit-xml",text:t}};let e;try{e=JSON.parse(t)}catch(i){return{kind:"unreadable",diagnostic:{reasonCode:"invalid-json",message:i instanceof Error?i.message:"The report is not valid JSON."}}}let n=Ql(e)?"kwikqa-json":xx(e)?"playwright-json":yu(e)?"mochawesome-json":bu(e)?"wdio-json":void 0;return n===void 0?{kind:"unreadable",diagnostic:{reasonCode:"unsupported-report-format",message:"The JSON is not a report KwikQA reads: Playwright JSON, KwikQA's Cypress or WebdriverIO reporter, mochawesome, or @wdio/json-reporter."}}:{kind:"classified",value:{file:r,format:n,text:t,json:e}}}function kx(r,t){switch(r.format){case"kwikqa-json":return eu(r.json);case"mochawesome-json":return gu(r.json,{...r.file.path===void 0?{}:{reportPath:r.file.path},...t.framework===void 0?{}:{framework:t.framework}});case"wdio-json":return vu(r.json);case"junit-xml":return lu(r.text,{...t.framework===void 0?{}:{framework:t.framework}});case"playwright-json":throw new Error("Playwright JSON is read by its own parser.")}}function Ze(r,t,e){let n=e.reasonCode==="missing-report"?"unavailable":"unreadable";return{kind:"unreadable",artifact:{artifactId:$("art",[r??n,t??"bytes"]),kind:"report",availability:n,...t===void 0?{}:{path:t},...r===void 0?{}:{sha256:r},warnings:[]},diagnostic:{...e,...t===void 0?{}:{path:t}}}}function Ix(r){if(r.length===1&&r[0]!==void 0)return Te(r[0].bytes);let t=r.map(e=>`${mx(e.path??"")}\0${Te(e.bytes)}`).sort();return ux("sha256").update(t.join(`
14
- `),"utf8").digest("hex")}function Gi(r,t){let e=t.reportPath;if(r.length===0)return Ze(void 0,e,{reasonCode:"missing-report",message:"No report files were found."});let n=Ix(r),i=[],s;for(let m of r){let y=vx(m);y.kind==="classified"?i.push(y.value):s??=y.diagnostic}if(i.length===0)return Ze(n,e,s??{reasonCode:"unsupported-report-format",message:"No report was found."});let a=wx.find(m=>i.some(y=>y.format===m)),o=i.filter(m=>m.format===a),d=i.length-o.length+(r.length-i.length),c=d>0?[`ignored-report-files:${d}`]:[];if(a==="playwright-json"){let m=o[0];return o.length!==1||m===void 0?Ze(n,e,{reasonCode:"invalid-report-shape",message:"Found several Playwright JSON reports; point --report at one, or merge them with `npx playwright merge-reports`."}):vr(m.file.bytes,{...t,...m.file.path===void 0?{}:{reportPath:m.file.path}})}let l;try{l=tu(o.map(m=>kx(m,t)))}catch(m){return Ze(n,e,{reasonCode:m instanceof ln?"unsupported-report-format":"invalid-report-shape",message:m instanceof Error?m.message:"The report could not be read."})}let u=new Set(Va[l.framework]),p=l.frameworkVersion,f=p!==void 0&&u.has(p),h=[...l.warnings,...c,p===void 0?"producer-version-unrecorded":f?void 0:`unverified-producer-version:${p}`].filter(m=>m!==void 0),g={artifactId:$("art",[n]),kind:"report",availability:"present",...e===void 0?{}:{path:e},sha256:n,format:l.format,...p===void 0?{}:{formatVersion:p},versionConfidence:f?"verified":"unverified",warnings:[...new Set(h)].sort()};try{return{kind:"parsed",run:hu({report:l,reportHash:n,artifact:g,options:t,warnings:h})}}catch(m){return Ze(n,e,{reasonCode:"invalid-report-shape",message:m instanceof Error?m.message:"The report could not be normalized."})}}async function Px(r){return(await px(r,{withFileTypes:!0})).filter(e=>e.isFile()&&/\.(?:json|xml|log)$/i.test(e.name)).map(e=>yx(r,e.name)).sort().slice(0,gx)}async function et(r,t){let e;try{e=await hx(r)}catch(o){let d=o.code==="ENOENT";return Ze(void 0,r,{reasonCode:d?"missing-report":"read-failed",message:d?`Test report does not exist: ${r}`:`Could not inspect: ${r}`})}let n;if(e.isDirectory()){try{n=await Px(r)}catch{return Ze(void 0,r,{reasonCode:"read-failed",message:`Could not list report directory: ${r}`})}if(n.length===0)return Ze(void 0,r,{reasonCode:"missing-report",message:`No .json or .xml report files in ${r}`})}else if(e.isFile())n=[r];else return Ze(void 0,r,{reasonCode:"not-a-file",message:`Test report path is not a regular file or directory: ${r}`});let i=[],s=0;for(let o of n)try{let d=await fx(o);if(s+=d.byteLength,s>ep)return Ze(void 0,r,{reasonCode:"read-failed",message:`Report files under ${r} exceed ${ep} bytes.`});i.push({path:o,bytes:d})}catch{return Ze(void 0,r,{reasonCode:"read-failed",message:`Could not read test report: ${o}`})}let a=Gi(i,{...t,reportPath:r});return a.kind!=="parsed"||a.run.framework==="playwright"?a:{kind:"parsed",run:await Lo(a.run)}}import{readFile as hI,realpath as mI}from"node:fs/promises";import{createRequire as yI}from"node:module";import{delimiter as gI,dirname as _f,isAbsolute as wI,join as tr}from"node:path";function Ki(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(Ki).join(",")}]`:`{${Object.entries(r).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${Ki(n)}`).join(",")}}`}function he(r,t,e,n,i){return $("evd",[r,t,e,Ki(n),i])}function we(r,t,e){return $("art",["m2",r,t,e])}function Sr(r){return Te(Buffer.from(Ki(r),"utf8"))}var Mo={policyVersion:"development-1",workspaceRoot:".",maxPacketBytes:256e3,maxArtifactBytes:16e6,maxTraceEntries:2e3,maxTraceEvents:2e3,maxReportFields:2e3,maxStackFrames:2e3,maxSteps:2e3,maxStdioChunks:2e3,maxStdioBytes:64e6,maxTraceExpandedBytes:64e6,maxConsoleEvents:100,maxNetworkEvents:200,includeNetworkBodies:!1,maxNetworkBodyBytes:0,maxDomDepth:6,maxDomNodes:200,maxDomTextBytes:16e3,maxSourceFiles:12,maxSourceBytes:128e3,maxSourceLinesPerFile:200,maxImportDepth:2,maxDiffBytes:128e3,maxDiffHunks:30,sensitiveNames:["authorization","cookie","set-cookie","password","passwd","secret","token","api-key","apikey"]},Rx=["maxPacketBytes","maxArtifactBytes","maxTraceEntries","maxTraceEvents","maxReportFields","maxStackFrames","maxSteps","maxStdioChunks","maxStdioBytes","maxTraceExpandedBytes","maxConsoleEvents","maxNetworkEvents","maxDomDepth","maxDomNodes","maxDomTextBytes","maxSourceFiles","maxSourceBytes","maxSourceLinesPerFile","maxImportDepth","maxDiffBytes","maxDiffHunks"];function $o(r){if(r===null||typeof r!="object")return"policy must be an object";if(typeof r.policyVersion!="string")return"policyVersion must be a string";if(r.policyVersion.length===0)return"policyVersion must not be empty";if(typeof r.workspaceRoot!="string")return"workspaceRoot must be a string";if(r.workspaceRoot.length===0)return"workspaceRoot must not be empty";if(typeof r.includeNetworkBodies!="boolean")return"includeNetworkBodies must be a boolean";if(!Array.isArray(r.sensitiveNames)||r.sensitiveNames.some(t=>typeof t!="string"||t.length===0))return"sensitiveNames must be an array of non-empty strings";if(r.sensitiveNames.some(t=>t.trim()!==t))return"sensitiveNames must not contain surrounding whitespace";for(let t of Rx){let e=r[t];if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)return`${t} must be a positive safe integer`}if(!Number.isSafeInteger(r.maxNetworkBodyBytes)||r.maxNetworkBodyBytes<0||r.includeNetworkBodies&&r.maxNetworkBodyBytes===0)return"maxNetworkBodyBytes must be positive when network bodies are enabled"}var Tx={button:"button",nav:"navigation",main:"main",header:"banner",footer:"contentinfo",form:"form",table:"table",img:"img",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",ul:"list",ol:"list",li:"listitem",section:"region",article:"article",dialog:"dialog",select:"combobox",textarea:"textbox"},Ax={button:"button",submit:"button",reset:"button",checkbox:"checkbox",radio:"radio",range:"slider",text:"textbox",search:"searchbox",email:"textbox",tel:"textbox",url:"textbox",password:"textbox"},Sx=new Set(["script","style","head","title","meta","link"]);function $e(r){let t=r[0];return typeof t=="string"?t.toLowerCase():void 0}function De(r){let t=r[1];if(typeof t!="object"||t===null||Array.isArray(t))return{};let e={};for(let[n,i]of Object.entries(t))typeof i=="string"&&(e[n.toLowerCase()]=i);return e}function Le(r){let t=typeof r[1]=="object"&&r[1]!==null&&!Array.isArray(r[1]);return r.slice(t?2:1)}function wt(r,t=0){let e=$e(r);if(e===void 0||Sx.has(e)||t>12)return"";let n=[];for(let i of Le(r))typeof i=="string"?n.push(i):Array.isArray(i)&&n.push(wt(i,t+1));return n.join(" ").replace(/\s+/g," ").trim()}function Xt(r){let t=De(r),e=t.role;if(e!==void 0&&e.length>0)return e.toLowerCase();let n=$e(r);if(n!==void 0)return n==="a"?t.href===void 0?void 0:"link":n==="input"?Ax[(t.type??"text").toLowerCase()]:Tx[n]}function Xi(r){let t=De(r),e=t["aria-label"]??t.alt??t.title;return e!==void 0&&e.trim().length>0?e.trim():wt(r)}function tp(r){return r.replace(/\s+/g," ").trim()}function Wi(r,t,e){let n=tp(r),i=tp(t);return e?n===i:n.toLowerCase().includes(i.toLowerCase())}var Ex=new Set(["input","textarea","select"]);function np(r){let t=[];for(let e of Le(r))if(typeof e=="string")t.push(e);else if(Array.isArray(e)){let n=$e(e);if(n!==void 0&&Ex.has(n))continue;t.push(wt(e))}return t.join(" ").replace(/\s+/g," ").trim()}function Cx(r,t){let e,n=i=>{if(e===void 0){if($e(i)==="label"&&De(i).for===t){e=np(i);return}for(let s of Le(i))Array.isArray(s)&&n(s)}};return n(r),e}function rp(r,t){let e=De(r),n=[];for(let s of["aria-label","placeholder","title"]){let a=e[s];a!==void 0&&a.trim().length>0&&n.push(a.trim())}for(let s=t.path.length-1;s>=0;s-=1){let a=sp(t.root,t.path.slice(0,s));if(a===void 0)break;if($e(a)==="label"){n.push(np(a));break}}let i=e.id;if(i!==void 0){let s=Cx(t.root,i);s!==void 0&&n.push(s)}return n}var Nx=`"((?:[^"\\\\]|\\\\.)*)"|'((?:[^'\\\\]|\\\\.)*)'`;function Ox(r){return r.replace(/\\(.)/g,"$1")}function Ji(r){let t=new RegExp(`^(?:${Nx})([is])?$`).exec(r.trim());if(t===null)return;let e=t[1]??t[2];if(e!==void 0)return{value:Ox(e),caseSensitive:t[3]!=="i"}}function Dx(r){let t=/^\[\s*([\w:-]+)\s*=\s*(.+?)\s*\]$/.exec(r.trim());if(t===null)return;let e=t[1]?.toLowerCase(),n=Ji(t[2]??"");if(!(e===void 0||n===void 0))return{describe:`[${e}]`,matches:i=>{let s=De(i)[e];return s!==void 0&&Wi(s,n.value,n.caseSensitive)}}}function Lx(r,t){if(r==="role"){let e=/^([\w-]+)(?:\[(.*)\])?$/.exec(t.trim()),n=e?.[1]?.toLowerCase();if(n===void 0)return;let i=e?.[2];if(i===void 0||i.trim()==="")return{describe:`role=${n}`,matches:o=>Xt(o)===n};let s=/^name\s*=\s*(.+)$/.exec(i.trim()),a=s===null?void 0:Ji(s[1]??"");return a===void 0?void 0:{describe:`role=${n}[name]`,matches:(o,d)=>Xt(o)===n&&[Xi(o),...rp(o,d)].some(c=>Wi(c,a.value,a.caseSensitive))}}if(r==="label"){let e=Ji(t);return e===void 0?void 0:{describe:"label",matches:(n,i)=>rp(n,i).some(s=>Wi(s,e.value,e.caseSensitive))}}if(r==="text"){let e=Ji(t);if(e===void 0)return;let n=i=>Wi(wt(i),e.value,e.caseSensitive);return{describe:"text",matches:i=>n(i)&&!Le(i).some(s=>Array.isArray(s)&&n(s))}}if(r==="testid"||r==="attr")return Dx(t)}function Mx(r){let t=r.match(/^[A-Za-z][\w-]*|#[\w-]+|\.[\w-]+|\[[^\]]*\]/g);if(t===null||t.join("")!==r)return;let e=[];for(let n of t)if(n.startsWith("#")){let i=n.slice(1);e.push(s=>De(s).id===i)}else if(n.startsWith(".")){let i=n.slice(1);e.push(s=>(De(s).class??"").split(/\s+/).includes(i))}else if(n.startsWith("[")){let i=/^\[\s*([\w:-]+)\s*(?:=\s*["']?([^"'\]]*)["']?)?\s*\]$/.exec(n),s=i?.[1]?.toLowerCase();if(s===void 0)return;let a=i?.[2];e.push(o=>{let d=De(o)[s];return d===void 0?!1:a===void 0||a===""?!0:d===a})}else{let i=n.toLowerCase();e.push(s=>$e(s)===i)}return{describe:r,matches:n=>e.every(i=>i(n))}}function $x(r){let t=r.trim(),e=/^internal:([\w-]+)=([\s\S]+)$/.exec(t);if(e!==null)return Lx(e[1]??"",e[2]??"");let n=/^role=([\w-]+)$/.exec(t);if(n!==null){let i=n[1]?.toLowerCase();return i===void 0?void 0:{describe:t,matches:s=>Xt(s)===i}}return Mx(t)}function _x(r){let t=[],e="",n;for(let i=0;i<r.length;i+=1){let s=r[i];if(s!==void 0){if(n!==void 0){if(s==="\\"){e+=s+(r[i+1]??""),i+=1;continue}s===n&&(n=void 0),e+=s;continue}if(s==='"'||s==="'"){n=s,e+=s;continue}if(s===">"&&r[i+1]===">"){t.push(e),e="",i+=1;continue}e+=s}}return t.push(e),t.map(i=>i.trim()).filter(i=>i.length>0)}function Fx(r){if(/^(?:internal:|role=)/.test(r))return[r];let t=[],e="",n=0,i;for(let s of r){if(i!==void 0){s===i&&(i=void 0),e+=s;continue}if((s==='"'||s==="'")&&(i=s),(s==="["||s==="(")&&(n+=1),(s==="]"||s===")")&&(n=Math.max(0,n-1)),n===0&&(s===" "||s===">")){e.trim()!==""&&t.push(e.trim()),e="";continue}e+=s}return e.trim()!==""&&t.push(e.trim()),t.length===0?[r]:t}function ip(r,t){let e=[{node:r,path:t}];return Le(r).forEach((n,i)=>{Array.isArray(n)&&e.push(...ip(n,[...t,i]))}),e}function sp(r,t){let e=r;for(let n of t){let i=Le(e)[n];if(!Array.isArray(i))return;e=i}return e}function Tn(r,t){if(!Array.isArray(r))return{kind:"unsupported",reason:"snapshot root is not an element"};let e=_x(t).flatMap(Fx);if(e.length===0)return{kind:"unsupported",reason:"empty selector"};let n=[{node:r,path:[]}];for(let i of e){if(i===".."){let o=new Map;for(let d of n){if(d.path.length===0)continue;let c=d.path.slice(0,-1),l=sp(r,c);l!==void 0&&o.set(c.join("."),{node:l,path:c})}n=[...o.values()];continue}let s=$x(i);if(s===void 0)return{kind:"unsupported",reason:i};let a=new Map;for(let o of n)for(let d of ip(o.node,o.path))s.matches(d.node,{root:r,path:d.path})&&a.set(d.path.join("."),d);if(n=[...a.values()],n.length===0)break}return{kind:"resolved",matches:n}}var jx=/\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001B]*(?:\u0007|\u001B\\))/g;function ut(r){return r.replace(jx,"")}function ae(r,t,e,n){let i=ut(r),s=[];for(let a of[...new Set(n.map(o=>o.toLowerCase()))].sort()){let o=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),d=new RegExp(`(["']?${o}["']?\\s*[:=]\\s*)(?:"[^"\\r\\n]*"|'[^'\\r\\n]*'|[^,;&}\\r\\n]*?(?=\\s+(?:and\\s+)?[A-Za-z_$][\\w$.-]*\\s*[:=]|\\s*$|[,;&}]))`,"gim"),c=0;if(i=i.replace(d,(l,u)=>(c+=1,`${u}[REDACTED]`)),c===0){let l=new RegExp(`(${o}\\s*[:=]\\s*)\\S+`,"gi");i=i.replace(l,(u,p)=>(c+=1,`${p}[REDACTED]`))}c>0&&s.push({redactionId:$("red",[t,e,a]),ruleId:`sensitive-name:${a}`,channel:t,locator:e,action:"mask",count:c})}return{value:i,records:s}}function An(r,t){let e=r.toLowerCase();return t.map(n=>n.toLowerCase()).sort().find(n=>e===n||e.includes(n))}function Yi(r,t,e,n){let i=[],s=new Map;for(let o of r){let d=An(o.name,n);if(d===void 0){i.push(o);continue}s.set(d,(s.get(d)??0)+1)}let a=[...s.entries()].sort(([o],[d])=>o.localeCompare(d)).map(([o,d])=>({redactionId:$("red",[t,e,`header:${o}`]),ruleId:`sensitive-header:${o}`,channel:t,locator:e,action:"remove",count:d}));return{value:i,records:a}}function Nt(r,t,e,n){let i;try{i=new URL(r)}catch{return ae(r,t,e,n)}let s=[];(i.username!==""||i.password!=="")&&(i.username="",i.password="",s.push({redactionId:$("red",[t,e,"url-userinfo"]),ruleId:"url-userinfo",channel:t,locator:e,action:"remove",count:1}));let a=new Map;for(let o of[...i.searchParams.keys()]){let d=An(o,n);d!==void 0&&(i.searchParams.set(o,"[REDACTED]"),a.set(d,(a.get(d)??0)+1))}for(let[o,d]of[...a.entries()].sort(([c],[l])=>c.localeCompare(l)))s.push({redactionId:$("red",[t,e,`query:${o}`]),ruleId:`sensitive-query:${o}`,channel:t,locator:e,action:"mask",count:d});return{value:i.toString(),records:s}}var Bx=new Set(["value","data-value","content","__playwright_value_","__playwright_checked_","__playwright_selected_"]),ap=["type","name","id","autocomplete","placeholder","aria-label"];function _o(r,t,e,n){if(r==="")return{value:r,records:[]};let i=t.filter(s=>ap.includes(s.name.toLowerCase())).map(s=>An(s.value,n)).find(s=>s!==void 0);return i===void 0?{value:r,records:[]}:{value:"[REDACTED]",records:[{redactionId:$("red",["dom",e,`text:${i}`]),ruleId:`sensitive-element-text:${i}`,channel:"dom",locator:e,action:"mask",count:1}]}}function Fo(r,t,e){let n=r.filter(o=>ap.includes(o.name.toLowerCase())).map(o=>An(o.value,e)).find(o=>o!==void 0),i=[],s=new Map;for(let o of r){let d=An(o.name,e),c=n!==void 0&&Bx.has(o.name.toLowerCase())?n:void 0,l=d??c;if(l===void 0||o.value===""){i.push(o);continue}i.push({name:o.name,value:"[REDACTED]"});let u=d===void 0?`sensitive-element:${l}`:`sensitive-field:${l}`;s.set(u,(s.get(u)??0)+1)}let a=[...s.entries()].sort(([o],[d])=>o.localeCompare(d)).map(([o,d])=>({redactionId:$("red",["dom",t,o]),ruleId:o,channel:"dom",locator:t,action:"mask",count:d}));return{value:i,records:a}}function Vx(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function _(r){return typeof r=="string"?r:void 0}function ke(r){return typeof r=="number"&&Number.isFinite(r)?r:void 0}function op(r){return typeof r=="boolean"?r:void 0}function pe(r){return Vx(r)?r:void 0}function He(r){return Array.isArray(r)?r:void 0}function _e(r){try{return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}function Qi(r){let t=[];return r.split(/\r?\n/).forEach((e,n)=>{let i=e.trim();if(i.length!==0)try{t.push({line:n+1,value:JSON.parse(i),parsed:!0})}catch{t.push({line:n+1,value:void 0,parsed:!1})}}),t}function ge(r,t){let e;try{e=typeof r=="string"?r:JSON.stringify(r)??""}catch{return"[unserializable]"}let n=ut(e).replace(/\s+/g," ").trim(),i=Buffer.from(n,"utf8");if(i.byteLength<=t)return n;let s=t;for(;s>0&&((i[s]??0)&192)===128;)s-=1;return`${i.subarray(0,s).toString("utf8")}\u2026`}var cp=new Set(["script","style","noscript","template","head"]),dp=120,zx=200,Hx={__playwright_value_:"value",__playwright_checked_:"checked",__playwright_selected_:"selected"},qx=new Set(["button","link","textbox","searchbox","checkbox","radio","combobox","listbox","option","menuitem","tab","switch","slider","spinbutton","heading","dialog","img","cell","row"]),lp=["data-testid","data-test-id","data-test","data-qa","data-cy"],Ux=new Set(["internal","role","testid","data","name","text","label","attr","has","nth","visible","true","false","exact","css","xpath","and","the"]);function Gx(r){let t=[];for(let[e,n]of Object.entries(De(r))){let i=Hx[e];if(i!==void 0){t.push({name:i,value:ge(n,dp)});continue}e.startsWith("__playwright")||/^on[a-z]+$/.test(e)||t.push({name:e,value:ge(n,dp)})}return t.sort((e,n)=>e.name.localeCompare(n.name))}function up(r,t){let e,n=(i,s)=>{if(e===void 0){if(De(i).__playwright_target__===t){e={node:i,path:s};return}Le(i).forEach((a,o)=>{Array.isArray(a)&&n(a,[...s,o])})}};return n(r,[]),e}function Kx(r){return Le(r).filter(t=>typeof t=="string").join(" ").replace(/\s+/g," ").trim()}function Sn(r,t,e){let n=[],i=[],s=0,a=0,o=!1,d=(c,l)=>{if(o)return;let u=$e(c);if(u===void 0||cp.has(u))return;if(l>e.maxDepth||a>=e.maxNodes){o=!0;return}let p=`${t}/${a}`,f=Gx(c),h=Fo(f,p,e.sensitiveNames),g=_o(ge(Kx(c),zx),f,p,e.sensitiveNames);i.push(...h.records,...g.records);let m=h.value.map(x=>` ${x.name}="${x.value}"`).join(""),y=`${" ".repeat(l)}<${u}${m}>${g.value===""?"":` ${g.value}`}`,w=Buffer.byteLength(y,"utf8")+1;if(s+w>e.maxBytes){o=!0;return}n.push(y),s+=w,a+=1;for(let x of Le(c))Array.isArray(x)&&d(x,l+1)};return d(r,0),{text:n.join(`
15
- `),redactions:i,nodes:a,truncated:o}}function En(r,t=[],e){let n=De(r),i=Xt(r),s=Xi(r),a=ge(s===""&&e!==void 0?e:s,80),o=[i===void 0?`<${$e(r)??"?"}>`:i];a!==""&&o.push(JSON.stringify(a));for(let c of[...new Set([...t,...lp,"id","name"])]){let l=n[c];l!==void 0&&l!==""&&o.push(`${c}=${ge(l,60)}`)}let d=n.placeholder;return d!==void 0&&d!==""&&o.push(`placeholder=${JSON.stringify(ge(d,60))}`),o.join(" ")}function Er(r){let t=r.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(e=>e.length>=3&&!Ux.has(e));return[...new Set(t)]}function Wx(r){return/(?:^|>>\s*)(?:internal:)?role=([\w-]+)/.exec(r)?.[1]?.toLowerCase()}function Jx(r){return[...r.matchAll(/\[\s*([\w:-]+)\s*=/g)].map(t=>t[1]?.toLowerCase()).filter(t=>t!==void 0&&t!=="name")}function Zi(r,t,e,n,i,s){let a=Er(t),o=Wx(t),d=Jx(t),c=new Set(e.map(v=>v.path.join("."))),l=[],u=0,p=new Map,f=v=>{if($e(v)==="label"){let I=De(v).for;I!==void 0&&p.set(I,wt(v))}for(let I of Le(v))Array.isArray(I)&&f(I)};f(r);let h=(v,I,R)=>{let E=$e(v);if(E===void 0||cp.has(E))return;let A=De(v),N=(A.id===void 0?void 0:p.get(A.id))??R,B=Xt(v),V=d.some(O=>A[O]!==void 0)||lp.some(O=>A[O]!==void 0);if(B!==void 0&&qx.has(B)||V){let O=En(v,d,N),M=`${O} ${ge(wt(v),200)}`.toLowerCase(),H=c.has(I.join(".")),k=(H?100:0)+(o!==void 0&&B===o?2:0)+a.filter(T=>M.includes(T)).length*3;l.push({line:`${H?"match: ":""}${O}`,score:k,order:u++})}let P=E==="label"?wt(v):R;Le(v).forEach((O,M)=>{Array.isArray(O)&&h(O,[...I,M],P)})};h(r,[],void 0);let g=[...l].sort((v,I)=>I.score-v.score||v.order-I.order),m=[],y=[],w=0,x=g.length>i.maxItems;for(let v of g.slice(0,i.maxItems)){let I=ae(v.line,"dom",n,s),R=Buffer.byteLength(I.value,"utf8")+1;if(w+R>i.maxBytes){x=!0;break}y.push(...I.records),m.push(I.value),w+=R}return{text:m.join(`
16
- `),redactions:y,nodes:m.length,truncated:x}}import{open as Zx}from"node:fs/promises";import{realpath as pp,stat as Xx}from"node:fs/promises";import{isAbsolute as mp,relative as Yx,resolve as Qx,sep as fp}from"node:path";function hp(r,t){let e=Yx(r,t);if(e==="")return"";if(!(e===".."||e.startsWith(`..${fp}`)||mp(e)))return e.split(fp).join("/")}async function Cn(r,t){if(t.includes("\0"))return{kind:"unauthorized",message:"Path contains a NUL byte."};let e;try{e=await pp(r)}catch{return{kind:"unreadable",message:"Authorized root could not be resolved."}}let n=mp(t)?t:Qx(e,t);if(hp(e,n)===void 0)return{kind:"unauthorized",message:"Path escapes the authorized root."};let i;try{i=await pp(n)}catch(a){return a.code==="ENOENT"?{kind:"unavailable",message:"Authorized artifact does not exist."}:{kind:"unreadable",message:"Authorized artifact could not be resolved."}}let s=hp(e,i);if(s===void 0)return{kind:"unauthorized",message:"Resolved path escapes the authorized root."};try{if(!(await Xx(i)).isFile())return{kind:"unreadable",message:"Authorized artifact is not a regular file."}}catch{return{kind:"unreadable",message:"Authorized artifact could not be inspected."}}return{kind:"authorized",absolutePath:i,relativePath:s}}function jo(r){return r.length===0||r.includes("\0")||r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/.test(r)?!1:r.split("/").every(e=>e!==".."&&e!==".")}async function K(r,t,e){let n=await Cn(r,t);if(n.kind!=="authorized")return n;let i;try{i=await Zx(n.absolutePath,"r");let s=await i.stat();if(s.size>e)return{kind:"over-budget",message:`Artifact exceeds the ${e}-byte limit.`,relativePath:n.relativePath};let a=new Uint8Array(s.size),o=0;for(;o<a.byteLength;){let d=await i.read(a,o,a.byteLength-o,o);if(d.bytesRead===0)break;o+=d.bytesRead}return o!==a.byteLength?{kind:"unreadable",message:"Artifact changed or ended while it was being read.",relativePath:n.relativePath}:{kind:"read",bytes:a,sha256:Te(a),relativePath:n.relativePath}}catch{return{kind:"unreadable",message:"Authorized artifact could not be read.",relativePath:n.relativePath}}finally{await i?.close()}}import{createRequire as ev}from"module";var tv=ev("/"),Dr,rv,nv;try{Dr=tv("worker_threads"),rv=Dr.Worker,nv=Dr.isMarkedAsUntransferable}catch{}var Ee=Uint8Array,Cr=Uint16Array,iv=Int32Array,yp=new Ee([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),gp=new Ee([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),sv=new Ee([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),wp=function(r,t){for(var e=new Cr(31),n=0;n<31;++n)e[n]=t+=1<<r[n-1];for(var i=new iv(e[30]),n=1;n<30;++n)for(var s=e[n];s<e[n+1];++s)i[s]=s-e[n]<<5|n;return{b:e,r:i}},Dr=wp(yp,2),bp=Dr.b,av=Dr.r;bp[28]=258,av[258]=28;var xp=wp(gp,0),ov=xp.b,WC=xp.r,Ho=new Cr(32768);for(re=0;re<32768;++re)bt=(re&43690)>>1|(re&21845)<<1,bt=(bt&52428)>>2|(bt&13107)<<2,bt=(bt&61680)>>4|(bt&3855)<<4,Ho[re]=((bt&65280)>>8|(bt&255)<<8)>>1;var bt,re,On=(function(r,t,e){for(var n=r.length,i=0,s=new Cr(t);i<n;++i)r[i]&&++s[r[i]-1];var a=new Cr(t);for(i=1;i<t;++i)a[i]=a[i-1]+s[i-1]<<1;var o;if(e){o=new Cr(1<<t);var d=15-t;for(i=0;i<n;++i)if(r[i])for(var c=i<<4|r[i],l=t-r[i],u=a[r[i]-1]++<<l,p=u|(1<<l)-1;u<=p;++u)o[Ho[u]>>d]=c}else for(o=new Cr(n),i=0;i<n;++i)r[i]&&(o[i]=Ho[a[r[i]-1]++]>>15-r[i]);return o}),Ln=new Ee(288);for(re=0;re<144;++re)Ln[re]=8;var re;for(re=144;re<256;++re)Ln[re]=9;var re;for(re=256;re<280;++re)Ln[re]=7;var re;for(re=280;re<288;++re)Ln[re]=8;var re,vp=new Ee(32);for(re=0;re<32;++re)vp[re]=5;var re;var dv=On(Ln,9,1);var cv=On(vp,5,1),Bo=function(r){for(var t=r[0],e=1;e<r.length;++e)r[e]>t&&(t=r[e]);return t},tt=function(r,t,e){var n=t/8|0;return(r[n]|r[n+1]<<8)>>(t&7)&e},Vo=function(r,t){var e=t/8|0;return(r[e]|r[e+1]<<8|r[e+2]<<16)>>(t&7)},lv=function(r){return(r+7)/8|0},Dn=function(r,t,e){return(t==null||t<0)&&(t=0),(e==null||e>r.length)&&(e=r.length),new Ee(r.subarray(t,e))};var uv=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ie=function(r,t,e){var n=new Error(t||uv[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,Ie),!e)throw n;return n},pv=function(r,t,e,n){var i=r.length,s=n?n.length:0;if(!i||t.f&&!t.l)return e||new Ee(0);var a=!e,o=a||t.i!=2,d=t.i;a&&(e=new Ee(i*3));var c=function(an){var on=e.length;if(an>on){var dn=new Ee(Math.max(on*2,an));dn.set(e),e=dn}},l=t.f||0,u=t.p||0,p=t.b||0,f=t.l,h=t.d,g=t.m,m=t.n,y=i*8;do{if(!f){l=tt(r,u,1);var w=tt(r,u+1,3);if(u+=3,w)if(w==1)f=dv,h=cv,g=9,m=5;else if(w==2){var R=tt(r,u,31)+257,E=tt(r,u+10,15)+4,A=R+tt(r,u+5,31)+1;u+=14;for(var N=new Ee(A),B=new Ee(19),V=0;V<E;++V)B[sv[V]]=tt(r,u+V*3,7);u+=E*3;for(var P=Bo(B),O=(1<<P)-1,M=On(B,P,1),V=0;V<A;){var H=M[tt(r,u,O)];u+=H&15;var x=H>>4;if(x<16)N[V++]=x;else{var k=0,T=0;for(x==16?(T=3+tt(r,u,3),u+=2,k=N[V-1]):x==17?(T=3+tt(r,u,7),u+=3):x==18&&(T=11+tt(r,u,127),u+=7);T--;)N[V++]=k}}var L=N.subarray(0,R),j=N.subarray(R);g=Bo(L),m=Bo(j),f=On(L,g,1),h=On(j,m,1)}else Ie(1);else{var x=lv(u)+4,v=r[x-4]|r[x-3]<<8,I=x+v;if(I>i){d&&Ie(0);break}o&&c(p+v),e.set(r.subarray(x,I),p),t.b=p+=v,t.p=u=I*8,t.f=l;continue}if(u>y){d&&Ie(0);break}}o&&c(p+131072);for(var se=(1<<g)-1,fe=(1<<m)-1,ue=u;;ue=u){var k=f[Vo(r,u)&se],Y=k>>4;if(u+=k&15,u>y){d&&Ie(0);break}if(k||Ie(2),Y<256)e[p++]=Y;else if(Y==256){ue=u,f=null;break}else{var ve=Y-254;if(Y>264){var V=Y-257,Re=yp[V];ve=tt(r,u,(1<<Re)-1)+bp[V],u+=Re}var mt=h[Vo(r,u)&fe],At=mt>>4;mt||Ie(3),u+=mt&15;var j=ov[At];if(At>3){var Re=gp[At];j+=Vo(r,u)&(1<<Re)-1,u+=Re}if(u>y){d&&Ie(0);break}o&&c(p+131072);var nn=p+ve;if(p<j){var sn=s-j,wi=Math.min(j,nn);for(sn+p<0&&Ie(3);p<wi;++p)e[p]=n[sn+p]}for(;p<nn;++p)e[p]=e[p-j]}}t.l=f,t.p=ue,t.b=p,t.f=l,f&&(l=1,t.m=g,t.d=h,t.n=m)}while(!l);return p!=e.length&&a?Dn(e,0,p):e.subarray(0,p)};var Nn=new Ee(0);var Nr=function(r,t){return r[t]|r[t+1]<<8},Or=function(r,t){return(r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24)>>>0},zo=function(r,t){return Or(r,t)+Or(r,t+4)*4294967296};var fv=(function(){function r(t,e){typeof t=="function"&&(e=t,t={}),this.ondata=e;var n=t&&t.dictionary&&t.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new Ee(32768),this.p=new Ee(0),n&&this.o.set(n)}return r.prototype.e=function(t){if(this.ondata||Ie(5),this.d&&Ie(4),!this.p.length)this.p=t;else if(t.length){var e=new Ee(this.p.length+t.length);e.set(this.p),e.set(t,this.p.length),this.p=e}},r.prototype.c=function(t){this.s.i=+(this.d=t||!1);var e=this.s.b,n=pv(this.p,this.s,this.o);this.ondata(Dn(n,e,this.s.b),this.d),this.o=Dn(n,this.s.b-32768),this.s.b=this.o.length,this.p=Dn(this.p,this.s.p/8|0),this.s.p&=7},r.prototype.push=function(t,e){this.e(t),this.c(e)},r})();var qo=typeof TextDecoder<"u"&&new TextDecoder,hv=0;try{qo.decode(Nn,{stream:!0}),hv=1}catch{}var mv=function(r){for(var t="",e=0;;){var n=r[e++],i=(n>127)+(n>223)+(n>239);if(e+i>r.length)return{s:t,r:Dn(r,e-1)};i?i==3?(n=((n&15)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,t+=String.fromCharCode(55296|n>>10,56320|n&1023)):i&1?t+=String.fromCharCode((n&31)<<6|r[e++]&63):t+=String.fromCharCode((n&15)<<12|(r[e++]&63)<<6|r[e++]&63):t+=String.fromCharCode(n)}};function yv(r,t){if(t){for(var e="",n=0;n<r.length;n+=16384)e+=String.fromCharCode.apply(null,r.subarray(n,n+16384));return e}else{if(qo)return qo.decode(r);var i=mv(r),s=i.s,e=i.r;return e.length&&Ie(8),s}}var gv=function(r,t,e,n,i,s,a){var o=i==4294967295,d=s==4294967295,c=a==4294967295,l=t+e,u=o+d+c;if(n&&u){for(;t+4<l;t+=4+Nr(r,t+2))if(Nr(r,t)==1)return[o?zo(r,t+4+8*d):i,d?zo(r,t+4):s,c?zo(r,t+4+8*(d+o)):a,1];n<2&&Ie(13)}return[i,s,a,0]};var wv=(function(){function r(){}return r.prototype.push=function(t,e){this.ondata(null,t,e)},r.compression=0,r})();var kp=(function(){function r(){var t=this;this.i=new fv(function(e,n){t.ondata(null,e,n)})}return r.prototype.push=function(t,e){try{this.i.push(t,e)}catch(n){this.ondata(n,null,e)}},r.compression=8,r})();var Ip=(function(){function r(t){this.onfile=t,this.k=[],this.o={0:wv},this.p=Nn}return r.prototype.push=function(t,e){var n=this;if(this.onfile||Ie(5),this.p||Ie(4),this.c>0){var i=Math.min(this.c,t.length),s=t.subarray(0,i);if(this.c-=i,this.d?this.d.push(s,!this.c):this.k[0].push(s),t=t.subarray(i),t.length)return this.push(t,e)}else{var a=0,o=0,d=void 0,c=void 0;this.p.length?t.length?(c=new Ee(this.p.length+t.length),c.set(this.p),c.set(t,this.p.length)):c=this.p:c=t;for(var l=c.length,u=this.c,p=u&&this.d,f=function(){var y=Or(c,o);if(y==67324752){a=1,d=o,h.d=null,h.c=0;var w=Nr(c,o+6),x=Nr(c,o+8),v=w&2048,I=w&8,R=Nr(c,o+26),E=Nr(c,o+28);if(l>o+30+R+E){var A=[];h.k.unshift(A),a=2;var N=Or(c,o+18),B=Or(c,o+22),V=yv(c.subarray(o+30,o+=30+R),!v),P=gv(c,o,E,2,N,B,0),O=P[0],M=P[1],H=P[3];I&&(O=-1-H),o+=E,h.c=O;var k,T={name:V,compression:x,start:function(){if(T.ondata||Ie(5),!O)T.ondata(null,Nn,!0);else{var L=n.o[x];L||T.ondata(Ie(14,"unknown compression type "+x,1),null,!1),k=O<0?new L(V):new L(V,O,M),k.ondata=function(ue,Y,ve){T.ondata(ue,Y,ve)};for(var j=0,se=A;j<se.length;j++){var fe=se[j];k.push(fe,!1)}n.k[0]==A&&n.c?n.d=k:k.push(Nn,!0)}},terminate:function(){k&&k.terminate&&k.terminate()}};O>=0&&(T.size=O,T.originalSize=M),h.onfile(T)}return"break"}else if(u){if(y==134695760)return d=o+=12+(u==-2&&8),a=3,h.c=0,"break";if(y==33639248)return d=o-=4,a=3,h.c=0,"break"}},h=this;o<l-4;++o){var g=f();if(g==="break")break}if(this.p=Nn,u<0){var m=a?c.subarray(0,d-12-(u==-2&&8)-(Or(c,d-16)==134695760&&4)):c.subarray(0,o);p?p.push(m,!!a):this.k[+(a==2)].push(m)}if(a&2)return this.push(c.subarray(o),e);this.p=c.subarray(o)}e&&(this.c&&Ie(13),this.p=null)},r.prototype.register=function(t){this.o[t.compression]=t},r})();var Pp=65536;function bv(r,t){let e=new Uint8Array(t),n=0;for(let i of r)e.set(i,n),n+=i.length;return e}function es(r,t,e){if(r.byteLength===0)return{kind:"unreadable",message:"Archive is empty."};if(r[0]!==80||r[1]!==75)return{kind:"unreadable",message:"Archive does not begin with a ZIP signature."};let n=new Map,i=[],s=0,a=0,o,d=new Set,c=new Ip;c.register(kp),c.onfile=l=>{let u=l.name,p=typeof l.originalSize=="number"&&l.originalSize>0,f=l.originalSize??0;if(!jo(u)){i.push({entry:u,reason:"unsafe-entry-name",declaredBytes:f});return}if(!e(u))return;if(d.has(u)){i.push({entry:u,reason:"duplicate-selected-name",declaredBytes:f});return}if(s>=t.maxEntries){i.push({entry:u,reason:"entry-budget-exceeded",declaredBytes:f});return}let h=t.maxExpandedBytes-a;if(p&&f>h){i.push({entry:u,reason:"expanded-budget-exceeded",declaredBytes:f});return}s+=1,d.add(u);let g=[],m=0,y=!1;l.ondata=(w,x,v)=>{if(o!==void 0||y)return;if(w!==null){o=`Archive entry ${u} could not be inflated.`;return}m+=x.length;let I=p&&m>f;if(I||m>h){y=!0,g.length=0,i.push({entry:u,reason:I?"declared-size-mismatch":"expanded-budget-exceeded",declaredBytes:f});return}if(g.push(x.slice()),v){if(p&&m!==f){g.length=0,y=!0,i.push({entry:u,reason:"declared-size-mismatch",declaredBytes:f});return}a+=m,n.set(u,bv(g,m))}},l.start()};try{for(let l=0;l<r.byteLength;l+=Pp){let u=Math.min(l+Pp,r.byteLength);if(c.push(r.subarray(l,u),u===r.byteLength),o!==void 0)break}}catch{return{kind:"unreadable",message:"Archive could not be read as a ZIP container."}}return o!==void 0?{kind:"unreadable",message:o}:{kind:"read",contents:{entries:n,skipped:i}}}var Rp=256,Tp={before:"before",action:"action",input:"action",after:"after"};function Uo(r){return Array.isArray(r)&&typeof r[0]=="string"}function xv(r){return Array.isArray(r)&&Array.isArray(r[0])&&typeof r[0][0]=="number"&&typeof r[0][1]=="number"}function Ap(r){let t=r[1],e=typeof t=="object"&&t!==null&&!Array.isArray(t);return r.slice(e?2:1)}function vv(r){let t=_(r.snapshotName),e=_(r.callId),n=Tp[_(r.phase)??""];if(t!==void 0){let i=t.indexOf("@");i>0&&(n??=Tp[t.slice(0,i)],e??=t.slice(i+1))}return{...e===void 0?{}:{callId:e},...n===void 0?{}:{phase:n},...t===void 0?{}:{name:t}}}var ts=class{frames=new Map;literals=new Map;byCall=new Map;add(t,e,n){let i=pe(n.snapshot);if(i===void 0||i.html===void 0)return;let s=vv(i),a=_(i.frameId)??_(i.pageId)??"unknown-frame",o=`${t}
17
- ${a}`,d=this.frames.get(o)??[],c=_(i.frameUrl),l={entry:t,line:e,frameId:a,index:d.length,snapshotId:s.name??(s.callId===void 0?`${t}#line=${e}`:`${s.phase??"snapshot"}@${s.callId}`),...s.callId===void 0?{}:{callId:s.callId},...s.phase===void 0?{}:{phase:s.phase},...c===void 0?{}:{frameUrl:c},isMainFrame:op(i.isMainFrame)??!0,html:i.html};if(d.push(l),this.frames.set(o,d),l.callId!==void 0){let u=this.byCall.get(l.callId)??[];u.push(l),this.byCall.set(l.callId,u)}return l}forCall(t){return this.byCall.get(t)??[]}get size(){let t=0;for(let e of this.frames.values())t+=e.length;return t}literalNodes(t){let e=this.literals.get(t);if(e!==void 0)return e;let n=[],i=(s,a)=>{if(typeof s=="string"){n.push(s);return}if(!(!Uo(s)||a>Rp)){for(let o of Ap(s))i(o,a+1);n.push(s)}};return i(t.html,0),this.literals.set(t,n),n}rebuild(t,e){let n=this.frames.get(`${t.entry}
18
- ${t.frameId}`)??[],i=0,s=!1,a=(d,c,l)=>{if(i>=e||l>Rp){s=!0;return}if(typeof d=="string")return i+=1,d;if(xv(d)){let[h,g]=d[0],m=c-h,y=n[m];if(h<1||y===void 0)return;let w=this.literalNodes(y)[g];return w===void 0?void 0:a(w,m,l)}if(!Uo(d))return;i+=1;let u=d[1],p=typeof u=="object"&&u!==null&&!Array.isArray(u)?u:{},f=[];for(let h of Ap(d)){let g=a(h,c,l+1);g!==void 0&&f.push(g)}return[d[0],p,...f]},o=a(t.html,t.index,0);return{...Uo(o)?{root:o}:{},truncated:s,nodes:i}}};var Yt=["trace","console","network","dom","accessibility"],Go=/(?:^|\/)(?:\d+-)?(?:trace|test)\.trace$/,rs=/(?:^|\/)(?:\d+-)?trace\.network$/,Ko=/(?:^|\/)(?:\d+-)?trace\.stacks$/,Qt=512,Xo=2e3,Op=200,kv=2,Wo=5e4,Jo=25,Iv=new Set(["screencast-frame","object","resource","input"]),Z={failure:5,failedCall:4,significant:3,context:2,ordinary:1,afterFailure:0};function Pv(r,t){switch(t){case"console":return r.maxConsoleEvents;case"network":return r.maxNetworkEvents;case"dom":case"accessibility":return r.maxDomNodes;default:return r.maxTraceEvents}}function ne(r,t,e,n,i,s){r.omissions.push({omissionId:$("omi",[r.input.attemptId,t,e,i??"",n]),channel:t,reason:e,message:n,...i===void 0?{}:{locator:i},...s===void 0?{}:{cap:s}})}function ns(r,t,e,n,i,s,a){let o=r.channels[t].artifact,d=he(r.runId,o.artifactId,e,n,i);r.evidence.push({evidenceId:d,kind:e,artifactId:o.artifactId,logicalTestId:r.input.logicalTestId,attemptId:r.input.attemptId,locator:n,observation:i,availability:i.length===0?"empty":"present",redactionIds:s.map(c=>c.redactionId)}),r.redactions.push(...s),r.priorities.set(d,a),r.channels[t].included+=1}function Mn(r,t,e,n){let i=ae(n,t,e,r.policy.sensitiveNames);return{value:i.value,records:i.records}}function Sp(r){let t=He(r);if(t===void 0)return[];let e=[];for(let n of t){let i=pe(n),s=_(i?.name);s!==void 0&&e.push({name:s,value:_(i?.value)??""})}return e}function Rv(r){let t=_(r.type);if(t==="console")return{type:_(r.messageType)??"log",text:_(r.text)??ge(r.args,Xo)};if(t!=="event"||!(_(r.class)==="ConsoleMessage"||_(r.method)==="console"))return;let n=pe(r.params);return{type:_(n?.type)??_(n?.messageType)??"log",text:_(n?.text)??ge(n,Xo)}}function $n(r){let t=pe(r.error);return _(t?.message)??_(pe(t?.error)?.message)}function Dp(r){return r===void 0?"unknown":_(r.apiName)??([_(r.class),_(r.method)].filter(Boolean).join(".")||"unknown")}function Tv(r){let t=pe(r?.params);return _(t?.selector)}function Av(r,t){let e=_(r.type),n=Dp(e==="after"?t??r:r),i=_(r.title),s=r.params===void 0?"":` params=${ge(r.params,Qt)}`,a=$n(r),o=a===void 0?"":` error=${ge(a,Qt)}`;switch(e){case"before":return`action started: ${n}${i===void 0?"":` "${ge(i,120)}"`}${s}`;case"after":return`action finished: ${n}${o}`;case"action":return`action: ${n}${s}${o}`;case"log":return`log: ${ge(r.message,Qt)}`;case"error":return`error: ${ge(r.message,Qt)}`;case"stdout":case"stderr":return`${e}: ${ge(r.text,Qt)}`;case"context-options":return`context options: ${ge({browserName:_(r.browserName),platform:_(r.platform),playwrightVersion:_(r.playwrightVersion),sdkLanguage:_(r.sdkLanguage)},Qt)}`;case"event":return`event: ${n}${s}`;default:return}}function Sv(r){return ke(r.startTime)??ke(r.endTime)??ke(r.time)}function Ev(r,t,e){let n=_e(e);if(n===void 0){r.channels.trace.failed=!0,ne(r,"trace","unreadable",`${t} is not valid UTF-8.`,t);return}let i=Qi(n);i.length===0&&(r.channels.trace.parsed=!0);let s=new Set;for(let a of i){let o=`${t}#line=${a.line}`;if(!a.parsed){r.channels.trace.failed=!0,ne(r,"trace","parse-failed",`${o} is not valid JSON.`,o);continue}let d=pe(a.value),c=_(d?.type);if(d===void 0||c===void 0){r.channels.trace.failed=!0,ne(r,"trace","unrecognized",`${o} is not a typed trace event.`,o);continue}if(r.channels.trace.parsed=!0,c==="frame-snapshot"){r.snapshots.add(t,a.line,d)===void 0&&ne(r,"dom","unrecognized",`${o} does not carry a readable frame snapshot.`,o);continue}if(c==="resource-snapshot"){Mp(r,t,a.line,d,new Map);continue}let l=Sv(d);if(c==="error"){l!==void 0&&r.errorTimes.push(l);for(let y of He(d.stack)??[]){if(r.seeds.length>=Op)break;let w=pe(y),x=_(w?.file),v=ke(w?.line);if(x===void 0||v===void 0)continue;let I=ke(w?.column);r.seeds.push({file:x,line:v,...I===void 0?{}:{column:I},origin:`${t}#line=${a.line}:error`,logicalTestId:r.input.logicalTestId,attemptId:r.input.attemptId})}}let u=Rv(d);if(u!==void 0){let y=Mn(r,"console",o,`console.${u.type}: ${ge(u.text,Xo)}`);r.candidates.push({channel:"console",kind:"console-event",locator:{type:"trace-event",entry:t,line:a.line,eventType:"console",...l===void 0?{}:{timestamp:l}},locatorText:o,observation:y.value,redactions:y.records,order:r.candidates.length,...l===void 0?{}:{time:l},error:u.type==="error"||u.type==="warning"});continue}if(Iv.has(c))continue;let p=_(d.callId),f=p===void 0?void 0:`${t}
19
- ${p}`;if(f!==void 0&&p!==void 0){if(c==="before")r.actions.set(f,{callId:p,entry:t,before:{line:a.line,event:d}});else if(c==="after"){let y=r.actions.get(f)??{callId:p,entry:t};y.after={line:a.line,event:d},r.actions.set(f,y);let w=ke(d.endTime);$n(d)!==void 0&&w!==void 0&&r.errorTimes.push(w)}}let h=f===void 0?void 0:r.actions.get(f)?.before,g=Av(d,h?.event);if(g===void 0){s.add(c);continue}let m=Mn(r,"trace",o,g);r.candidates.push({channel:"trace",kind:"trace-event",locator:{type:"trace-event",entry:t,line:a.line,eventType:c,...p===void 0?{}:{eventId:p},...l===void 0?{}:{timestamp:l}},locatorText:o,observation:m.value,redactions:m.records,order:r.candidates.length,...l===void 0?{}:{time:l},...p===void 0?{}:{callId:p},error:c==="error"||$n(d)!==void 0})}for(let a of[...s].sort())ne(r,"trace","unrecognized",`Trace event type ${a} is not interpreted by this adapter.`,t)}function Cv(r){let t=[];for(let e of r.actions.values()){let n=Tv(e.before?.event);if(n===void 0||e.before===void 0||_(e.before.event.class)==="Test")continue;let i=e.after!==void 0&&$n(e.after.event)!==void 0,s=e.after===void 0;!i&&!s||t.push({callId:e.callId,entry:e.entry,selector:n,apiName:Dp(e.before.event),time:ke(e.before.event.startTime)??0,unfinished:s})}return t.sort((e,n)=>n.time-e.time||e.callId.localeCompare(n.callId))}function Nv(r){let t={after:3,action:2,before:1};return[...r].filter(e=>e.isMainFrame||r.length===1).sort((e,n)=>(t[n.phase??"before"]??0)-(t[e.phase??"before"]??0)||n.line-e.line)[0]}function Ov(r,t){let e=Nv(r.snapshots.forCall(t.callId)),n=`${t.apiName} on ${t.selector}`;if(e===void 0){ne(r,"dom","unavailable",`No DOM snapshot was recorded for the failed ${n}.`,`${t.entry}#${t.callId}`);return}let i=r.snapshots.rebuild(e,Wo),s=`${e.entry}#${e.snapshotId}`;if(i.root===void 0){ne(r,"dom","unreadable",`Snapshot ${e.snapshotId} could not be rebuilt.`,s);return}i.truncated&&ne(r,"dom","budget-exceeded",`Snapshot ${e.snapshotId} was rebuilt only up to ${Wo} nodes.`,s,Wo);let a={maxDepth:r.policy.maxDomDepth,maxNodes:r.policy.maxDomNodes,maxBytes:r.policy.maxDomTextBytes,sensitiveNames:r.policy.sensitiveNames},o=up(i.root,t.callId),d=Tn(i.root,t.selector),c=d.kind==="resolved"?d.matches:void 0,l=o!==void 0&&(c===void 0||c.length<=1)?[o]:c??[],u=e.phase??"snapshot";if(l.length===1&&l[0]!==void 0){let h=l[0],g=Sn(h.node,s,a);ns(r,"dom","dom-subtree",{type:"dom-node",snapshotId:e.snapshotId,nodePath:h.path},`${u} snapshot of the element targeted by the failed ${n}:
20
- ${g.text}`,g.redactions,Z.failure),g.truncated&&ne(r,"dom","budget-exceeded",`The target subtree in ${e.snapshotId} was cut at ${a.maxDepth} levels, ${a.maxNodes} elements, or ${a.maxBytes} bytes.`,s,a.maxNodes);let m=Mn(r,"accessibility",s,En(h.node));ns(r,"accessibility","accessibility-node",{type:"dom-node",snapshotId:e.snapshotId,nodePath:h.path},`target of the failed ${t.apiName}: ${m.value}`,m.records,Z.failure);return}let p=d.kind==="unsupported"?`uses a selector form (${d.reason}) the local DOM adapter does not evaluate`:`matched ${l.length} elements`,f=Zi(i.root,t.selector,l,s,{maxItems:Jo,maxBytes:a.maxBytes},r.policy.sensitiveNames);ns(r,"dom","dom-candidates",{type:"dom-node",snapshotId:e.snapshotId,nodePath:[]},`In the ${u} snapshot of the failed ${n}, the locator ${p}. Elements most like it, best first:
21
- ${f.text}`,f.redactions,Z.failure),f.truncated&&ne(r,"dom","budget-exceeded",`Only the ${Jo} closest candidates in ${e.snapshotId} were listed.`,s,Jo)}function Dv(r,t){let e=new Set(t.map(s=>s.callId));for(let s of r.actions.values())s.after!==void 0&&$n(s.after.event)!==void 0&&e.add(s.callId);let n=r.errorTimes.length>0?Math.min(...r.errorTimes):t.length>0?Math.min(...t.map(s=>s.time)):void 0,i=s=>s.error?s.channel==="trace"?Z.failedCall+.95:Z.significant:s.callId!==void 0&&e.has(s.callId)?Z.failedCall:n!==void 0&&s.time!==void 0&&s.time>n+1?Z.afterFailure:s.channel==="trace"?Z.context:Z.ordinary;for(let s of["trace","console","network"]){let a=r.candidates.filter(l=>l.channel===s),o=Pv(r.policy,s),d=a.map(l=>({candidate:l,priority:i(l)})).sort((l,u)=>u.priority-l.priority||u.candidate.order-l.candidate.order),c=d.slice(0,o).sort((l,u)=>l.candidate.order-u.candidate.order);for(let{candidate:l,priority:u}of c){let p=a.length===0?0:l.order/(a.length*25);ns(r,s,l.kind,l.locator,l.observation,l.redactions,u+p)}d.length>o&&ne(r,s,"budget-exceeded",`Kept the ${o} ${s} observations closest to the failure; ${d.length-o} earlier or less relevant ones were not included.`,d[o]?.candidate.locatorText,o)}}function Lp(r){let t=pe(r.snapshot)??r,e=pe(t.response),n=pe(e?.content);return _(n?._sha1)??_(n?.sha1)}function Mp(r,t,e,n,i){let s=pe(n.snapshot)??n,a=pe(s.request),o=_(a?.url),d=`${t}#line=${e}`;if(o===void 0){ne(r,"network","unrecognized",`${d} has no request URL.`,d);return}let c=Nt(o,"network",d,r.policy.sensitiveNames),l=Yi(Sp(a?.headers),"network",`${d}/request-headers`,r.policy.sensitiveNames),u=pe(s.response),p=Yi(Sp(u?.headers),"network",`${d}/response-headers`,r.policy.sensitiveNames),f=_(a?.method)??"GET",h=ke(u?.status),g=pe(u?.content),m=[`${f} ${c.value}`,h===void 0||h<=0?"-> (no response)":`-> ${h} ${_(u?.statusText)??""}`.trim()],y=_(g?.mimeType),w=ke(g?.size);(y!==void 0||w!==void 0)&&m.push(`(${y??"unknown"}, ${w??"unknown"} bytes)`);let x=_(g?.text)??_(u?.body),v=Lp(n);if(x===void 0&&v!==void 0&&r.policy.includeNetworkBodies){let O=i.get(v)??i.get(`resources/${v}`);O===void 0?ne(r,"network","unavailable",`Referenced response resource ${v} was not present in the trace archive.`,d):O.byteLength>r.policy.maxNetworkBodyBytes?ne(r,"network","budget-exceeded",`Referenced response resource ${v} exceeds the network body byte limit.`,d,r.policy.maxNetworkBodyBytes):(x=_e(O),x===void 0&&ne(r,"network","irrelevant",`Referenced response resource ${v} is not textual UTF-8.`,d))}let I=y?.toLowerCase()??"",R=I.startsWith("image/")||I.startsWith("audio/")||I.startsWith("video/")||I.includes("multipart")||I.includes("octet-stream"),E=[];if(r.policy.includeNetworkBodies)if(x!==void 0&&!R){let O=Mn(r,"network",`${d}/body`,ge(x,r.policy.maxNetworkBodyBytes));E.push(...O.records),m.push(`body=${O.value}`)}else x!==void 0&&R&&ne(r,"network","irrelevant","Response body omitted because it is binary or multipart.",d);else(x!==void 0||g!==void 0)&&ne(r,"network","policy-disabled","Response body withheld because includeNetworkBodies is disabled.",d);let A=ke(s.time);A!==void 0&&m.push(`time=${A}ms`);let N=_(s._failureText);N!==void 0&&m.push(`failure=${ge(N,Qt)}`);let B=Mn(r,"network",d,m.join(" ")),V=_(s._requestref)??$("req",[f,c.value,String(e)]),P=ke(s._monotonicTime);r.candidates.push({channel:"network",kind:"network-event",locator:{type:"network-request",requestId:V,eventIndex:e},locatorText:d,observation:B.value,redactions:[...B.records,...E,...c.records,...l.records,...p.records],order:r.candidates.length,...P===void 0?{}:{time:P},error:N!==void 0||h!==void 0&&(h>=400||h<=0)})}function Lv(r,t,e){let n=_e(e);if(n===void 0){r.channels.trace.failed=!0,ne(r,"trace","unreadable",`${t} is not valid UTF-8.`,t);return}let i;try{i=JSON.parse(n),r.channels.trace.parsed=!0}catch{r.channels.trace.failed=!0,ne(r,"trace","parse-failed",`${t} is not valid JSON.`,t);return}let s=pe(i),a=He(s?.files)??[],o=He(s?.stacks)??[];for(let d of o){let c=He(d),l=_(c?.[0])??"unknown";for(let u of He(c?.[1])??[]){if(r.seeds.length>=Op)return;let p=He(u),f=ke(p?.[0]),h=ke(p?.[1]);if(f===void 0||h===void 0)continue;let g=_(a[f]);if(g===void 0)continue;let m=ke(p?.[2]);r.seeds.push({file:g,line:h,...m===void 0?{}:{column:m},origin:`${t}:${l}`,logicalTestId:r.input.logicalTestId,attemptId:r.input.attemptId})}}}function Ep(r,t,e,n){let i={};for(let s of Yt)i[s]={artifact:{artifactId:we(r,s,`${t.attemptId}:${t.attachmentId}`),channel:s,availability:e,...n.path===void 0?{}:{path:n.path},...n.sha256===void 0?{}:{sha256:n.sha256},format:n.format??"playwright-trace-zip",...n.producerVersion===void 0?{}:{producerVersion:n.producerVersion},attemptId:t.attemptId,warnings:n.warnings},included:0,parsed:!1,failed:!1};return i}function Cp(r,t,e,n){return{runId:r,policy:t,input:e,channels:n,evidence:[],redactions:[],omissions:[],seeds:[],priorities:new Map,candidates:[],actions:new Map,snapshots:new ts,errorTimes:[]}}function Np(r,t){return{artifacts:r,evidence:[],redactions:[],omissions:t,seeds:[],priorities:new Map,failedSelectors:[]}}async function $p(r,t,e,n){let i=await K(n,e.path,t.maxArtifactBytes);if(i.kind!=="read"){let f=i.kind==="unavailable"?"unavailable":"unreadable",h=i.kind==="over-budget"?"budget-exceeded":i.kind==="unauthorized"?"unauthorized-path":i.kind,g=Ep(r,e,f,{warnings:[i.message]}),m=Cp(r,t,e,g);for(let y of Yt)ne(m,y,h,i.message,e.path);return Np(Yt.map(y=>g[y].artifact),m.omissions)}let a=es(i.bytes,{maxEntries:t.maxTraceEntries,maxExpandedBytes:t.maxTraceExpandedBytes},f=>Go.test(f)||rs.test(f)||Ko.test(f)),o=e.info?.producerVersion===void 0,d=Ep(r,e,"present",{path:i.relativePath,sha256:i.sha256,warnings:o?["Trace producer version was not supplied; adapter compatibility is unverified."]:[],...e.info?.producerVersion===void 0?{}:{producerVersion:e.info.producerVersion},...e.info?.format===void 0?{}:{format:e.info.format}}),c=Cp(r,t,e,d);if(a.kind!=="read"){let f=a.message;for(let h of Yt)ne(c,h,"unreadable",f,i.relativePath);return Np(Yt.map(h=>({...d[h].artifact,availability:"unreadable",warnings:[f]})),c.omissions)}o&&ne(c,"trace","unrecognized","Trace producer version was not supplied; parsed evidence is not version-qualified.",i.relativePath);let l=new Set;if(t.includeNetworkBodies){for(let[f,h]of a.contents.entries){if(!rs.test(f))continue;let g=_e(h);if(g!==void 0)for(let m of Qi(g)){let y=pe(m.value);if(y===void 0)continue;let w=Lp(y);w!==void 0&&(l.add(w),l.add(`resources/${w}`))}}if(l.size>0){let f=es(i.bytes,{maxEntries:t.maxTraceEntries,maxExpandedBytes:t.maxTraceExpandedBytes},h=>Go.test(h)||rs.test(h)||Ko.test(h)||l.has(h));f.kind==="read"?a=f:ne(c,"network","unreadable",f.message,i.relativePath)}}for(let f of a.contents.skipped){let h=f.reason==="unsafe-entry-name"?"unauthorized-path":"budget-exceeded";ne(c,"trace",h,`Archive entry ${f.entry} was not read (${f.reason}, ${f.declaredBytes} declared bytes).`,`${i.relativePath}!${f.entry}`)}let u=[...a.contents.entries.keys()].sort();for(let f of u.filter(h=>Ko.test(h)))Lv(c,f,a.contents.entries.get(f));for(let f of u.filter(h=>Go.test(h)))Ev(c,f,a.contents.entries.get(f));for(let f of u.filter(h=>rs.test(h))){let h=_e(a.contents.entries.get(f));if(h===void 0){c.channels.network.failed=!0,ne(c,"network","unreadable",`${f} is not valid UTF-8.`,f);continue}let g=Qi(h);g.length===0&&(c.channels.network.parsed=!0);for(let m of g){if(!m.parsed){c.channels.network.failed=!0,ne(c,"network","parse-failed",`${f}#line=${m.line} is not valid JSON.`,`${f}#line=${m.line}`);continue}let y=pe(m.value);if(y===void 0){c.channels.network.failed=!0,ne(c,"network","unrecognized",`${f}#line=${m.line} is not a network record.`,`${f}#line=${m.line}`);continue}c.channels.network.parsed=!0,Mp(c,f,m.line,y,a.contents.entries)}}let p=Cv(c);Dv(c,p);for(let f of p.slice(0,kv))Ov(c,f);if(p.length===0&&c.snapshots.size>0&&ne(c,"dom","irrelevant","No failed action targeted an element, so no DOM snapshot was examined.",i.relativePath),u.length===0)for(let f of Yt)d[f].failed=!0,ne(c,f,"unreadable","Archive contained no Playwright trace, network, or stacks entry.",i.relativePath);return{artifacts:Yt.map(f=>{let h=d[f],g=h.included>0?"present":h.failed&&!h.parsed?"unreadable":"empty";return{...h.artifact,availability:g}}),evidence:c.evidence,redactions:c.redactions,omissions:c.omissions,seeds:c.seeds,priorities:c.priorities,failedSelectors:p.map(f=>ut(f.selector))}}var Mv="application/vnd.kwikqa.capture+json",_p=["trace","console","network","dom","accessibility"],Fp=25,$v=2,_v=25,Yo=600,Fv=new Set(["type","setValue","addValue","keys"]),jv=new Set(["get","find","contains","$","$$","within"]),Bv=/pass|secret|token|otp|pin\b|card|cvv|cvc|ssn|credential|auth/i;function Qo(r){return r.name==="kwikqa-capture"||r.contentType.toLowerCase().split(";")[0]?.trim()===Mv}function xt(r,t=""){return typeof r=="string"?r:t}function Vv(r){if(typeof r!="object"||r===null||Array.isArray(r))return;let t=r;if(t.schema!=="kwikqa-capture"||String(t.schemaVersion??"").split(".")[0]!=="1")return;let e=t.framework==="webdriverio"?"webdriverio":"cypress",n=i=>Array.isArray(t[i])?t[i].filter(s=>typeof s=="object"&&s!==null&&!Array.isArray(s)):[];return{framework:e,url:xt(t.url),title:xt(t.title),...Array.isArray(t.dom)?{dom:t.dom}:{},domTruncated:t.domTruncated===!0,commands:n("commands").map(i=>({name:xt(i.name),...typeof i.displayName=="string"?{displayName:i.displayName}:{},message:xt(i.message),state:xt(i.state),...typeof i.error=="string"?{error:i.error}:{},...typeof i.repeated=="number"?{repeated:i.repeated}:{}})),console:n("console").map(i=>({level:xt(i.level,"log"),text:xt(i.text)})),network:n("network").map(i=>({message:xt(i.message),state:xt(i.state),...typeof i.url=="string"?{url:i.url}:{}}))}}function zv(r){let t=/^([A-Z]+)\s+(\d{3})\s+(\S+)/.exec(r.trim());if(t!==null)return{method:t[1]??"GET",status:Number(t[2]),url:t[3]??""};let e=/^([A-Z]+)\s+(\S+)\s+(\S+)$/.exec(r.trim());return e!==null&&/^https?:|^\//.test(e[3]??"")?{method:e[1]??"GET",url:e[3]??"",failure:e[2]??"failed"}:{method:"",url:r}}function Hv(r){for(let t of Le(r))if(Array.isArray(t)&&$e(t)==="body")return t;return r}function qv(r){let t=/^([a-z][\w-]*)\*?=/i.exec(r);return t!==null&&!r.includes("[")?t[1]??r:r}async function jp(r,t,e,n){let{attachment:i}=e,s=`${e.attemptId}.attachments[${i.sourceIndex}]`,a=Object.fromEntries(_p.map(k=>[k,we(r,k,`${e.attemptId}:${i.attachmentId}`)])),o=[],d=[],c=[],l=new Map,u=[],p=(k,T,L,j)=>{c.push({omissionId:$("omi",[e.attemptId,k,T,s,L]),channel:k,reason:T,message:L,locator:s,...j===void 0?{}:{cap:j}})},f=(k,T={})=>_p.map(L=>({artifactId:a[L],channel:L,availability:k(L),format:"kwikqa-capture",attemptId:e.attemptId,warnings:[],...T}));if(i.path===void 0)return p("dom","unavailable","The failure capture attachment has no path."),{artifacts:f(()=>"unavailable"),evidence:o,redactions:d,omissions:c,priorities:l,failedSelectors:u};let h=await K(n,i.path,t.maxArtifactBytes);if(h.kind!=="read"){let k=h.kind==="over-budget"?"budget-exceeded":h.kind==="unauthorized"?"unauthorized-path":h.kind;return p("dom",k,h.message),{artifacts:f(()=>h.kind==="unavailable"?"unavailable":"unreadable",{path:i.path,warnings:[h.message]}),evidence:o,redactions:d,omissions:c,priorities:l,failedSelectors:u}}let g=Te(h.bytes),m=_e(h.bytes),y;try{y=m===void 0?void 0:Vv(JSON.parse(m))}catch{y=void 0}if(y===void 0)return p("dom","unrecognized","The failure capture is not a KwikQA capture."),{artifacts:f(()=>"unreadable",{path:h.relativePath,sha256:g}),evidence:o,redactions:d,omissions:c,priorities:l,failedSelectors:u};let w=(k,T,L,j,se,fe)=>{let ue=he(r,a[k],T,L,j);o.push({evidenceId:ue,kind:T,artifactId:a[k],logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:L,observation:j,availability:"present",redactionIds:se.map(Y=>Y.redactionId)}),d.push(...se),l.set(ue,fe)},x=(k,T,L)=>ae(ut(T),k,L,t.sensitiveNames),v=y.framework==="cypress"?"cy":"browser",I=y.commands.filter(k=>k.name!==""&&k.state!=="pending"),R=I.findIndex(k=>k.state==="failed"),E=R<0?I.length:R+1,A=Math.max(0,E-Fp);A>0&&p("trace","budget-exceeded",`Kept the ${E-A} commands up to the failure; ${A} earlier ones were left out.`,Fp);let N="";I.slice(A,Math.min(I.length,E+3)).forEach((k,T)=>{let L=A+T,j=k.state==="failed",ue=Fv.has(k.name)&&(Bv.test(N)||t.sensitiveNames.some(At=>N.toLowerCase().includes(At.toLowerCase())))?`<${k.message.length} typed characters, not shown>`:k.message;jv.has(k.name)&&k.message!==""&&(N=k.message),j&&N!==""&&u.push(N.split(",")[0]?.trim()??N);let ve=k.repeated===void 0?"":` (x${k.repeated})`,Re=`${j?"command failed":L>=E?"command after the failure":"command"}: ${v}.${k.displayName??k.name}(${ue.slice(0,Yo)})${ve}${k.error===void 0?"":` error=${k.error.slice(0,Yo)}`}`,mt=x("trace",Re,`${s}#commands[${L}]`);w("trace","trace-event",{type:"trace-event",entry:`${i.attachmentId}#commands`,line:L+1,eventType:j?"command-failed":"command"},mt.value,mt.records,j?Z.failure:L>=E?Z.afterFailure:Z.context+(L-A)/1e3)}),I.length===0&&p("trace","unavailable","The capture recorded no commands."),y.console.slice(0,t.maxConsoleEvents).forEach((k,T)=>{let L=k.level==="pageerror"?"uncaught page error":`console.${k.level}`,j=x("console",`${L}: ${k.text.slice(0,Yo)}`,`${s}#console[${T}]`);w("console","console-event",{type:"trace-event",entry:`${i.attachmentId}#console`,line:T+1,eventType:"console"},j.value,j.records,k.level==="error"||k.level==="pageerror"?Z.significant:Z.ordinary)}),y.console.length>t.maxConsoleEvents&&p("console","budget-exceeded",`Kept ${t.maxConsoleEvents} of ${y.console.length} console messages.`,t.maxConsoleEvents),y.network.slice(0,t.maxNetworkEvents).forEach((k,T)=>{let L=zv(k.message),j=Nt(k.url??L.url,"network",`${s}#network[${T}]`,t.sensitiveNames),se=L.status!==void 0?`-> ${L.status}`:L.failure!==void 0?`failure=${L.failure}`:`(${k.state})`,fe=`${L.method===""?"request":L.method} ${j.value} ${se}`,ue=(L.status??0)>=400||L.failure!==void 0;w("network","network-event",{type:"network-request",requestId:`${i.attachmentId}#${T}`,eventIndex:T},fe,j.records,ue?Z.significant:Z.ordinary)}),y.network.length>t.maxNetworkEvents&&p("network","budget-exceeded",`Kept ${t.maxNetworkEvents} of ${y.network.length} network responses.`,t.maxNetworkEvents);let B=y.dom,V=`${i.attachmentId}#dom`,P=Nt(y.url,"dom",`${s}#url`,t.sensitiveNames);d.push(...P.records);let O=`the page ${P.value}${y.title===""?"":` ("${y.title.slice(0,120)}")`} when the attempt failed`,M={maxDepth:t.maxDomDepth,maxNodes:t.maxDomNodes,maxBytes:t.maxDomTextBytes,sensitiveNames:t.sensitiveNames};if(B===void 0)p("dom","unavailable","The capture recorded no DOM.");else{y.domTruncated&&p("dom","budget-exceeded","The page was larger than the capture's node limit; later nodes were not recorded.");let k=[...new Set([...u,...e.focus])].map(qv).filter(T=>T!=="").slice(0,$v);for(let T of k){let L=Tn(B,T),j=L.kind==="resolved"?L.matches:[];if(j.length===1&&j[0]!==void 0){let ue=j[0],Y=Sn(ue.node,`${s}#dom`,M);w("dom","dom-subtree",{type:"dom-node",snapshotId:V,nodePath:ue.path},`In ${O}, the element ${T} selects:
22
- ${Y.text}`,Y.redactions,Z.failure);let ve=x("accessibility",En(ue.node),`${s}#a11y`);w("accessibility","accessibility-node",{type:"dom-node",snapshotId:V,nodePath:ue.path},`element selected by ${T}: ${ve.value}`,ve.records,Z.failure);continue}let se=L.kind==="unsupported"?`uses a selector form (${L.reason}) the local DOM adapter does not evaluate`:`matched ${j.length} elements`,fe=Zi(B,T,j,`${s}#dom`,{maxItems:_v,maxBytes:M.maxBytes},t.sensitiveNames);w("dom","dom-candidates",{type:"dom-node",snapshotId:V,nodePath:[]},`In ${O}, the selector ${T} ${se}. Elements most like it, best first:
23
- ${fe.text}`,fe.redactions,Z.failure)}if(k.length===0){let T=Sn(Hv(B),`${s}#dom`,M);w("dom","dom-subtree",{type:"dom-node",snapshotId:V,nodePath:[]},`Outline of ${O}:
24
- ${T.text}`,T.redactions,Z.significant),T.truncated&&p("dom","budget-exceeded",`The page outline was cut at ${M.maxNodes} elements or ${M.maxBytes} bytes.`,M.maxNodes)}}let H=new Set(o.map(k=>k.artifactId));return{artifacts:f(k=>H.has(a[k])?"present":"empty",{path:h.relativePath,sha256:g}),evidence:o,redactions:d,omissions:c,priorities:l,failedSelectors:u}}import{execFile as Qv}from"node:child_process";import{isAbsolute as Zv,relative as ek,resolve as id,sep as Vp}from"node:path";import{promisify as tk}from"node:util";import{execFile as Uv}from"node:child_process";import{promisify as Gv}from"node:util";import{isAbsolute as Kv,relative as Zo,resolve as is,sep as ed}from"node:path";var Wv=Gv(Uv),Jv=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/,Xv=1e4;function ss(r){let t=[],e,n,i=()=>{if(n===void 0||e===void 0)return;let[,s,a,o,d]=n.header;t.push({path:e,oldStart:Number.parseInt(s??"0",10),oldLines:a===void 0?1:Number.parseInt(a,10),newStart:Number.parseInt(o??"0",10),newLines:d===void 0?1:Number.parseInt(d,10),body:n.lines.join(`
25
- `)}),n=void 0};for(let s of r.split(/\r?\n/)){if(s.startsWith("diff --git ")){i(),e=void 0;continue}if(s.startsWith("+++ ")){i();let o=s.slice(4).trim();e=o==="/dev/null"?void 0:o.replace(/^b\//,"");continue}let a=Jv.exec(s);if(a!==null){i(),n={header:a,lines:[s]};continue}n!==void 0&&n.lines.push(s)}return i(),t}function Zt(r,t,e,n){return{omissionId:$("omi",["diff",r,e??"",t]),channel:"diff",reason:r,message:t,...e===void 0?{}:{locator:e},...n===void 0?{}:{cap:n}}}async function Yv(r,t,e){let n=["-C",r,"--no-optional-locks","-c","core.quotePath=false","diff","--no-color","--no-ext-diff","--no-renames","--unified=3","HEAD","--",...t];try{return{text:(await Wv("git",n,{timeout:Xv,maxBuffer:e,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}}catch(i){let s=i;if(s.code==="ENOENT")return{error:"git executable was not found."};let a=(s.stderr??s.message??"").trim().split(`
26
- `)[0]??"";return{error:a===""?"git diff failed.":a}}}async function Bp(r,t,e,n){let i=we(r,"diff",n.gitRoot??t.workspaceRoot),s=(v,I=[])=>({artifactId:i,channel:"diff",availability:v,...n.gitRoot===void 0?{}:{path:n.gitRoot},format:"git-unified-diff",warnings:I});if(!n.authorized)return{artifacts:[s("unavailable")],evidence:[],redactions:[],omissions:[Zt("policy-disabled","Current-diff selection was not authorized for this run.")]};if(n.gitRoot===void 0)return{artifacts:[s("unavailable")],evidence:[],redactions:[],omissions:[Zt("unavailable","The workspace has no containing git repository root.")]};let a=is(n.workspaceRoot??n.gitRoot),o=is(n.gitRoot),d=Zo(o,a);if(d===".."||d.startsWith(`..${ed}`))return{artifacts:[s("unavailable")],evidence:[],redactions:[],omissions:[Zt("unauthorized-path","The authorized workspace is outside the configured git root.",a)]};let c=[...new Set(e.map(v=>{let I=Kv(v)?is(v):is(a,v),R=Zo(o,I).split(ed).join("/");return R===""||R.startsWith("../")||R===".."?void 0:R}).filter(v=>v!==void 0))].sort();if(c.length===0)return{artifacts:[s("empty")],evidence:[],redactions:[],omissions:[Zt("irrelevant","No evidence-bearing file was eligible for diff selection.")]};let l=Math.max(t.maxDiffBytes*4,1e6),u=await Yv(o,c,l);if("error"in u)return{artifacts:[s("unreadable",[u.error])],evidence:[],redactions:[],omissions:[Zt("unreadable",u.error,n.gitRoot)]};let p=a===o?"":`${Zo(o,a).split(ed).join("/")}/`,f=ss(u.text).map(v=>({...v,path:p!==""&&v.path.startsWith(p)?v.path.slice(p.length):v.path}));if(f.length===0)return{artifacts:[s("empty")],evidence:[],redactions:[],omissions:[]};let h=[],g=[],m=[],y=0,w=!1,x=!1;for(let v of f){if(h.length>=t.maxDiffHunks){w||(w=!0,m.push(Zt("budget-exceeded",`Reached the ${t.maxDiffHunks}-hunk limit; later hunks were not included.`,v.path,t.maxDiffHunks)));break}let I=`${v.path}@${v.newStart}`,R=ae(v.body,"diff",I,t.sensitiveNames),E=Buffer.byteLength(R.value,"utf8");if(y+E>t.maxDiffBytes){x||(x=!0,m.push(Zt("budget-exceeded",`Reached the ${t.maxDiffBytes}-byte diff limit; later hunks were not included.`,v.path,t.maxDiffBytes)));break}y+=E,g.push(...R.records);let A={type:"diff-hunk",path:v.path,oldStart:v.oldStart,oldLines:v.oldLines,newStart:v.newStart,newLines:v.newLines};h.push({evidenceId:he(r,i,"diff-hunk",A,R.value),kind:"diff-hunk",artifactId:i,locator:A,observation:R.value,availability:"present",redactionIds:R.records.map(N=>N.redactionId)})}return{artifacts:[s("present")],evidence:h,redactions:g,omissions:m}}var rk=tk(Qv),nk=1e4,ik=4e6,sk=16,Yp=3,ak=120,zp=50,Hp=20,qp=30,td=12,Up=24e3,rd=40,Qp=20,Gp=120,Zp=1440*60*1e3,ok=new Set(["alert","article","button","cell","checkbox","combobox","dialog","false","heading","hidden","img","link","list","listitem","main","menu","menuitem","navigation","null","option","radio","region","row","status","tab","table","textbox","true","undefined","visible"]),ef=/\.(?:[cm]?[jt]sx?|vue|svelte|astro|html?|css|scss|sass|less|json|ya?ml|py|rb|php|java|kt|cs|go|rs|swift|erb|hbs|ejs|pug|liquid|twig|jinja2?|properties|po|xliff|xlf|strings|resx)$/i,tf=/(?:^|\/)(?:node_modules|dist|build|out|coverage|vendor|\.next|\.nuxt|\.svelte-kit|\.kwikqa|__snapshots__|test-results|playwright-report|\.git)\/|(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|composer\.lock|Gemfile\.lock|Cargo\.lock|poetry\.lock)$|\.min\.[cm]?js$|\.map$/,dk=/\u001b\[[0-9;]*m/g,Kp=/"([^"\n]{3,120})"|'([^'\n]{3,120})'|`([^`\n]{3,120})`/g,ck=/^\s*(?:Expected|Received)(?: string| pattern| value)?:\s*(.+)$/gm,lk=/^(?:[A-Z]+|request) (\S+) (?:-> (\d{3})|failure=)/;function uk(r){let t=r.trim();return/^(["'`])(.*)\1$/.exec(t)?.[2]??t}function Wp(r){let t=r.trim();if(!(t.length<Yp||t.length>ak)&&!ok.has(t.toLowerCase())&&!(/^[\d\s.,:%$-]+$/.test(t)&&!/^[$€£]?\d+[.,]\d+$/.test(t))&&!/^(?:\/|[A-Za-z]:\\|file:)|\.(?:spec|test|cy)\.[cm]?[jt]sx?\b|node_modules|:\d+:\d+/.test(t))return t}function nd(r){let t=[];for(let e of r.matchAll(/\[[\w-]+[~|^$*]?=\s*["']?([^"'\]]+)["']?\]/g))t.push(e[1]??"");for(let e of r.matchAll(/[#.]([A-Za-z][\w-]{2,})/g))t.push(e[1]??"");return t}var pk=8;function fk(r){let t=r.trim().split(/\s+/);if(t.length<3)return[];let e=[];for(let n=0;n+1<t.length;n+=1){let i=`${t[n]} ${t[n+1]}`;(i.match(new RegExp("\\p{L}","gu"))??[]).length>=pk&&e.push(i)}return e}function hk(r){let t;try{t=new URL(r,"http://localhost").pathname}catch{return}if(/\.(?:js|css|png|jpe?g|gif|svg|ico|woff2?|map)$/i.test(t))return;let e=[];for(let i of t.split("/").filter(Boolean)){if(/^\d+$|^[0-9a-f-]{16,}$|^[0-9a-f]{8,}$/i.test(i))break;e.push(i)}let n=`/${e.join("/")}`;return e.length===0?void 0:n}function rf(r,t,e=[]){let n=[],i=[];for(let c of r){for(let l of t(c)){for(let u of l.matchAll(Kp)){let p=u[1]??u[2]??u[3]??"";n.push(p,...nd(p))}/[('"`]/.test(l)||n.push(...nd(l))}for(let l of c.errors){let u=(l.message??"").replace(dk,"");for(let f of u.matchAll(ck)){let h=uk(f[1]??"");n.push(h),i.push(h)}let p=u.split(`
7
+ `):i=String.fromCharCode(n),++this.state.curLine,this.state.lineStart=this.state.pos,i}jsxReadString(e){let n="",i=++this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(b.UnterminatedString,this.state.startLoc);let s=this.input.charCodeAt(this.state.pos);if(s===e)break;s===38?(n+=this.input.slice(i,this.state.pos),n+=this.jsxReadEntity(),i=this.state.pos):Rr(s)?(n+=this.input.slice(i,this.state.pos),n+=this.jsxReadNewLine(!1),i=this.state.pos):++this.state.pos}n+=this.input.slice(i,this.state.pos++),this.finishToken(134,n)}jsxReadEntity(){let e=++this.state.pos;if(this.codePointAtPos(this.state.pos)===35){++this.state.pos;let n=10;this.codePointAtPos(this.state.pos)===120&&(n=16,++this.state.pos);let i=this.readInt(n,void 0,!1,"bail");if(i!==null&&this.codePointAtPos(this.state.pos)===59)return++this.state.pos,String.fromCodePoint(i)}else{let n=0,i=!1;for(;n++<10&&this.state.pos<this.length&&!(i=this.codePointAtPos(this.state.pos)===59);)++this.state.pos;if(i){let s=this.input.slice(e,this.state.pos),a=Ab[s];if(++this.state.pos,a)return a}}return this.state.pos=e,"&"}jsxReadWord(){let e,n=this.state.pos;do e=this.input.charCodeAt(++this.state.pos);while(Xt(e)||e===45);this.finishToken(141,this.input.slice(n,this.state.pos))}jsxParseIdentifier(){let e=this.startNode();return this.match(141)?e.name=this.state.value:$o(this.state.type)?e.name=Nt(this.state.type):this.unexpected(),this.next(),this.finishNode(e,"JSXIdentifier")}jsxParseNamespacedName(){let e=this.state.startLoc,n=this.jsxParseIdentifier();if(!this.eat(14))return n;let i=this.startNodeAt(e);return i.namespace=n,i.name=this.jsxParseIdentifier(),this.finishNode(i,"JSXNamespacedName")}jsxParseElementName(){let e=this.state.startLoc,n=this.jsxParseNamespacedName();if(n.type==="JSXNamespacedName")return n;for(;this.eat(16);){let i=this.startNodeAt(e);i.object=n,i.property=this.jsxParseIdentifier(),n=this.finishNode(i,"JSXMemberExpression")}return n}jsxParseAttributeValue(){let e;switch(this.state.type){case 5:return e=this.startNode(),this.setContext(te.brace),this.next(),e=this.jsxParseExpressionContainer(e,te.j_oTag),e.expression.type==="JSXEmptyExpression"&&this.raise(Wt.AttributeIsEmpty,e),e;case 143:case 134:return this.parseExprAtom();default:throw this.raise(Wt.UnsupportedJsxValue,this.state.startLoc)}}jsxParseEmptyExpression(){let e=this.startNodeAt(this.state.lastTokEndLoc);return this.finishNodeAt(e,"JSXEmptyExpression",this.state.startLoc)}jsxParseSpreadChild(e){return this.next(),e.expression=this.parseExpression(),this.setContext(te.j_expr),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXSpreadChild")}jsxParseExpressionContainer(e,n){if(this.match(8))e.expression=this.jsxParseEmptyExpression();else{let i=this.parseExpression();e.expression=i}return this.setContext(n),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXExpressionContainer")}jsxParseAttribute(){let e=this.startNode();return this.match(5)?(this.setContext(te.brace),this.next(),this.expect(21),e.argument=this.parseMaybeAssignAllowIn(),this.setContext(te.j_oTag),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXSpreadAttribute")):(e.name=this.jsxParseNamespacedName(),e.value=this.eat(29)?this.jsxParseAttributeValue():null,this.finishNode(e,"JSXAttribute"))}jsxParseOpeningElementAt(e){let n=this.startNodeAt(e);return this.eat(144)?this.finishNode(n,"JSXOpeningFragment"):(n.name=this.jsxParseElementName(),this.jsxParseOpeningElementAfterName(n))}jsxParseOpeningElementAfterName(e){let n=[];for(;!this.match(56)&&!this.match(144);)n.push(this.jsxParseAttribute());return e.attributes=n,e.selfClosing=this.eat(56),this.expect(144),this.finishNode(e,"JSXOpeningElement")}jsxParseClosingElementAt(e){let n=this.startNodeAt(e);return this.eat(144)?this.finishNode(n,"JSXClosingFragment"):(n.name=this.jsxParseElementName(),this.expect(144),this.finishNode(n,"JSXClosingElement"))}jsxParseElementAt(e){let n=this.startNodeAt(e),i=[],s=this.jsxParseOpeningElementAt(e),a=null;if(!s.selfClosing){e:for(;;)switch(this.state.type){case 143:if(e=this.state.startLoc,this.next(),this.eat(56)){a=this.jsxParseClosingElementAt(e);break e}i.push(this.jsxParseElementAt(e));break;case 142:i.push(this.parseLiteral(this.state.value,"JSXText"));break;case 5:{let o=this.startNode();this.setContext(te.brace),this.next(),this.match(21)?i.push(this.jsxParseSpreadChild(o)):i.push(this.jsxParseExpressionContainer(o,te.j_expr));break}default:this.unexpected()}Ct(s)&&!Ct(a)&&a!==null?this.raise(Wt.MissingClosingTagFragment,a):!Ct(s)&&Ct(a)?this.raise(Wt.MissingClosingTagElement,a,{openingTagName:Pr(s.name)}):!Ct(s)&&!Ct(a)&&Pr(a.name)!==Pr(s.name)&&this.raise(Wt.MissingClosingTagElement,a,{openingTagName:Pr(s.name)})}if(Ct(s)?(n.openingFragment=s,n.closingFragment=a):(n.openingElement=s,n.closingElement=a),n.children=i,this.match(47))throw this.raise(Wt.UnwrappedAdjacentJSXElements,this.state.startLoc);return Ct(s)?this.finishNode(n,"JSXFragment"):this.finishNode(n,"JSXElement")}jsxParseElement(){let e=this.state.startLoc;return this.next(),this.jsxParseElementAt(e)}setContext(e){let{context:n}=this.state;n[n.length-1]=e}parseExprAtom(e){return this.match(143)?this.jsxParseElement():this.match(47)&&this.input.charCodeAt(this.state.pos)!==33?(this.replaceToken(143),this.jsxParseElement()):super.parseExprAtom(e)}skipSpace(){this.curContext().preserveSpace||super.skipSpace()}getTokenFromCode(e){let n=this.curContext();if(n===te.j_expr){this.jsxReadToken();return}if(n===te.j_oTag||n===te.j_cTag){if(ct(e)){this.jsxReadWord();return}if(e===62){++this.state.pos,this.finishToken(144);return}if((e===34||e===39)&&n===te.j_oTag){this.jsxReadString(e);return}}if(e===60&&this.state.canStartJSXElement&&this.input.charCodeAt(this.state.pos+1)!==33){++this.state.pos,this.finishToken(143);return}super.getTokenFromCode(e)}updateContext(e){let{context:n,type:i}=this.state;if(i===56&&e===143)n.splice(-2,2,te.j_cTag),this.state.canStartJSXElement=!1;else if(i===143)n.push(te.j_oTag);else if(i===144){let s=n[n.length-1];s===te.j_oTag&&e===56||s===te.j_cTag?(n.pop(),this.state.canStartJSXElement=n[n.length-1]===te.j_expr):(this.setContext(te.j_expr),this.state.canStartJSXElement=!0)}else this.state.canStartJSXElement=rb(i)}},po=class extends vn{constructor(...t){super(...t),this.tsNames=new Map}},fo=class extends kn{constructor(...t){super(...t),this.importsStack=[]}createScope(t){return this.importsStack.push(new Set),new po(t)}enter(t){t===1024&&this.importsStack.push(new Set),super.enter(t)}exit(){let t=super.exit();return t===1024&&this.importsStack.pop(),t}hasImport(t,e){let n=this.importsStack.length;if(this.importsStack[n-1].has(t))return!0;if(!e&&n>1){for(let i=0;i<n-1;i++)if(this.importsStack[i].has(t))return!0}return!1}declareName(t,e,n){if(e&4096){this.hasImport(t,!0)&&this.parser.raise(b.VarRedeclaration,n,{identifierName:t}),this.importsStack[this.importsStack.length-1].add(t);return}let i=this.currentScope(),s=i.tsNames.get(t)||0;if(e&1024){this.maybeExportDefined(i,t),i.tsNames.set(t,s|16);return}super.declareName(t,e,n),e&2&&(e&1||(this.checkRedeclarationInScope(i,t,e,n),this.maybeExportDefined(i,t)),s=s|1),e&256&&(s=s|2),e&512&&(s=s|4),e&128&&(s=s|8),s&&i.tsNames.set(t,s)}isRedeclaredInScope(t,e,n){let i=t.tsNames.get(e);if((i&2)>0){if(n&256){let s=!!(n&512),a=(i&4)>0;return s!==a}return!0}return n&128&&(i&8)>0?t.names.get(e)&2?!!(n&1):!1:n&2&&(i&1)>0?!0:super.isRedeclaredInScope(t,e,n)}checkLocalExport(t){let{name:e}=t;if(this.hasImport(e))return;let n=this.scopeStack.length;for(let i=n-1;i>=0;i--){let a=this.scopeStack[i].tsNames.get(e);if((a&1)>0||(a&16)>0)return}super.checkLocalExport(t)}},ho=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()&2)>0}get hasYield(){return(this.currentFlags()&1)>0}get hasReturn(){return(this.currentFlags()&4)>0}get hasIn(){return(this.currentFlags()&8)>0}};function Ui(r,t){return(r?2:0)|(t?1:0)}var mo=class{constructor(){this.sawUnambiguousESM=!1,this.ambiguousScriptDifferentAst=!1}sourceToOffsetPos(t){return t+this.startIndex}offsetToSourcePos(t){return t-this.startIndex}hasPlugin(t){if(typeof t=="string")return this.plugins.has(t);{let[e,n]=t;if(!this.hasPlugin(e))return!1;let i=this.plugins.get(e);for(let s of Object.keys(n))if(i?.[s]!==n[s])return!1;return!0}}getPluginOption(t,e){var n;return(n=this.plugins.get(t))==null?void 0:n[e]}};function Xu(r,t){r.trailingComments===void 0?r.trailingComments=t:r.trailingComments.unshift(...t)}function Nb(r,t){r.leadingComments===void 0?r.leadingComments=t:r.leadingComments.unshift(...t)}function In(r,t){r.innerComments===void 0?r.innerComments=t:r.innerComments.unshift(...t)}function Ye(r,t,e){let n=null,i=t.length;for(;n===null&&i>0;)n=t[--i];n===null||n.start>e.start?In(r,e.comments):Xu(n,e.comments)}var yo=class extends mo{addComment(t){this.filename&&(t.loc.filename=this.filename);let{commentsLen:e}=this.state;this.comments.length!==e&&(this.comments.length=e),this.comments.push(t),this.state.commentsLen++}processComment(t){let{commentStack:e}=this.state,n=e.length;if(n===0)return;let i=n-1,s=e[i];s.start===t.end&&(s.leadingNode=t,i--);let{start:a}=t;for(;i>=0;i--){let o=e[i],d=o.end;if(d>a)o.containingNode=t,this.finalizeComment(o),e.splice(i,1);else{d===a&&(o.trailingNode=t);break}}}finalizeComment(t){var e;let{comments:n}=t;if(t.leadingNode!==null||t.trailingNode!==null)t.leadingNode!==null&&Xu(t.leadingNode,n),t.trailingNode!==null&&Nb(t.trailingNode,n);else{let i=t.containingNode,s=t.start;if(this.input.charCodeAt(this.offsetToSourcePos(s)-1)===44)switch(i.type){case"ObjectExpression":case"ObjectPattern":Ye(i,i.properties,t);break;case"CallExpression":case"NewExpression":case"OptionalCallExpression":Ye(i,i.arguments,t);break;case"ImportExpression":Ye(i,[i.source,(e=i.options)!=null?e:null],t);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":case"ObjectMethod":case"ClassMethod":case"ClassPrivateMethod":case"TSTypeParameterDeclaration":Ye(i,i.params,t);break;case"ArrayExpression":case"ArrayPattern":Ye(i,i.elements,t);break;case"ExportNamedDeclaration":case"ImportDeclaration":Ye(i,i.specifiers,t);break;case"TSEnumDeclaration":Ye(i,i.members,t);break;case"TSEnumBody":Ye(i,i.members,t);break;case"TSInterfaceBody":Ye(i,i.body,t);break;default:{if(i.type==="RecordExpression"){Ye(i,i.properties,t);break}if(i.type==="TupleExpression"){Ye(i,i.elements,t);break}In(i,n)}}else In(i,n)}}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:n}=e;if(n===0)return;let i=e[n-1];i.leadingNode===t&&(i.leadingNode=null)}takeSurroundingComments(t,e,n){let{commentStack:i}=this.state,s=i.length;if(s===0)return;let a=s-1;for(;a>=0;a--){let o=i[a],d=o.end;if(o.start===n)o.leadingNode=t;else if(d===e)o.trailingNode=t;else if(d<e)break}}},go=class r{constructor(){this.flags=1024,this.startIndex=void 0,this.curLine=void 0,this.lineStart=void 0,this.startLoc=void 0,this.endLoc=void 0,this.errors=[],this.potentialArrowAt=-1,this.noArrowAt=[],this.noArrowParamsConversionAt=[],this.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null},this.labels=[],this.commentsLen=0,this.commentStack=[],this.pos=0,this.type=140,this.value=null,this.start=0,this.end=0,this.lastTokEndLoc=null,this.lastTokStartLoc=null,this.context=[te.brace],this.firstInvalidTemplateEscapePos=null,this.strictErrors=new Map,this.tokensLength=0}get strict(){return(this.flags&1)>0}set strict(t){t?this.flags|=1:this.flags&=-2}init({strictMode:t,sourceType:e,startIndex:n,startLine:i,startColumn:s}){this.strict=t===!1?!1:t===!0?!0:e==="module",this.startIndex=n,this.curLine=i,this.lineStart=-s,this.startLoc=this.endLoc=new lt(i,s,n)}get maybeInArrowParameters(){return(this.flags&2)>0}set maybeInArrowParameters(t){t?this.flags|=2:this.flags&=-3}get inType(){return(this.flags&4)>0}set inType(t){t?this.flags|=4:this.flags&=-5}get noAnonFunctionType(){return(this.flags&8)>0}set noAnonFunctionType(t){t?this.flags|=8:this.flags&=-9}get hasFlowComment(){return(this.flags&16)>0}set hasFlowComment(t){t?this.flags|=16:this.flags&=-17}get isAmbientContext(){return(this.flags&32)>0}set isAmbientContext(t){t?this.flags|=32:this.flags&=-33}get inAbstractClass(){return(this.flags&64)>0}set inAbstractClass(t){t?this.flags|=64:this.flags&=-65}get inDisallowConditionalTypesContext(){return(this.flags&128)>0}set inDisallowConditionalTypesContext(t){t?this.flags|=128:this.flags&=-129}get soloAwait(){return(this.flags&256)>0}set soloAwait(t){t?this.flags|=256:this.flags&=-257}get inFSharpPipelineDirectBody(){return(this.flags&512)>0}set inFSharpPipelineDirectBody(t){t?this.flags|=512:this.flags&=-513}get canStartJSXElement(){return(this.flags&1024)>0}set canStartJSXElement(t){t?this.flags|=1024:this.flags&=-1025}get containsEsc(){return(this.flags&2048)>0}set containsEsc(t){t?this.flags|=2048:this.flags&=-2049}get hasTopLevelAwait(){return(this.flags&4096)>0}set hasTopLevelAwait(t){t?this.flags|=4096:this.flags&=-4097}curPosition(){return new lt(this.curLine,this.pos-this.lineStart,this.pos+this.startIndex)}clone(){let t=new r;return t.flags=this.flags,t.startIndex=this.startIndex,t.curLine=this.curLine,t.lineStart=this.lineStart,t.startLoc=this.startLoc,t.endLoc=this.endLoc,t.errors=this.errors.slice(),t.potentialArrowAt=this.potentialArrowAt,t.noArrowAt=this.noArrowAt.slice(),t.noArrowParamsConversionAt=this.noArrowParamsConversionAt.slice(),t.topicContext=this.topicContext,t.labels=this.labels.slice(),t.commentsLen=this.commentsLen,t.commentStack=this.commentStack.slice(),t.pos=this.pos,t.type=this.type,t.value=this.value,t.start=this.start,t.end=this.end,t.lastTokEndLoc=this.lastTokEndLoc,t.lastTokStartLoc=this.lastTokStartLoc,t.context=this.context.slice(),t.firstInvalidTemplateEscapePos=this.firstInvalidTemplateEscapePos,t.strictErrors=this.strictErrors,t.tokensLength=this.tokensLength,t}},Ob=function(t){return t>=48&&t<=57},Mu={decBinOct:new Set([46,66,69,79,95,98,101,111]),hex:new Set([46,88,95,120])},zi={bin:r=>r===48||r===49,oct:r=>r>=48&&r<=55,dec:r=>r>=48&&r<=57,hex:r=>r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102};function $u(r,t,e,n,i,s){let a=e,o=n,d=i,c="",l=null,u=e,{length:p}=t;for(;;){if(e>=p){s.unterminated(a,o,d),c+=t.slice(u,e);break}let f=t.charCodeAt(e);if(Db(r,f,t,e)){c+=t.slice(u,e);break}if(f===92){c+=t.slice(u,e);let h=Lb(t,e,n,i,r==="template",s);h.ch===null&&!l?l={pos:e,lineStart:n,curLine:i}:c+=h.ch,{pos:e,lineStart:n,curLine:i}=h,u=e}else f===8232||f===8233?(++e,++i,n=e):f===10||f===13?r==="template"?(c+=t.slice(u,e)+`
8
+ `,++e,f===13&&t.charCodeAt(e)===10&&++e,++i,u=n=e):s.unterminated(a,o,d):++e}return{pos:e,str:c,firstInvalidLoc:l,lineStart:n,curLine:i,containsInvalid:!!l}}function Db(r,t,e,n){return r==="template"?t===96||t===36&&e.charCodeAt(n+1)===123:t===(r==="double"?34:39)}function Lb(r,t,e,n,i,s){let a=!i;t++;let o=c=>({pos:t,ch:c,lineStart:e,curLine:n}),d=r.charCodeAt(t++);switch(d){case 110:return o(`
9
+ `);case 114:return o("\r");case 120:{let c;return{code:c,pos:t}=wo(r,t,e,n,2,!1,a,s),o(c===null?null:String.fromCharCode(c))}case 117:{let c;return{code:c,pos:t}=Qu(r,t,e,n,a,s),o(c===null?null:String.fromCodePoint(c))}case 116:return o(" ");case 98:return o("\b");case 118:return o("\v");case 102:return o("\f");case 13:r.charCodeAt(t)===10&&++t;case 10:e=t,++n;case 8232:case 8233:return o("");case 56:case 57:if(i)return o(null);s.strictNumericEscape(t-1,e,n);default:if(d>=48&&d<=55){let c=t-1,u=/^[0-7]+/.exec(r.slice(c,t+2))[0],p=parseInt(u,8);p>255&&(u=u.slice(0,-1),p=parseInt(u,8)),t+=u.length-1;let f=r.charCodeAt(t);if(u!=="0"||f===56||f===57){if(i)return o(null);s.strictNumericEscape(c,e,n)}return o(String.fromCharCode(p))}return o(String.fromCharCode(d))}}function wo(r,t,e,n,i,s,a,o){let d=t,c;return{n:c,pos:t}=Yu(r,t,e,n,16,i,s,!1,o,!a),c===null&&(a?o.invalidEscapeSequence(d,e,n):t=d-1),{code:c,pos:t}}function Yu(r,t,e,n,i,s,a,o,d,c){let l=t,u=i===16?Mu.hex:Mu.decBinOct,p=i===16?zi.hex:i===10?zi.dec:i===8?zi.oct:zi.bin,f=!1,h=0;for(let g=0,m=s??1/0;g<m;++g){let y=r.charCodeAt(t),w;if(y===95&&o!=="bail"){let x=r.charCodeAt(t-1),v=r.charCodeAt(t+1);if(o){if(Number.isNaN(v)||!p(v)||u.has(x)||u.has(v)){if(c)return{n:null,pos:t};d.unexpectedNumericSeparator(t,e,n)}}else{if(c)return{n:null,pos:t};d.numericSeparatorInEscapeSequence(t,e,n)}++t;continue}if(y>=97?w=y-97+10:y>=65?w=y-65+10:Ob(y)?w=y-48:w=1/0,w>=i){if(w<=9&&c)return{n:null,pos:t};if(w<=9&&d.invalidDigit(t,e,n,i))w=0;else if(a)w=0,f=!0;else break}++t,h=h*i+w}return t===l||s!=null&&t-l!==s||f?{n:null,pos:t}:{n:h,pos:t}}function Qu(r,t,e,n,i,s){let a=r.charCodeAt(t),o;if(a===123){if(++t,{code:o,pos:t}=wo(r,t,e,n,r.indexOf("}",t)-t,!0,i,s),++t,o!==null&&o>1114111)if(i)s.invalidCodePoint(t,e,n);else return{code:null,pos:t}}else({code:o,pos:t}=wo(r,t,e,n,4,!1,i,s));return{code:o,pos:t}}function gn(r,t,e){return new lt(e,r-t,r)}var Mb=new Set([103,109,115,105,121,117,100,118]),dt=class{constructor(t){let e=t.startIndex||0;this.type=t.type,this.value=t.value,this.start=e+t.start,this.end=e+t.end,this.loc=new Ar(t.startLoc,t.endLoc)}},bo=class extends yo{constructor(t,e){super(),this.isLookahead=void 0,this.tokens=[],this.errorHandlers_readInt={invalidDigit:(n,i,s,a)=>this.optionFlags&2048?(this.raise(b.InvalidDigit,gn(n,i,s),{radix:a}),!0):!1,numericSeparatorInEscapeSequence:this.errorBuilder(b.NumericSeparatorInEscapeSequence),unexpectedNumericSeparator:this.errorBuilder(b.UnexpectedNumericSeparator)},this.errorHandlers_readCodePoint=Object.assign({},this.errorHandlers_readInt,{invalidEscapeSequence:this.errorBuilder(b.InvalidEscapeSequence),invalidCodePoint:this.errorBuilder(b.InvalidCodePoint)}),this.errorHandlers_readStringContents_string=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:(n,i,s)=>{this.recordStrictModeErrors(b.StrictNumericEscape,gn(n,i,s))},unterminated:(n,i,s)=>{throw this.raise(b.UnterminatedString,gn(n-1,i,s))}}),this.errorHandlers_readStringContents_template=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:this.errorBuilder(b.StrictNumericEscape),unterminated:(n,i,s)=>{throw this.raise(b.UnterminatedTemplate,gn(n,i,s))}}),this.state=new go,this.state.init(t),this.input=e,this.length=e.length,this.comments=[],this.isLookahead=!1}pushToken(t){this.tokens.length=this.state.tokensLength,this.tokens.push(t),++this.state.tokensLength}next(){this.checkKeywordEscapes(),this.optionFlags&256&&this.pushToken(new dt(this.state)),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 no.lastIndex=t,no.test(this.input)?no.lastIndex:t}lookaheadCharCode(){return this.lookaheadCharCodeSince(this.state.pos)}lookaheadCharCodeSince(t){return this.input.charCodeAt(this.nextTokenStartSince(t))}nextTokenInLineStart(){return this.nextTokenInLineStartSince(this.state.pos)}nextTokenInLineStartSince(t){return io.lastIndex=t,io.test(this.input)?io.lastIndex:t}lookaheadInLineCharCode(){return this.input.charCodeAt(this.nextTokenInLineStart())}codePointAtPos(t){let e=this.input.charCodeAt(t);if((e&64512)===55296&&++t<this.input.length){let n=this.input.charCodeAt(t);(n&64512)===56320&&(e=65536+((e&1023)<<10)+(n&1023))}return e}setStrict(t){this.state.strict=t,t&&(this.state.strictErrors.forEach(([e,n])=>this.raise(e,n)),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(140);return}this.getTokenFromCode(this.codePointAtPos(this.state.pos))}skipBlockComment(t){let e;this.isLookahead||(e=this.state.curPosition());let n=this.state.pos,i=this.input.indexOf(t,n+2);if(i===-1)throw this.raise(b.UnterminatedComment,this.state.curPosition());for(this.state.pos=i+t.length,Vi.lastIndex=n+2;Vi.test(this.input)&&Vi.lastIndex<=i;)++this.state.curLine,this.state.lineStart=Vi.lastIndex;if(this.isLookahead)return;let s={type:"CommentBlock",value:this.input.slice(n+2,i),start:this.sourceToOffsetPos(n),end:this.sourceToOffsetPos(i+t.length),loc:new Ar(e,this.state.curPosition())};return this.optionFlags&256&&this.pushToken(s),s}skipLineComment(t){let e=this.state.pos,n;this.isLookahead||(n=this.state.curPosition());let i=this.input.charCodeAt(this.state.pos+=t);if(this.state.pos<this.length)for(;!Rr(i)&&++this.state.pos<this.length;)i=this.input.charCodeAt(this.state.pos);if(this.isLookahead)return;let s=this.state.pos,o={type:"CommentLine",value:this.input.slice(e+t,s),start:this.sourceToOffsetPos(e),end:this.sourceToOffsetPos(s),loc:new Ar(n,this.state.curPosition())};return this.optionFlags&256&&this.pushToken(o),o}skipSpace(){let t=this.state.pos,e=this.optionFlags&4096?[]:null;e:for(;this.state.pos<this.length;){let n=this.input.charCodeAt(this.state.pos);switch(n){case 32:case 160:case 9:++this.state.pos;break;case 13:this.input.charCodeAt(this.state.pos+1)===10&&++this.state.pos;case 10:case 8232:case 8233:++this.state.pos,++this.state.curLine,this.state.lineStart=this.state.pos;break;case 47:switch(this.input.charCodeAt(this.state.pos+1)){case 42:{let i=this.skipBlockComment("*/");i!==void 0&&(this.addComment(i),e?.push(i));break}case 47:{let i=this.skipLineComment(2);i!==void 0&&(this.addComment(i),e?.push(i));break}default:break e}break;default:if(Eb(n))++this.state.pos;else if(n===45&&!this.inModule&&this.optionFlags&8192){let i=this.state.pos;if(this.input.charCodeAt(i+1)===45&&this.input.charCodeAt(i+2)===62&&(t===0||this.state.lineStart>t)){let s=this.skipLineComment(3);s!==void 0&&(this.addComment(s),e?.push(s))}else break e}else if(n===60&&!this.inModule&&this.optionFlags&8192){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 s=this.skipLineComment(4);s!==void 0&&(this.addComment(s),e?.push(s))}else break e}else break e}}if(e?.length>0){let n=this.state.pos,i={start:this.sourceToOffsetPos(t),end:this.sourceToOffsetPos(n),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 n=this.state.type;this.state.type=t,this.state.value=e,this.isLookahead||this.updateContext(n)}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(b.UnexpectedDigitAfterHash,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?b.RecordExpressionHashIncorrectStartSyntaxType:b.TupleExpressionHashIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,e===123?this.finishToken(7):this.finishToken(1)}else ct(e)?(++this.state.pos,this.finishToken(139,this.readWord1(e))):e===92?(++this.state.pos,this.finishToken(139,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;!Rr(t)&&++this.state.pos<this.length;)t=this.input.charCodeAt(this.state.pos);let n=this.input.slice(e+2,this.state.pos);return this.finishToken(28,n),!0}readToken_mult_modulo(t){let e=t===42?55:54,n=1,i=this.input.charCodeAt(this.state.pos+1);t===42&&i===42&&(n++,i=this.input.charCodeAt(this.state.pos+2),e=57),i===61&&!this.state.inType&&(n++,e=t===37?33:30),this.finishOp(e,n)}readToken_pipe_amp(t){let e=this.input.charCodeAt(this.state.pos+1);if(e===t){this.input.charCodeAt(this.state.pos+2)===61?this.finishOp(30,3):this.finishOp(t===124?41:42,2);return}if(t===124){if(e===62){this.finishOp(39,2);return}if(this.hasPlugin("recordAndTuple")&&e===125){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(b.RecordExpressionBarIncorrectEndSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(9);return}if(this.hasPlugin("recordAndTuple")&&e===93){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(b.TupleExpressionBarIncorrectEndSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(4);return}}if(e===61){this.finishOp(30,2);return}this.finishOp(t===124?43:45,1)}readToken_caret(){let t=this.input.charCodeAt(this.state.pos+1);t===61&&!this.state.inType?this.finishOp(32,2):t===94&&this.hasPlugin(["pipelineOperator",{proposal:"hack",topicToken:"^^"}])?(this.finishOp(37,2),this.input.codePointAt(this.state.pos)===94&&this.unexpected()):this.finishOp(44,1)}readToken_atSign(){this.input.charCodeAt(this.state.pos+1)===64&&this.hasPlugin(["pipelineOperator",{proposal:"hack",topicToken:"@@"}])?this.finishOp(38,2):this.finishOp(26,1)}readToken_plus_min(t){let e=this.input.charCodeAt(this.state.pos+1);if(e===t){this.finishOp(34,2);return}e===61?this.finishOp(30,2):this.finishOp(53,1)}readToken_lt(){let{pos:t}=this.state,e=this.input.charCodeAt(t+1);if(e===60){if(this.input.charCodeAt(t+2)===61){this.finishOp(30,3);return}this.finishOp(51,2);return}if(e===61){this.finishOp(49,2);return}this.finishOp(47,1)}readToken_gt(){let{pos:t}=this.state,e=this.input.charCodeAt(t+1);if(e===62){let n=this.input.charCodeAt(t+2)===62?3:2;if(this.input.charCodeAt(t+n)===61){this.finishOp(30,n+1);return}this.finishOp(52,n);return}if(e===61){this.finishOp(49,2);return}this.finishOp(48,1)}readToken_eq_excl(t){let e=this.input.charCodeAt(this.state.pos+1);if(e===61){this.finishOp(46,this.input.charCodeAt(this.state.pos+2)===61?3:2);return}if(t===61&&e===62){this.state.pos+=2,this.finishToken(19);return}this.finishOp(t===61?29:35,1)}readToken_question(){let t=this.input.charCodeAt(this.state.pos+1),e=this.input.charCodeAt(this.state.pos+2);t===63?e===61?this.finishOp(30,3):this.finishOp(40,2):t===46&&!(e>=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(b.TupleExpressionBarIncorrectStartSyntaxType,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(b.RecordExpressionBarIncorrectStartSyntaxType,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(ct(t)){this.readWord(t);return}}throw this.raise(b.InvalidOrUnexpectedToken,this.state.curPosition(),{unexpected:String.fromCodePoint(t)})}finishOp(t,e){let n=this.input.slice(this.state.pos,this.state.pos+e);this.state.pos+=e,this.finishToken(t,n)}readRegexp(){let t=this.state.startLoc,e=this.state.start+1,n,i,{pos:s}=this.state;for(;;++s){if(s>=this.length)throw this.raise(b.UnterminatedRegExp,Oe(t,1));let c=this.input.charCodeAt(s);if(Rr(c))throw this.raise(b.UnterminatedRegExp,Oe(t,1));if(n)n=!1;else{if(c===91)i=!0;else if(c===93&&i)i=!1;else if(c===47&&!i)break;n=c===92}}let a=this.input.slice(e,s);++s;let o="",d=()=>Oe(t,s+2-e);for(;s<this.length;){let c=this.codePointAtPos(s),l=String.fromCharCode(c);if(Mb.has(c))c===118?o.includes("u")&&this.raise(b.IncompatibleRegExpUVFlags,d()):c===117&&o.includes("v")&&this.raise(b.IncompatibleRegExpUVFlags,d()),o.includes(l)&&this.raise(b.DuplicateRegExpFlags,d());else if(Xt(c)||c===92)this.raise(b.MalformedRegExpFlags,d());else break;++s,o+=l}this.state.pos=s,this.finishToken(138,{pattern:a,flags:o})}readInt(t,e,n=!1,i=!0){let{n:s,pos:a}=Yu(this.input,this.state.pos,this.state.lineStart,this.state.curLine,t,e,n,i,this.errorHandlers_readInt,!1);return this.state.pos=a,s}readRadixNumber(t){let e=this.state.pos,n=this.state.curPosition(),i=!1;this.state.pos+=2;let s=this.readInt(t);s==null&&this.raise(b.InvalidDigit,Oe(n,2),{radix:t});let a=this.input.charCodeAt(this.state.pos);if(a===110)++this.state.pos,i=!0;else if(a===109)throw this.raise(b.InvalidDecimal,n);if(ct(this.codePointAtPos(this.state.pos)))throw this.raise(b.NumberIdentifier,this.state.curPosition());if(i){let o=this.input.slice(e,this.state.pos).replace(/[_n]/g,"");this.finishToken(136,o);return}this.finishToken(135,s)}readNumber(t){let e=this.state.pos,n=this.state.curPosition(),i=!1,s=!1,a=!1,o=!1;!t&&this.readInt(10)===null&&this.raise(b.InvalidNumber,this.state.curPosition());let d=this.state.pos-e>=2&&this.input.charCodeAt(e)===48;if(d){let f=this.input.slice(e,this.state.pos);if(this.recordStrictModeErrors(b.StrictOctalLiteral,n),!this.state.strict){let h=f.indexOf("_");h>0&&this.raise(b.ZeroDigitNumericSeparator,Oe(n,h))}o=d&&!/[89]/.test(f)}let c=this.input.charCodeAt(this.state.pos);if(c===46&&!o&&(++this.state.pos,this.readInt(10),i=!0,c=this.input.charCodeAt(this.state.pos)),(c===69||c===101)&&!o&&(c=this.input.charCodeAt(++this.state.pos),(c===43||c===45)&&++this.state.pos,this.readInt(10)===null&&this.raise(b.InvalidOrMissingExponent,n),i=!0,a=!0,c=this.input.charCodeAt(this.state.pos)),c===110&&((i||d)&&this.raise(b.InvalidBigIntLiteral,n),++this.state.pos,s=!0),c===109){this.expectPlugin("decimal",this.state.curPosition()),(a||d)&&this.raise(b.InvalidDecimal,n),++this.state.pos;var l=!0}if(ct(this.codePointAtPos(this.state.pos)))throw this.raise(b.NumberIdentifier,this.state.curPosition());let u=this.input.slice(e,this.state.pos).replace(/[_mn]/g,"");if(s){this.finishToken(136,u);return}if(l){this.finishToken(137,u);return}let p=o?parseInt(u,8):parseFloat(u);this.finishToken(135,p)}readCodePoint(t){let{code:e,pos:n}=Qu(this.input,this.state.pos,this.state.lineStart,this.state.curLine,t,this.errorHandlers_readCodePoint);return this.state.pos=n,e}readString(t){let{str:e,pos:n,curLine:i,lineStart:s}=$u(t===34?"double":"single",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_string);this.state.pos=n+1,this.state.lineStart=s,this.state.curLine=i,this.finishToken(134,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:n,pos:i,curLine:s,lineStart:a}=$u("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=a,this.state.curLine=s,n&&(this.state.firstInvalidTemplateEscapePos=new lt(n.curLine,n.pos-n.lineStart,this.sourceToOffsetPos(n.pos))),this.input.codePointAt(i)===96?this.finishToken(24,n?null:t+e+"`"):(this.state.pos++,this.finishToken(25,n?null:t+e+"${"))}recordStrictModeErrors(t,e){let n=e.index;this.state.strict&&!this.state.strictErrors.has(n)?this.raise(t,e):this.state.strictErrors.set(n,[t,e])}readWord1(t){this.state.containsEsc=!1;let e="",n=this.state.pos,i=this.state.pos;for(t!==void 0&&(this.state.pos+=t<=65535?1:2);this.state.pos<this.length;){let s=this.codePointAtPos(this.state.pos);if(Xt(s))this.state.pos+=s<=65535?1:2;else if(s===92){this.state.containsEsc=!0,e+=this.input.slice(i,this.state.pos);let a=this.state.curPosition(),o=this.state.pos===n?ct:Xt;if(this.input.charCodeAt(++this.state.pos)!==117){this.raise(b.MissingUnicodeEscape,this.state.curPosition()),i=this.state.pos-1;continue}++this.state.pos;let d=this.readCodePoint(!0);d!==null&&(o(d)||this.raise(b.EscapedCharNotAnIdentifier,a),e+=String.fromCodePoint(d)),i=this.state.pos}else break}return e+this.input.slice(i,this.state.pos)}readWord(t){let e=this.readWord1(t),n=Co.get(e);n!==void 0?this.finishToken(n,Nt(n)):this.finishToken(132,e)}checkKeywordEscapes(){let{type:t}=this.state;$o(t)&&this.state.containsEsc&&this.raise(b.InvalidEscapedReservedWord,this.state.startLoc,{reservedWord:Nt(t)})}raise(t,e,n={}){let i=e instanceof lt?e:e.loc.start,s=t(i,n);if(!(this.optionFlags&2048))throw s;return this.isLookahead||this.state.errors.push(s),s}raiseOverwrite(t,e,n={}){let i=e instanceof lt?e:e.loc.start,s=i.index,a=this.state.errors;for(let o=a.length-1;o>=0;o--){let d=a[o];if(d.loc.index===s)return a[o]=t(i,n);if(d.loc.index<s)break}return this.raise(t,e,n)}updateContext(t){}unexpected(t,e){throw this.raise(b.UnexpectedToken,t??this.state.startLoc,{expected:e?Nt(e):null})}expectPlugin(t,e){if(this.hasPlugin(t))return!0;throw this.raise(b.MissingPlugin,e??this.state.startLoc,{missingPlugin:[t]})}expectOnePlugin(t){if(!t.some(e=>this.hasPlugin(e)))throw this.raise(b.MissingOneOfPlugins,this.state.startLoc,{missingPlugin:t})}errorBuilder(t){return(e,n,i)=>{this.raise(t,gn(e,n,i))}}},xo=class{constructor(){this.privateNames=new Set,this.loneAccessors=new Map,this.undefinedPrivateNames=new Map}},vo=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 xo)}exit(){let t=this.stack.pop(),e=this.current();for(let[n,i]of Array.from(t.undefinedPrivateNames))e?e.undefinedPrivateNames.has(n)||e.undefinedPrivateNames.set(n,i):this.parser.raise(b.InvalidPrivateFieldResolution,i,{identifierName:n})}declarePrivateName(t,e,n){let{privateNames:i,loneAccessors:s,undefinedPrivateNames:a}=this.current(),o=i.has(t);if(e&3){let d=o&&s.get(t);if(d){let c=d&4,l=e&4,u=d&3,p=e&3;o=u===p||c!==l,o||s.delete(t)}else o||s.set(t,e)}o&&this.parser.raise(b.PrivateNameRedeclaration,n,{identifierName:t}),i.add(t),a.delete(t)}usePrivateName(t,e){let n;for(n of this.stack)if(n.privateNames.has(t))return;n?n.undefinedPrivateNames.set(t,e):this.parser.raise(b.InvalidPrivateFieldResolution,e,{identifierName:t})}},Sr=class{constructor(t=0){this.type=t}canBeArrowParameterDeclaration(){return this.type===2||this.type===1}isCertainlyParameterDeclaration(){return this.type===3}},Wi=class extends Sr{constructor(t){super(t),this.declarationErrors=new Map}recordDeclarationError(t,e){let n=e.index;this.declarationErrors.set(n,[t,e])}clearDeclarationError(t){this.declarationErrors.delete(t)}iterateErrors(t){this.declarationErrors.forEach(t)}},ko=class{constructor(t){this.parser=void 0,this.stack=[new Sr],this.parser=t}enter(t){this.stack.push(t)}exit(){this.stack.pop()}recordParameterInitializerError(t,e){let n=e.loc.start,{stack:i}=this,s=i.length-1,a=i[s];for(;!a.isCertainlyParameterDeclaration();){if(a.canBeArrowParameterDeclaration())a.recordDeclarationError(t,n);else return;a=i[--s]}this.parser.raise(t,n)}recordArrowParameterBindingError(t,e){let{stack:n}=this,i=n[n.length-1],s=e.loc.start;if(i.isCertainlyParameterDeclaration())this.parser.raise(t,s);else if(i.canBeArrowParameterDeclaration())i.recordDeclarationError(t,s);else return}recordAsyncArrowParametersError(t){let{stack:e}=this,n=e.length-1,i=e[n];for(;i.canBeArrowParameterDeclaration();)i.type===2&&i.recordDeclarationError(b.AwaitBindingIdentifier,t),i=e[--n]}validateAsPattern(){let{stack:t}=this,e=t[t.length-1];e.canBeArrowParameterDeclaration()&&e.iterateErrors(([n,i])=>{this.parser.raise(n,i);let s=t.length-2,a=t[s];for(;a.canBeArrowParameterDeclaration();)a.clearDeclarationError(i.index),a=t[--s]})}};function $b(){return new Sr(3)}function _b(){return new Wi(1)}function Fb(){return new Wi(2)}function Zu(){return new Sr}var Io=class extends bo{addExtra(t,e,n,i=!0){if(!t)return;let{extra:s}=t;s==null&&(s={},t.extra=s),i?s[e]=n:Object.defineProperty(s,e,{enumerable:i,value:n})}isContextual(t){return this.state.type===t&&!this.state.containsEsc}isUnparsedContextual(t,e){if(this.input.startsWith(e,t)){let n=this.input.charCodeAt(t+e.length);return!(Xt(n)||(n&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,this.state.startLoc);this.unexpected(null,t)}}canInsertSemicolon(){return this.match(140)||this.match(8)||this.hasPrecedingLineBreak()}hasPrecedingLineBreak(){return Lu(this.input,this.offsetToSourcePos(this.state.lastTokEndLoc.index),this.state.start)}hasFollowingLineBreak(){return Lu(this.input,this.state.end,this.nextTokenStart())}isLineTerminator(){return this.eat(13)||this.canInsertSemicolon()}semicolon(t=!0){(t?this.isLineTerminator():this.eat(13))||this.raise(b.MissingSemicolon,this.state.lastTokEndLoc)}expect(t,e){this.eat(t)||this.unexpected(e,t)}tryParse(t,e=this.state.clone()){let n={node:null};try{let i=t((s=null)=>{throw n.node=s,n});if(this.state.errors.length>e.errors.length){let s=this.state;return this.state=e,this.state.tokensLength=s.tokensLength,{node:i,error:s.errors[e.errors.length],thrown:!1,aborted:!1,failState:s}}return{node:i,error:null,thrown:!1,aborted:!1,failState:null}}catch(i){let s=this.state;if(this.state=e,i instanceof SyntaxError)return{node:null,error:i,thrown:!0,aborted:!1,failState:s};if(i===n)return{node:n.node,error:null,thrown:!1,aborted:!0,failState:s};throw i}}checkExpressionErrors(t,e){if(!t)return!1;let{shorthandAssignLoc:n,doubleProtoLoc:i,privateKeyLoc:s,optionalParametersLoc:a,voidPatternLoc:o}=t,d=!!n||!!i||!!a||!!s||!!o;if(!e)return d;n!=null&&this.raise(b.InvalidCoverInitializedName,n),i!=null&&this.raise(b.DuplicateProto,i),s!=null&&this.raise(b.UnexpectedPrivateField,s),a!=null&&this.unexpected(a),o!=null&&this.raise(b.InvalidCoverDiscardElement,o)}isLiteralPropertyName(){return Hu(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 n=this.exportedIdentifiers;this.exportedIdentifiers=new Set;let i=this.inModule;this.inModule=t;let s=this.scope,a=this.getScopeHandler();this.scope=new a(this,t);let o=this.prodParam;this.prodParam=new ho;let d=this.classScope;this.classScope=new vo(this);let c=this.expressionScope;return this.expressionScope=new ko(this),()=>{this.state.labels=e,this.exportedIdentifiers=n,this.inModule=i,this.scope=s,this.prodParam=o,this.classScope=d,this.expressionScope=c}}enterInitialScopes(){let t=0;(this.inModule||this.optionFlags&1)&&(t|=2),this.optionFlags&32&&(t|=1);let e=!this.inModule&&this.options.sourceType==="commonjs";(e||this.optionFlags&2)&&(t|=4),this.prodParam.enter(t);let n=e?514:1;this.optionFlags&4&&(n|=512),this.scope.enter(n)}checkDestructuringPrivate(t){let{privateKeyLoc:e}=t;e!==null&&this.expectPlugin("destructuringPrivate",e)}},Tr=class{constructor(){this.shorthandAssignLoc=null,this.doubleProtoLoc=null,this.privateKeyLoc=null,this.optionalParametersLoc=null,this.voidPatternLoc=null}},Er=class{constructor(t,e,n){this.type="",this.start=e,this.end=0,this.loc=new Ar(n),t?.optionFlags&128&&(this.range=[e,0]),t!=null&&t.filename&&(this.loc.filename=t.filename)}},Po=Er.prototype;Po.__clone=function(){let r=new Er(void 0,this.start,this.loc.start),t=Object.keys(this);for(let e=0,n=t.length;e<n;e++){let i=t[e];i!=="leadingComments"&&i!=="trailingComments"&&i!=="innerComments"&&(r[i]=this[i])}return r};var Ro=class extends Io{startNode(){let t=this.state.startLoc;return new Er(this,t.index,t)}startNodeAt(t){return new Er(this,t.index,t)}startNodeAtNode(t){return this.startNodeAt(t.loc.start)}finishNode(t,e){return this.finishNodeAt(t,e,this.state.lastTokEndLoc)}finishNodeAt(t,e,n){return t.type=e,t.end=n.index,t.loc.end=n,this.optionFlags&128&&(t.range[1]=n.index),this.optionFlags&4096&&this.processComment(t),t}resetStartLocation(t,e){t.start=e.index,t.loc.start=e,this.optionFlags&128&&(t.range[0]=e.index)}resetEndLocation(t,e=this.state.lastTokEndLoc){t.end=e.index,t.loc.end=e,this.optionFlags&128&&(t.range[1]=e.index)}resetStartLocationFromNode(t,e){this.resetStartLocation(t,e.loc.start)}castNodeTo(t,e){return t.type=e,t}cloneIdentifier(t){let{type:e,start:n,end:i,loc:s,range:a,name:o}=t,d=Object.create(Po);return d.type=e,d.start=n,d.end=i,d.loc=s,d.range=a,d.name=o,t.extra&&(d.extra=t.extra),d}cloneStringLiteral(t){let{type:e,start:n,end:i,loc:s,range:a,extra:o}=t,d=Object.create(Po);return d.type=e,d.start=n,d.end=i,d.loc=s,d.range=a,d.extra=o,d.value=t.value,d}},To=r=>r.type==="ParenthesizedExpression"?To(r.expression):r,Ao=class extends Ro{toAssignable(t,e=!1){var n,i;let s;switch((t.type==="ParenthesizedExpression"||(n=t.extra)!=null&&n.parenthesized)&&(s=To(t),e?s.type==="Identifier"?this.expressionScope.recordArrowParameterBindingError(b.InvalidParenthesizedAssignment,t):s.type!=="CallExpression"&&s.type!=="MemberExpression"&&!this.isOptionalMemberExpression(s)&&this.raise(b.InvalidParenthesizedAssignment,t):this.raise(b.InvalidParenthesizedAssignment,t)),t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":break;case"ObjectExpression":this.castNodeTo(t,"ObjectPattern");for(let o=0,d=t.properties.length,c=d-1;o<d;o++){var a;let l=t.properties[o],u=o===c;this.toAssignableObjectExpressionProp(l,u,e),u&&l.type==="RestElement"&&(a=t.extra)!=null&&a.trailingCommaLoc&&this.raise(b.RestTrailingComma,t.extra.trailingCommaLoc)}break;case"ObjectProperty":{let{key:o,value:d}=t;this.isPrivateName(o)&&this.classScope.usePrivateName(this.getPrivateNameSV(o),o.loc.start),this.toAssignable(d,e);break}case"SpreadElement":throw new Error("Internal @babel/parser error (this is a bug, please report it). SpreadElement should be converted by .toAssignable's caller.");case"ArrayExpression":this.castNodeTo(t,"ArrayPattern"),this.toAssignableList(t.elements,(i=t.extra)==null?void 0:i.trailingCommaLoc,e);break;case"AssignmentExpression":t.operator!=="="&&this.raise(b.MissingEqInAssignment,t.left.loc.end),this.castNodeTo(t,"AssignmentPattern"),delete t.operator,t.left.type==="VoidPattern"&&this.raise(b.VoidPatternInitializer,t.left),this.toAssignable(t.left,e);break;case"ParenthesizedExpression":this.toAssignable(s,e);break}}toAssignableObjectExpressionProp(t,e,n){if(t.type==="ObjectMethod")this.raise(t.kind==="get"||t.kind==="set"?b.PatternHasAccessor:b.PatternHasMethod,t.key);else if(t.type==="SpreadElement"){this.castNodeTo(t,"RestElement");let i=t.argument;this.checkToRestConversion(i,!1),this.toAssignable(i,n),e||this.raise(b.RestTrailingComma,t)}else this.toAssignable(t,n)}toAssignableList(t,e,n){let i=t.length-1;for(let s=0;s<=i;s++){let a=t[s];a&&(this.toAssignableListItem(t,s,n),a.type==="RestElement"&&(s<i?this.raise(b.RestTrailingComma,a):e&&this.raise(b.RestTrailingComma,e)))}}toAssignableListItem(t,e,n){let i=t[e];if(i.type==="SpreadElement"){this.castNodeTo(i,"RestElement");let s=i.argument;this.checkToRestConversion(s,!0),this.toAssignable(s,n)}else this.toAssignable(i,n)}isAssignable(t,e){switch(t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":return!0;case"ObjectExpression":{let n=t.properties.length-1;return t.properties.every((i,s)=>i.type!=="ObjectMethod"&&(s===n||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(n=>n===null||this.isAssignable(n));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 n of t)n?.type==="ArrayExpression"&&this.toReferencedListDeep(n.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();this.next();let e=this.parseBindingAtom();return e.type==="VoidPattern"&&this.raise(b.UnexpectedVoidPattern,e),t.argument=e,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);case 88:return this.parseVoidPattern(null)}return this.parseIdentifier()}parseBindingList(t,e,n){let i=n&1,s=[],a=!0;for(;!this.eat(t);)if(a?a=!1:this.expect(12),i&&this.match(12))s.push(null);else{if(this.eat(t))break;if(this.match(21)){let o=this.parseRestBinding();if((this.hasPlugin("flow")||n&2)&&(o=this.parseFunctionParamType(o)),s.push(o),!this.checkCommaAfterRest(e)){this.expect(t);break}}else{let o=[];if(n&2)for(this.match(26)&&this.hasPlugin("decorators")&&this.raise(b.UnsupportedParameterDecorator,this.state.startLoc);this.match(26);)o.push(this.parseDecorator());s.push(this.parseBindingElement(n,o))}}return s}parseBindingRestProperty(t){return this.next(),this.hasPlugin("discardBinding")&&this.match(88)?(t.argument=this.parseVoidPattern(null),this.raise(b.UnexpectedVoidPattern,t.argument)):t.argument=this.parseIdentifier(),this.checkCommaAfterRest(125),this.finishNode(t,"RestElement")}parseBindingProperty(){let{type:t,startLoc:e}=this.state;if(t===21)return this.parseBindingRestProperty(this.startNode());let n=this.startNode();return t===139?(this.expectPlugin("destructuringPrivate",e),this.classScope.usePrivateName(this.state.value,e),n.key=this.parsePrivateName()):this.parsePropertyName(n),n.method=!1,this.parseObjPropValue(n,e,!1,!1,!0,!1)}parseBindingElement(t,e){let n=this.parseMaybeDefault();return(this.hasPlugin("flow")||t&2)&&this.parseFunctionParamType(n),e.length&&(n.decorators=e,this.resetStartLocationFromNode(n,e[0])),this.parseMaybeDefault(n.loc.start,n)}parseFunctionParamType(t){return t}parseMaybeDefault(t,e){if(t??(t=this.state.startLoc),e=e??this.parseBindingAtom(),!this.eat(29))return e;let n=this.startNodeAt(t);return e.type==="VoidPattern"&&this.raise(b.VoidPatternInitializer,e),n.left=e,n.right=this.parseMaybeAssignAllowIn(),this.finishNode(n,"AssignmentPattern")}isValidLVal(t,e,n,i){switch(t){case"AssignmentPattern":return"left";case"RestElement":return"argument";case"ObjectProperty":return"value";case"ParenthesizedExpression":return"expression";case"ArrayPattern":return"elements";case"ObjectPattern":return"properties";case"VoidPattern":return!0;case"CallExpression":if(!e&&!this.state.strict&&this.optionFlags&8192)return!0}return!1}isOptionalMemberExpression(t){return t.type==="OptionalMemberExpression"}checkLVal(t,e,n=64,i=!1,s=!1,a=!1,o=!1){var d;let c=t.type;if(this.isObjectMethod(t))return;let l=this.isOptionalMemberExpression(t);if(l||c==="MemberExpression"){l&&(this.expectPlugin("optionalChainingAssign",t.loc.start),e.type!=="AssignmentExpression"&&this.raise(b.InvalidLhsOptionalChaining,t,{ancestor:e})),n!==64&&this.raise(b.InvalidPropertyBindingPattern,t);return}if(c==="Identifier"){this.checkIdentifier(t,n,s);let{name:y}=t;i&&(i.has(y)?this.raise(b.ParamDupe,t):i.add(y));return}else c==="VoidPattern"&&e.type==="CatchClause"&&this.raise(b.VoidPatternCatchClauseParam,t);let u=To(t);o||(o=u.type==="CallExpression"&&(u.callee.type==="Import"||u.callee.type==="Super"));let p=this.isValidLVal(c,o,!(a||(d=t.extra)!=null&&d.parenthesized)&&e.type==="AssignmentExpression",n);if(p===!0)return;if(p===!1){let y=n===64?b.InvalidLhs:b.InvalidLhsBinding;this.raise(y,t,{ancestor:e});return}let f,h;typeof p=="string"?(f=p,h=c==="ParenthesizedExpression"):[f,h]=p;let g=c==="ArrayPattern"||c==="ObjectPattern"?{type:c}:e,m=t[f];if(Array.isArray(m))for(let y of m)y&&this.checkLVal(y,g,n,i,s,h,!0);else m&&this.checkLVal(m,g,n,i,s,h,o)}checkIdentifier(t,e,n=!1){this.state.strict&&(n?Ju(t.name,this.inModule):Wu(t.name))&&(e===64?this.raise(b.StrictEvalArguments,t,{referenceName:t.name}):this.raise(b.StrictEvalArgumentsBinding,t,{bindingName:t.name})),e&8192&&t.name==="let"&&this.raise(b.LetInLexicalBinding,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(b.InvalidRestAssignmentPattern,t)}}checkCommaAfterRest(t){return this.match(12)?(this.raise(this.lookaheadCharCode()===t?b.RestTrailingComma:b.ElementAfterRest,this.state.startLoc),!0):!1}},so=/in(?:stanceof)?|as|satisfies/y;function jb(r){if(r==null)throw new Error(`Unexpected ${r} value.`);return r}function _u(r){if(!r)throw new Error("Assert fail")}var D=Qe`typescript`({AbstractMethodHasImplementation:({methodName:r})=>`Method '${r}' cannot have an implementation because it is marked abstract.`,AbstractPropertyHasInitializer:({propertyName:r})=>`Property '${r}' cannot have an initializer because it is marked abstract.`,AccessorCannotBeOptional:"An 'accessor' property cannot be declared optional.",AccessorCannotDeclareThisParameter:"'get' and 'set' accessors cannot declare 'this' parameters.",AccessorCannotHaveTypeParameters:"An accessor cannot have type parameters.",ClassMethodHasDeclare:"Class methods cannot have the 'declare' modifier.",ClassMethodHasReadonly:"Class methods cannot have the 'readonly' modifier.",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"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:r})=>`'declare' is not allowed in ${r}ters.`,DeclareClassFieldHasInitializer:"Initializers are not allowed in ambient contexts.",DeclareFunctionHasImplementation:"An implementation cannot be declared in ambient contexts.",DuplicateAccessibilityModifier:({modifier:r})=>`Accessibility modifier already seen: '${r}'.`,DuplicateModifier:({modifier:r})=>`Duplicate modifier: '${r}'.`,EmptyHeritageClauseType:({token:r})=>`'${r}' 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:r})=>`'${r[0]}' modifier cannot be used with '${r[1]}' modifier.`,IndexSignatureHasAbstract:"Index signatures cannot have the 'abstract' modifier.",IndexSignatureHasAccessibility:({modifier:r})=>`Index signatures cannot have an accessibility modifier ('${r}').`,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.",InvalidHeritageClauseType:({token:r})=>`'${r}' list can only include identifiers or qualified-names with optional type arguments.`,InvalidModifierOnAwaitUsingDeclaration:r=>`'${r}' modifier cannot appear on an await using declaration.`,InvalidModifierOnTypeMember:({modifier:r})=>`'${r}' modifier cannot appear on a type member.`,InvalidModifierOnTypeParameter:({modifier:r})=>`'${r}' modifier cannot appear on a type parameter.`,InvalidModifierOnTypeParameterPositions:({modifier:r})=>`'${r}' modifier can only appear on a type parameter of a class, interface or type alias.`,InvalidModifierOnUsingDeclaration:r=>`'${r}' modifier cannot appear on a using declaration.`,InvalidModifiersOrder:({orderedModifiers:r})=>`'${r[0]}' modifier must precede '${r[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.",NonAbstractClassHasAbstractMethod:"Abstract methods can only appear within an abstract class.",NonClassMethodPropertyHasAbstractModifier:"'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:r})=>`Private elements cannot have an accessibility modifier ('${r}').`,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 `<T,>() => ...`.",ReservedTypeAssertion:"This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",SetAccessorCannotHaveOptionalParameter:"A 'set' accessor cannot have an optional parameter.",SetAccessorCannotHaveRestParameter:"A 'set' accessor cannot have rest parameter.",SetAccessorCannotHaveReturnType:"A 'set' accessor cannot have a return type annotation.",SingleTypeParameterWithoutTrailingComma:({typeParameterName:r})=>`Single type parameter ${r} should have a trailing comma. Example usage: <${r},>.`,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:r})=>`Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${r}.`,UsingDeclarationInAmbientContext:r=>`'${r}' declarations are not allowed in ambient contexts.`});function Bb(r){switch(r){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 Fu(r){return r==="private"||r==="public"||r==="protected"}function Vb(r){return r==="in"||r==="out"}var zb=r=>class extends r{constructor(...e){super(...e),this.tsParseInOutModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out"],disallowedModifiers:["const","public","private","protected","readonly","declare","abstract","override"],errorTemplate:D.InvalidModifierOnTypeParameter}),this.tsParseConstModifier=this.tsParseModifiers.bind(this,{allowedModifiers:["const"],disallowedModifiers:["in","out"],errorTemplate:D.InvalidModifierOnTypeParameterPositions}),this.tsParseInOutConstModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out","const"],disallowedModifiers:["public","private","protected","readonly","declare","abstract","override"],errorTemplate:D.InvalidModifierOnTypeParameter})}getScopeHandler(){return fo}tsIsIdentifier(){return re(this.state.type)}tsTokenCanFollowModifier(){return this.match(0)||this.match(5)||this.match(55)||this.match(21)||this.match(139)||this.isLiteralPropertyName()}tsNextTokenOnSameLineAndCanFollowModifier(){return this.next(),this.hasPrecedingLineBreak()?!1:this.tsTokenCanFollowModifier()}tsNextTokenCanFollowModifier(){return this.match(106)?(this.next(),this.tsTokenCanFollowModifier()):this.tsNextTokenOnSameLineAndCanFollowModifier()}tsParseModifier(e,n,i){if(!re(this.state.type)&&this.state.type!==58&&this.state.type!==75)return;let s=this.state.value;if(e.includes(s)){if(i&&this.match(106)||n&&this.tsIsStartOfStaticBlocks())return;if(this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this)))return s}}tsParseModifiers({allowedModifiers:e,disallowedModifiers:n,stopOnStartOfClassStaticBlock:i,errorTemplate:s=D.InvalidModifierOnTypeMember},a){let o=(c,l,u,p)=>{l===u&&a[p]&&this.raise(D.InvalidModifiersOrder,c,{orderedModifiers:[u,p]})},d=(c,l,u,p)=>{(a[u]&&l===p||a[p]&&l===u)&&this.raise(D.IncompatibleModifiers,c,{modifiers:[u,p]})};for(;;){let{startLoc:c}=this.state,l=this.tsParseModifier(e.concat(n??[]),i,a.static);if(!l)break;Fu(l)?a.accessibility?this.raise(D.DuplicateAccessibilityModifier,c,{modifier:l}):(o(c,l,l,"override"),o(c,l,l,"static"),o(c,l,l,"readonly"),a.accessibility=l):Vb(l)?(a[l]&&this.raise(D.DuplicateModifier,c,{modifier:l}),a[l]=!0,o(c,l,"in","out")):(hasOwnProperty.call(a,l)?this.raise(D.DuplicateModifier,c,{modifier:l}):(o(c,l,"static","readonly"),o(c,l,"static","override"),o(c,l,"override","readonly"),o(c,l,"abstract","override"),d(c,l,"declare","override"),d(c,l,"static","abstract")),a[l]=!0),n!=null&&n.includes(l)&&this.raise(s,c,{modifier:l})}}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,n){let i=[];for(;!this.tsIsListTerminator(e);)i.push(n());return i}tsParseDelimitedList(e,n,i){return jb(this.tsParseDelimitedListWorker(e,n,!0,i))}tsParseDelimitedListWorker(e,n,i,s){let a=[],o=-1;for(;!this.tsIsListTerminator(e);){o=-1;let d=n();if(d==null)return;if(a.push(d),this.eat(12)){o=this.state.lastTokStartLoc.index;continue}if(this.tsIsListTerminator(e))break;i&&this.expect(12);return}return s&&(s.value=o),a}tsParseBracketedList(e,n,i,s,a){s||(i?this.expect(0):this.expect(47));let o=this.tsParseDelimitedList(e,n,a);return i?this.expect(3):this.expect(48),o}tsParseImportType(){let e=this.startNode();return this.expect(83),this.expect(10),this.match(134)?e.argument=this.parseStringLiteral(this.state.value):(this.raise(D.UnsupportedImportTypeArgument,this.state.startLoc),e.argument=super.parseExprAtom()),this.eat(12)?e.options=this.tsParseImportTypeOptions():e.options=null,this.expect(11),this.eat(16)&&(e.qualifier=this.tsParseEntityName(3)),this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSImportType")}tsParseImportTypeOptions(){let e=this.startNode();this.expect(5);let n=this.startNode();return this.isContextual(76)?(n.method=!1,n.key=this.parseIdentifier(!0),n.computed=!1,n.shorthand=!1):this.unexpected(null,76),this.expect(14),n.value=this.tsParseImportTypeWithPropertyValue(),e.properties=[this.finishObjectProperty(n)],this.eat(12),this.expect(8),this.finishNode(e,"ObjectExpression")}tsParseImportTypeWithPropertyValue(){let e=this.startNode(),n=[];for(this.expect(5);!this.match(8);){let i=this.state.type;re(i)||i===134?n.push(super.parsePropertyDefinition(null)):this.unexpected(),this.eat(12)}return e.properties=n,this.next(),this.finishNode(e,"ObjectExpression")}tsParseEntityName(e){let n;if(e&1&&this.match(78))if(e&2)n=this.parseIdentifier(!0);else{let i=this.startNode();this.next(),n=this.finishNode(i,"ThisExpression")}else n=this.parseIdentifier(!!(e&1));for(;this.eat(16);){let i=this.startNodeAtNode(n);i.left=n,i.right=this.parseIdentifier(!!(e&1)),n=this.finishNode(i,"TSQualifiedName")}return n}tsParseTypeReference(){let e=this.startNode();return e.typeName=this.tsParseEntityName(1),!this.hasPrecedingLineBreak()&&this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSTypeReference")}tsParseThisTypePredicate(e){this.next();let n=this.startNodeAtNode(e);return n.parameterName=e,n.typeAnnotation=this.tsParseTypeAnnotation(!1),n.asserts=!1,this.finishNode(n,"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(3),!this.hasPrecedingLineBreak()&&this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSTypeQuery")}tsParseTypeParameter(e){let n=this.startNode();return e(n),n.name=this.tsParseTypeParameterName(),n.constraint=this.tsEatThenParseType(81),n.default=this.tsEatThenParseType(29),this.finishNode(n,"TSTypeParameter")}tsTryParseTypeParameters(e){if(this.match(47))return this.tsParseTypeParameters(e)}tsParseTypeParameters(e){let n=this.startNode();this.match(47)||this.match(143)?this.next():this.unexpected();let i={value:-1};return n.params=this.tsParseBracketedList("TypeParametersOrArguments",this.tsParseTypeParameter.bind(this,e),!1,!0,i),n.params.length===0&&this.raise(D.EmptyTypeParameters,n),i.value!==-1&&this.addExtra(n,"trailingComma",i.value),this.finishNode(n,"TSTypeParameterDeclaration")}tsFillSignature(e,n){let i=e===19,s="parameters",a="typeAnnotation";n.typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier),this.expect(10),n[s]=this.tsParseBindingListForSignature(),i?n[a]=this.tsParseTypeOrTypePredicateAnnotation(e):this.match(e)&&(n[a]=this.tsParseTypeOrTypePredicateAnnotation(e))}tsParseBindingListForSignature(){let e=super.parseBindingList(11,41,2);for(let n of e){let{type:i}=n;(i==="AssignmentPattern"||i==="TSParameterProperty")&&this.raise(D.UnsupportedSignatureParameterKind,n,{type:i})}return e}tsParseTypeMemberSemicolon(){!this.eat(12)&&!this.isLineTerminator()&&this.expect(13)}tsParseSignatureMember(e,n){return this.tsFillSignature(14,n),this.tsParseTypeMemberSemicolon(),this.finishNode(n,e)}tsIsUnambiguouslyIndexSignature(){return this.next(),re(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 n=this.parseIdentifier();n.typeAnnotation=this.tsParseTypeAnnotation(),this.resetEndLocation(n),this.expect(3),e.parameters=[n];let i=this.tsTryParseTypeAnnotation();return i&&(e.typeAnnotation=i),this.tsParseTypeMemberSemicolon(),this.finishNode(e,"TSIndexSignature")}tsParsePropertyOrMethodSignature(e,n){if(this.eat(17)&&(e.optional=!0),this.match(10)||this.match(47)){n&&this.raise(D.ReadonlyForMethodSignature,e);let i=e;i.kind&&this.match(47)&&this.raise(D.AccessorCannotHaveTypeParameters,this.state.curPosition()),this.tsFillSignature(14,i),this.tsParseTypeMemberSemicolon();let s="parameters",a="typeAnnotation";if(i.kind==="get")i[s].length>0&&(this.raise(b.BadGetterArity,this.state.curPosition()),this.isThisParam(i[s][0])&&this.raise(D.AccessorCannotDeclareThisParameter,this.state.curPosition()));else if(i.kind==="set"){if(i[s].length!==1)this.raise(b.BadSetterArity,this.state.curPosition());else{let o=i[s][0];this.isThisParam(o)&&this.raise(D.AccessorCannotDeclareThisParameter,this.state.curPosition()),o.type==="Identifier"&&o.optional&&this.raise(D.SetAccessorCannotHaveOptionalParameter,this.state.curPosition()),o.type==="RestElement"&&this.raise(D.SetAccessorCannotHaveRestParameter,this.state.curPosition())}i[a]&&this.raise(D.SetAccessorCannotHaveReturnType,i[a])}else i.kind="method";return this.finishNode(i,"TSMethodSignature")}else{let i=e;n&&(i.readonly=!0);let s=this.tsTryParseTypeAnnotation();return s&&(i.typeAnnotation=s),this.tsParseTypeMemberSemicolon(),this.finishNode(i,"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 n=this.tsTryParseIndexSignature(e);return n||(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.match(10)&&!this.match(47)&&this.unexpected(null,10)),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(122):(this.isContextual(122)&&this.next(),!this.match(0)||(this.next(),!this.tsIsIdentifier())?!1:(this.next(),this.match(58)))}tsParseMappedType(){let e=this.startNode();this.expect(5),this.match(53)?(e.readonly=this.state.value,this.next(),this.expectContextual(122)):this.eatContextual(122)&&(e.readonly=!0),this.expect(0);let n=this.startNode();return n.name=this.tsParseTypeParameterName(),n.constraint=this.tsExpectThenParseType(58),e.typeParameter=this.finishNode(n,"TSTypeParameter"),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 n=!1;return e.elementTypes.forEach(i=>{let{type:s}=i;n&&s!=="TSRestType"&&s!=="TSOptionalType"&&!(s==="TSNamedTupleMember"&&i.optional)&&this.raise(D.OptionalTypeBeforeRequired,i),n||(n=s==="TSNamedTupleMember"&&i.optional||s==="TSOptionalType")}),this.finishNode(e,"TSTupleType")}tsParseTupleElementType(){let e=this.state.startLoc,n=this.eat(21),{startLoc:i}=this.state,s,a,o,d,l=Ze(this.state.type)?this.lookaheadCharCode():null;if(l===58)s=!0,o=!1,a=this.parseIdentifier(!0),this.expect(14),d=this.tsParseType();else if(l===63){o=!0;let u=this.state.value,p=this.tsParseNonArrayType();this.lookaheadCharCode()===58?(s=!0,a=this.createIdentifier(this.startNodeAt(i),u),this.expect(17),this.expect(14),d=this.tsParseType()):(s=!1,d=p,this.expect(17))}else d=this.tsParseType(),o=this.eat(17),s=this.eat(14);if(s){let u;a?(u=this.startNodeAt(i),u.optional=o,u.label=a,u.elementType=d,this.eat(17)&&(u.optional=!0,this.raise(D.TupleOptionalAfterType,this.state.lastTokStartLoc))):(u=this.startNodeAt(i),u.optional=o,this.raise(D.InvalidTupleMemberLabel,d),u.label=d,u.elementType=this.tsParseType()),d=this.finishNode(u,"TSNamedTupleMember")}else if(o){let u=this.startNodeAt(i);u.typeAnnotation=d,d=this.finishNode(u,"TSOptionalType")}if(n){let u=this.startNodeAt(e);u.typeAnnotation=d,d=this.finishNode(u,"TSRestType")}return d}tsParseParenthesizedType(){let e=this.startNode();return this.expect(10),e.typeAnnotation=this.tsParseType(),this.expect(11),this.finishNode(e,"TSParenthesizedType")}tsParseFunctionOrConstructorType(e,n){let i=this.startNode();return e==="TSConstructorType"&&(i.abstract=!!n,n&&this.next(),this.next()),this.tsInAllowConditionalTypesContext(()=>this.tsFillSignature(19,i)),this.finishNode(i,e)}tsParseLiteralTypeNode(){let e=this.startNode();switch(this.state.type){case 135:case 136:case 134: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(116)&&!this.hasPrecedingLineBreak()?this.tsParseThisTypePredicate(e):e}tsParseNonArrayType(){switch(this.state.type){case 134:case 135:case 136:case 85:case 86:return this.tsParseLiteralTypeNode();case 53:if(this.state.value==="-"){let e=this.startNode(),n=this.lookahead();return n.type!==135&&n.type!==136&&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(re(e)||e===88||e===84){let n=e===88?"TSVoidKeyword":e===84?"TSNullKeyword":Bb(this.state.value);if(n!==void 0&&this.lookaheadCharCode()!==46){let i=this.startNode();return this.next(),this.finishNode(i,n)}return this.tsParseTypeReference()}}}throw this.unexpected()}tsParseArrayTypeOrHigher(){let{startLoc:e}=this.state,n=this.tsParseNonArrayType();for(;!this.hasPrecedingLineBreak()&&this.eat(0);)if(this.match(3)){let i=this.startNodeAt(e);i.elementType=n,this.expect(3),n=this.finishNode(i,"TSArrayType")}else{let i=this.startNodeAt(e);i.objectType=n,i.indexType=this.tsParseType(),this.expect(3),n=this.finishNode(i,"TSIndexedAccessType")}return n}tsParseTypeOperator(){let e=this.startNode(),n=this.state.value;return this.next(),e.operator=n,e.typeAnnotation=this.tsParseTypeOperatorOrHigher(),n==="readonly"&&this.tsCheckTypeAnnotationForReadOnly(e),this.finishNode(e,"TSTypeOperator")}tsCheckTypeAnnotationForReadOnly(e){switch(e.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(D.UnexpectedReadonly,e)}}tsParseInferType(){let e=this.startNode();this.expectContextual(115);let n=this.startNode();return n.name=this.tsParseTypeParameterName(),n.constraint=this.tsTryParse(()=>this.tsParseConstraintForInferType()),e.typeParameter=this.finishNode(n,"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 db(this.state.type)&&!this.state.containsEsc?this.tsParseTypeOperator():this.isContextual(115)?this.tsParseInferType():this.tsInAllowConditionalTypesContext(()=>this.tsParseArrayTypeOrHigher())}tsParseUnionOrIntersectionType(e,n,i){let s=this.startNode(),a=this.eat(i),o=[];do o.push(n());while(this.eat(i));return o.length===1&&!a?o[0]:(s.types=o,this.finishNode(s,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(re(this.state.type)||this.match(78))return this.next(),!0;if(this.match(5)){let{errors:e}=this.state,n=e.length;try{return this.parseObjectLike(8,!0),e.length===n}catch{return!1}}if(this.match(0)){this.next();let{errors:e}=this.state,n=e.length;try{return super.parseBindingList(3,93,1),e.length===n}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 n=this.startNode();this.expect(e);let i=this.startNode(),s=!!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));if(s&&this.match(78)){let d=this.tsParseThisTypeOrThisTypePredicate();return d.type==="TSThisType"?(i.parameterName=d,i.asserts=!0,i.typeAnnotation=null,d=this.finishNode(i,"TSTypePredicate")):(this.resetStartLocationFromNode(d,i),d.asserts=!0),n.typeAnnotation=d,this.finishNode(n,"TSTypeAnnotation")}let a=this.tsIsIdentifier()&&this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));if(!a)return s?(i.parameterName=this.parseIdentifier(),i.asserts=s,i.typeAnnotation=null,n.typeAnnotation=this.finishNode(i,"TSTypePredicate"),this.finishNode(n,"TSTypeAnnotation")):this.tsParseTypeAnnotation(!1,n);let o=this.tsParseTypeAnnotation(!1);return i.parameterName=a,i.typeAnnotation=o,i.asserts=s,n.typeAnnotation=this.finishNode(i,"TSTypePredicate"),this.finishNode(n,"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(116)&&!this.hasPrecedingLineBreak())return this.next(),e}tsParseTypePredicateAsserts(){if(this.state.type!==109)return!1;let e=this.state.containsEsc;return this.next(),!re(this.state.type)&&!this.match(78)?!1:(e&&this.raise(b.InvalidEscapedReservedWord,this.state.lastTokStartLoc,{reservedWord:"asserts"}),!0)}tsParseTypeAnnotation(e=!0,n=this.startNode()){return this.tsInType(()=>{e&&this.expect(14),n.typeAnnotation=this.tsParseType()}),this.finishNode(n,"TSTypeAnnotation")}tsParseType(){_u(this.state.inType);let e=this.tsParseNonConditionalType();if(this.state.inDisallowConditionalTypesContext||this.hasPrecedingLineBreak()||!this.eat(81))return e;let n=this.startNodeAtNode(e);return n.checkType=e,n.extendsType=this.tsInDisallowConditionalTypesContext(()=>this.tsParseNonConditionalType()),this.expect(17),n.trueType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.expect(14),n.falseType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.finishNode(n,"TSConditionalType")}isAbstractConstructorSignature(){return this.isContextual(124)&&this.isLookaheadContextual("new")}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(D.ReservedTypeAssertion,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 n=this.state.startLoc,i=this.tsParseDelimitedList("HeritageClauseElement",()=>{let s=this.startNode();return s.expression=this.tsParseEntityName(3),this.match(47)&&(s.typeParameters=this.tsParseTypeArguments()),this.finishNode(s,"TSExpressionWithTypeArguments")});return i.length||this.raise(D.EmptyHeritageClauseType,n,{token:e}),i}tsParseInterfaceDeclaration(e,n={}){if(this.hasFollowingLineBreak())return null;this.expectContextual(129),n.declare&&(e.declare=!0),re(this.state.type)?(e.id=this.parseIdentifier(),this.checkIdentifier(e.id,130)):(e.id=null,this.raise(D.MissingInterfaceName,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(114)&&this.lookaheadCharCode()!==46){let n=this.startNode();return this.next(),this.finishNode(n,"TSIntrinsicKeyword")}return this.tsParseType()}),this.semicolon(),this.finishNode(e,"TSTypeAliasDeclaration")}tsInTopLevelContext(e){if(this.curContext()!==te.brace){let n=this.state.context;this.state.context=[n[0]];try{return e()}finally{this.state.context=n}}else return e()}tsInType(e){let n=this.state.inType;this.state.inType=!0;try{return e()}finally{this.state.inType=n}}tsInDisallowConditionalTypesContext(e){let n=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!0;try{return e()}finally{this.state.inDisallowConditionalTypesContext=n}}tsInAllowConditionalTypesContext(e){let n=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!1;try{return e()}finally{this.state.inDisallowConditionalTypesContext=n}}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(134)?super.parseStringLiteral(this.state.value):this.parseIdentifier(!0),this.eat(29)&&(e.initializer=super.parseMaybeAssignAllowIn()),this.finishNode(e,"TSEnumMember")}tsParseEnumDeclaration(e,n={}){return n.const&&(e.const=!0),n.declare&&(e.declare=!0),this.expectContextual(126),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")}tsParseEnumBody(){let e=this.startNode();return this.expect(5),e.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(8),this.finishNode(e,"TSEnumBody")}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,n=!1){if(e.id=this.parseIdentifier(),n||this.checkIdentifier(e.id,1024),this.eat(16)){let i=this.startNode();this.tsParseModuleOrNamespaceDeclaration(i,!0),e.body=i}else this.scope.enter(1024),this.prodParam.enter(0),e.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit();return this.finishNode(e,"TSModuleDeclaration")}tsParseAmbientExternalModuleDeclaration(e){return this.isContextual(112)?(e.kind="global",e.global=!0,e.id=this.parseIdentifier()):this.match(134)?(e.kind="module",e.id=super.parseStringLiteral(this.state.value)):this.unexpected(),this.match(5)?(this.scope.enter(1024),this.prodParam.enter(0),e.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit()):this.semicolon(),this.finishNode(e,"TSModuleDeclaration")}tsParseImportEqualsDeclaration(e,n,i){e.isExport=i||!1,e.id=n||this.parseIdentifier(),this.checkIdentifier(e.id,4096),this.expect(29);let s=this.tsParseModuleReference();return e.importKind==="type"&&s.type!=="TSExternalModuleReference"&&this.raise(D.ImportAliasHasImportType,s),e.moduleReference=s,this.semicolon(),this.finishNode(e,"TSImportEqualsDeclaration")}tsIsExternalModuleReference(){return this.isContextual(119)&&this.lookaheadCharCode()===40}tsParseModuleReference(){return this.tsIsExternalModuleReference()?this.tsParseExternalModuleReference():this.tsParseEntityName(0)}tsParseExternalModuleReference(){let e=this.startNode();return this.expectContextual(119),this.expect(10),this.match(134)||this.unexpected(),e.expression=super.parseExprAtom(),this.expect(11),this.sawUnambiguousESM=!0,this.finishNode(e,"TSExternalModuleReference")}tsLookAhead(e){let n=this.state.clone(),i=e();return this.state=n,i}tsTryParseAndCatch(e){let n=this.tryParse(i=>e()||i());if(!(n.aborted||!n.node))return n.error&&(this.state=n.failState),n.node}tsTryParse(e){let n=this.state.clone(),i=e();if(i!==void 0&&i!==!1)return i;this.state=n}tsTryParseDeclare(e){if(this.isLineTerminator())return;let n=this.state.type;return this.tsInAmbientContext(()=>{switch(n){case 68:return e.declare=!0,super.parseFunctionStatement(e,!1,!1);case 80:return e.declare=!0,this.parseClass(e,!0,!1);case 126:return this.tsParseEnumDeclaration(e,{declare:!0});case 112:return this.tsParseAmbientExternalModuleDeclaration(e);case 100:if(this.state.containsEsc)return;case 75:case 74:return!this.match(75)||!this.isLookaheadContextual("enum")?(e.declare=!0,this.parseVarStatement(e,this.state.value,!0)):(this.expect(75),this.tsParseEnumDeclaration(e,{const:!0,declare:!0}));case 107:if(this.isUsing())return this.raise(D.InvalidModifierOnUsingDeclaration,this.state.startLoc,"declare"),e.declare=!0,this.parseVarStatement(e,"using",!0);break;case 96:if(this.isAwaitUsing())return this.raise(D.InvalidModifierOnAwaitUsingDeclaration,this.state.startLoc,"declare"),e.declare=!0,this.next(),this.parseVarStatement(e,"await using",!0);break;case 129:{let i=this.tsParseInterfaceDeclaration(e,{declare:!0});if(i)return i}default:if(re(n))return this.tsParseDeclaration(e,this.state.type,!0,null)}})}tsTryParseExportDeclaration(){return this.tsParseDeclaration(this.startNode(),this.state.type,!0,null)}tsParseDeclaration(e,n,i,s){switch(n){case 124:if(this.tsCheckLineTerminator(i)&&(this.match(80)||re(this.state.type)))return this.tsParseAbstractDeclaration(e,s);break;case 127:if(this.tsCheckLineTerminator(i)){if(this.match(134))return this.tsParseAmbientExternalModuleDeclaration(e);if(re(this.state.type))return e.kind="module",this.tsParseModuleOrNamespaceDeclaration(e)}break;case 128:if(this.tsCheckLineTerminator(i)&&re(this.state.type))return e.kind="namespace",this.tsParseModuleOrNamespaceDeclaration(e);break;case 130:if(this.tsCheckLineTerminator(i)&&re(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 n=this.state.maybeInArrowParameters;this.state.maybeInArrowParameters=!0;let i=this.tsTryParseAndCatch(()=>{let s=this.startNodeAt(e);return s.typeParameters=this.tsParseTypeParameters(this.tsParseConstModifier),super.parseFunctionParams(s),s.returnType=this.tsTryParseTypeOrTypePredicateAnnotation(),this.expect(19),s});if(this.state.maybeInArrowParameters=n,!!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.tsInTopLevelContext(()=>(this.expect(47),this.tsParseDelimitedList("TypeParametersOrArguments",this.tsParseType.bind(this))))),e.params.length===0?this.raise(D.EmptyTypeArguments,e):!this.state.inType&&this.curContext()===te.brace&&this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TSTypeParameterInstantiation")}tsIsDeclarationStart(){return cb(this.state.type)}isExportDefaultSpecifier(){return this.tsIsDeclarationStart()?!1:super.isExportDefaultSpecifier()}parseBindingElement(e,n){let i=n.length?n[0].loc.start:this.state.startLoc,s={};this.tsParseModifiers({allowedModifiers:["public","private","protected","override","readonly"]},s);let a=s.accessibility,o=s.override,d=s.readonly;!(e&4)&&(a||d||o)&&this.raise(D.UnexpectedParameterModifier,i);let c=this.parseMaybeDefault();e&2&&this.parseFunctionParamType(c);let l=this.parseMaybeDefault(c.loc.start,c);if(a||d||o){let u=this.startNodeAt(i);return n.length&&(u.decorators=n),a&&(u.accessibility=a),d&&(u.readonly=d),o&&(u.override=o),l.type!=="Identifier"&&l.type!=="AssignmentPattern"&&this.raise(D.UnsupportedParameterPropertyKind,u),u.parameter=l,this.finishNode(u,"TSParameterProperty")}return n.length&&(c.decorators=n),l}isSimpleParameter(e){return e.type==="TSParameterProperty"&&super.isSimpleParameter(e.parameter)||super.isSimpleParameter(e)}tsDisallowOptionalPattern(e){for(let n of e.params)n.type!=="Identifier"&&n.optional&&!this.state.isAmbientContext&&this.raise(D.PatternIsOptional,n)}setArrowFunctionParameters(e,n,i){super.setArrowFunctionParameters(e,n,i),this.tsDisallowOptionalPattern(e)}parseFunctionBodyAndFinish(e,n,i=!1){this.match(14)&&(e.returnType=this.tsParseTypeOrTypePredicateAnnotation(14));let s=n==="FunctionDeclaration"?"TSDeclareFunction":n==="ClassMethod"||n==="ClassPrivateMethod"?"TSDeclareMethod":void 0;return s&&!this.match(5)&&this.isLineTerminator()?this.finishNode(e,s):s==="TSDeclareFunction"&&this.state.isAmbientContext&&(this.raise(D.DeclareFunctionHasImplementation,e),e.declare)?super.parseFunctionBodyAndFinish(e,s,i):(this.tsDisallowOptionalPattern(e),super.parseFunctionBodyAndFinish(e,n,i))}registerFunctionStatementId(e){!e.body&&e.id?this.checkIdentifier(e.id,1024):super.registerFunctionStatementId(e)}tsCheckForInvalidTypeCasts(e){e.forEach(n=>{n?.type==="TSTypeCastExpression"&&this.raise(D.UnexpectedTypeAnnotation,n.typeAnnotation)})}toReferencedList(e,n){return this.tsCheckForInvalidTypeCasts(e),e}parseArrayLike(e,n,i){let s=super.parseArrayLike(e,n,i);return s.type==="ArrayExpression"&&this.tsCheckForInvalidTypeCasts(s.elements),s}parseSubscript(e,n,i,s){if(!this.hasPrecedingLineBreak()&&this.match(35)){this.state.canStartJSXElement=!1,this.next();let o=this.startNodeAt(n);return o.expression=e,this.finishNode(o,"TSNonNullExpression")}let a=!1;if(this.match(18)&&this.lookaheadCharCode()===60){if(i)return s.stop=!0,e;s.optionalChainMember=a=!0,this.next()}if(this.match(47)||this.match(51)){let o,d=this.tsTryParseAndCatch(()=>{if(!i&&this.atPossibleAsyncArrow(e)){let p=this.tsTryParseGenericAsyncArrowFunction(n);if(p)return s.stop=!0,p}let c=this.tsParseTypeArgumentsInExpression();if(!c)return;if(a&&!this.match(10)){o=this.state.curPosition();return}if(Ki(this.state.type)){let p=super.parseTaggedTemplateExpression(e,n,s);return p.typeParameters=c,p}if(!i&&this.eat(10)){let p=this.startNodeAt(n);return p.callee=e,p.arguments=this.parseCallExpressionArguments(),this.tsCheckForInvalidTypeCasts(p.arguments),p.typeParameters=c,s.optionalChainMember&&(p.optional=a),this.finishCallExpression(p,s.optionalChainMember)}let l=this.state.type;if(l===48||l===52||l!==10&&l!==93&&l!==120&&wn(l)&&!this.hasPrecedingLineBreak())return;let u=this.startNodeAt(n);return u.expression=e,u.typeParameters=c,this.finishNode(u,"TSInstantiationExpression")});if(o&&this.unexpected(o,10),d)return d.type==="TSInstantiationExpression"&&((this.match(16)||this.match(18)&&this.lookaheadCharCode()!==40)&&this.raise(D.InvalidPropertyAccessAfterInstantiationExpression,this.state.startLoc),!this.match(16)&&!this.match(18)&&(d.expression=super.stopParseSubscript(e,s))),d}return super.parseSubscript(e,n,i,s)}parseNewCallee(e){var n;super.parseNewCallee(e);let{callee:i}=e;i.type==="TSInstantiationExpression"&&!((n=i.extra)!=null&&n.parenthesized)&&(e.typeParameters=i.typeParameters,e.callee=i.expression)}parseExprOp(e,n,i){let s;if(qi(58)>i&&!this.hasPrecedingLineBreak()&&(this.isContextual(93)||(s=this.isContextual(120)))){let a=this.startNodeAt(n);return a.expression=e,a.typeAnnotation=this.tsInType(()=>(this.next(),this.match(75)?(s&&this.raise(b.UnexpectedKeyword,this.state.startLoc,{keyword:"const"}),this.tsParseTypeReference()):this.tsParseType())),this.finishNode(a,s?"TSSatisfiesExpression":"TSAsExpression"),this.reScan_lt_gt(),this.parseExprOp(a,n,i)}return super.parseExprOp(e,n,i)}checkReservedWord(e,n,i,s){this.state.isAmbientContext||super.checkReservedWord(e,n,i,s)}checkImportReflection(e){super.checkImportReflection(e),e.module&&e.importKind!=="value"&&this.raise(D.ImportReflectionHasImportType,e.specifiers[0].loc.start)}checkDuplicateExports(){}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return!0;if(this.isContextual(130)){let n=this.lookaheadCharCode();return e?n===123||n===42:n!==61}return!e&&this.isContextual(87)}applyImportPhase(e,n,i,s){super.applyImportPhase(e,n,i,s),n?e.exportKind=i==="type"?"type":"value":e.importKind=i==="type"||i==="typeof"?i:"value"}parseImport(e){if(this.match(134))return e.importKind="value",super.parseImport(e);let n;if(re(this.state.type)&&this.lookaheadCharCode()===61)return e.importKind="value",this.tsParseImportEqualsDeclaration(e);if(this.isContextual(130)){let i=this.parseMaybeImportPhase(e,!1);if(this.lookaheadCharCode()===61)return this.tsParseImportEqualsDeclaration(e,i);n=super.parseImportSpecifiersAndAfter(e,i)}else n=super.parseImport(e);return n.importKind==="type"&&n.specifiers.length>1&&n.specifiers[0].type==="ImportDefaultSpecifier"&&this.raise(D.TypeImportCannotSpecifyDefaultAndNamed,n),n}parseExport(e,n){if(this.match(83)){let i=e;this.next();let s=null;return this.isContextual(130)&&this.isPotentialImportPhase(!1)?s=this.parseMaybeImportPhase(i,!1):i.importKind="value",this.tsParseImportEqualsDeclaration(i,s,!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(128),i.id=this.parseIdentifier(),this.semicolon(),this.finishNode(i,"TSNamespaceExportDeclaration")}else return super.parseExport(e,n)}isAbstractClass(){return this.isContextual(124)&&this.isLookaheadContextual("class")}parseExportDefaultExpression(){if(this.isAbstractClass()){let e=this.startNode();return this.next(),e.abstract=!0,this.parseClass(e,!0,!0)}if(this.match(129)){let e=this.tsParseInterfaceDeclaration(this.startNode());if(e)return e}return super.parseExportDefaultExpression()}parseVarStatement(e,n,i=!1){let{isAmbientContext:s}=this.state,a=super.parseVarStatement(e,n,i||s);if(!s)return a;if(!e.declare&&(n==="using"||n==="await using"))return this.raiseOverwrite(D.UsingDeclarationInAmbientContext,e,n),a;for(let{id:o,init:d}of a.declarations)d&&(n==="var"||n==="let"||o.typeAnnotation?this.raise(D.InitializerNotAllowedInAmbientContext,d):qb(d,this.hasPlugin("estree"))||this.raise(D.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference,d));return a}parseStatementContent(e,n){if(!this.state.containsEsc)switch(this.state.type){case 75:{if(this.isLookaheadContextual("enum")){let i=this.startNode();return this.expect(75),this.tsParseEnumDeclaration(i,{const:!0})}break}case 124:case 125:{if(this.nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine()){let i=this.state.type,s=this.startNode();this.next();let a=i===125?this.tsTryParseDeclare(s):this.tsParseAbstractDeclaration(s,n);return a?(i===125&&(a.declare=!0),a):(s.expression=this.createIdentifier(this.startNodeAt(s.loc.start),i===125?"declare":"abstract"),this.semicolon(!1),this.finishNode(s,"ExpressionStatement"))}break}case 126:return this.tsParseEnumDeclaration(this.startNode());case 112:{if(this.lookaheadCharCode()===123){let s=this.startNode();return this.tsParseAmbientExternalModuleDeclaration(s)}break}case 129:{let i=this.tsParseInterfaceDeclaration(this.startNode());if(i)return i;break}case 127:{if(this.nextTokenIsIdentifierOrStringLiteralOnSameLine()){let i=this.startNode();return this.next(),this.tsParseDeclaration(i,127,!1,n)}break}case 128:{if(this.nextTokenIsIdentifierOnSameLine()){let i=this.startNode();return this.next(),this.tsParseDeclaration(i,128,!1,n)}break}case 130:{if(this.nextTokenIsIdentifierOnSameLine()){let i=this.startNode();return this.next(),this.tsParseTypeAliasDeclaration(i)}break}}return super.parseStatementContent(e,n)}parseAccessModifier(){return this.tsParseModifier(["public","protected","private"])}tsHasSomeModifiers(e,n){return n.some(i=>Fu(i)?e.accessibility===i:!!e[i])}tsIsStartOfStaticBlocks(){return this.isContextual(106)&&this.lookaheadCharCode()===123}parseClassMember(e,n,i){let s=["declare","private","public","protected","override","abstract","readonly","static"];this.tsParseModifiers({allowedModifiers:s,disallowedModifiers:["in","out"],stopOnStartOfClassStaticBlock:!0,errorTemplate:D.InvalidModifierOnTypeParameterPositions},n);let a=()=>{this.tsIsStartOfStaticBlocks()?(this.next(),this.next(),this.tsHasSomeModifiers(n,s)&&this.raise(D.StaticBlockCannotHaveModifier,this.state.curPosition()),super.parseClassStaticBlock(e,n)):this.parseClassMemberWithIsStatic(e,n,i,!!n.static)};n.declare?this.tsInAmbientContext(a):a()}parseClassMemberWithIsStatic(e,n,i,s){let a=this.tsTryParseIndexSignature(n);if(a){e.body.push(a),n.abstract&&this.raise(D.IndexSignatureHasAbstract,n),n.accessibility&&this.raise(D.IndexSignatureHasAccessibility,n,{modifier:n.accessibility}),n.declare&&this.raise(D.IndexSignatureHasDeclare,n),n.override&&this.raise(D.IndexSignatureHasOverride,n);return}!this.state.inAbstractClass&&n.abstract&&this.raise(D.NonAbstractClassHasAbstractMethod,n),n.override&&(i.hadSuperClass||this.raise(D.OverrideNotInSubClass,n)),super.parseClassMemberWithIsStatic(e,n,i,s)}parsePostMemberNameModifiers(e){this.eat(17)&&(e.optional=!0),e.readonly&&this.match(10)&&this.raise(D.ClassMethodHasReadonly,e),e.declare&&this.match(10)&&this.raise(D.ClassMethodHasDeclare,e)}shouldParseExportDeclaration(){return this.tsIsDeclarationStart()?!0:super.shouldParseExportDeclaration()}parseConditional(e,n,i){if(!this.match(17))return e;if(this.state.maybeInArrowParameters){let s=this.lookaheadCharCode();if(s===44||s===61||s===58||s===41)return this.setOptionalParametersError(i),e}return super.parseConditional(e,n,i)}parseParenItem(e,n){let i=super.parseParenItem(e,n);if(this.eat(17)&&(i.optional=!0,this.resetEndLocation(e)),this.match(14)){let s=this.startNodeAt(n);return s.expression=e,s.typeAnnotation=this.tsParseTypeAnnotation(),this.finishNode(s,"TSTypeCastExpression")}return e}parseExportDeclaration(e){if(!this.state.isAmbientContext&&this.isContextual(125))return this.tsInAmbientContext(()=>this.parseExportDeclaration(e));let n=this.state.startLoc,i=this.eatContextual(125);if(i&&(this.isContextual(125)||!this.shouldParseExportDeclaration()))throw this.raise(D.ExpectedAmbientAfterExportDeclare,this.state.startLoc);let a=re(this.state.type)&&this.tsTryParseExportDeclaration()||super.parseExportDeclaration(e);return a?((a.type==="TSInterfaceDeclaration"||a.type==="TSTypeAliasDeclaration"||i)&&(e.exportKind="type"),i&&a.type!=="TSImportEqualsDeclaration"&&(this.resetStartLocation(a,n),a.declare=!0),a):null}parseClassId(e,n,i,s){if((!n||i)&&this.isContextual(113))return;super.parseClassId(e,n,i,e.declare?1024:8331);let a=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);a&&(e.typeParameters=a)}parseClassPropertyAnnotation(e){e.optional||(this.eat(35)?e.definite=!0:this.eat(17)&&(e.optional=!0));let n=this.tsTryParseTypeAnnotation();n&&(e.typeAnnotation=n)}parseClassProperty(e){if(this.parseClassPropertyAnnotation(e),this.state.isAmbientContext&&!(e.readonly&&!e.typeAnnotation)&&this.match(29)&&this.raise(D.DeclareClassFieldHasInitializer,this.state.startLoc),e.abstract&&this.match(29)){let{key:n}=e;this.raise(D.AbstractPropertyHasInitializer,this.state.startLoc,{propertyName:n.type==="Identifier"&&!e.computed?n.name:`[${this.input.slice(this.offsetToSourcePos(n.start),this.offsetToSourcePos(n.end))}]`})}return super.parseClassProperty(e)}parseClassPrivateProperty(e){return e.abstract&&this.raise(D.PrivateElementHasAbstract,e),e.accessibility&&this.raise(D.PrivateElementHasAccessibility,e,{modifier:e.accessibility}),this.parseClassPropertyAnnotation(e),super.parseClassPrivateProperty(e)}parseClassAccessorProperty(e){return this.parseClassPropertyAnnotation(e),e.optional&&this.raise(D.AccessorCannotBeOptional,e),super.parseClassAccessorProperty(e)}pushClassMethod(e,n,i,s,a,o){let d=this.tsTryParseTypeParameters(this.tsParseConstModifier);d&&a&&this.raise(D.ConstructorHasTypeParameters,d);let{declare:c=!1,kind:l}=n;c&&(l==="get"||l==="set")&&this.raise(D.DeclareAccessor,n,{kind:l}),d&&(n.typeParameters=d),super.pushClassMethod(e,n,i,s,a,o)}pushClassPrivateMethod(e,n,i,s){let a=this.tsTryParseTypeParameters(this.tsParseConstModifier);a&&(n.typeParameters=a),super.pushClassPrivateMethod(e,n,i,s)}declareClassPrivateMethodInScope(e,n){e.type!=="TSDeclareMethod"&&(e.type==="MethodDefinition"&&e.value.body==null||super.declareClassPrivateMethodInScope(e,n))}parseClassSuper(e){if(super.parseClassSuper(e),e.superClass)if(e.superClass.type==="TSInstantiationExpression"){let n=e.superClass,i=n.expression;this.takeSurroundingComments(i,i.start,i.end);let s=n.typeParameters;this.takeSurroundingComments(s,s.start,s.end),e.superClass=i,e.superTypeParameters=s}else(this.match(47)||this.match(51))&&(e.superTypeParameters=this.tsParseTypeArgumentsInExpression());this.eatContextual(113)&&(e.implements=this.tsParseHeritageClause("implements"))}parseObjPropValue(e,n,i,s,a,o,d){let c=this.tsTryParseTypeParameters(this.tsParseConstModifier);return c&&(e.typeParameters=c),super.parseObjPropValue(e,n,i,s,a,o,d)}parseFunctionParams(e,n){let i=this.tsTryParseTypeParameters(this.tsParseConstModifier);i&&(e.typeParameters=i),super.parseFunctionParams(e,n)}parseVarId(e,n){super.parseVarId(e,n),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,n){return this.match(14)&&(e.returnType=this.tsParseTypeAnnotation()),super.parseAsyncArrowFromCallExpression(e,n)}parseMaybeAssign(e,n){var i,s,a,o,d;let c,l,u;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){if(c=this.state.clone(),l=this.tryParse(()=>super.parseMaybeAssign(e,n),c),!l.error)return l.node;let{context:h}=this.state,g=h[h.length-1];(g===te.j_oTag||g===te.j_expr)&&h.pop()}if(!((i=l)!=null&&i.error)&&!this.match(47))return super.parseMaybeAssign(e,n);(!c||c===this.state)&&(c=this.state.clone());let p,f=this.tryParse(h=>{var g,m;p=this.tsParseTypeParameters(this.tsParseConstModifier);let y=super.parseMaybeAssign(e,n);return(y.type!=="ArrowFunctionExpression"||(g=y.extra)!=null&&g.parenthesized)&&h(),((m=p)==null?void 0:m.params.length)!==0&&this.resetStartLocationFromNode(y,p),y.typeParameters=p,y},c);if(!f.error&&!f.aborted)return p&&this.reportReservedArrowTypeParam(p),f.node;if(!l&&(_u(!this.hasPlugin("jsx")),u=this.tryParse(()=>super.parseMaybeAssign(e,n),c),!u.error))return u.node;if((s=l)!=null&&s.node)return this.state=l.failState,l.node;if(f.node)return this.state=f.failState,p&&this.reportReservedArrowTypeParam(p),f.node;if((a=u)!=null&&a.node)return this.state=u.failState,u.node;throw((o=l)==null?void 0:o.error)||f.error||((d=u)==null?void 0:d.error)}reportReservedArrowTypeParam(e){var n;e.params.length===1&&!e.params[0].constraint&&!((n=e.extra)!=null&&n.trailingComma)&&this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(D.ReservedArrowTypeParam,e)}parseMaybeUnary(e,n){return!this.hasPlugin("jsx")&&this.match(47)?this.tsParseTypeAssertion():super.parseMaybeUnary(e,n)}parseArrow(e){if(this.match(14)){let n=this.tryParse(i=>{let s=this.tsParseTypeOrTypePredicateAnnotation(14);return(this.canInsertSemicolon()||!this.match(19))&&i(),s});if(n.aborted)return;n.thrown||(n.error&&(this.state=n.failState),e.returnType=n.node)}return super.parseArrow(e)}parseFunctionParamType(e){this.eat(17)&&(e.optional=!0);let n=this.tsTryParseTypeAnnotation();return n&&(e.typeAnnotation=n),this.resetEndLocation(e),e}isAssignable(e,n){switch(e.type){case"TSTypeCastExpression":return this.isAssignable(e.expression,n);case"TSParameterProperty":return!0;default:return super.isAssignable(e,n)}}toAssignable(e,n=!1){switch(e.type){case"ParenthesizedExpression":this.toAssignableParenthesizedExpression(e,n);break;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":n?this.expressionScope.recordArrowParameterBindingError(D.UnexpectedTypeCastInParameter,e):this.raise(D.UnexpectedTypeCastInParameter,e),this.toAssignable(e.expression,n);break;case"AssignmentExpression":!n&&e.left.type==="TSTypeCastExpression"&&(e.left=this.typeCastToParameter(e.left));default:super.toAssignable(e,n)}}toAssignableParenthesizedExpression(e,n){switch(e.expression.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":case"ParenthesizedExpression":this.toAssignable(e.expression,n);break;default:super.toAssignable(e,n)}}checkToRestConversion(e,n){switch(e.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":this.checkToRestConversion(e.expression,!1);break;default:super.checkToRestConversion(e,n)}}isValidLVal(e,n,i,s){switch(e){case"TSTypeCastExpression":return!0;case"TSParameterProperty":return"parameter";case"TSNonNullExpression":return"expression";case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":return(s!==64||!i)&&["expression",!0];default:return super.isValidLVal(e,n,i,s)}}parseBindingAtom(){return this.state.type===78?this.parseIdentifier(!0):super.parseBindingAtom()}parseMaybeDecoratorArguments(e,n){if(this.match(47)||this.match(51)){let i=this.tsParseTypeArgumentsInExpression();if(this.match(10)){let s=super.parseMaybeDecoratorArguments(e,n);return s.typeParameters=i,s}this.unexpected(null,10)}return super.parseMaybeDecoratorArguments(e,n)}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,n){let i=super.parseMaybeDefault(e,n);return i.type==="AssignmentPattern"&&i.typeAnnotation&&i.right.start<i.typeAnnotation.start&&this.raise(D.TypeAnnotationAfterAssign,i.typeAnnotation),i}getTokenFromCode(e){if(this.state.inType){if(e===62){this.finishOp(48,1);return}if(e===60){this.finishOp(47,1);return}}super.getTokenFromCode(e)}reScan_lt_gt(){let{type:e}=this.state;e===47?(this.state.pos-=1,this.readToken_lt()):e===48&&(this.state.pos-=1,this.readToken_gt())}reScan_lt(){let{type:e}=this.state;return e===51?(this.state.pos-=2,this.finishOp(47,1),47):e}toAssignableListItem(e,n,i){let s=e[n];s.type==="TSTypeCastExpression"&&(e[n]=this.typeCastToParameter(s)),super.toAssignableListItem(e,n,i)}typeCastToParameter(e){return e.expression.typeAnnotation=e.typeAnnotation,this.resetEndLocation(e.expression,e.typeAnnotation.loc.end),e.expression}shouldParseArrow(e){return this.match(14)?e.every(n=>this.isAssignable(n,!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 n=this.tsTryParseAndCatch(()=>this.tsParseTypeArgumentsInExpression());n&&(e.typeParameters=n)}return super.jsxParseOpeningElementAfterName(e)}getGetterSetterExpectedParamCount(e){let n=super.getGetterSetterExpectedParamCount(e),s=this.getObjectOrClassMethodParams(e)[0];return s&&this.isThisParam(s)?n+1:n}parseCatchClauseParam(){let e=super.parseCatchClauseParam(),n=this.tsTryParseTypeAnnotation();return n&&(e.typeAnnotation=n,this.resetEndLocation(e)),e}tsInAmbientContext(e){let{isAmbientContext:n,strict:i}=this.state;this.state.isAmbientContext=!0,this.state.strict=!1;try{return e()}finally{this.state.isAmbientContext=n,this.state.strict=i}}parseClass(e,n,i){let s=this.state.inAbstractClass;this.state.inAbstractClass=!!e.abstract;try{return super.parseClass(e,n,i)}finally{this.state.inAbstractClass=s}}tsParseAbstractDeclaration(e,n){if(this.match(80))return e.abstract=!0,this.maybeTakeDecorators(n,this.parseClass(e,!0,!1));if(this.isContextual(129))return this.hasFollowingLineBreak()?null:(e.abstract=!0,this.raise(D.NonClassMethodPropertyHasAbstractModifier,e),this.tsParseInterfaceDeclaration(e));throw this.unexpected(null,80)}parseMethod(e,n,i,s,a,o,d){let c=super.parseMethod(e,n,i,s,a,o,d);if((c.abstract||c.type==="TSAbstractMethodDefinition")&&(this.hasPlugin("estree")?c.value:c).body){let{key:p}=c;this.raise(D.AbstractMethodHasImplementation,c,{methodName:p.type==="Identifier"&&!c.computed?p.name:`[${this.input.slice(this.offsetToSourcePos(p.start),this.offsetToSourcePos(p.end))}]`})}return c}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,n,i,s){return!n&&s?(this.parseTypeOnlyImportExportSpecifier(e,!1,i),this.finishNode(e,"ExportSpecifier")):(e.exportKind="value",super.parseExportSpecifier(e,n,i,s))}parseImportSpecifier(e,n,i,s,a){return!n&&s?(this.parseTypeOnlyImportExportSpecifier(e,!0,i),this.finishNode(e,"ImportSpecifier")):(e.importKind="value",super.parseImportSpecifier(e,n,i,s,i?4098:4096))}parseTypeOnlyImportExportSpecifier(e,n,i){let s=n?"imported":"local",a=n?"local":"exported",o=e[s],d,c=!1,l=!0,u=o.loc.start;if(this.isContextual(93)){let f=this.parseIdentifier();if(this.isContextual(93)){let h=this.parseIdentifier();Ze(this.state.type)?(c=!0,o=f,d=n?this.parseIdentifier():this.parseModuleExportName(),l=!1):(d=h,l=!1)}else Ze(this.state.type)?(l=!1,d=n?this.parseIdentifier():this.parseModuleExportName()):(c=!0,o=f)}else Ze(this.state.type)&&(c=!0,n?(o=this.parseIdentifier(!0),this.isContextual(93)||this.checkReservedWord(o.name,o.loc.start,!0,!0)):o=this.parseModuleExportName());c&&i&&this.raise(n?D.TypeModifierIsUsedInTypeImports:D.TypeModifierIsUsedInTypeExports,u),e[s]=o,e[a]=d;let p=n?"importKind":"exportKind";e[p]=c?"type":"value",l&&this.eatContextual(93)&&(e[a]=n?this.parseIdentifier():this.parseModuleExportName()),e[a]||(e[a]=this.cloneIdentifier(e[s])),n&&this.checkIdentifier(e[a],c?4098:4096)}fillOptionalPropertiesForTSESLint(e){var n,i,s,a,o,d,c,l,u,p,f,h,g,m,y,w,x,v,I,R,E,A,O,j,V,P,C,M,z,k,T,L,q,Q,ie,de,K,ve,Re,mt,St,sn,an,ki,on,dn,cn,Nl,Ol;switch(e.type){case"ImportDeclaration":(n=e.phase)!=null||(e.phase=null);return;case"ExpressionStatement":(i=e.directive)!=null||(e.directive=void 0);return;case"RestElement":e.value=void 0;case"Identifier":case"ArrayPattern":case"AssignmentPattern":case"ObjectPattern":(s=e.decorators)!=null||(e.decorators=[]),(a=e.optional)!=null||(e.optional=!1),(o=e.typeAnnotation)!=null||(e.typeAnnotation=void 0);return;case"TSParameterProperty":(d=e.accessibility)!=null||(e.accessibility=void 0),(c=e.decorators)!=null||(e.decorators=[]),(l=e.override)!=null||(e.override=!1),(u=e.readonly)!=null||(e.readonly=!1),(p=e.static)!=null||(e.static=!1);return;case"TSEmptyBodyFunctionExpression":e.body=null;case"TSDeclareFunction":case"FunctionDeclaration":case"FunctionExpression":case"ClassMethod":case"ClassPrivateMethod":(f=e.declare)!=null||(e.declare=!1),(h=e.returnType)!=null||(e.returnType=void 0),(g=e.typeParameters)!=null||(e.typeParameters=void 0);return;case"Property":(m=e.optional)!=null||(e.optional=!1);return;case"TSMethodSignature":case"TSPropertySignature":(y=e.optional)!=null||(e.optional=!1);case"TSIndexSignature":(w=e.accessibility)!=null||(e.accessibility=void 0),(x=e.readonly)!=null||(e.readonly=!1),(v=e.static)!=null||(e.static=!1);return;case"TSAbstractPropertyDefinition":case"PropertyDefinition":case"TSAbstractAccessorProperty":case"AccessorProperty":(I=e.declare)!=null||(e.declare=!1),(R=e.definite)!=null||(e.definite=!1),(E=e.readonly)!=null||(e.readonly=!1),(A=e.typeAnnotation)!=null||(e.typeAnnotation=void 0);case"TSAbstractMethodDefinition":case"MethodDefinition":(O=e.accessibility)!=null||(e.accessibility=void 0),(j=e.decorators)!=null||(e.decorators=[]),(V=e.override)!=null||(e.override=!1),(P=e.optional)!=null||(e.optional=!1);return;case"ClassExpression":(C=e.id)!=null||(e.id=null);case"ClassDeclaration":(M=e.abstract)!=null||(e.abstract=!1),(z=e.declare)!=null||(e.declare=!1),(k=e.decorators)!=null||(e.decorators=[]),(T=e.implements)!=null||(e.implements=[]),(L=e.superTypeArguments)!=null||(e.superTypeArguments=void 0),(q=e.typeParameters)!=null||(e.typeParameters=void 0);return;case"TSTypeAliasDeclaration":case"VariableDeclaration":(Q=e.declare)!=null||(e.declare=!1);return;case"VariableDeclarator":(ie=e.definite)!=null||(e.definite=!1);return;case"TSEnumDeclaration":(de=e.const)!=null||(e.const=!1),(K=e.declare)!=null||(e.declare=!1);return;case"TSEnumMember":(ve=e.computed)!=null||(e.computed=!1);return;case"TSImportType":(Re=e.qualifier)!=null||(e.qualifier=null),(mt=e.options)!=null||(e.options=null);return;case"TSInterfaceDeclaration":(St=e.declare)!=null||(e.declare=!1),(sn=e.extends)!=null||(e.extends=[]);return;case"TSMappedType":(an=e.optional)!=null||(e.optional=!1),(ki=e.readonly)!=null||(e.readonly=void 0);return;case"TSModuleDeclaration":(on=e.declare)!=null||(e.declare=!1),(dn=e.global)!=null||(e.global=e.kind==="global");return;case"TSTypeParameter":(cn=e.const)!=null||(e.const=!1),(Nl=e.in)!=null||(e.in=!1),(Ol=e.out)!=null||(e.out=!1);return}}chStartsBindingIdentifierAndNotRelationalOperator(e,n){if(ct(e)){if(so.lastIndex=n,so.test(this.input)){let i=this.codePointAtPos(so.lastIndex);if(!Xt(i)&&i!==92)return!1}return!0}else return e===92}nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine(){let e=this.nextTokenInLineStart(),n=this.codePointAtPos(e);return this.chStartsBindingIdentifierAndNotRelationalOperator(n,e)}nextTokenIsIdentifierOrStringLiteralOnSameLine(){let e=this.nextTokenInLineStart(),n=this.codePointAtPos(e);return this.chStartsBindingIdentifier(n,e)||n===34||n===39}};function Hb(r){if(r.type!=="MemberExpression")return!1;let{computed:t,property:e}=r;return t&&e.type!=="StringLiteral"&&(e.type!=="TemplateLiteral"||e.expressions.length>0)?!1:tp(r.object)}function qb(r,t){var e;let{type:n}=r;if((e=r.extra)!=null&&e.parenthesized)return!1;if(t){if(n==="Literal"){let{value:i}=r;if(typeof i=="string"||typeof i=="boolean")return!0}}else if(n==="StringLiteral"||n==="BooleanLiteral")return!0;return!!(ep(r,t)||Ub(r,t)||n==="TemplateLiteral"&&r.expressions.length===0||Hb(r))}function ep(r,t){return t?r.type==="Literal"&&(typeof r.value=="number"||"bigint"in r):r.type==="NumericLiteral"||r.type==="BigIntLiteral"}function Ub(r,t){if(r.type==="UnaryExpression"){let{operator:e,argument:n}=r;if(e==="-"&&ep(n,t))return!0}return!1}function tp(r){return r.type==="Identifier"?!0:r.type!=="MemberExpression"||r.computed?!1:tp(r.object)}var ju=Qe`placeholders`({ClassNameIsRequired:"A class name is required.",UnexpectedSpace:"Unexpected space in placeholder."}),Gb=r=>class extends r{parsePlaceholder(e){if(this.match(133)){let n=this.startNode();return this.next(),this.assertNoSpace(),n.name=super.parseIdentifier(!0),this.assertNoSpace(),this.expect(133),this.finishPlaceholder(n,e)}}finishPlaceholder(e,n){let i=e;return(!i.expectedNode||!i.type)&&(i=this.finishNode(i,"Placeholder")),i.expectedNode=n,i}getTokenFromCode(e){e===37&&this.input.charCodeAt(this.state.pos+1)===37?this.finishOp(133,2):super.getTokenFromCode(e)}parseExprAtom(e){return this.parsePlaceholder("Expression")||super.parseExprAtom(e)}parseIdentifier(e){return this.parsePlaceholder("Identifier")||super.parseIdentifier(e)}checkReservedWord(e,n,i,s){e!==void 0&&super.checkReservedWord(e,n,i,s)}cloneIdentifier(e){let n=super.cloneIdentifier(e);return n.type==="Placeholder"&&(n.expectedNode=e.expectedNode),n}cloneStringLiteral(e){return e.type==="Placeholder"?this.cloneIdentifier(e):super.cloneStringLiteral(e)}parseBindingAtom(){return this.parsePlaceholder("Pattern")||super.parseBindingAtom()}isValidLVal(e,n,i,s){return e==="Placeholder"||super.isValidLVal(e,n,i,s)}toAssignable(e,n){e&&e.type==="Placeholder"&&e.expectedNode==="Expression"?e.expectedNode="Pattern":super.toAssignable(e,n)}chStartsBindingIdentifier(e,n){if(super.chStartsBindingIdentifier(e,n))return!0;let i=this.nextTokenStart();return this.input.charCodeAt(i)===37&&this.input.charCodeAt(i+1)===37}verifyBreakContinue(e,n){var i;((i=e.label)==null?void 0:i.type)!=="Placeholder"&&super.verifyBreakContinue(e,n)}parseExpressionStatement(e,n){var i;if(n.type!=="Placeholder"||(i=n.extra)!=null&&i.parenthesized)return super.parseExpressionStatement(e,n);if(this.match(14)){let a=e;return a.label=this.finishPlaceholder(n,"Identifier"),this.next(),a.body=super.parseStatementOrSloppyAnnexBFunctionDeclaration(),this.finishNode(a,"LabeledStatement")}this.semicolon();let s=e;return s.name=n.name,this.finishPlaceholder(s,"Statement")}parseBlock(e,n,i){return this.parsePlaceholder("BlockStatement")||super.parseBlock(e,n,i)}parseFunctionId(e){return this.parsePlaceholder("Identifier")||super.parseFunctionId(e)}parseClass(e,n,i){let s=n?"ClassDeclaration":"ClassExpression";this.next();let a=this.state.strict,o=this.parsePlaceholder("Identifier");if(o)if(this.match(81)||this.match(133)||this.match(5))e.id=o;else{if(i||!n)return e.id=null,e.body=this.finishPlaceholder(o,"ClassBody"),this.finishNode(e,s);throw this.raise(ju.ClassNameIsRequired,this.state.startLoc)}else this.parseClassId(e,n,i);return super.parseClassSuper(e),e.body=this.parsePlaceholder("ClassBody")||super.parseClassBody(!!e.superClass,a),this.finishNode(e,s)}parseExport(e,n){let i=this.parsePlaceholder("Identifier");if(!i)return super.parseExport(e,n);let s=e;if(!this.isContextual(98)&&!this.match(12))return s.specifiers=[],s.source=null,s.declaration=this.finishPlaceholder(i,"Declaration"),this.finishNode(s,"ExportNamedDeclaration");this.expectPlugin("exportDefaultFrom");let a=this.startNode();return a.exported=i,s.specifiers=[this.finishNode(a,"ExportDefaultSpecifier")],super.parseExport(s,n)}isExportDefaultSpecifier(){if(this.match(65)){let e=this.nextTokenStart();if(this.isUnparsedContextual(e,"from")&&this.input.startsWith(Nt(133),this.nextTokenStartSince(e+4)))return!0}return super.isExportDefaultSpecifier()}maybeParseExportDefaultSpecifier(e,n){var i;return(i=e.specifiers)!=null&&i.length?!0:super.maybeParseExportDefaultSpecifier(e,n)}checkExport(e){let{specifiers:n}=e;n!=null&&n.length&&(e.specifiers=n.filter(i=>i.exported.type==="Placeholder")),super.checkExport(e),e.specifiers=n}parseImport(e){let n=this.parsePlaceholder("Identifier");if(!n)return super.parseImport(e);if(e.specifiers=[],!this.isContextual(98)&&!this.match(12))return e.source=this.finishPlaceholder(n,"StringLiteral"),this.semicolon(),this.finishNode(e,"ImportDeclaration");let i=this.startNodeAtNode(n);return i.local=n,e.specifiers.push(this.finishNode(i,"ImportDefaultSpecifier")),this.eat(12)&&(this.maybeParseStarImportSpecifier(e)||this.parseNamedImportSpecifiers(e)),this.expectContextual(98),e.source=this.parseImportSource(),this.semicolon(),this.finishNode(e,"ImportDeclaration")}parseImportSource(){return this.parsePlaceholder("StringLiteral")||super.parseImportSource()}assertNoSpace(){this.state.start>this.offsetToSourcePos(this.state.lastTokEndLoc.index)&&this.raise(ju.UnexpectedSpace,this.state.lastTokEndLoc)}},Kb=r=>class extends r{parseV8Intrinsic(){if(this.match(54)){let e=this.state.startLoc,n=this.startNode();if(this.next(),re(this.state.type)){let i=this.parseIdentifierName(),s=this.createIdentifier(n,i);if(this.castNodeTo(s,"V8IntrinsicIdentifier"),this.match(10))return s}this.unexpected(e)}}parseExprAtom(e){return this.parseV8Intrinsic()||super.parseExprAtom(e)}},Bu=["minimal","fsharp","hack","smart"],Vu=["^^","@@","^","%","#"];function Wb(r){if(r.has("decorators")){if(r.has("decorators-legacy"))throw new Error("Cannot use the decorators and decorators-legacy plugin together");let n=r.get("decorators").decoratorsBeforeExport;if(n!=null&&typeof n!="boolean")throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");let i=r.get("decorators").allowCallParenthesized;if(i!=null&&typeof i!="boolean")throw new Error("'allowCallParenthesized' must be a boolean.")}if(r.has("flow")&&r.has("typescript"))throw new Error("Cannot combine flow and typescript plugins.");if(r.has("placeholders")&&r.has("v8intrinsic"))throw new Error("Cannot combine placeholders and v8intrinsic plugins.");if(r.has("pipelineOperator")){var t;let n=r.get("pipelineOperator").proposal;if(!Bu.includes(n)){let i=Bu.map(s=>`"${s}"`).join(", ");throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${i}.`)}if(n==="hack"){var e;if(r.has("placeholders"))throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");if(r.has("v8intrinsic"))throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");let i=r.get("pipelineOperator").topicToken;if(!Vu.includes(i)){let s=Vu.map(a=>`"${a}"`).join(", ");throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${s}.`)}if(i==="#"&&((e=r.get("recordAndTuple"))==null?void 0:e.syntaxType)==="hash")throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple",r.get("recordAndTuple")])}\`.`)}else if(n==="smart"&&((t=r.get("recordAndTuple"))==null?void 0:t.syntaxType)==="hash")throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple",r.get("recordAndTuple")])}\`.`)}if(r.has("moduleAttributes")){if(r.has("deprecatedImportAssert")||r.has("importAssertions"))throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.");if(r.get("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(r.has("importAssertions")&&r.has("deprecatedImportAssert"))throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins.");if(r.has("deprecatedImportAssert")||r.has("importAttributes")&&r.get("importAttributes").deprecatedAssertSyntax&&r.set("deprecatedImportAssert",{}),r.has("recordAndTuple")){let n=r.get("recordAndTuple").syntaxType;if(n!=null){let i=["hash","bar"];if(!i.includes(n))throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: "+i.map(s=>`'${s}'`).join(", "))}}if(r.has("asyncDoExpressions")&&!r.has("doExpressions")){let n=new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");throw n.missingPlugins="doExpressions",n}if(r.has("optionalChainingAssign")&&r.get("optionalChainingAssign").version!=="2023-07")throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option, representing the last proposal update. Currently, the only supported value is '2023-07'.");if(r.has("discardBinding")&&r.get("discardBinding").syntaxType!=="void")throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'.")}var rp={estree:Qw,jsx:Cb,flow:Tb,typescript:zb,v8intrinsic:Kb,placeholders:Gb},Jb=Object.keys(rp),So=class extends Ao{checkProto(t,e,n,i){if(t.type==="SpreadElement"||this.isObjectMethod(t)||t.computed||t.shorthand)return n;let s=t.key;return(s.type==="Identifier"?s.name:s.value)==="__proto__"?e?(this.raise(b.RecordNoProto,s),!0):(n&&(i?i.doubleProtoLoc===null&&(i.doubleProtoLoc=s.loc.start):this.raise(b.DuplicateProto,s)),!0):n}shouldExitDescending(t,e){return t.type==="ArrowFunctionExpression"&&this.offsetToSourcePos(t.start)===e}getExpression(){if(this.enterInitialScopes(),this.nextToken(),this.match(140))throw this.raise(b.ParseExpressionEmptyInput,this.state.startLoc);let t=this.parseExpression();if(!this.match(140))throw this.raise(b.ParseExpressionExpectsEOF,this.state.startLoc,{unexpected:this.input.codePointAt(this.state.start)});return this.finalizeRemainingComments(),t.comments=this.comments,t.errors=this.state.errors,this.optionFlags&256&&(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,n=this.parseMaybeAssign(t);if(this.match(12)){let i=this.startNodeAt(e);for(i.expressions=[n];this.eat(12);)i.expressions.push(this.parseMaybeAssign(t));return this.toReferencedList(i.expressions),this.finishNode(i,"SequenceExpression")}return n}parseMaybeAssignDisallowIn(t,e){return this.disallowInAnd(()=>this.parseMaybeAssign(t,e))}parseMaybeAssignAllowIn(t,e){return this.allowInAnd(()=>this.parseMaybeAssign(t,e))}setOptionalParametersError(t){t.optionalParametersLoc=this.state.startLoc}parseMaybeAssign(t,e){let n=this.state.startLoc,i=this.isContextual(108);if(i&&this.prodParam.hasYield){this.next();let d=this.parseYield(n);return e&&(d=e.call(this,d,n)),d}let s;t?s=!1:(t=new Tr,s=!0);let{type:a}=this.state;(a===10||re(a))&&(this.state.potentialArrowAt=this.state.start);let o=this.parseMaybeConditional(t);if(e&&(o=e.call(this,o,n)),nb(this.state.type)){let d=this.startNodeAt(n),c=this.state.value;if(d.operator=c,this.match(29)){this.toAssignable(o,!0),d.left=o;let l=n.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),t.voidPatternLoc!=null&&t.voidPatternLoc.index>=l&&(t.voidPatternLoc=null)}else d.left=o;return this.next(),d.right=this.parseMaybeAssign(),this.checkLVal(o,this.finishNode(d,"AssignmentExpression"),void 0,void 0,void 0,void 0,c==="||="||c==="&&="||c==="??="),d}else s&&this.checkExpressionErrors(t,!0);if(i){let{type:d}=this.state;if((this.hasPlugin("v8intrinsic")?wn(d):wn(d)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(b.YieldNotInGeneratorFunction,n),this.parseYield(n)}return o}parseMaybeConditional(t){let e=this.state.startLoc,n=this.state.potentialArrowAt,i=this.parseExprOps(t);return this.shouldExitDescending(i,n)?i:this.parseConditional(i,e,t)}parseConditional(t,e,n){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(139)?this.parsePrivateName():this.parseMaybeUnary(t)}parseExprOps(t){let e=this.state.startLoc,n=this.state.potentialArrowAt,i=this.parseMaybeUnaryOrPrivate(t);return this.shouldExitDescending(i,n)?i:this.parseExprOp(i,e,-1)}parseExprOp(t,e,n){if(this.isPrivateName(t)){let s=this.getPrivateNameSV(t);(n>=qi(58)||!this.prodParam.hasIn||!this.match(58))&&this.raise(b.PrivateInExpectedIn,t,{identifierName:s}),this.classScope.usePrivateName(s,t.loc.start)}let i=this.state.type;if(sb(i)&&(this.prodParam.hasIn||!this.match(58))){let s=qi(i);if(s>n){if(i===39){if(this.expectPlugin("pipelineOperator"),this.state.inFSharpPipelineDirectBody)return t;this.checkPipelineAtInfixOperator(t,e)}let a=this.startNodeAt(e);a.left=t,a.operator=this.state.value;let o=i===41||i===42,d=i===40;if(d&&(s=qi(42)),this.next(),i===39&&this.hasPlugin(["pipelineOperator",{proposal:"minimal"}])&&this.state.type===96&&this.prodParam.hasAwait)throw this.raise(b.UnexpectedAwaitAfterPipelineBody,this.state.startLoc);a.right=this.parseExprOpRightExpr(i,s);let c=this.finishNode(a,o||d?"LogicalExpression":"BinaryExpression"),l=this.state.type;if(d&&(l===41||l===42)||o&&l===40)throw this.raise(b.MixingCoalesceWithLogical,this.state.startLoc);return this.parseExprOp(c,e,n)}}return t}parseExprOpRightExpr(t,e){let n=this.state.startLoc;switch(t){case 39:switch(this.getPluginOption("pipelineOperator","proposal")){case"hack":return this.withTopicBindingContext(()=>this.parseHackPipeBody());case"fsharp":return this.withSoloAwaitPermittingContext(()=>this.parseFSharpPipelineBody(e))}if(this.getPluginOption("pipelineOperator","proposal")==="smart")return this.withTopicBindingContext(()=>{if(this.prodParam.hasYield&&this.isContextual(108))throw this.raise(b.PipeBodyIsTighter,this.state.startLoc);return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(t,e),n)});default:return this.parseExprOpBaseRightExpr(t,e)}}parseExprOpBaseRightExpr(t,e){let n=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnaryOrPrivate(),n,lb(t)?e-1:e)}parseHackPipeBody(){var t;let{startLoc:e}=this.state,n=this.parseMaybeAssign();return qw.has(n.type)&&!((t=n.extra)!=null&&t.parenthesized)&&this.raise(b.PipeUnparenthesizedBody,e,{type:n.type}),this.topicReferenceWasUsedInCurrentContext()||this.raise(b.PipeTopicUnused,e),n}checkExponentialAfterUnary(t){this.match(57)&&this.raise(b.UnexpectedTokenUnaryExponentiation,t.argument)}parseMaybeUnary(t,e){let n=this.state.startLoc,i=this.isContextual(96);if(i&&this.recordAwaitIfAllowed()){this.next();let d=this.parseAwait(n);return e||this.checkExponentialAfterUnary(d),d}let s=this.match(34),a=this.startNode();if(ob(this.state.type)){a.operator=this.state.value,a.prefix=!0,this.match(72)&&this.expectPlugin("throwExpressions");let d=this.match(89);if(this.next(),a.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(t,!0),this.state.strict&&d){let c=a.argument;c.type==="Identifier"?this.raise(b.StrictDelete,a):this.hasPropertyAsPrivateName(c)&&this.raise(b.DeletePrivateField,a)}if(!s)return e||this.checkExponentialAfterUnary(a),this.finishNode(a,"UnaryExpression")}let o=this.parseUpdate(a,s,t);if(i){let{type:d}=this.state;if((this.hasPlugin("v8intrinsic")?wn(d):wn(d)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(b.AwaitNotInAsyncContext,n),this.parseAwait(n)}return o}parseUpdate(t,e,n){if(e){let a=t;return this.checkLVal(a.argument,this.finishNode(a,"UpdateExpression")),t}let i=this.state.startLoc,s=this.parseExprSubscripts(n);if(this.checkExpressionErrors(n,!1))return s;for(;ab(this.state.type)&&!this.canInsertSemicolon();){let a=this.startNodeAt(i);a.operator=this.state.value,a.prefix=!1,a.argument=s,this.next(),this.checkLVal(s,s=this.finishNode(a,"UpdateExpression"))}return s}parseExprSubscripts(t){let e=this.state.startLoc,n=this.state.potentialArrowAt,i=this.parseExprAtom(t);return this.shouldExitDescending(i,n)?i:this.parseSubscripts(i,e)}parseSubscripts(t,e,n){let i={optionalChainMember:!1,maybeAsyncArrow:this.atPossibleAsyncArrow(t),stop:!1};do t=this.parseSubscript(t,e,n,i),i.maybeAsyncArrow=!1;while(!i.stop);return t}parseSubscript(t,e,n,i){let{type:s}=this.state;if(!n&&s===15)return this.parseBind(t,e,i);if(Ki(s))return this.parseTaggedTemplateExpression(t,e,i);let a=!1;if(s===18){if(n&&(this.raise(b.OptionalChainingNoNew,this.state.startLoc),this.lookaheadCharCode()===40))return this.stopParseSubscript(t,i);i.optionalChainMember=a=!0,this.next()}if(!n&&this.match(10))return this.parseCoverCallAndAsyncArrowHead(t,e,i,a);{let o=this.eat(0);return o||a||this.eat(16)?this.parseMember(t,e,i,o,a):this.stopParseSubscript(t,i)}}stopParseSubscript(t,e){return e.stop=!0,t}parseMember(t,e,n,i,s){let a=this.startNodeAt(e);return a.object=t,a.computed=i,i?(a.property=this.parseExpression(),this.expect(3)):this.match(139)?(t.type==="Super"&&this.raise(b.SuperPrivateField,e),this.classScope.usePrivateName(this.state.value,this.state.startLoc),a.property=this.parsePrivateName()):a.property=this.parseIdentifier(!0),n.optionalChainMember?(a.optional=s,this.finishNode(a,"OptionalMemberExpression")):this.finishNode(a,"MemberExpression")}parseBind(t,e,n){let i=this.startNodeAt(e);i.object=t,this.next();let s=this.match(83),a=this.parseNoCallExpr();if(a.type==="Super"||s&&a.type==="ImportExpression"||a.type==="Import")throw this.raise(b.UnsupportedBindRHS,a);return i.callee=a,n.stop=!0,this.parseSubscripts(this.finishNode(i,"BindExpression"),e,!1)}parseCoverCallAndAsyncArrowHead(t,e,n,i){let s=this.state.maybeInArrowParameters,a=null;this.state.maybeInArrowParameters=!0,this.next();let o=this.startNodeAt(e);o.callee=t;let{maybeAsyncArrow:d,optionalChainMember:c}=n;d&&(this.expressionScope.enter(Fb()),a=new Tr),c&&(o.optional=i),i?o.arguments=this.parseCallExpressionArguments():o.arguments=this.parseCallExpressionArguments(t.type!=="Super",o,a);let l=this.finishCallExpression(o,c);return d&&this.shouldParseAsyncArrow()&&!i?(n.stop=!0,this.checkDestructuringPrivate(a),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),l=this.parseAsyncArrowFromCallExpression(this.startNodeAt(e),l)):(d&&(this.checkExpressionErrors(a,!0),this.expressionScope.exit()),this.toReferencedArguments(l)),this.state.maybeInArrowParameters=s,l}toReferencedArguments(t,e){this.toReferencedListDeep(t.arguments,e)}parseTaggedTemplateExpression(t,e,n){let i=this.startNodeAt(e);return i.tag=t,i.quasi=this.parseTemplate(!0),n.optionalChainMember&&this.raise(b.OptionalChainingNoTemplate,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&&this.offsetToSourcePos(t.start)===this.state.potentialArrowAt}finishCallExpression(t,e){if(t.callee.type==="Import")if(t.arguments.length===0||t.arguments.length>2)this.raise(b.ImportCallArity,t);else for(let n of t.arguments)n.type==="SpreadElement"&&this.raise(b.ImportCallSpreadArgument,n);return this.finishNode(t,e?"OptionalCallExpression":"CallExpression")}parseCallExpressionArguments(t,e,n){let i=[],s=!0,a=this.state.inFSharpPipelineDirectBody;for(this.state.inFSharpPipelineDirectBody=!1;!this.eat(11);){if(s)s=!1;else if(this.expect(12),this.match(11)){e&&this.addTrailingCommaExtraToNode(e),this.next();break}i.push(this.parseExprListItem(11,!1,n,t))}return this.state.inFSharpPipelineDirectBody=a,i}shouldParseAsyncArrow(){return this.match(19)&&!this.canInsertSemicolon()}parseAsyncArrowFromCallExpression(t,e){var n;return this.resetPreviousNodeTrailingComments(e),this.expect(19),this.parseArrowExpression(t,e.arguments,!0,(n=e.extra)==null?void 0:n.trailingCommaLoc),e.innerComments&&In(t,e.innerComments),e.callee.trailingComments&&In(t,e.callee.trailingComments),t}parseNoCallExpr(){let t=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),t,!0)}parseExprAtom(t){let e,n=null,{type:i}=this.state;switch(i){case 79:return this.parseSuper();case 83:return e=this.startNode(),this.next(),this.match(16)?this.parseImportMetaPropertyOrPhaseCall(e):this.match(10)?this.optionFlags&512?this.parseImportCall(e):this.finishNode(e,"Import"):(this.raise(b.UnsupportedImport,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 135:return this.parseNumericLiteral(this.state.value);case 136:return this.parseBigIntLiteral(this.state.value);case 134: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 s=this.state.potentialArrowAt===this.state.start;return this.parseParenAndDistinguishExpression(s)}case 0:return this.parseArrayLike(3,!1,t);case 5:return this.parseObjectLike(8,!1,!1,t);case 68:return this.parseFunctionOrFunctionSent();case 26:n=this.parseDecorators();case 80:return this.parseClass(this.maybeTakeDecorators(n,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 s=e.callee=this.parseNoCallExpr();if(s.type==="MemberExpression")return this.finishNode(e,"BindExpression");throw this.raise(b.UnsupportedBind,s)}case 139:return this.raise(b.PrivateInExpectedIn,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 s=this.getPluginOption("pipelineOperator","proposal");if(s)return this.parseTopicReference(s);throw this.unexpected()}case 47:{let s=this.input.codePointAt(this.nextTokenStart());throw ct(s)||s===62?this.expectOnePlugin(["jsx","flow","typescript"]):this.unexpected()}default:if(i===137)return this.parseDecimalLiteral(this.state.value);if(i===2||i===1)return this.parseArrayLike(this.state.type===2?4:3,!0);if(i===6||i===7)return this.parseObjectLike(this.state.type===6?9:8,!1,!0);if(re(i)){if(this.isContextual(127)&&this.lookaheadInLineCharCode()===123)return this.parseModuleExpression();let s=this.state.potentialArrowAt===this.state.start,a=this.state.containsEsc,o=this.parseIdentifier();if(!a&&o.name==="async"&&!this.canInsertSemicolon()){let{type:d}=this.state;if(d===68)return this.resetPreviousNodeTrailingComments(o),this.next(),this.parseAsyncFunctionExpression(this.startNodeAtNode(o));if(re(d))return s&&this.lookaheadCharCode()===61?this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(o)):o;if(d===90)return this.resetPreviousNodeTrailingComments(o),this.parseDo(this.startNodeAtNode(o),!0)}return s&&this.match(19)&&!this.canInsertSemicolon()?(this.next(),this.parseArrowExpression(this.startNodeAtNode(o),[o],!1)):o}else throw this.unexpected()}}parseTopicReferenceThenEqualsSign(t,e){let n=this.getPluginOption("pipelineOperator","proposal");if(n)return this.state.type=t,this.state.value=e,this.state.pos--,this.state.end--,this.state.endLoc=Oe(this.state.endLoc,-1),this.parseTopicReference(n);throw this.unexpected()}parseTopicReference(t){let e=this.startNode(),n=this.state.startLoc,i=this.state.type;return this.next(),this.finishTopicReference(e,n,t,i)}finishTopicReference(t,e,n,i){if(this.testTopicReferenceConfiguration(n,e,i))return n==="hack"?(this.topicReferenceIsAllowedInCurrentContext()||this.raise(b.PipeTopicUnbound,e),this.registerTopicReference(),this.finishNode(t,"TopicReference")):(this.topicReferenceIsAllowedInCurrentContext()||this.raise(b.PrimaryTopicNotAllowed,e),this.registerTopicReference(),this.finishNode(t,"PipelinePrimaryTopicReference"));throw this.raise(b.PipeTopicUnconfiguredToken,e,{token:Nt(i)})}testTopicReferenceConfiguration(t,e,n){switch(t){case"hack":return this.hasPlugin(["pipelineOperator",{topicToken:Nt(n)}]);case"smart":return n===27;default:throw this.raise(b.PipeTopicRequiresHackPipes,e)}}parseAsyncArrowUnaryFunction(t){this.prodParam.enter(Ui(!0,this.prodParam.hasYield));let e=[this.parseIdentifier()];return this.prodParam.exit(),this.hasPrecedingLineBreak()&&this.raise(b.LineTerminatorBeforeArrow,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 n=this.state.labels;return this.state.labels=[],e?(this.prodParam.enter(2),t.body=this.parseBlock(),this.prodParam.exit()):t.body=this.parseBlock(),this.state.labels=n,this.finishNode(t,"DoExpression")}parseSuper(){let t=this.startNode();return this.next(),this.match(10)&&!this.scope.allowDirectSuper?this.optionFlags&16||this.raise(b.SuperNotAllowed,t):this.scope.allowSuper||this.optionFlags&16||this.raise(b.UnexpectedSuper,t),!this.match(10)&&!this.match(0)&&!this.match(16)&&this.raise(b.UnsupportedSuper,t),this.finishNode(t,"Super")}parsePrivateName(){let t=this.startNode(),e=this.startNodeAt(Oe(this.state.startLoc,1)),n=this.state.value;return this.next(),t.id=this.createIdentifier(e,n),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(103)?this.expectPlugin("functionSent"):this.hasPlugin("functionSent")||this.unexpected(),this.parseMetaProperty(t,e,"sent")}return this.parseFunction(t)}parseMetaProperty(t,e,n){t.meta=e;let i=this.state.containsEsc;return t.property=this.parseIdentifier(!0),(t.property.name!==n||i)&&this.raise(b.UnsupportedMetaProperty,t.property,{target:e.name,onlyValidPropertyName:n}),this.finishNode(t,"MetaProperty")}parseImportMetaPropertyOrPhaseCall(t){if(this.next(),this.isContextual(105)||this.isContextual(97)){let e=this.isContextual(105);return this.expectPlugin(e?"sourcePhaseImports":"deferredImportEvaluation"),this.next(),t.phase=e?"source":"defer",this.parseImportCall(t)}else{let e=this.createIdentifierAt(this.startNodeAtNode(t),"import",this.state.lastTokStartLoc);return this.isContextual(101)&&(this.inModule||this.raise(b.ImportMetaOutsideModule,e),this.sawUnambiguousESM=!0),this.parseMetaProperty(t,e,"meta")}}parseLiteralAtNode(t,e,n){return this.addExtra(n,"rawValue",t),this.addExtra(n,"raw",this.input.slice(this.offsetToSourcePos(n.start),this.state.end)),n.value=t,this.next(),this.finishNode(n,e)}parseLiteral(t,e){let n=this.startNode();return this.parseLiteralAtNode(t,e,n)}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.startNode();return this.addExtra(e,"raw",this.input.slice(this.offsetToSourcePos(e.start),this.state.end)),e.pattern=t.pattern,e.flags=t.flags,this.next(),this.finishNode(e,"RegExpLiteral")}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,n;this.next(),this.expressionScope.enter(_b());let i=this.state.maybeInArrowParameters,s=this.state.inFSharpPipelineDirectBody;this.state.maybeInArrowParameters=!0,this.state.inFSharpPipelineDirectBody=!1;let a=this.state.startLoc,o=[],d=new Tr,c=!0,l,u;for(;!this.match(11);){if(c)c=!1;else if(this.expect(12,d.optionalParametersLoc===null?null:d.optionalParametersLoc),this.match(11)){u=this.state.startLoc;break}if(this.match(21)){let h=this.state.startLoc;if(l=this.state.startLoc,o.push(this.parseParenItem(this.parseRestBinding(),h)),!this.checkCommaAfterRest(41))break}else o.push(this.parseMaybeAssignAllowInOrVoidPattern(11,d,this.parseParenItem))}let p=this.state.lastTokEndLoc;this.expect(11),this.state.maybeInArrowParameters=i,this.state.inFSharpPipelineDirectBody=s;let f=this.startNodeAt(e);return t&&this.shouldParseArrow(o)&&(f=this.parseArrow(f))?(this.checkDestructuringPrivate(d),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),this.parseArrowExpression(f,o,!1),f):(this.expressionScope.exit(),o.length||this.unexpected(this.state.lastTokStartLoc),u&&this.unexpected(u),l&&this.unexpected(l),this.checkExpressionErrors(d,!0),this.toReferencedListDeep(o,!0),o.length>1?(n=this.startNodeAt(a),n.expressions=o,this.finishNode(n,"SequenceExpression"),this.resetEndLocation(n,p)):n=o[0],this.wrapParenthesis(e,n))}wrapParenthesis(t,e){if(!(this.optionFlags&1024))return this.addExtra(e,"parenthesized",!0),this.addExtra(e,"parenStart",t.index),this.takeSurroundingComments(e,t.index,this.state.lastTokEndLoc.index),e;let n=this.startNodeAt(t);return n.expression=e,this.finishNode(n,"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 n=this.parseMetaProperty(t,e,"target");return this.scope.allowNewTarget||this.raise(b.UnexpectedNewTarget,n),n}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){let e=this.match(83),n=this.parseNoCallExpr();t.callee=n,(e&&n.type==="ImportExpression"||n.type==="Import")&&this.raise(b.ImportCallNotNewExpression,n),n.type==="Super"&&this.raise(b.SuperCallNotNewExpression,n)}parseTemplateElement(t){let{start:e,startLoc:n,end:i,value:s}=this.state,a=e+1,o=this.startNodeAt(Oe(n,1));s===null&&(t||this.raise(b.InvalidEscapeSequenceTemplate,Oe(this.state.firstInvalidTemplateEscapePos,1)));let d=this.match(24),c=d?-1:-2,l=i+c;o.value={raw:this.input.slice(a,l).replace(/\r\n?/g,`
10
+ `),cooked:s===null?null:s.slice(1,c)},o.tail=d,this.next();let u=this.finishNode(o,"TemplateElement");return this.resetEndLocation(u,Oe(this.state.lastTokEndLoc,c)),u}parseTemplate(t){let e=this.startNode(),n=this.parseTemplateElement(t),i=[n],s=[];for(;!n.tail;)s.push(this.parseTemplateSubstitution()),this.readTemplateContinuation(),i.push(n=this.parseTemplateElement(t));return e.expressions=s,e.quasis=i,this.finishNode(e,"TemplateLiteral")}parseTemplateSubstitution(){return this.parseExpression()}parseObjectLike(t,e,n,i){n&&this.expectPlugin("recordAndTuple");let s=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let a=!1,o=!0,d=this.startNode();for(d.properties=[],this.next();!this.match(t);){if(o)o=!1;else if(this.expect(12),this.match(t)){this.addTrailingCommaExtraToNode(d);break}let l;e?l=this.parseBindingProperty():(l=this.parsePropertyDefinition(i),a=this.checkProto(l,n,a,i)),n&&!this.isObjectProperty(l)&&l.type!=="SpreadElement"&&this.raise(b.InvalidRecordProperty,l),l.shorthand&&this.addExtra(l,"shorthand",!0),d.properties.push(l)}this.next(),this.state.inFSharpPipelineDirectBody=s;let c="ObjectExpression";return e?c="ObjectPattern":n&&(c="RecordExpression"),this.finishNode(d,c)}addTrailingCommaExtraToNode(t){this.addExtra(t,"trailingComma",this.state.lastTokStartLoc.index),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(b.UnsupportedPropertyDecorator,this.state.startLoc);this.match(26);)e.push(this.parseDecorator());let n=this.startNode(),i=!1,s=!1,a;if(this.match(21))return e.length&&this.unexpected(),this.parseSpread();e.length&&(n.decorators=e,e=[]),n.method=!1,t&&(a=this.state.startLoc);let o=this.eat(55);this.parsePropertyNamePrefixOperator(n);let d=this.state.containsEsc;if(this.parsePropertyName(n,t),!o&&!d&&this.maybeAsyncOrAccessorProp(n)){let{key:c}=n,l=c.name;l==="async"&&!this.hasPrecedingLineBreak()&&(i=!0,this.resetPreviousNodeTrailingComments(c),o=this.eat(55),this.parsePropertyName(n)),(l==="get"||l==="set")&&(s=!0,this.resetPreviousNodeTrailingComments(c),n.kind=l,this.match(55)&&(o=!0,this.raise(b.AccessorIsGenerator,this.state.curPosition(),{kind:l}),this.next()),this.parsePropertyName(n))}return this.parseObjPropValue(n,a,o,i,!1,s,t)}getGetterSetterExpectedParamCount(t){return t.kind==="get"?0:1}getObjectOrClassMethodParams(t){return t.params}checkGetterSetterParams(t){var e;let n=this.getGetterSetterExpectedParamCount(t),i=this.getObjectOrClassMethodParams(t);i.length!==n&&this.raise(t.kind==="get"?b.BadGetterArity:b.BadSetterArity,t),t.kind==="set"&&((e=i[i.length-1])==null?void 0:e.type)==="RestElement"&&this.raise(b.BadSetterRestParameter,t)}parseObjectMethod(t,e,n,i,s){if(s){let a=this.parseMethod(t,e,!1,!1,!1,"ObjectMethod");return this.checkGetterSetterParams(a),a}if(n||e||this.match(10))return i&&this.unexpected(),t.kind="method",t.method=!0,this.parseMethod(t,e,n,!1,!1,"ObjectMethod")}parseObjectProperty(t,e,n,i){if(t.shorthand=!1,this.eat(14))return t.value=n?this.parseMaybeDefault(this.state.startLoc):this.parseMaybeAssignAllowInOrVoidPattern(8,i),this.finishObjectProperty(t);if(!t.computed&&t.key.type==="Identifier"){if(this.checkReservedWord(t.key.name,t.key.loc.start,!0,!1),n)t.value=this.parseMaybeDefault(e,this.cloneIdentifier(t.key));else if(this.match(29)){let s=this.state.startLoc;i!=null?i.shorthandAssignLoc===null&&(i.shorthandAssignLoc=s):this.raise(b.InvalidCoverInitializedName,s),t.value=this.parseMaybeDefault(e,this.cloneIdentifier(t.key))}else t.value=this.cloneIdentifier(t.key);return t.shorthand=!0,this.finishObjectProperty(t)}}finishObjectProperty(t){return this.finishNode(t,"ObjectProperty")}parseObjPropValue(t,e,n,i,s,a,o){let d=this.parseObjectMethod(t,n,i,s,a)||this.parseObjectProperty(t,e,s,o);return d||this.unexpected(),d}parsePropertyName(t,e){if(this.eat(0))t.computed=!0,t.key=this.parseMaybeAssignAllowIn(),this.expect(3);else{let{type:n,value:i}=this.state,s;if(Ze(n))s=this.parseIdentifier(!0);else switch(n){case 135:s=this.parseNumericLiteral(i);break;case 134:s=this.parseStringLiteral(i);break;case 136:s=this.parseBigIntLiteral(i);break;case 139:{let a=this.state.startLoc;e!=null?e.privateKeyLoc===null&&(e.privateKeyLoc=a):this.raise(b.UnexpectedPrivateField,a),s=this.parsePrivateName();break}default:if(n===137){s=this.parseDecimalLiteral(i);break}this.unexpected()}t.key=s,n!==139&&(t.computed=!1)}}initFunction(t,e){t.id=null,t.generator=!1,t.async=e}parseMethod(t,e,n,i,s,a,o=!1){this.initFunction(t,n),t.generator=e,this.scope.enter(530|(o?576:0)|(s?32:0)),this.prodParam.enter(Ui(n,t.generator)),this.parseFunctionParams(t,i);let d=this.parseFunctionBodyAndFinish(t,a,!0);return this.prodParam.exit(),this.scope.exit(),d}parseArrayLike(t,e,n){e&&this.expectPlugin("recordAndTuple");let i=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let s=this.startNode();return this.next(),s.elements=this.parseExprList(t,!e,n,s),this.state.inFSharpPipelineDirectBody=i,this.finishNode(s,e?"TupleExpression":"ArrayExpression")}parseArrowExpression(t,e,n,i){this.scope.enter(518);let s=Ui(n,!1);!this.match(5)&&this.prodParam.hasIn&&(s|=8),this.prodParam.enter(s),this.initFunction(t,n);let a=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=a,this.finishNode(t,"ArrowFunctionExpression")}setArrowFunctionParameters(t,e,n){this.toAssignableList(e,n,!1),t.params=e}parseFunctionBodyAndFinish(t,e,n=!1){return this.parseFunctionBody(t,!1,n),this.finishNode(t,e)}parseFunctionBody(t,e,n=!1){let i=e&&!this.match(5);if(this.expressionScope.enter(Zu()),i)t.body=this.parseMaybeAssign(),this.checkParams(t,!1,e,!1);else{let s=this.state.strict,a=this.state.labels;this.state.labels=[],this.prodParam.enter(this.prodParam.currentFlags()|4),t.body=this.parseBlock(!0,!1,o=>{let d=!this.isSimpleParamList(t.params);o&&d&&this.raise(b.IllegalLanguageModeDirective,(t.kind==="method"||t.kind==="constructor")&&t.key?t.key.loc.end:t);let c=!s&&this.state.strict;this.checkParams(t,!this.state.strict&&!e&&!n&&!d,e,c),this.state.strict&&t.id&&this.checkIdentifier(t.id,65,c)}),this.prodParam.exit(),this.state.labels=a}this.expressionScope.exit()}isSimpleParameter(t){return t.type==="Identifier"}isSimpleParamList(t){for(let e=0,n=t.length;e<n;e++)if(!this.isSimpleParameter(t[e]))return!1;return!0}checkParams(t,e,n,i=!0){let s=!e&&new Set,a={type:"FormalParameters"};for(let o of t.params)this.checkLVal(o,a,5,s,i)}parseExprList(t,e,n,i){let s=[],a=!0;for(;!this.eat(t);){if(a)a=!1;else if(this.expect(12),this.match(t)){i&&this.addTrailingCommaExtraToNode(i),this.next();break}s.push(this.parseExprListItem(t,e,n))}return s}parseExprListItem(t,e,n,i){let s;if(this.match(12))e||this.raise(b.UnexpectedToken,this.state.curPosition(),{unexpected:","}),s=null;else if(this.match(21)){let a=this.state.startLoc;s=this.parseParenItem(this.parseSpread(n),a)}else if(this.match(17)){this.expectPlugin("partialApplication"),i||this.raise(b.UnexpectedArgumentPlaceholder,this.state.startLoc);let a=this.startNode();this.next(),s=this.finishNode(a,"ArgumentPlaceholder")}else s=this.parseMaybeAssignAllowInOrVoidPattern(t,n,this.parseParenItem);return s}parseIdentifier(t){let e=this.startNode(),n=this.parseIdentifierName(t);return this.createIdentifier(e,n)}createIdentifier(t,e){return t.name=e,t.loc.identifierName=e,this.finishNode(t,"Identifier")}createIdentifierAt(t,e,n){return t.name=e,t.loc.identifierName=e,this.finishNodeAt(t,"Identifier",n)}parseIdentifierName(t){let e,{startLoc:n,type:i}=this.state;Ze(i)?e=this.state.value:this.unexpected();let s=tb(i);return t?s&&this.replaceToken(132):this.checkReservedWord(e,n,s,!1),this.next(),e}checkReservedWord(t,e,n,i){if(t.length>10||!xb(t))return;if(n&&gb(t)){this.raise(b.UnexpectedKeyword,e,{keyword:t});return}if((this.state.strict?i?Ju:Ku:Gu)(t,this.inModule)){this.raise(b.UnexpectedReservedWord,e,{reservedWord:t});return}else if(t==="yield"){if(this.prodParam.hasYield){this.raise(b.YieldBindingIdentifier,e);return}}else if(t==="await"){if(this.prodParam.hasAwait){this.raise(b.AwaitBindingIdentifier,e);return}if(this.scope.inStaticBlock){this.raise(b.AwaitBindingIdentifierInStaticBlock,e);return}this.expressionScope.recordAsyncArrowParametersError(e)}else if(t==="arguments"&&this.scope.inClassAndNotInNonArrowFunction){this.raise(b.ArgumentsInClass,e);return}}recordAwaitIfAllowed(){let t=this.prodParam.hasAwait;return t&&!this.scope.inFunction&&(this.state.hasTopLevelAwait=!0),t}parseAwait(t){let e=this.startNodeAt(t);return this.expressionScope.recordParameterInitializerError(b.AwaitExpressionFormalParameter,e),this.eat(55)&&this.raise(b.ObsoleteAwaitStar,e),!this.scope.inFunction&&!(this.optionFlags&1)&&(this.isAmbiguousPrefixOrIdentifier()?this.ambiguousScriptDifferentAst=!0:this.sawUnambiguousESM=!0),this.state.soloAwait||(e.argument=this.parseMaybeUnary(null,!0)),this.finishNode(e,"AwaitExpression")}isAmbiguousPrefixOrIdentifier(){if(this.hasPrecedingLineBreak())return!0;let{type:t}=this.state;return t===53||t===10||t===0||Ki(t)||t===102&&!this.state.containsEsc||t===138||t===56||this.hasPlugin("v8intrinsic")&&t===54}parseYield(t){let e=this.startNodeAt(t);this.expressionScope.recordParameterInitializerError(b.YieldInParameter,e);let n=!1,i=null;if(!this.hasPrecedingLineBreak())switch(n=this.eat(55),this.state.type){case 13:case 140:case 8:case 11:case 3:case 9:case 14:case 12:if(!n)break;default:i=this.parseMaybeAssign()}return e.delegate=n,e.argument=i,this.finishNode(e,"YieldExpression")}parseImportCall(t){if(this.next(),t.source=this.parseMaybeAssignAllowIn(),t.options=null,this.eat(12)){if(this.match(11))this.addTrailingCommaExtraToNode(t.source);else if(t.options=this.parseMaybeAssignAllowIn(),this.eat(12)&&(this.addTrailingCommaExtraToNode(t.options),!this.match(11))){do this.parseMaybeAssignAllowIn();while(this.eat(12)&&!this.match(11));this.raise(b.ImportCallArity,t)}}return this.expect(11),this.finishNode(t,"ImportExpression")}checkPipelineAtInfixOperator(t,e){this.hasPlugin(["pipelineOperator",{proposal:"smart"}])&&t.type==="SequenceExpression"&&this.raise(b.PipelineHeadSequenceExpression,e)}parseSmartPipelineBodyInStyle(t,e){if(this.isSimpleReference(t)){let n=this.startNodeAt(e);return n.callee=t,this.finishNode(n,"PipelineBareFunction")}else{let n=this.startNodeAt(e);return this.checkSmartPipeTopicBodyEarlyErrors(e),n.expression=t,this.finishNode(n,"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(b.PipelineBodyNoArrow,this.state.startLoc);this.topicReferenceWasUsedInCurrentContext()||this.raise(b.PipelineTopicUnused,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(8&~e){this.prodParam.enter(e|8);try{return t()}finally{this.prodParam.exit()}}return t()}disallowInAnd(t){let e=this.prodParam.currentFlags();if(8&e){this.prodParam.enter(e&-9);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 n=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!0;let i=this.parseExprOp(this.parseMaybeUnaryOrPrivate(),e,t);return this.state.inFSharpPipelineDirectBody=n,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 n=this.initializeScopes(!0);this.enterInitialScopes();try{t.body=this.parseProgram(e,8,"module")}finally{n()}return this.finishNode(t,"ModuleExpression")}parseVoidPattern(t){this.expectPlugin("discardBinding");let e=this.startNode();return t!=null&&(t.voidPatternLoc=this.state.startLoc),this.next(),this.finishNode(e,"VoidPattern")}parseMaybeAssignAllowInOrVoidPattern(t,e,n){if(e!=null&&this.match(88)){let i=this.lookaheadCharCode();if(i===44||i===(t===3?93:t===8?125:41)||i===61)return this.parseMaybeDefault(this.state.startLoc,this.parseVoidPattern(e))}return this.parseMaybeAssignAllowIn(e,n)}parsePropertyNamePrefixOperator(t){}},ao={kind:1},Xb={kind:2},Yb=/[\uD800-\uDFFF]/u,oo=/in(?:stanceof)?/y;function Qb(r,t,e){for(let n=0;n<r.length;n++){let i=r[n],{type:s}=i;if(typeof s=="number"){if(s===139){let{loc:a,start:o,value:d,end:c}=i,l=o+1,u=Oe(a.start,1);r.splice(n,1,new dt({type:yt(27),value:"#",start:o,end:l,startLoc:a.start,endLoc:u}),new dt({type:yt(132),value:d,start:l,end:c,startLoc:u,endLoc:a.end})),n++;continue}if(Ki(s)){let{loc:a,start:o,value:d,end:c}=i,l=o+1,u=Oe(a.start,1),p;t.charCodeAt(o-e)===96?p=new dt({type:yt(22),value:"`",start:o,end:l,startLoc:a.start,endLoc:u}):p=new dt({type:yt(8),value:"}",start:o,end:l,startLoc:a.start,endLoc:u});let f,h,g,m;s===24?(h=c-1,g=Oe(a.end,-1),f=d===null?null:d.slice(1,-1),m=new dt({type:yt(22),value:"`",start:h,end:c,startLoc:g,endLoc:a.end})):(h=c-2,g=Oe(a.end,-2),f=d===null?null:d.slice(1,-2),m=new dt({type:yt(23),value:"${",start:h,end:c,startLoc:g,endLoc:a.end})),r.splice(n,1,p,new dt({type:yt(20),value:f,start:l,end:h,startLoc:u,endLoc:g}),m),n+=2;continue}i.type=yt(s)}}return r}var Eo=class extends So{parseTopLevel(t,e){return t.program=this.parseProgram(e,140,this.options.sourceType==="module"?"module":"script"),t.comments=this.comments,this.optionFlags&256&&(t.tokens=Qb(this.tokens,this.input,this.startIndex)),this.finishNode(t,"File")}parseProgram(t,e,n){if(t.sourceType=n,t.interpreter=this.parseInterpreterDirective(),this.parseBlockBody(t,!0,!0,e),this.inModule){if(!(this.optionFlags&64)&&this.scope.undefinedExports.size>0)for(let[s,a]of Array.from(this.scope.undefinedExports))this.raise(b.ModuleExportUndefined,a,{localName:s});this.addExtra(t,"topLevelAwait",this.state.hasTopLevelAwait)}let i;return e===140?i=this.finishNode(t,"Program"):i=this.finishNodeAt(t,"Program",Oe(this.state.startLoc,-1)),i}stmtToDirective(t){let e=this.castNodeTo(t,"Directive"),n=this.castNodeTo(t.expression,"DirectiveLiteral"),i=n.value,s=this.input.slice(this.offsetToSourcePos(n.start),this.offsetToSourcePos(n.end)),a=n.value=s.slice(1,-1);return this.addExtra(n,"raw",s),this.addExtra(n,"rawValue",a),this.addExtra(n,"expressionValue",i),e.value=n,delete t.expression,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(100)?this.hasFollowingBindingAtom():!1}isUsing(){return this.isContextual(107)?this.nextTokenIsIdentifierOnSameLine():!1}isForUsing(){if(!this.isContextual(107))return!1;let t=this.nextTokenInLineStart(),e=this.codePointAtPos(t);if(this.isUnparsedContextual(t,"of")){let n=this.lookaheadCharCodeSince(t+2);if(n!==61&&n!==58&&n!==59)return!1}return!!(this.chStartsBindingIdentifier(e,t)||this.isUnparsedContextual(t,"void"))}nextTokenIsIdentifierOnSameLine(){let t=this.nextTokenInLineStart(),e=this.codePointAtPos(t);return this.chStartsBindingIdentifier(e,t)}isAwaitUsing(){if(!this.isContextual(96))return!1;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!0}return!1}chStartsBindingIdentifier(t,e){if(ct(t)){if(oo.lastIndex=e,oo.test(this.input)){let n=this.codePointAtPos(oo.lastIndex);if(!Xt(n)&&n!==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)}hasInLineFollowingBindingIdentifierOrBrace(){let t=this.nextTokenInLineStart(),e=this.codePointAtPos(t);return e===123||this.chStartsBindingIdentifier(e,t)}allowsUsing(){return(this.scope.inModule||!this.scope.inTopLevel)&&!this.scope.inBareCaseStatement}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 n=this.state.type,i=this.startNode(),s=!!(t&2),a=!!(t&4),o=t&1;switch(n){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 a||this.raise(this.state.strict?b.StrictFunction:this.options.annexB?b.SloppyFunctionAnnexB:b.SloppyFunction,this.state.startLoc),this.parseFunctionStatement(i,!1,!s&&a);case 80:return s||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.isAwaitUsing())return this.allowsUsing()?s?this.recordAwaitIfAllowed()||this.raise(b.AwaitUsingNotInAsyncContext,i):this.raise(b.UnexpectedLexicalDeclaration,i):this.raise(b.UnexpectedUsingDeclaration,i),this.next(),this.parseVarStatement(i,"await using");break;case 107:if(this.state.containsEsc||!this.hasInLineFollowingBindingIdentifierOrBrace())break;return this.allowsUsing()?s||this.raise(b.UnexpectedLexicalDeclaration,this.state.startLoc):this.raise(b.UnexpectedUsingDeclaration,this.state.startLoc),this.parseVarStatement(i,"using");case 100:{if(this.state.containsEsc)break;let l=this.nextTokenStart(),u=this.codePointAtPos(l);if(u!==91&&(!s&&this.hasFollowingLineBreak()||!this.chStartsBindingIdentifier(u,l)&&u!==123))break}case 75:s||this.raise(b.UnexpectedLexicalDeclaration,this.state.startLoc);case 74:{let l=this.state.value;return this.parseVarStatement(i,l)}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 l=this.lookaheadCharCode();if(l===40||l===46)break}case 82:{!(this.optionFlags&8)&&!o&&this.raise(b.UnexpectedImportExport,this.state.startLoc),this.next();let l;return n===83?l=this.parseImport(i):l=this.parseExport(i,e),this.assertModuleNodeAllowed(l),l}default:if(this.isAsyncFunction())return s||this.raise(b.AsyncFunctionInSingleStatementContext,this.state.startLoc),this.next(),this.parseFunctionStatement(i,!0,!s&&a)}let d=this.state.value,c=this.parseExpression();return re(n)&&c.type==="Identifier"&&this.eat(14)?this.parseLabeledStatement(i,d,c,t):this.parseExpressionStatement(i,c,e)}assertModuleNodeAllowed(t){!(this.optionFlags&8)&&!this.inModule&&this.raise(b.ImportOutsideModule,t)}decoratorsEnabledBeforeExport(){return this.hasPlugin("decorators-legacy")?!0:this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")!==!1}maybeTakeDecorators(t,e,n){if(t){var i;(i=e.decorators)!=null&&i.length?(typeof this.getPluginOption("decorators","decoratorsBeforeExport")!="boolean"&&this.raise(b.DecoratorsBeforeAfterExport,e.decorators[0]),e.decorators.unshift(...t)):e.decorators=t,this.resetStartLocationFromNode(e,t[0]),n&&this.resetStartLocationFromNode(n,e)}return 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(b.DecoratorExportClass,this.state.startLoc);else if(!this.canHaveLeadingDecorator())throw this.raise(b.UnexpectedLeadingDecorator,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,n;if(this.match(10)){let i=this.state.startLoc;this.next(),n=this.parseExpression(),this.expect(11),n=this.wrapParenthesis(i,n);let s=this.state.startLoc;t.expression=this.parseMaybeDecoratorArguments(n,i),this.getPluginOption("decorators","allowCallParenthesized")===!1&&t.expression!==n&&this.raise(b.DecoratorArgumentsOutsideParentheses,s)}else{for(n=this.parseIdentifier(!1);this.eat(16);){let i=this.startNodeAt(e);i.object=n,this.match(139)?(this.classScope.usePrivateName(this.state.value,this.state.startLoc),i.property=this.parsePrivateName()):i.property=this.parseIdentifier(!0),i.computed=!1,n=this.finishNode(i,"MemberExpression")}t.expression=this.parseMaybeDecoratorArguments(n,e)}}else t.expression=this.parseExprSubscripts();return this.finishNode(t,"Decorator")}parseMaybeDecoratorArguments(t,e){if(this.eat(10)){let n=this.startNodeAt(e);return n.callee=t,n.arguments=this.parseCallExpressionArguments(),this.toReferencedList(n.arguments),this.finishNode(n,"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 n;for(n=0;n<this.state.labels.length;++n){let i=this.state.labels[n];if((t.label==null||i.name===t.label.name)&&(i.kind!=null&&(e||i.kind===1)||t.label&&e))break}if(n===this.state.labels.length){let i=e?"BreakStatement":"ContinueStatement";this.raise(b.IllegalBreakContinue,t,{type:i})}}parseDebuggerStatement(t){return this.next(),this.semicolon(),this.finishNode(t,"DebuggerStatement")}parseHeaderExpression(){this.expect(10);let t=this.parseExpression();return this.expect(11),t}parseDoWhileStatement(t){return this.next(),this.state.labels.push(ao),t.body=this.withSmartMixTopicForbiddingContext(()=>this.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(ao);let e=null;if(this.isContextual(96)&&this.recordAwaitIfAllowed()&&(e=this.state.startLoc,this.next()),this.scope.enter(0),this.expect(10),this.match(13))return e!==null&&this.unexpected(e),this.parseFor(t,null);let n=this.isContextual(100);{let d=this.isAwaitUsing(),c=d||this.isForUsing(),l=n&&this.hasFollowingBindingAtom()||c;if(this.match(74)||this.match(75)||l){let u=this.startNode(),p;d?(p="await using",this.recordAwaitIfAllowed()||this.raise(b.AwaitUsingNotInAsyncContext,this.state.startLoc),this.next()):p=this.state.value,this.next(),this.parseVar(u,!0,p);let f=this.finishNode(u,"VariableDeclaration"),h=this.match(58);return h&&c&&this.raise(b.ForInUsing,f),(h||this.isContextual(102))&&f.declarations.length===1?this.parseForIn(t,f,e):(e!==null&&this.unexpected(e),this.parseFor(t,f))}}let i=this.isContextual(95),s=new Tr,a=this.parseExpression(!0,s),o=this.isContextual(102);if(o&&(n&&this.raise(b.ForOfLet,a),e===null&&i&&a.type==="Identifier"&&this.raise(b.ForOfAsync,a)),o||this.match(58)){this.checkDestructuringPrivate(s),this.toAssignable(a,!0);let d=o?"ForOfStatement":"ForInStatement";return this.checkLVal(a,{type:d}),this.parseForIn(t,a,e)}else this.checkExpressionErrors(s,!0);return e!==null&&this.unexpected(e),this.parseFor(t,a)}parseFunctionStatement(t,e,n){return this.next(),this.parseFunction(t,1|(n?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.raise(b.IllegalReturn,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(Xb),this.scope.enter(256);let n;for(let i;!this.match(8);)if(this.match(61)||this.match(65)){let s=this.match(61);n&&this.finishNode(n,"SwitchCase"),e.push(n=this.startNode()),n.consequent=[],this.next(),s?n.test=this.parseExpression():(i&&this.raise(b.MultipleDefaultsInSwitch,this.state.lastTokStartLoc),i=!0,n.test=null),this.expect(14)}else n?n.consequent.push(this.parseStatementListItem()):this.unexpected();return this.scope.exit(),n&&this.finishNode(n,"SwitchCase"),this.next(),this.state.labels.pop(),this.finishNode(t,"SwitchStatement")}parseThrowStatement(t){return this.next(),this.hasPrecedingLineBreak()&&this.raise(b.NewlineAfterThrow,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,{type:"CatchClause"},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(b.NoCatchOrFinally,t),this.finishNode(t,"TryStatement")}parseVarStatement(t,e,n=!1){return this.next(),this.parseVar(t,!1,e,n),this.semicolon(),this.finishNode(t,"VariableDeclaration")}parseWhileStatement(t){return this.next(),t.test=this.parseHeaderExpression(),this.state.labels.push(ao),t.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.state.labels.pop(),this.finishNode(t,"WhileStatement")}parseWithStatement(t){return this.state.strict&&this.raise(b.StrictWith,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,n,i){for(let a of this.state.labels)a.name===e&&this.raise(b.LabelRedeclaration,n,{labelName:e});let s=ib(this.state.type)?1:this.match(71)?2:null;for(let a=this.state.labels.length-1;a>=0;a--){let o=this.state.labels[a];if(o.statementStart===t.start)o.statementStart=this.sourceToOffsetPos(this.state.start),o.kind=s;else break}return this.state.labels.push({name:e,kind:s,statementStart:this.sourceToOffsetPos(this.state.start)}),t.body=i&8?this.parseStatementOrSloppyAnnexBFunctionDeclaration(!0):this.parseStatement(),this.state.labels.pop(),t.label=n,this.finishNode(t,"LabeledStatement")}parseExpressionStatement(t,e,n){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")}parseBlock(t=!1,e=!0,n){let i=this.startNode();return t&&this.state.strictErrors.clear(),this.expect(5),e&&this.scope.enter(0),this.parseBlockBody(i,t,!1,8,n),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,n,i,s){let a=t.body=[],o=t.directives=[];this.parseBlockOrModuleBlockBody(a,e?o:void 0,n,i,s)}parseBlockOrModuleBlockBody(t,e,n,i,s){let a=this.state.strict,o=!1,d=!1;for(;!this.match(i);){let c=n?this.parseModuleItem():this.parseStatementListItem();if(e&&!d){if(this.isValidDirective(c)){let l=this.stmtToDirective(c);e.push(l),!o&&l.value.value==="use strict"&&(o=!0,this.setStrict(!0));continue}d=!0,this.state.strictErrors.clear()}t.push(c)}s?.call(this,o),a||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,n){let i=this.match(58);return this.next(),i?n!==null&&this.unexpected(n):t.await=n!==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(b.ForInOfLoopInitializer,e,{type:i?"ForInStatement":"ForOfStatement"}),e.type==="AssignmentPattern"&&this.raise(b.InvalidLhs,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,n,i=!1){let s=t.declarations=[];for(t.kind=n;;){let a=this.startNode();if(this.parseVarId(a,n),a.init=this.eat(29)?e?this.parseMaybeAssignDisallowIn():this.parseMaybeAssignAllowIn():null,a.init===null&&!i&&(a.id.type!=="Identifier"&&!(e&&(this.match(58)||this.isContextual(102)))?this.raise(b.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:"destructuring"}):(n==="const"||n==="using"||n==="await using")&&!(this.match(58)||this.isContextual(102))&&this.raise(b.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:n})),s.push(this.finishNode(a,"VariableDeclarator")),!this.eat(12))break}return t}parseVarId(t,e){let n=this.parseBindingAtom();e==="using"||e==="await using"?(n.type==="ArrayPattern"||n.type==="ObjectPattern")&&this.raise(b.UsingDeclarationHasBindingPattern,n.loc.start):n.type==="VoidPattern"&&this.raise(b.UnexpectedVoidPattern,n.loc.start),this.checkLVal(n,{type:"VariableDeclarator"},e==="var"?5:8201),t.id=n}parseAsyncFunctionExpression(t){return this.parseFunction(t,8)}parseFunction(t,e=0){let n=e&2,i=!!(e&1),s=i&&!(e&4),a=!!(e&8);this.initFunction(t,a),this.match(55)&&(n&&this.raise(b.GeneratorInSingleStatementContext,this.state.startLoc),this.next(),t.generator=!0),i&&(t.id=this.parseFunctionId(s));let o=this.state.maybeInArrowParameters;return this.state.maybeInArrowParameters=!1,this.scope.enter(514),this.prodParam.enter(Ui(a,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&&!n&&this.registerFunctionStatementId(t),this.state.maybeInArrowParameters=o,t}parseFunctionId(t){return t||re(this.state.type)?this.parseIdentifier():null}parseFunctionParams(t,e){this.expect(10),this.expressionScope.enter($b()),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,n){this.next();let i=this.state.strict;return this.state.strict=!0,this.parseClassId(t,e,n),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)}nameIsConstructor(t){return t.type==="Identifier"&&t.name==="constructor"||t.type==="StringLiteral"&&t.value==="constructor"}isNonstaticConstructor(t){return!t.computed&&!t.static&&this.nameIsConstructor(t.key)}parseClassBody(t,e){this.classScope.enter();let n={hadConstructor:!1,hadSuperClass:t},i=[],s=this.startNode();if(s.body=[],this.expect(5),this.withSmartMixTopicForbiddingContext(()=>{for(;!this.match(8);){if(this.eat(13)){if(i.length>0)throw this.raise(b.DecoratorSemicolon,this.state.lastTokEndLoc);continue}if(this.match(26)){i.push(this.parseDecorator());continue}let a=this.startNode();i.length&&(a.decorators=i,this.resetStartLocationFromNode(a,i[0]),i=[]),this.parseClassMember(s,a,n),a.kind==="constructor"&&a.decorators&&a.decorators.length>0&&this.raise(b.DecoratorConstructor,a)}}),this.state.strict=e,this.next(),i.length)throw this.raise(b.TrailingDecorator,this.state.startLoc);return this.classScope.exit(),this.finishNode(s,"ClassBody")}parseClassMemberFromModifier(t,e){let n=this.parseIdentifier(!0);if(this.isClassMethod()){let i=e;return i.kind="method",i.computed=!1,i.key=n,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=n,i.static=!1,t.body.push(this.parseClassProperty(i)),!0}return this.resetPreviousNodeTrailingComments(n),!1}parseClassMember(t,e,n){let i=this.isContextual(106);if(i){if(this.parseClassMemberFromModifier(t,e))return;if(this.eat(5)){this.parseClassStaticBlock(t,e);return}}this.parseClassMemberWithIsStatic(t,e,n,i)}parseClassMemberWithIsStatic(t,e,n,i){let s=e,a=e,o=e,d=e,c=e,l=s,u=s;if(e.static=i,this.parsePropertyNamePrefixOperator(e),this.eat(55)){l.kind="method";let y=this.match(139);if(this.parseClassElementName(l),this.parsePostMemberNameModifiers(l),y){this.pushClassPrivateMethod(t,a,!0,!1);return}this.isNonstaticConstructor(s)&&this.raise(b.ConstructorIsGenerator,s.key),this.pushClassMethod(t,s,!0,!1,!1,!1);return}let p=!this.state.containsEsc&&re(this.state.type),f=this.parseClassElementName(e),h=p?f.name:null,g=this.isPrivateName(f),m=this.state.startLoc;if(this.parsePostMemberNameModifiers(u),this.isClassMethod()){if(l.kind="method",g){this.pushClassPrivateMethod(t,a,!1,!1);return}let y=this.isNonstaticConstructor(s),w=!1;y&&(s.kind="constructor",n.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(b.DuplicateConstructor,f),y&&this.hasPlugin("typescript")&&e.override&&this.raise(b.OverrideOnConstructor,f),n.hadConstructor=!0,w=n.hadSuperClass),this.pushClassMethod(t,s,!1,!1,y,w)}else if(this.isClassProperty())g?this.pushClassPrivateProperty(t,d):this.pushClassProperty(t,o);else if(h==="async"&&!this.isLineTerminator()){this.resetPreviousNodeTrailingComments(f);let y=this.eat(55);u.optional&&this.unexpected(m),l.kind="method";let w=this.match(139);this.parseClassElementName(l),this.parsePostMemberNameModifiers(u),w?this.pushClassPrivateMethod(t,a,y,!0):(this.isNonstaticConstructor(s)&&this.raise(b.ConstructorIsAsync,s.key),this.pushClassMethod(t,s,y,!0,!1,!1))}else if((h==="get"||h==="set")&&!(this.match(55)&&this.isLineTerminator())){this.resetPreviousNodeTrailingComments(f),l.kind=h;let y=this.match(139);this.parseClassElementName(s),y?this.pushClassPrivateMethod(t,a,!1,!1):(this.isNonstaticConstructor(s)&&this.raise(b.ConstructorIsAccessor,s.key),this.pushClassMethod(t,s,!1,!1,!1,!1)),this.checkGetterSetterParams(s)}else if(h==="accessor"&&!this.isLineTerminator()){this.expectPlugin("decoratorAutoAccessors"),this.resetPreviousNodeTrailingComments(f);let y=this.match(139);this.parseClassElementName(o),this.pushClassAccessorProperty(t,c,y)}else this.isLineTerminator()?g?this.pushClassPrivateProperty(t,d):this.pushClassProperty(t,o):this.unexpected()}parseClassElementName(t){let{type:e,value:n}=this.state;if((e===132||e===134)&&t.static&&n==="prototype"&&this.raise(b.StaticPrototype,this.state.startLoc),e===139){n==="constructor"&&this.raise(b.ConstructorClassPrivateField,this.state.startLoc);let i=this.parsePrivateName();return t.key=i,i}return this.parsePropertyName(t),t.key}parseClassStaticBlock(t,e){var n;this.scope.enter(720);let i=this.state.labels;this.state.labels=[],this.prodParam.enter(0);let s=e.body=[];this.parseBlockOrModuleBlockBody(s,void 0,!1,8),this.prodParam.exit(),this.scope.exit(),this.state.labels=i,t.body.push(this.finishNode(e,"StaticBlock")),(n=e.decorators)!=null&&n.length&&this.raise(b.DecoratorStaticBlock,e)}pushClassProperty(t,e){!e.computed&&this.nameIsConstructor(e.key)&&this.raise(b.ConstructorClassField,e.key),t.body.push(this.parseClassProperty(e))}pushClassPrivateProperty(t,e){let n=this.parseClassPrivateProperty(e);t.body.push(n),this.classScope.declarePrivateName(this.getPrivateNameSV(n.key),0,n.key.loc.start)}pushClassAccessorProperty(t,e,n){!n&&!e.computed&&this.nameIsConstructor(e.key)&&this.raise(b.ConstructorClassField,e.key);let i=this.parseClassAccessorProperty(e);t.body.push(i),n&&this.classScope.declarePrivateName(this.getPrivateNameSV(i.key),0,i.key.loc.start)}pushClassMethod(t,e,n,i,s,a){t.body.push(this.parseMethod(e,n,i,s,a,"ClassMethod",!0))}pushClassPrivateMethod(t,e,n,i){let s=this.parseMethod(e,n,i,!1,!1,"ClassPrivateMethod",!0);t.body.push(s);let a=s.kind==="get"?s.static?6:2:s.kind==="set"?s.static?5:1:0;this.declareClassPrivateMethodInScope(s,a)}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(592),this.expressionScope.enter(Zu()),this.prodParam.enter(0),t.value=this.eat(29)?this.parseMaybeAssignAllowIn():null,this.expressionScope.exit(),this.prodParam.exit(),this.scope.exit()}parseClassId(t,e,n,i=8331){if(re(this.state.type))t.id=this.parseIdentifier(),e&&this.declareNameFromIdentifier(t.id,i);else if(n||!e)t.id=null;else throw this.raise(b.MissingClassName,this.state.startLoc)}parseClassSuper(t){t.superClass=this.eat(81)?this.parseExprSubscripts():null}parseExport(t,e){let n=this.parseMaybeImportPhase(t,!0),i=this.maybeParseExportDefaultSpecifier(t,n),s=!i||this.eat(12),a=s&&this.eatExportStar(t),o=a&&this.maybeParseExportNamespaceSpecifier(t),d=s&&(!o||this.eat(12)),c=i||a;if(a&&!o){if(i&&this.unexpected(),e)throw this.raise(b.UnsupportedDecoratorExport,t);return this.parseExportFrom(t,!0),this.sawUnambiguousESM=!0,this.finishNode(t,"ExportAllDeclaration")}let l=this.maybeParseExportNamedSpecifiers(t);i&&s&&!a&&!l&&this.unexpected(null,5),o&&d&&this.unexpected(null,98);let u;if(c||l){if(u=!1,e)throw this.raise(b.UnsupportedDecoratorExport,t);this.parseExportFrom(t,c)}else u=this.maybeParseExportDeclaration(t);if(c||l||u){var p;let f=t;if(this.checkExport(f,!0,!1,!!f.source),((p=f.declaration)==null?void 0:p.type)==="ClassDeclaration")this.maybeTakeDecorators(e,f.declaration,f);else if(e)throw this.raise(b.UnsupportedDecoratorExport,t);return this.sawUnambiguousESM=!0,this.finishNode(f,"ExportNamedDeclaration")}if(this.eat(65)){let f=t,h=this.parseExportDefaultExpression();if(f.declaration=h,h.type==="ClassDeclaration")this.maybeTakeDecorators(e,h,f);else if(e)throw this.raise(b.UnsupportedDecoratorExport,t);return this.checkExport(f,!0,!0),this.sawUnambiguousESM=!0,this.finishNode(f,"ExportDefaultDeclaration")}throw this.unexpected(null,5)}eatExportStar(t){return this.eat(55)}maybeParseExportDefaultSpecifier(t,e){if(e||this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom",e?.loc.start);let n=e||this.parseIdentifier(!0),i=this.startNodeAtNode(n);return i.exported=n,t.specifiers=[this.finishNode(i,"ExportDefaultSpecifier")],!0}return!1}maybeParseExportNamespaceSpecifier(t){if(this.isContextual(93)){var e,n;(n=(e=t).specifiers)!=null||(e.specifiers=[]);let i=this.startNodeAt(this.state.lastTokStartLoc);return this.next(),i.exported=this.parseModuleExportName(),t.specifiers.push(this.finishNode(i,"ExportNamespaceSpecifier")),!0}return!1}maybeParseExportNamedSpecifiers(t){if(this.match(5)){let e=t;e.specifiers||(e.specifiers=[]);let n=e.exportKind==="type";return e.specifiers.push(...this.parseExportSpecifiers(n)),e.source=null,this.hasPlugin("importAssertions")?e.assertions=[]:e.attributes=[],e.declaration=null,!0}return!1}maybeParseExportDeclaration(t){return this.shouldParseExportDeclaration()?(t.specifiers=[],t.source=null,this.hasPlugin("importAssertions")?t.assertions=[]:t.attributes=[],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(b.DecoratorBeforeExport,this.state.startLoc),this.parseClass(this.maybeTakeDecorators(this.parseDecorators(!1),this.startNode()),!0,!0);if(this.match(75)||this.match(74)||this.isLet()||this.isUsing()||this.isAwaitUsing())throw this.raise(b.UnsupportedDefaultExport,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(re(t)){if(t===95&&!this.state.containsEsc||t===100)return!1;if((t===130||t===129)&&!this.state.containsEsc){let i=this.nextTokenStart(),s=this.input.charCodeAt(i);if(s===123||this.chStartsBindingIdentifier(s,i)&&!this.input.startsWith("from",i))return this.expectOnePlugin(["flow","typescript"]),!1}}else if(!this.match(65))return!1;let e=this.nextTokenStart(),n=this.isUnparsedContextual(e,"from");if(this.input.charCodeAt(e)===44||re(this.state.type)&&n)return!0;if(this.match(65)&&n){let i=this.input.charCodeAt(this.nextTokenStartSince(e+4));return i===34||i===39}return!1}parseExportFrom(t,e){this.eatContextual(98)?(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(b.DecoratorBeforeExport,this.state.startLoc),!0):this.isUsing()?(this.raise(b.UsingDeclarationExport,this.state.startLoc),!0):this.isAwaitUsing()?(this.raise(b.UsingDeclarationExport,this.state.startLoc),!0):t===74||t===75||t===68||t===80||this.isLet()||this.isAsyncFunction()}checkExport(t,e,n,i){if(e){var s;if(n){if(this.checkDuplicateExports(t,"default"),this.hasPlugin("exportDefaultFrom")){var a;let o=t.declaration;o.type==="Identifier"&&o.name==="from"&&o.end-o.start===4&&!((a=o.extra)!=null&&a.parenthesized)&&this.raise(b.ExportDefaultFromAsIdentifier,o)}}else if((s=t.specifiers)!=null&&s.length)for(let o of t.specifiers){let{exported:d}=o,c=d.type==="Identifier"?d.name:d.value;if(this.checkDuplicateExports(o,c),!i&&o.local){let{local:l}=o;l.type!=="Identifier"?this.raise(b.ExportBindingIsString,o,{localName:l.value,exportName:c}):(this.checkReservedWord(l.name,l.loc.start,!0,!1),this.scope.checkLocalExport(l))}}else if(t.declaration){let o=t.declaration;if(o.type==="FunctionDeclaration"||o.type==="ClassDeclaration"){let{id:d}=o;if(!d)throw new Error("Assertion failure");this.checkDuplicateExports(t,d.name)}else if(o.type==="VariableDeclaration")for(let d of o.declarations)this.checkDeclaration(d.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(b.DuplicateDefaultExport,t):this.raise(b.DuplicateExport,t,{exportName:e})),this.exportedIdentifiers.add(e)}parseExportSpecifiers(t){let e=[],n=!0;for(this.expect(5);!this.eat(8);){if(n)n=!1;else if(this.expect(12),this.eat(8))break;let i=this.isContextual(130),s=this.match(134),a=this.startNode();a.local=this.parseModuleExportName(),e.push(this.parseExportSpecifier(a,s,t,i))}return e}parseExportSpecifier(t,e,n,i){return this.eatContextual(93)?t.exported=this.parseModuleExportName():e?t.exported=this.cloneStringLiteral(t.local):t.exported||(t.exported=this.cloneIdentifier(t.local)),this.finishNode(t,"ExportSpecifier")}parseModuleExportName(){if(this.match(134)){let t=this.parseStringLiteral(this.state.value),e=Yb.exec(t.value);return e&&this.raise(b.ModuleExportNameHasLoneSurrogate,t,{surrogateCharCode:e[0].charCodeAt(0)}),t}return this.parseIdentifier(!0)}isJSONModuleImport(t){return t.assertions!=null?t.assertions.some(({key:e,value:n})=>n.value==="json"&&(e.type==="Identifier"?e.name==="type":e.value==="type")):!1}checkImportReflection(t){let{specifiers:e}=t,n=e.length===1?e[0].type:null;if(t.phase==="source")n!=="ImportDefaultSpecifier"&&this.raise(b.SourcePhaseImportRequiresDefault,e[0].loc.start);else if(t.phase==="defer")n!=="ImportNamespaceSpecifier"&&this.raise(b.DeferImportRequiresNamespace,e[0].loc.start);else if(t.module){var i;n!=="ImportDefaultSpecifier"&&this.raise(b.ImportReflectionNotBinding,e[0].loc.start),((i=t.assertions)==null?void 0:i.length)>0&&this.raise(b.ImportReflectionHasAssertion,e[0].loc.start)}}checkJSONModuleImport(t){if(this.isJSONModuleImport(t)&&t.type!=="ExportAllDeclaration"){let{specifiers:e}=t;if(e!=null){let n=e.find(i=>{let s;if(i.type==="ExportSpecifier"?s=i.local:i.type==="ImportSpecifier"&&(s=i.imported),s!==void 0)return s.type==="Identifier"?s.name!=="default":s.value!=="default"});n!==void 0&&this.raise(b.ImportJSONBindingNotDefault,n.loc.start)}}}isPotentialImportPhase(t){return t?!1:this.isContextual(105)||this.isContextual(97)||this.isContextual(127)}applyImportPhase(t,e,n,i){e||(n==="module"?(this.expectPlugin("importReflection",i),t.module=!0):this.hasPlugin("importReflection")&&(t.module=!1),n==="source"?(this.expectPlugin("sourcePhaseImports",i),t.phase="source"):n==="defer"?(this.expectPlugin("deferredImportEvaluation",i),t.phase="defer"):this.hasPlugin("sourcePhaseImports")&&(t.phase=null))}parseMaybeImportPhase(t,e){if(!this.isPotentialImportPhase(e))return this.applyImportPhase(t,e,null),null;let n=this.startNode(),i=this.parseIdentifierName(!0),{type:s}=this.state;return(Ze(s)?s!==98||this.lookaheadCharCode()===102:s!==12)?(this.applyImportPhase(t,e,i,n.loc.start),null):(this.applyImportPhase(t,e,null),this.createIdentifier(n,i))}isPrecedingIdImportPhase(t){let{type:e}=this.state;return re(e)?e!==98||this.lookaheadCharCode()===102:e!==12}parseImport(t){return this.match(134)?this.parseImportSourceAndAttributes(t):this.parseImportSpecifiersAndAfter(t,this.parseMaybeImportPhase(t,!1))}parseImportSpecifiersAndAfter(t,e){t.specifiers=[];let i=!this.maybeParseDefaultImportSpecifier(t,e)||this.eat(12),s=i&&this.maybeParseStarImportSpecifier(t);return i&&!s&&this.parseNamedImportSpecifiers(t),this.expectContextual(98),this.parseImportSourceAndAttributes(t)}parseImportSourceAndAttributes(t){var e;return(e=t.specifiers)!=null||(t.specifiers=[]),t.source=this.parseImportSource(),this.maybeParseImportAttributes(t),this.checkImportReflection(t),this.checkJSONModuleImport(t),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(t,"ImportDeclaration")}parseImportSource(){return this.match(134)||this.unexpected(),this.parseExprAtom()}parseImportSpecifierLocal(t,e,n){e.local=this.parseIdentifier(),t.specifiers.push(this.finishImportSpecifier(e,n))}finishImportSpecifier(t,e,n=8201){return this.checkLVal(t.local,{type:e},n),this.finishNode(t,e)}parseImportAttributes(){this.expect(5);let t=[],e=new Set;do{if(this.match(8))break;let n=this.startNode(),i=this.state.value;if(e.has(i)&&this.raise(b.ModuleAttributesWithDuplicateKeys,this.state.startLoc,{key:i}),e.add(i),this.match(134)?n.key=this.parseStringLiteral(i):n.key=this.parseIdentifier(!0),this.expect(14),!this.match(134))throw this.raise(b.ModuleAttributeInvalidValue,this.state.startLoc);n.value=this.parseStringLiteral(this.state.value),t.push(this.finishNode(n,"ImportAttribute"))}while(this.eat(12));return this.expect(8),t}parseModuleAttributes(){let t=[],e=new Set;do{let n=this.startNode();if(n.key=this.parseIdentifier(!0),n.key.name!=="type"&&this.raise(b.ModuleAttributeDifferentFromType,n.key),e.has(n.key.name)&&this.raise(b.ModuleAttributesWithDuplicateKeys,n.key,{key:n.key.name}),e.add(n.key.name),this.expect(14),!this.match(134))throw this.raise(b.ModuleAttributeInvalidValue,this.state.startLoc);n.value=this.parseStringLiteral(this.state.value),t.push(this.finishNode(n,"ImportAttribute"))}while(this.eat(12));return t}maybeParseImportAttributes(t){let e;var n=!1;if(this.match(76)){if(this.hasPrecedingLineBreak()&&this.lookaheadCharCode()===40)return;this.next(),this.hasPlugin("moduleAttributes")?(e=this.parseModuleAttributes(),this.addExtra(t,"deprecatedWithLegacySyntax",!0)):e=this.parseImportAttributes(),n=!0}else this.isContextual(94)&&!this.hasPrecedingLineBreak()?(!this.hasPlugin("deprecatedImportAssert")&&!this.hasPlugin("importAssertions")&&this.raise(b.ImportAttributesUseAssert,this.state.startLoc),this.hasPlugin("importAssertions")||this.addExtra(t,"deprecatedAssertSyntax",!0),this.next(),e=this.parseImportAttributes()):e=[];!n&&this.hasPlugin("importAssertions")?t.assertions=e:t.attributes=e}maybeParseDefaultImportSpecifier(t,e){if(e){let n=this.startNodeAtNode(e);return n.local=e,t.specifiers.push(this.finishImportSpecifier(n,"ImportDefaultSpecifier")),!0}else if(Ze(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(b.DestructureNamedImport,this.state.startLoc);if(this.expect(12),this.eat(8))break}let n=this.startNode(),i=this.match(134),s=this.isContextual(130);n.imported=this.parseModuleExportName();let a=this.parseImportSpecifier(n,i,t.importKind==="type"||t.importKind==="typeof",s,void 0);t.specifiers.push(a)}}parseImportSpecifier(t,e,n,i,s){if(this.eatContextual(93))t.local=this.parseIdentifier();else{let{imported:a}=t;if(e)throw this.raise(b.ImportBindingIsString,t,{importName:a.value});this.checkReservedWord(a.name,t.loc.start,!0,!0),t.local||(t.local=this.cloneIdentifier(a))}return this.finishImportSpecifier(t,"ImportSpecifier",s)}isThisParam(t){return t.type==="Identifier"&&t.name==="this"}},Ji=class extends Eo{constructor(t,e,n){let i=Xw(t);super(i,e),this.options=i,this.initializeScopes(),this.plugins=n,this.filename=i.sourceFilename,this.startIndex=i.startIndex;let s=0;i.allowAwaitOutsideFunction&&(s|=1),i.allowReturnOutsideFunction&&(s|=2),i.allowImportExportEverywhere&&(s|=8),i.allowSuperOutsideMethod&&(s|=16),i.allowUndeclaredExports&&(s|=64),i.allowNewTargetOutsideFunction&&(s|=4),i.allowYieldOutsideFunction&&(s|=32),i.ranges&&(s|=128),i.tokens&&(s|=256),i.createImportExpressions&&(s|=512),i.createParenthesizedExpressions&&(s|=1024),i.errorRecovery&&(s|=2048),i.attachComment&&(s|=4096),i.annexB&&(s|=8192),this.optionFlags=s}getScopeHandler(){return kn}parse(){this.enterInitialScopes();let t=this.startNode(),e=this.startNode();this.nextToken(),t.errors=null;let n=this.parseTopLevel(t,e);return n.errors=this.state.errors,n.comments.length=this.state.commentsLen,n}};function Zb(r,t){var e;if(((e=t)==null?void 0:e.sourceType)==="unambiguous"){t=Object.assign({},t);try{t.sourceType="module";let n=bn(t,r),i=n.parse();if(n.sawUnambiguousESM)return i;if(n.ambiguousScriptDifferentAst)try{return t.sourceType="script",bn(t,r).parse()}catch{}else i.program.sourceType="script";return i}catch(n){try{return t.sourceType="script",bn(t,r).parse()}catch{}throw n}}else return bn(t,r).parse()}function ex(r,t){let e=bn(t,r);return e.options.strictMode&&(e.state.strict=!0),e.getExpression()}function tx(r){let t={};for(let e of Object.keys(r))t[e]=yt(r[e]);return t}var rx=tx(eb);function bn(r,t){let e=Ji,n=new Map;if(r!=null&&r.plugins){for(let i of r.plugins){let s,a;typeof i=="string"?s=i:[s,a]=i,n.has(s)||n.set(s,a||{})}Wb(n),e=nx(n)}return new e(r,t,n)}var zu=new Map;function nx(r){let t=[];for(let i of Jb)r.has(i)&&t.push(i);let e=t.join("|"),n=zu.get(e);if(!n){n=Ji;for(let i of t)n=rp[i](n);zu.set(e,n)}return n}Pn.parse=Zb;Pn.parseExpression=ex;Pn.tokTypes=rx});import{parseArgs as sE}from"node:util";import{createHash as cg}from"node:crypto";import{access as q0,appendFile as U0,mkdir as G0,readdir as K0,readFile as Ba,realpath as Va,stat as lg,writeFile as mg}from"node:fs/promises";import{isAbsolute as ug,join as je,relative as Tl,resolve as pg}from"node:path";import{mkdir as xT,writeFile as vT}from"node:fs/promises";import{join as mm}from"node:path";import{lstat as Hg,readFile as Ll,realpath as Ua}from"node:fs/promises";import{dirname as za,isAbsolute as qg,join as Ri,relative as Ti,resolve as Pi,sep as Ml}from"node:path";var $l=["ts","mts","cts","js","mjs","cjs"],_l={playwright:"playwright.config",cypress:"cypress.config",webdriverio:"wdio.conf"},Ug={playwright:["@playwright/test"],cypress:["cypress"],webdriverio:["@wdio/cli","webdriverio"]},Si={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"};function Ha(r,t){let e=Ti(r,t);return e===""||!qg(e)&&e!==".."&&!e.startsWith(`..${Ml}`)}async function Ai(r){return(await Hg(r).catch(()=>{}))?.isFile()===!0}function qa(r){return r.split(Ml).join("/")}async function Fl(r){let t=await Ua(r),e={};try{let i=JSON.parse(await Ll(Ri(t,"package.json"),"utf8"));e={...i.dependencies,...i.devDependencies}}catch{e={}}let n=[];for(let i of["playwright","cypress","webdriverio"]){let s=Ug[i].find(o=>o in e),a;for(let o of $l){let d=`${_l[i]}.${o}`;if(await Ai(Ri(t,d))){a=d;break}}(s!==void 0||a!==void 0)&&n.push({framework:i,...a===void 0?{}:{configFile:a},...s===void 0?{}:{packageName:s}})}return n}async function Ei(r,t,e){let n=await Ua(r),i=za(Pi(n,e));for(Ha(n,i)||(i=n);;){for(let a of $l){let o=Ri(i,`${_l[t]}.${a}`);if(await Ai(o))return qa(Ti(n,o))}if(i===n)return;let s=za(i);if(!Ha(n,s))return;i=s}}async function Ci(r,t){let e=await Ua(r),n=t===void 0?e:za(Pi(e,t));if(t!==void 0){let i=await Ll(Pi(e,t),"utf8").catch(()=>"");if(/\bsupportFile\s*:\s*false\b/.test(i))return null;let s=/\bsupportFile\s*:\s*["'`]([^"'`]+)["'`]/.exec(i)?.[1];if(s!==void 0){let a=Pi(n,s);return Ha(e,a)&&await Ai(a)?qa(Ti(e,a)):void 0}}for(let i of["ts","js","tsx","jsx"]){let s=Ri(n,"cypress","support",`e2e.${i}`);if(await Ai(s))return qa(Ti(e,s))}}import{createHash as jl}from"node:crypto";function Gg(r){return`${Buffer.byteLength(r,"utf8")}:${r}`}function Te(r){return jl("sha256").update(r).digest("hex")}function $(r,t){let e=t.map(Gg).join("|"),n=jl("sha256").update(e,"utf8").digest("hex");return`${r}_${n.slice(0,24)}`}import{isAbsolute as Bl,relative as Kg,sep as Vl}from"node:path";var Ni=["1.55.0","1.64.1"],xr=["playwright","cypress","webdriverio"];var Ga={playwright:Ni,cypress:["16.2.0"],webdriverio:["10.1.0"]};function Wa(r){return{...r}}function Oi(r,t,e){return{errorId:$("err",[t,e]),source:e,...r.message===void 0?{}:{message:r.message},...r.name===void 0?{}:{name:r.name},...r.stack===void 0?{}:{stack:r.stack},...r.snippet===void 0?{}:{snippet:r.snippet},...r.value===void 0?{}:{value:r.value},...r.location===void 0?{}:{location:Wa(r.location)}}}function ql(r){return{type:r.type,...r.description===void 0?{}:{description:r.description},...r.location===void 0?{}:{location:Wa(r.location)}}}function zl(r){return"text"in r?{kind:"text",text:r.text}:{kind:"base64",base64:r.buffer}}function Wg(r,t,e){return{attachmentId:$("att",[t,String(e)]),name:r.name,contentType:r.contentType,sourceIndex:e,...r.path===void 0?{}:{path:r.path},...r.body===void 0?{}:{bodyBase64:r.body}}}function Ul(r,t,e){return{title:r.title,duration:r.duration,...r.error===void 0?{}:{error:Oi(r.error,t,`${e}.error`)},steps:r.steps.map((n,i)=>Ul(n,t,`${e}.steps[${i}]`))}}function Jg(r){let t=[],e=(n,i,s)=>{n.forEach((a,o)=>{let d=`${s}[${o}]`,c=a.title.length===0?i:[...i,a.title];a.specs.forEach((l,u)=>{l.tests.forEach((p,f)=>{t.push({titlePath:[...c,l.title],spec:l,test:p,sourcePath:`${d}.specs[${u}].tests[${f}]`})})}),e(a.suites,c,`${d}.suites`)})};return e(r.suites,[],"$report.suites"),t}function Ka(r,t){if(!Bl(t))return;let e=Kg(r,t);if(!(Bl(e)||e===".."||e.startsWith(`..${Vl}`)))return e.split(Vl).join("/")}function Xg(r,t){return r.config.projects.map(e=>{let n=e.testDir===void 0?void 0:Ka(t,e.testDir);return{projectId:$("prj",[e.id,e.name]),frameworkProjectId:e.id,name:e.name,repeatEach:e.repeatEach,retries:e.retries,...n===void 0?{}:{testDir:n}}}).sort((e,n)=>e.projectId.localeCompare(n.projectId))}function Yg(r,t,e,n){let i=$("atm",[t,String(r.retry),"repeat:unknown",String(e)]),s=[];return r.error!==void 0&&s.push(Oi(r.error,i,`${n}.error`)),r.errors.forEach((a,o)=>{s.push(Oi(a,i,`${n}.errors[${o}]`))}),{attemptId:i,sourceIndex:e,retry:r.retry,repeat:{state:"unknown",reason:"not-serialized-by-playwright-json-reporter"},status:r.status,duration:r.duration,startTime:new Date(r.startTime).toISOString(),workerIndex:r.workerIndex,parallelIndex:r.parallelIndex,errors:s,stdout:r.stdout.map(zl),stderr:r.stderr.map(zl),steps:r.steps.map((a,o)=>Ul(a,i,`${n}.steps[${o}]`)),attachments:r.attachments.map((a,o)=>Wg(a,i,o)),annotations:r.annotations.map(ql),...r.errorLocation===void 0?{}:{errorLocation:Wa(r.errorLocation)}}}function Qg(r,t){return r.length===0?"zero-tests":r.some(e=>e.attempts.some(n=>n.status==="interrupted"))?"interrupted":t.length>0?"report-errors":"analysis-ready"}function Gl(r){let{report:t,reportHash:e,artifact:n,options:i}=r,s=i.workspaceRoot,a=Xg(t,s),o=t.config.rootDir===void 0?void 0:Ka(s,t.config.rootDir),d=y=>{let w=y.replaceAll("\\","/");return o===void 0||o===""?w:`${o}/${w}`},c=t.config.configFile===void 0?void 0:Ka(s,t.config.configFile),l=new Map(a.map(y=>[y.frameworkProjectId,y.projectId])),p=Jg(t).map(({spec:y,test:w,titlePath:x,sourcePath:v})=>{let I=l.get(w.projectId);if(I===void 0)throw new Error(`Validated test references unknown project ID: ${w.projectId}`);let R=d(y.file),E=$("tst",[s,I,R,...x]);return{logicalTestId:E,projectId:I,title:y.title,titlePath:x,tags:[...y.tags].sort(),location:{file:R,line:y.line,column:y.column},timeout:w.timeout,expectedStatus:w.expectedStatus,status:w.status,annotations:w.annotations.map(ql),attempts:w.results.map((A,O)=>Yg(A,E,O,`${v}.results[${O}]`))}});p.sort((y,w)=>y.logicalTestId.localeCompare(w.logicalTestId));let f=t.errors.map((y,w)=>Oi(y,n.artifactId,`$report.errors[${w}]`)),h=p.reduce((y,w)=>y+w.attempts.reduce((x,v)=>x+v.attachments.length,0),0),g=new Date(t.stats.startTime).toISOString(),m=$("run",[e,s,i.gitRoot??"","1.2","1"]);return{schemaVersion:"1.2",runId:m,framework:"playwright",createdAt:g,workspace:{root:s,...i.gitRoot===void 0?{}:{gitRoot:i.gitRoot}},sourceHashes:{report:e},artifact:n,usability:Qg(p,f),projects:a,...c===void 0?{}:{configFile:c},logicalTests:p,reportErrors:f,collections:{tests:p.length===0?"empty":"present",errors:f.length===0?"empty":"present",attachments:h===0?"empty":"present"},warnings:[...r.warnings].sort(),stats:{...t.stats,startTime:g}}}var kr=class extends Error{constructor(t){super(t),this.name="ReportValidationError"}};function Se(r,t){throw new kr(`${r} must be ${t}`)}function Z(r,t){return typeof r!="object"||r===null||Array.isArray(r)?Se(t,"an object"):r}function Ut(r,t){return Array.isArray(r)?r:Se(t,"an array")}function H(r,t){return typeof r!="string"?Se(t,"a string"):r}function ue(r,t){return r===void 0?void 0:H(r,t)}function ze(r,t){return typeof r!="number"||!Number.isFinite(r)?Se(t,"a finite number"):r}function Di(r,t){let e=ze(r,t);return Number.isInteger(e)?e:Se(t,"an integer")}function ye(r,t){let e=Di(r,t);return e<0?Se(t,"a non-negative integer"):e}function Ja(r,t){let e=H(r,t);return!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(e)||new Date(e).toISOString()!==e?Se(t,"an ISO 8601 UTC timestamp with millisecond precision"):e}function Kl(r,t){return typeof r!="boolean"?Se(t,"a boolean"):r}function ce(r,t,e,n){let i=r[t];return i===void 0?void 0:e(i,`${n}.${t}`)}function X(r,t,e){return Ut(r,t).map((n,i)=>e(n,`${t}[${i}]`))}function Zg(r){return r.length===0?!0:r.length%4!==0?!1:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(r)}function Xa(r,t){let e=H(r,t);return Zg(e)?e:Se(t,"canonical base64")}function Gt(r,t,e){let n=H(r,t);return e.has(n)?n:Se(t,`one of ${[...e].join(", ")}`)}function Li(r,t){return t===void 0?{}:{[r]:t}}function Ya(r,t){let e=Z(r,t),n=ce(e,"line",ye,t),i=ce(e,"column",ye,t);return{file:H(e.file,`${t}.file`),...n===void 0?{}:{line:n},...i===void 0?{}:{column:i}}}function Mi(r,t){let e=Z(r,t),n=ce(e,"message",H,t),i=ce(e,"name",H,t),s=ce(e,"stack",H,t),a=ce(e,"snippet",H,t),o=ce(e,"value",H,t),d=ce(e,"location",Ya,t);return{...n===void 0?{}:{message:n},...i===void 0?{}:{name:i},...s===void 0?{}:{stack:s},...a===void 0?{}:{snippet:a},...o===void 0?{}:{value:o},...d===void 0?{}:{location:d}}}function Jl(r,t){let e=Z(r,t),n=ce(e,"description",H,t),i=ce(e,"location",Ya,t);return{type:H(e.type,`${t}.type`),...n===void 0?{}:{description:n},...i===void 0?{}:{location:i}}}function Wl(r,t){let e=Z(r,t),n=typeof e.text=="string",i=typeof e.buffer=="string";return n===i?Se(t,"exactly one of text or buffer"):n?{text:H(e.text,`${t}.text`)}:{buffer:Xa(e.buffer,`${t}.buffer`)}}function ew(r,t){let e=Z(r,t),n=ce(e,"path",H,t),i=ce(e,"body",Xa,t);return{name:H(e.name,`${t}.name`),contentType:H(e.contentType,`${t}.contentType`),...n===void 0?{}:{path:n},...i===void 0?{}:{body:i}}}function Xl(r,t){let e=Z(r,t),n=ce(e,"error",Mi,t);return{title:H(e.title,`${t}.title`),duration:ze(e.duration,`${t}.duration`),...n===void 0?{}:{error:n},steps:X(e.steps??[],`${t}.steps`,Xl)}}var Yl=new Set(["passed","failed","timedOut","skipped","interrupted"]),tw=new Set(["expected","unexpected","flaky","skipped"]);function rw(r,t){let e=Z(r,t),n=ce(e,"error",Mi,t),i=ce(e,"errorLocation",Ya,t);return{workerIndex:Di(e.workerIndex,`${t}.workerIndex`),parallelIndex:Di(e.parallelIndex,`${t}.parallelIndex`),status:Gt(e.status,`${t}.status`,Yl),duration:ze(e.duration,`${t}.duration`),startTime:Ja(e.startTime,`${t}.startTime`),retry:ye(e.retry,`${t}.retry`),...n===void 0?{}:{error:n},errors:X(e.errors??[],`${t}.errors`,Mi),stdout:X(e.stdout??[],`${t}.stdout`,Wl),stderr:X(e.stderr??[],`${t}.stderr`,Wl),steps:X(e.steps??[],`${t}.steps`,Xl),attachments:X(e.attachments??[],`${t}.attachments`,ew),annotations:X(e.annotations??[],`${t}.annotations`,Jl),...i===void 0?{}:{errorLocation:i}}}function nw(r,t){let e=Z(r,t);return{timeout:ze(e.timeout,`${t}.timeout`),annotations:X(e.annotations??[],`${t}.annotations`,Jl),expectedStatus:Gt(e.expectedStatus,`${t}.expectedStatus`,Yl),projectName:H(e.projectName,`${t}.projectName`),projectId:H(e.projectId,`${t}.projectId`),results:X(e.results,`${t}.results`,rw),status:Gt(e.status,`${t}.status`,tw)}}function iw(r,t){let e=Z(r,t);return{title:H(e.title,`${t}.title`),ok:Kl(e.ok,`${t}.ok`),tags:X(e.tags??[],`${t}.tags`,H),tests:X(e.tests,`${t}.tests`,nw),file:H(e.file,`${t}.file`),line:ye(e.line,`${t}.line`),column:ye(e.column,`${t}.column`)}}function Ql(r,t){let e=Z(r,t),n=ce(e,"file",H,t),i=ce(e,"line",ye,t),s=ce(e,"column",ye,t);return{title:H(e.title,`${t}.title`),...n===void 0?{}:{file:n},...i===void 0?{}:{line:i},...s===void 0?{}:{column:s},suites:X(e.suites??[],`${t}.suites`,Ql),specs:X(e.specs??[],`${t}.specs`,iw)}}function sw(r,t){let e=Z(r,t);return{id:H(e.id,`${t}.id`),name:H(e.name,`${t}.name`),repeatEach:ye(e.repeatEach,`${t}.repeatEach`),retries:ye(e.retries,`${t}.retries`),...Li("testDir",ue(e.testDir,`${t}.testDir`))}}function Zl(r){let t=Z(r,"$report"),e=Z(t.config,"$report.config"),n=Z(t.stats,"$report.stats");return{config:{version:H(e.version,"$report.config.version"),projects:X(e.projects,"$report.config.projects",sw),...Li("rootDir",ue(e.rootDir,"$report.config.rootDir")),...Li("configFile",ue(e.configFile,"$report.config.configFile"))},suites:X(t.suites,"$report.suites",Ql),errors:X(t.errors??[],"$report.errors",Mi),stats:{startTime:Ja(n.startTime,"$report.stats.startTime"),duration:ze(n.duration,"$report.stats.duration"),expected:ye(n.expected,"$report.stats.expected"),skipped:ye(n.skipped,"$report.stats.skipped"),unexpected:ye(n.unexpected,"$report.stats.unexpected"),flaky:ye(n.flaky,"$report.stats.flaky")}}}var aw=new TextDecoder("utf-8",{fatal:!0});function Kt(r,t,e){return{kind:"unreadable",artifact:{artifactId:$("art",[r??"unavailable",t??"bytes"]),kind:"report",availability:"unreadable",...t===void 0?{}:{path:t},...r===void 0?{}:{sha256:r},warnings:[]},diagnostic:e}}function ow(r){return new Set(r??Ni)}function Ir(r,t){let e=Te(r);if(r.byteLength===0)return Kt(e,t.reportPath,{reasonCode:"empty-input",message:"The Playwright JSON report is empty.",...t.reportPath===void 0?{}:{path:t.reportPath}});let n;try{n=aw.decode(r)}catch{return Kt(e,t.reportPath,{reasonCode:"invalid-utf8",message:"The Playwright JSON report is not valid UTF-8.",...t.reportPath===void 0?{}:{path:t.reportPath}})}let i;try{i=JSON.parse(n)}catch(p){return Kt(e,t.reportPath,{reasonCode:"invalid-json",message:p instanceof Error?p.message:"The report is not valid JSON.",...t.reportPath===void 0?{}:{path:t.reportPath}})}let s;try{s=Zl(i)}catch(p){return Kt(e,t.reportPath,{reasonCode:"invalid-report-shape",message:p instanceof kr?p.message:"The JSON value is not a supported Playwright report.",...t.reportPath===void 0?{}:{path:t.reportPath}})}let a=new Set;for(let p of s.config.projects){if(a.has(p.id))return Kt(e,t.reportPath,{reasonCode:"invalid-report-shape",message:`$report.config.projects contains duplicate project ID: ${p.id}`,...t.reportPath===void 0?{}:{path:t.reportPath}});a.add(p.id)}if(new Set(t.incompatiblePlaywrightVersions??[]).has(s.config.version))return Kt(e,t.reportPath,{reasonCode:"incompatible-playwright-version",message:`Playwright ${s.config.version} is configured as incompatible.`,...t.reportPath===void 0?{}:{path:t.reportPath}});let c=ow(t.testedPlaywrightVersions).has(s.config.version),l=[];c||l.push(`unverified-producer-version:${s.config.version}`),s.config.projects.some(p=>p.repeatEach>1)&&l.push("repeat-index-unavailable");let u={artifactId:$("art",[e]),kind:"report",availability:"present",...t.reportPath===void 0?{}:{path:t.reportPath},sha256:e,format:"playwright-json",formatVersion:s.config.version,versionConfidence:c?"verified":"unverified",warnings:[...l].sort()};try{return{kind:"parsed",run:Gl({report:s,reportHash:e,artifact:u,options:t,warnings:l})}}catch(p){return Kt(e,t.reportPath,{reasonCode:"invalid-report-shape",message:p instanceof Error?p.message:"The report could not be normalized.",...t.reportPath===void 0?{}:{path:t.reportPath}})}}import{createHash as bx}from"node:crypto";import{readdir as xx,readFile as vx,stat as kx}from"node:fs/promises";import{basename as Ix,join as Px}from"node:path";import{join as cw}from"node:path";var dw=/(?:\(|\bat\s+|^)((?:webpack:\/\/[^\s()]*|file:\/\/[^\s()]*|(?:[A-Za-z]:)?[^():\s][^():]*?)):(\d+):(\d+)\)?\s*$/;function tu(r){let t=r,e=/^webpack:\/\/[^/]*\/(.*)$/.exec(t);return e!==null&&(t=e[1]??""),t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7)).replaceAll("\\","/"),/^\/[A-Za-z]:\//.test(t)&&(t=t.slice(1))),t.replace(/^(?:\.\/)+/,"")}function eu(r){return/^https?:\/\//.test(r)||r.includes("/__cypress/")||r.includes("node_modules/")||r.startsWith("node:")||r.startsWith("internal/")}function ru(r){let t=[];for(let e of r.split(/\r?\n/)){let n=dw.exec(e.trim());if(n===null)continue;let[,i,s,a]=n;if(i===void 0||s===void 0||a===void 0||eu(i))continue;let o=tu(i);o===""||eu(o)||t.push({file:o,line:Number.parseInt(s,10),column:Number.parseInt(a,10)})}return t}function at(r,t){if(r===void 0)return;let e=ru(r);if(t!==void 0){let n=t.replaceAll("\\","/").replace(/^(?:\.\/)+/,""),i=e.find(s=>{let a=s.file.replaceAll("\\","/");return a===n||a.endsWith(`/${n}`)||n.endsWith(`/${a}`)});if(i!==void 0)return i}return e[0]}var $i="kwikqa-test-report",Qa="1.0",lw="1",uw=new Set(["cypress","webdriverio"]),pw=new Set(["passed","failed","timedOut","skipped","interrupted"]);function nu(r,t){let e=t.replaceAll("\\","/");return/^(?:[A-Za-z]:\/|\/|file:\/\/)/.test(e)?t:cw(r,e.replace(/^(?:\.\/)+/,""))}function fw(r){let t=r.rootDir;return t===void 0?r:{...r,tests:r.tests.map(e=>({...e,file:nu(t,e.file),attempts:e.attempts.map(n=>({...n,attachments:n.attachments.map(i=>i.path===void 0?i:{...i,path:nu(t,i.path)})}))}))}}function iu(r){return typeof r=="object"&&r!==null&&r.schema===$i}function hw(r,t){let e=Z(r,t),n=ce(e,"line",ye,t),i=ce(e,"column",ye,t);return{file:H(e.file,`${t}.file`),...n===void 0?{}:{line:n},...i===void 0?{}:{column:i}}}function su(r,t,e){let n=Z(r,t),i=ue(n.message,`${t}.message`),s=ue(n.name,`${t}.name`),a=ue(n.stack,`${t}.stack`),o=ue(n.snippet,`${t}.snippet`),d=ue(n.expected,`${t}.expected`),c=ue(n.actual,`${t}.actual`),u=ce(n,"location",hw,t)??at(a,e);return{...i===void 0?{}:{message:i},...s===void 0?{}:{name:s},...a===void 0?{}:{stack:a},...o===void 0?{}:{snippet:o},...d===void 0&&c===void 0?{}:{value:`Expected: ${d??"(not recorded)"}
11
+ Received: ${c??"(not recorded)"}`},...u===void 0?{}:{location:u}}}function mw(r,t,e){let n=Z(r,t),i=ue(n.startTime,`${t}.startTime`);return{status:Gt(n.status,`${t}.status`,pw),retry:ye(n.retry,`${t}.retry`),...i===void 0?{}:{startTime:i},duration:ze(n.duration??0,`${t}.duration`),errors:X(n.errors??[],`${t}.errors`,(s,a)=>su(s,a,e)),attachments:X(n.attachments??[],`${t}.attachments`,(s,a)=>{let o=Z(s,a),d=ue(o.path,`${a}.path`);return{name:H(o.name,`${a}.name`),contentType:H(o.contentType,`${a}.contentType`),...d===void 0?{}:{path:d}}}),stdout:X(n.stdout??[],`${t}.stdout`,H),stderr:X(n.stderr??[],`${t}.stderr`,H),steps:[]}}function yw(r,t){let e=Z(r,t),n=H(e.file,`${t}.file`),i=X(e.titlePath,`${t}.titlePath`,H);i.length===0&&Se(`${t}.titlePath`,"a non-empty array");let s=ce(e,"line",ye,t),a=ce(e,"column",ye,t),o=ce(e,"timeout",ze,t);return{file:n,titlePath:i,...s===void 0?{}:{line:s},...a===void 0?{}:{column:a},projectId:H(e.project,`${t}.project`),...o===void 0?{}:{timeout:o},tags:X(e.tags??[],`${t}.tags`,H),attempts:X(e.attempts,`${t}.attempts`,(d,c)=>mw(d,c,n))}}function au(r){let t=Z(r,"$report");t.schema!==$i&&Se("$report.schema",$i),String(t.schemaVersion??"").split(".")[0]!==Qa.split(".")[0]&&Se("$report.schemaVersion",`a ${Qa.split(".")[0]}.x version`);let n=Gt(t.framework,"$report.framework",uw),i=ue(t.frameworkVersion,"$report.frameworkVersion"),s=ue(t.rootDir,"$report.rootDir"),a=ue(t.configFile,"$report.configFile"),o=ue(t.startTime,"$report.startTime"),d=ce(t,"duration",ze,"$report"),c=X(t.projects,"$report.projects",(l,u)=>{let p=Z(l,u);return{id:H(p.id,`${u}.id`),name:H(p.name,`${u}.name`),retries:ye(p.retries??0,`${u}.retries`)}});return Ut(t.tests,"$report.tests"),{framework:n,format:"kwikqa-json",adapterVersion:lw,...i===void 0?{}:{frameworkVersion:i},...s===void 0?{}:{rootDir:s},...a===void 0?{}:{configFile:a},...o===void 0?{}:{startTime:o},...d===void 0?{}:{duration:d},projects:c,tests:X(t.tests,"$report.tests",yw),errors:X(t.errors??[],"$report.errors",(l,u)=>su(l,u,void 0)),interrupted:t.interrupted===!0,warnings:[]}}function ou(r){let t=r.map(fw),e=t[0];if(e===void 0)throw new Error("No report parts to merge.");let n=e.framework;if(t.some(l=>l.framework!==n))throw new Error("Report parts come from different frameworks.");let i=[...new Set(t.map(l=>l.frameworkVersion).filter(Boolean))],s=new Map;for(let l of t)for(let u of l.projects){let p=s.get(u.id);(p===void 0||u.retries>p.retries)&&s.set(u.id,u)}let a=t.map(l=>l.startTime).filter(l=>l!==void 0).sort(),o=[...new Set(t.map(l=>l.rootDir).filter(Boolean))],d=[...new Set(t.map(l=>l.configFile).filter(Boolean))],c=t.flatMap(l=>l.warnings);return i.length>1&&c.push(`mixed-framework-versions:${i.join(",")}`),o.length>1&&c.push("mixed-report-roots"),{framework:n,format:e.format,adapterVersion:e.adapterVersion,...i.length===1&&i[0]!==void 0?{frameworkVersion:i[0]}:{},...o.length===1&&o[0]!==void 0?{rootDir:o[0]}:{},...d.length===1&&d[0]!==void 0?{configFile:d[0]}:{},...a[0]===void 0?{}:{startTime:a[0]},duration:t.reduce((l,u)=>Math.max(l,u.duration??0),0),projects:[...s.values()],tests:t.flatMap(l=>l.tests),errors:t.flatMap(l=>l.errors),interrupted:t.some(l=>l.interrupted),warnings:c}}var _i=class extends Error{constructor(t){super(t),this.name="XmlError"}},gw=64,ww=5e5,bw=/^[A-Za-z_:][\w.:-]*/,xw={lt:"<",gt:">",amp:"&",quot:'"',apos:"'"};function du(r){return r.replace(/&(#x[0-9A-Fa-f]+|#\d+|[A-Za-z]+);/g,(t,e)=>{if(e.startsWith("#x")){let i=Number.parseInt(e.slice(2),16);return i<=1114111?String.fromCodePoint(i):t}if(e.startsWith("#")){let i=Number.parseInt(e.slice(1),10);return i<=1114111?String.fromCodePoint(i):t}let n=xw[e];if(n===void 0)throw new _i(`Unknown XML entity: &${e};`);return n})}function cu(r){let t=0,e=0,n=r.charCodeAt(0)===65279?r.slice(1):r,i=c=>{throw new _i(`${c} at offset ${t}`)},s=()=>{for(;;){for(;t<n.length&&/\s/.test(n[t]??"");)t+=1;if(n.startsWith("<?",t)){let c=n.indexOf("?>",t);c<0&&i("Unterminated processing instruction"),t=c+2}else if(n.startsWith("<!--",t)){let c=n.indexOf("-->",t);c<0&&i("Unterminated comment"),t=c+3}else if(n.startsWith("<!DOCTYPE",t)||n.startsWith("<!doctype",t))i("Document type declarations are not accepted");else return}},a=()=>{let c=bw.exec(n.slice(t,t+256));return c===null?i("Expected a name"):(t+=c[0].length,c[0])},o=c=>{c>gw&&i("XML nests too deeply"),e+=1,e>ww&&i("XML has too many nodes"),n[t]!=="<"&&i("Expected an element"),t+=1;let l=a(),u={};for(;;){for(;/\s/.test(n[t]??"");)t+=1;if(n.startsWith("/>",t))return t+=2,{name:l,attributes:u,children:[]};if(n[t]===">"){t+=1;break}let g=a();for(;/\s/.test(n[t]??"");)t+=1;for(n[t]!=="="&&i(`Expected = after attribute ${g}`),t+=1;/\s/.test(n[t]??"");)t+=1;let m=n[t];if(m!=='"'&&m!=="'")return i("Expected a quoted attribute value");let y=n.indexOf(m,t+1);y<0&&i("Unterminated attribute value");let w=n.slice(t+1,y);w.includes("<")&&i("Attribute values must not contain <"),u[g]=du(w),t=y+1}let p=[],f="",h=()=>{f.length>0&&(p.push(f),e+=1,f="")};for(;;){if(t>=n.length&&i(`Unterminated element <${l}>`),n.startsWith("</",t)){t+=2;let y=a();for(y!==l&&i(`Expected </${l}> but found </${y}>`);/\s/.test(n[t]??"");)t+=1;return n[t]!==">"&&i("Expected >"),t+=1,h(),{name:l,attributes:u,children:p}}if(n.startsWith("<![CDATA[",t)){let y=n.indexOf("]]>",t);y<0&&i("Unterminated CDATA section"),f+=n.slice(t+9,y),t=y+3;continue}if(n.startsWith("<!--",t)){let y=n.indexOf("-->",t);y<0&&i("Unterminated comment"),t=y+3;continue}if(n.startsWith("<?",t)){let y=n.indexOf("?>",t);y<0&&i("Unterminated processing instruction"),t=y+2;continue}if(n[t]==="<"){h(),p.push(o(c+1));continue}let g=n.indexOf("<",t),m=g<0?n.length:g;f+=du(n.slice(t,m)),t=m}};s();let d=o(0);return s(),t<n.length&&i("Unexpected content after the root element"),d}function ot(r,t){return r.children.filter(e=>typeof e!="string"&&(t===void 0||e.name===t))}function ln(r){return r.children.map(t=>typeof t=="string"?t:ln(t)).join("")}var lu="1",un=class extends Error{constructor(){super("This JUnit report does not say which framework wrote it. Pass --framework cypress or --framework webdriverio."),this.name="JunitFrameworkUnknownError"}};function uu(r){let t=r.slice(0,4096).replace(/^/,"");return/^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<testsuites?\b/.test(t)}function Za(r){if(r.name==="testsuite")return[r];if(r.name!=="testsuites")throw new Error("A JUnit report's root must be testsuites.");let t=[],e=n=>{for(let i of ot(n,"testsuite"))t.push(i),e(i)};return e(r),t}function pu(r){let t=new Map;for(let e of ot(r,"properties"))for(let n of ot(e,"property")){let i=n.attributes.name;i!==void 0&&t.set(i,n.attributes.value??ln(n))}return t}function vw(r,t){let e=Za(r);if(e.some(n=>pu(n).has("capabilities")))return"webdriverio";if(e.some(n=>n.attributes.name==="Root Suite")||/webpack:\/\/|__cypress|CypressError/.test(t))return"cypress"}function fu(r){let t=Number.parseFloat(r??"");return Number.isFinite(t)&&t>=0?Math.round(t*1e3):0}function hu(r,t){let e=ot(r,"failure")[0]??ot(r,"error")[0]??void 0,n=ot(r,"system-err").map(i=>ln(i).trim()).filter(i=>i!=="").join(`
12
+ `);if(e!==void 0){let i=ln(e).trim(),s=i!==""?i:n!==""?n:void 0,a=e.attributes.message,o=at(s,t);return{status:"failed",errors:[{...a===void 0?{}:{message:a},...e.attributes.type===void 0?{}:{name:e.attributes.type},...s===void 0?{}:{stack:s},...o===void 0?{}:{location:o}}]}}if(ot(r,"skipped").length>0){if(n!==""){let i=at(n,t),s=n.split(`
13
+ `)[0]?.replace(/^\w*Error:\s*/,"");return{status:"failed",errors:[{...s===void 0?{}:{message:s},stack:n,...i===void 0?{}:{location:i}}]}}return{status:"skipped",errors:[]}}return{status:"passed",errors:[]}}function kw(r,t,e){if(e===""||r===e||!r.endsWith(` ${e}`))return[r];let n=r.slice(0,-(e.length+1));return t===""||t==="Root Suite"?[n,e]:n===t?[t,e]:n.endsWith(` ${t}`)?[n.slice(0,-(t.length+1)),t,e]:[n,e]}function mu(r,t,e,n){return{status:r,retry:e,duration:n,errors:t,attachments:[],stdout:[],stderr:[],steps:[]}}function Iw(r){let t=[],e="";for(let n of Za(r)){n.attributes.file!==void 0&&n.attributes.file!==""&&(e=n.attributes.file);let i=n.attributes.name??"";for(let s of ot(n,"testcase")){let a=s.attributes.name??"",o=s.attributes.classname??a,d=hu(s,e);t.push({file:e,titlePath:kw(a,i,o),projectId:"",attempts:[mu(d.status,d.errors,0,fu(s.attributes.time))]})}}return{framework:"cypress",format:"junit-xml",adapterVersion:lu,projects:[{id:"",name:""}].map(n=>({...n,retries:0})),tests:t,errors:[],interrupted:!1,warnings:["final-attempt-only"]}}function Pw(r){let t=[],e=new Set;for(let n of Za(r)){let i=pu(n),s=i.get("file")??n.attributes.file??"",a=(i.get("capabilities")??"").split(".")[0]??"";e.add(a);let o=i.get("suiteName")??n.attributes.name??"",d=new Map,c=[];for(let l of ot(n,"testcase")){let u=l.attributes.name??"",p=hu(l,s),f=d.get(u);f===void 0&&(f=[],d.set(u,f),c.push(u)),f.push(mu(p.status,p.errors,f.length,fu(l.attributes.time)))}for(let l of c)t.push({file:s,titlePath:o===""?[l]:[o,l],projectId:a,attempts:d.get(l)??[]})}return{framework:"webdriverio",format:"junit-xml",adapterVersion:lu,projects:[...e].map(n=>({id:n,name:n,retries:0})),tests:t,errors:[],interrupted:!1,warnings:[]}}function yu(r,t){let e=cu(r);switch(vw(e,r)??t.framework){case"cypress":return Iw(e);case"webdriverio":return Pw(e);default:throw new un}}import{dirname as Ew,isAbsolute as Cw,join as Nw}from"node:path";import{isAbsolute as ji,relative as Rw,sep as pn}from"node:path";var Fi="1970-01-01T00:00:00.000Z";function fn(r,t){switch(r){case"playwright":return t;case"cypress":return[t.filter(e=>e!=="").join(" ")];case"webdriverio":return t.filter(e=>e!=="").slice(-2)}}function gu(r,t,e,n,i){return $("tst",[t,e,n,...r==="playwright"?[]:[`framework:${r}`],...fn(r,i)])}function Bi(r,t){if(!ji(t))return;let e=Rw(r,t);if(!(ji(e)||e===".."||e.startsWith(`..${pn}`)))return e.split(pn).join("/")}function hn(r){let t=r.trim();return t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7)).replaceAll("\\","/"),/^\/[A-Za-z]:\//.test(t)&&(t=t.slice(1))),t.replaceAll("\\","/")}function wu(r,t,e){let n=hn(e),i=pn==="\\"?n.replaceAll("/","\\"):n;if(ji(i)||/^[A-Za-z]:\//.test(n))return Bi(r,i)??n;let s=n.replace(/^(?:\.\/)+/,"");if(t===void 0)return s;let a=Bi(r,t);return a===void 0||a===""?s:`${a}/${s}`}function to(r,t,e,n,i){let s=r.location===void 0?void 0:{...r.location,file:wu(n,i,r.location.file)};return{errorId:$("err",[t,e]),source:e,...r.message===void 0?{}:{message:r.message},...r.name===void 0?{}:{name:r.name},...r.stack===void 0?{}:{stack:r.stack},...r.snippet===void 0?{}:{snippet:r.snippet},...r.value===void 0?{}:{value:r.value},...s===void 0?{}:{location:s}}}function bu(r,t,e,n,i){return{title:r.title,duration:r.duration,...r.error===void 0?{}:{error:to(r.error,t,`${e}.error`,n,i)},steps:r.steps.map((s,a)=>bu(s,t,`${e}.steps[${a}]`,n,i))}}function Tw(r,t){let e=hn(t),n=pn==="\\"?e.replaceAll("/","\\"):e;return ji(n)||r===void 0?n:`${r}${pn}${n.replace(/^(?:\.[/\\])+/,"")}`}function Aw(r){let t=r.filter(n=>n.status!=="skipped");return t.length===0?"skipped":t.at(-1)?.status==="passed"?t.some(n=>n.status!=="passed")?"flaky":"expected":"unexpected"}function Sw(r,t,e){return r.length===0?"zero-tests":e||r.some(n=>n.attempts.some(i=>i.status==="interrupted"))?"interrupted":t.length>0?"report-errors":"analysis-ready"}function eo(r){if(r===void 0)return;let t=new Date(r);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function xu(r){let{report:t,reportHash:e,artifact:n,options:i}=r,s=i.workspaceRoot,a=new Set(r.warnings),o=t.projects.map(w=>{let x=w.testDir===void 0?void 0:Bi(s,w.testDir);return{projectId:$("prj",[`framework:${t.framework}`,w.id,w.name]),frameworkProjectId:w.id,name:w.name,repeatEach:1,retries:w.retries,...x===void 0?{}:{testDir:x}}}).sort((w,x)=>w.projectId.localeCompare(x.projectId)),d=new Map(o.map(w=>[w.frameworkProjectId,w.projectId])),c=new Set,l=[];t.tests.forEach((w,x)=>{let v=d.get(w.projectId);if(v===void 0)throw new Error(`Test ${x} references unknown project: ${w.projectId}`);let I=wu(s,t.rootDir,w.file),R=gu(t.framework,s,v,I,w.titlePath);if(c.has(R)){a.add(`duplicate-test-identity:${I}`);return}c.add(R);let E=`$tests[${x}]`,A=w.attempts.map((j,V)=>{let P=$("atm",[R,String(j.retry),"repeat:unknown",String(V)]),C=`${E}.attempts[${V}]`,M=j.errors.map((k,T)=>to(k,P,`${C}.errors[${T}]`,s,t.rootDir)),z=M.find(k=>k.location!==void 0)?.location;return{attemptId:P,sourceIndex:V,retry:j.retry,repeat:{state:"unknown",reason:"not-serialized-by-report"},status:j.status,duration:j.duration,startTime:eo(j.startTime)??eo(t.startTime)??Fi,workerIndex:0,parallelIndex:0,errors:M,stdout:j.stdout.map(k=>({kind:"text",text:k})),stderr:j.stderr.map(k=>({kind:"text",text:k})),steps:j.steps.map((k,T)=>bu(k,P,`${C}.steps[${T}]`,s,t.rootDir)),attachments:j.attachments.map((k,T)=>({attachmentId:$("att",[P,String(T)]),name:k.name,contentType:k.contentType,sourceIndex:T,...k.path===void 0?{}:{path:Tw(t.rootDir,k.path)}})),annotations:[],...z===void 0?{}:{errorLocation:z}}}),O=Aw(w.attempts);l.push({logicalTestId:R,projectId:v,title:w.titlePath.at(-1)??"",titlePath:w.titlePath,tags:[...w.tags??[]].sort(),location:{file:I,...w.line===void 0?{}:{line:w.line},...w.column===void 0?{}:{column:w.column}},timeout:w.timeout??0,expectedStatus:O==="skipped"?"skipped":"passed",status:O,annotations:[],attempts:A})}),l.sort((w,x)=>w.logicalTestId.localeCompare(x.logicalTestId));let u=t.errors.map((w,x)=>to(w,n.artifactId,`$errors[${x}]`,s,t.rootDir)),p=l.reduce((w,x)=>w+x.attempts.reduce((v,I)=>v+I.attachments.length,0),0),f=l.flatMap(w=>w.attempts.map(x=>x.startTime)).filter(w=>w!==Fi).sort()[0],h=eo(t.startTime)??f??Fi;h===Fi&&a.add("start-time-unavailable");let g={expected:0,unexpected:0,flaky:0,skipped:0};for(let w of l)g[w.status]+=1;let m=t.configFile===void 0?void 0:Bi(s,hn(t.configFile)),y=$("run",[e,s,i.gitRoot??"","1.2",`${t.format}:${t.adapterVersion}`]);return{schemaVersion:"1.2",runId:y,framework:t.framework,createdAt:h,workspace:{root:s,...i.gitRoot===void 0?{}:{gitRoot:i.gitRoot}},sourceHashes:{report:e},artifact:n,usability:Sw(l,u,t.interrupted),projects:o,...m===void 0?{}:{configFile:m},logicalTests:l,reportErrors:u,collections:{tests:l.length===0?"empty":"present",errors:u.length===0?"empty":"present",attachments:p===0?"empty":"present"},warnings:[...a].sort(),stats:{startTime:h,duration:t.duration??0,...g}}}var Ow="1",Dw=/\.(?:png|jpe?g|webp|gif|mp4|webm)$/i;function ku(r){if(typeof r!="object"||r===null||Array.isArray(r))return!1;let t=r;if(!Array.isArray(t.results)||typeof t.stats!="object")return!1;let e=t.results[0];return e===void 0||typeof e=="object"&&e!==null&&"uuid"in e&&Array.isArray(e.suites)&&Array.isArray(e.tests)}function Lw(r,t){let e=[],n=i=>{if(typeof i=="string"){let s;try{s=JSON.parse(i)}catch{s=void 0}if(s!==void 0&&typeof s!="string"){n(s);return}let a=typeof s=="string"?s:i;Dw.test(a)&&!/^https?:/i.test(a)&&e.push(a);return}if(Array.isArray(i)){for(let s of i)n(s);return}typeof i=="object"&&i!==null&&n(i.value)};return n(r),e.map(i=>{let s=hn(i);return Cw(s)||t===void 0?s:Nw(t,s)})}function Mw(r){let t=JSON.stringify(r.results??[]).slice(0,2e5);return/webpack:\/\/|__cypress|\bcy\.|Cypress/.test(t)?"cypress":/\bbrowser\.|\$\(|webdriverio|wdio/.test(t)?"webdriverio":"cypress"}function vu(r){return r.pending===!0||r.skipped===!0?"skipped":r.state==="passed"||r.pass===!0?"passed":r.timedOut===!0?"timedOut":r.state==="failed"||r.fail===!0?"failed":"skipped"}function $w(r,t,e){let n=r.err;if(typeof n!="object"||n===null)return[];let i=n,s=ue(i.message,`${t}.err.message`),a=ue(i.estack,`${t}.err.estack`),o=ue(i.diff??void 0,`${t}.err.diff`);if(s===void 0&&a===void 0)return[];let d=at(a,e);return[{...s===void 0?{}:{message:s},...a===void 0?{}:{stack:a},...o===void 0||o===""?{}:{value:o},...d===void 0?{}:{location:d}}]}function Iu(r,t){let e=Z(r,"$report"),n=Ut(e.results,"$report.results"),i=Z(e.stats,"$report.stats"),s=t.reportPath===void 0?void 0:Ew(t.reportPath),a=t.framework??Mw(e),o=[],d=[],c=(u,p,f,h)=>{let g=Z(u,p),m=typeof g.title=="string"?g.title:"",y=(typeof g.file=="string"&&g.file!==""?g.file:void 0)??(typeof g.fullFile=="string"&&g.fullFile!==""?g.fullFile:void 0)??h,w=m===""?f:[...f,m];X(g.tests??[],`${p}.tests`,(x,v)=>{let I=Z(x,v),R=H(I.title,`${v}.title`),E=$w(I,v,y);if(I.isHook===!0){vu(I)!=="passed"&&d.push(...E);return}let A=Lw(I.context,s).map(O=>({name:/\.(?:mp4|webm)$/i.test(O)?"video":"screenshot",contentType:/\.(?:mp4|webm)$/i.test(O)?"video/mp4":/\.png$/i.test(O)?"image/png":"image/jpeg",path:O}));o.push({file:y,titlePath:[...w,R],projectId:"",attempts:[{status:vu(I),retry:0,duration:typeof I.duration=="number"?I.duration:0,errors:E,attachments:A,stdout:[],stderr:[],steps:[]}]})}),X(g.suites??[],`${p}.suites`,(x,v)=>c(x,v,w,y))};n.forEach((u,p)=>{c(u,`$report.results[${p}]`,[],"")});let l=ue(i.start,"$report.stats.start");return{framework:a,format:"mochawesome-json",adapterVersion:Ow,...l===void 0?{}:{startTime:l},...typeof i.duration=="number"?{duration:ze(i.duration,"$report.stats.duration")}:{},projects:[{id:"",name:"",retries:0}],tests:o,errors:d,interrupted:!1,warnings:["final-attempt-only"]}}var _w="1";function Ru(r){if(typeof r!="object"||r===null||Array.isArray(r))return!1;let t=r;return Array.isArray(t.suites)&&Array.isArray(t.specs)&&typeof t.capabilities=="object"&&t.capabilities!==null}function Tu(r){if(typeof r!="object"||r===null)return"";let t=r;if(typeof t.browserName=="string")return t.browserName;let e=Object.values(t);return e.length>0&&e.every(n=>typeof n=="object"&&n!==null)?"multiremote":""}function Fw(r){switch(r){case"passed":return"passed";case"failed":return"failed";default:return"skipped"}}function Pu(r,t,e){if(typeof r!="object"||r===null)return;let n=Z(r,t),i=ue(n.message,`${t}.message`),s=ue(n.name,`${t}.name`),a=ue(n.stack,`${t}.stack`),o=at(a,e);return{...i===void 0?{}:{message:i},...s===void 0?{}:{name:s},...a===void 0?{}:{stack:a},...o===void 0?{}:{location:o}}}function Au(r){let t=Z(r,"$report"),e=X(t.specs,"$report.specs",H),n=[];e.length!==1&&n.push("ambiguous-spec-file");let i=e[0]??"",s=Tu(t.capabilities),a=t.capabilities,o=typeof a.browserVersion=="string"?a.browserVersion:void 0,d=[];return Ut(t.suites,"$report.suites").forEach((c,l)=>{let u=`$report.suites[${l}]`,p=Z(c,u),f=typeof p.name=="string"?p.name:"",h=new Map,g=[];X(p.tests??[],`${u}.tests`,(m,y)=>{let w=Z(m,y),x=H(w.name,`${y}.name`),v=Pu(w.error,`${y}.error`,i),I=h.get(x);I===void 0&&(I=[],h.set(x,I),g.push(x)),I.push({status:Fw(w.state),retry:I.length,...typeof w.start=="string"?{startTime:w.start}:{},duration:typeof w.duration=="number"?w.duration:0,errors:v===void 0?[]:[v],attachments:[],stdout:[],stderr:[],steps:[]})}),X(p.hooks??[],`${u}.hooks`,(m,y)=>{let w=Z(m,y);if(w.state!=="failed")return;let x=Pu(w.error,`${y}.error`,i),v=typeof w.title=="string"?w.title:"hook",I=typeof w.associatedTest=="string"&&w.associatedTest!==""?w.associatedTest:v,R={...x??{},message:`${v}: ${x?.message??"failed"}`},E=h.get(I),A=E?.at(-1);if(E!==void 0&&A!==void 0){A.status!=="failed"&&(E[E.length-1]={...A,status:"failed",errors:[R]});return}h.set(I,[{status:"failed",retry:0,...typeof w.start=="string"?{startTime:w.start}:{},duration:typeof w.duration=="number"?w.duration:0,errors:[R],attachments:[],stdout:[],stderr:[],steps:[]}]),g.push(I)});for(let m of g)d.push({file:i,titlePath:f===""?[m]:[f,m],projectId:s,attempts:h.get(m)??[]})}),{framework:"webdriverio",format:"wdio-json",adapterVersion:_w,...typeof t.start=="string"?{startTime:t.start}:{},...typeof t.start=="string"&&typeof t.end=="string"?{duration:Math.max(0,Date.parse(t.end)-Date.parse(t.start))||0}:{},projects:[{id:s,name:s,retries:0}],tests:d,errors:[],interrupted:!1,warnings:[...n,...o===void 0?[]:[`browser-version:${s}@${o}`]]}}var sp=Ii(Rn(),1);import{lstat as ix,readFile as sx,realpath as np}from"node:fs/promises";import{isAbsolute as ip,relative as ax,resolve as ox,sep as dx}from"node:path";var cx=2*1024*1024,lx=new Set(["it","test","specify","xit","fit","xtest","xspecify"]),ux=new Set(["describe","context","suite","xdescribe","fdescribe","xcontext"]),px=new Set(["only","skip","fixme","serial","parallel","fail","slow"]);function Tn(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof r.type=="string"}function fx(r){let t=[],e=r;for(;Tn(e)&&e.type==="MemberExpression";){let s=e.property;Tn(s)&&s.type==="Identifier"&&t.unshift(String(s.name)),e=e.object}if(!Tn(e)||e.type!=="Identifier")return;t.unshift(String(e.name));let i=t.filter(s=>!px.has(s)).at(-1);if(i!==void 0){if(ux.has(i))return"suite";if(lx.has(i))return"test"}}function hx(r){if(Tn(r)){if(r.type==="StringLiteral")return String(r.value);if(r.type==="TemplateLiteral"){let t=r.expressions,e=r.quasis;if(t.length===0&&e.length===1)return e[0]?.value.cooked}}}function mx(r,t){let e=[],n=/\.([cm]?[jt]sx?)$/i.exec(t)?.[1]?.toLowerCase()??"ts";n.includes("t")&&e.push("typescript"),(n.endsWith("x")||!n.includes("t"))&&e.push("jsx");let i;try{i=(0,sp.parse)(r,{sourceType:"unambiguous",errorRecovery:!0,plugins:e})}catch{return[]}let s=[],a=(o,d)=>{if(Array.isArray(o)){for(let c of o)a(c,d);return}if(Tn(o)){if(o.type==="CallExpression"){let c=fx(o.callee),l=o.arguments,u=hx(l[0]);if(c!==void 0&&u!==void 0){if(c==="test"){let p=o.loc;p!==void 0&&s.push({titlePath:[...d,u],line:p.start.line,column:p.start.column+1});return}for(let p of l.slice(1))a(p,[...d,u]);return}}for(let[c,l]of Object.entries(o))c==="loc"||c==="start"||c==="end"||c==="extra"||typeof l=="object"&&l!==null&&a(l,d)}};return a(i,[]),s}function yx(r,t){let e=ax(r,t);return e===""||!ip(e)&&e!==".."&&!e.startsWith(`..${dx}`)}async function gx(r,t){if(!(ip(t)||t.split("/").includes("..")))try{let e=await np(r),n=await np(ox(e,t));if(!yx(e,n))return;let i=await ix(n);return!i.isFile()||i.size>cx?void 0:await sx(n,"utf8")}catch{return}}function wx(r,t,e){let n=fn(r,t),i=fn(r,e);return n.length===i.length&&n.every((s,a)=>s===i[a])}async function jo(r){let t=r.logicalTests.filter(i=>i.location.line===void 0);if(t.length===0)return r;let e=new Map;for(let i of new Set(t.map(s=>s.location.file))){let s=await gx(r.workspace.root,i);e.set(i,s===void 0?[]:mx(s,i))}let n=r.logicalTests.map(i=>{if(i.location.line!==void 0)return i;let s=(e.get(i.location.file)??[]).filter(o=>wx(r.framework,o.titlePath,i.titlePath)),a=s.length===1?s[0]:void 0;return a===void 0?i:{...i,location:{...i.location,line:a.line,column:a.column}}});return{...r,logicalTests:n}}var Rx=2e3,ap=256*1024*1024,Tx=["kwikqa-json","playwright-json","mochawesome-json","wdio-json","junit-xml"],Ax=new TextDecoder("utf-8",{fatal:!0});function Sx(r){if(typeof r!="object"||r===null||Array.isArray(r))return!1;let t=r,e=t.config;return typeof e=="object"&&e!==null&&"version"in e&&Array.isArray(t.suites)}function Ex(r){if(r.bytes.byteLength===0)return{kind:"unreadable",diagnostic:{reasonCode:"empty-input",message:"The report is empty."}};let t;try{t=Ax.decode(r.bytes)}catch{return{kind:"unreadable",diagnostic:{reasonCode:"invalid-utf8",message:"The report is not valid UTF-8."}}}if(uu(t))return{kind:"classified",value:{file:r,format:"junit-xml",text:t}};let e;try{e=JSON.parse(t)}catch(i){return{kind:"unreadable",diagnostic:{reasonCode:"invalid-json",message:i instanceof Error?i.message:"The report is not valid JSON."}}}let n=iu(e)?"kwikqa-json":Sx(e)?"playwright-json":ku(e)?"mochawesome-json":Ru(e)?"wdio-json":void 0;return n===void 0?{kind:"unreadable",diagnostic:{reasonCode:"unsupported-report-format",message:"The JSON is not a report KwikQA reads: Playwright JSON, KwikQA's Cypress or WebdriverIO reporter, mochawesome, or @wdio/json-reporter."}}:{kind:"classified",value:{file:r,format:n,text:t,json:e}}}function Cx(r,t){switch(r.format){case"kwikqa-json":return au(r.json);case"mochawesome-json":return Iu(r.json,{...r.file.path===void 0?{}:{reportPath:r.file.path},...t.framework===void 0?{}:{framework:t.framework}});case"wdio-json":return Au(r.json);case"junit-xml":return yu(r.text,{...t.framework===void 0?{}:{framework:t.framework}});case"playwright-json":throw new Error("Playwright JSON is read by its own parser.")}}function et(r,t,e){let n=e.reasonCode==="missing-report"?"unavailable":"unreadable";return{kind:"unreadable",artifact:{artifactId:$("art",[r??n,t??"bytes"]),kind:"report",availability:n,...t===void 0?{}:{path:t},...r===void 0?{}:{sha256:r},warnings:[]},diagnostic:{...e,...t===void 0?{}:{path:t}}}}function Nx(r){if(r.length===1&&r[0]!==void 0)return Te(r[0].bytes);let t=r.map(e=>`${Ix(e.path??"")}\0${Te(e.bytes)}`).sort();return bx("sha256").update(t.join(`
14
+ `),"utf8").digest("hex")}function Xi(r,t){let e=t.reportPath;if(r.length===0)return et(void 0,e,{reasonCode:"missing-report",message:"No report files were found."});let n=Nx(r),i=[],s;for(let m of r){let y=Ex(m);y.kind==="classified"?i.push(y.value):s??=y.diagnostic}if(i.length===0)return et(n,e,s??{reasonCode:"unsupported-report-format",message:"No report was found."});let a=Tx.find(m=>i.some(y=>y.format===m)),o=i.filter(m=>m.format===a),d=i.length-o.length+(r.length-i.length),c=d>0?[`ignored-report-files:${d}`]:[];if(a==="playwright-json"){let m=o[0];return o.length!==1||m===void 0?et(n,e,{reasonCode:"invalid-report-shape",message:"Found several Playwright JSON reports; point --report at one, or merge them with `npx playwright merge-reports`."}):Ir(m.file.bytes,{...t,...m.file.path===void 0?{}:{reportPath:m.file.path}})}let l;try{l=ou(o.map(m=>Cx(m,t)))}catch(m){return et(n,e,{reasonCode:m instanceof un?"unsupported-report-format":"invalid-report-shape",message:m instanceof Error?m.message:"The report could not be read."})}let u=new Set(Ga[l.framework]),p=l.frameworkVersion,f=p!==void 0&&u.has(p),h=[...l.warnings,...c,p===void 0?"producer-version-unrecorded":f?void 0:`unverified-producer-version:${p}`].filter(m=>m!==void 0),g={artifactId:$("art",[n]),kind:"report",availability:"present",...e===void 0?{}:{path:e},sha256:n,format:l.format,...p===void 0?{}:{formatVersion:p},versionConfidence:f?"verified":"unverified",warnings:[...new Set(h)].sort()};try{return{kind:"parsed",run:xu({report:l,reportHash:n,artifact:g,options:t,warnings:h})}}catch(m){return et(n,e,{reasonCode:"invalid-report-shape",message:m instanceof Error?m.message:"The report could not be normalized."})}}async function Ox(r){return(await xx(r,{withFileTypes:!0})).filter(e=>e.isFile()&&/\.(?:json|xml|log)$/i.test(e.name)).map(e=>Px(r,e.name)).sort().slice(0,Rx)}async function tt(r,t){let e;try{e=await kx(r)}catch(o){let d=o.code==="ENOENT";return et(void 0,r,{reasonCode:d?"missing-report":"read-failed",message:d?`Test report does not exist: ${r}`:`Could not inspect: ${r}`})}let n;if(e.isDirectory()){try{n=await Ox(r)}catch{return et(void 0,r,{reasonCode:"read-failed",message:`Could not list report directory: ${r}`})}if(n.length===0)return et(void 0,r,{reasonCode:"missing-report",message:`No .json or .xml report files in ${r}`})}else if(e.isFile())n=[r];else return et(void 0,r,{reasonCode:"not-a-file",message:`Test report path is not a regular file or directory: ${r}`});let i=[],s=0;for(let o of n)try{let d=await vx(o);if(s+=d.byteLength,s>ap)return et(void 0,r,{reasonCode:"read-failed",message:`Report files under ${r} exceed ${ap} bytes.`});i.push({path:o,bytes:d})}catch{return et(void 0,r,{reasonCode:"read-failed",message:`Could not read test report: ${o}`})}let a=Xi(i,{...t,reportPath:r});return a.kind!=="parsed"||a.run.framework==="playwright"?a:{kind:"parsed",run:await jo(a.run)}}import{readFile as kI,realpath as II}from"node:fs/promises";import{createRequire as PI}from"node:module";import{delimiter as RI,dirname as Hf,isAbsolute as TI,join as rr}from"node:path";function Yi(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(Yi).join(",")}]`:`{${Object.entries(r).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${Yi(n)}`).join(",")}}`}function he(r,t,e,n,i){return $("evd",[r,t,e,Yi(n),i])}function we(r,t,e){return $("art",["m2",r,t,e])}function Cr(r){return Te(Buffer.from(Yi(r),"utf8"))}var Bo={policyVersion:"development-1",workspaceRoot:".",maxPacketBytes:256e3,maxArtifactBytes:16e6,maxTraceEntries:2e3,maxTraceEvents:2e3,maxReportFields:2e3,maxStackFrames:2e3,maxSteps:2e3,maxStdioChunks:2e3,maxStdioBytes:64e6,maxTraceExpandedBytes:64e6,maxConsoleEvents:100,maxNetworkEvents:200,includeNetworkBodies:!1,maxNetworkBodyBytes:0,maxDomDepth:6,maxDomNodes:200,maxDomTextBytes:16e3,maxSourceFiles:12,maxSourceBytes:128e3,maxSourceLinesPerFile:200,maxImportDepth:2,maxDiffBytes:128e3,maxDiffHunks:30,sensitiveNames:["authorization","cookie","set-cookie","password","passwd","secret","token","api-key","apikey"]},Dx=["maxPacketBytes","maxArtifactBytes","maxTraceEntries","maxTraceEvents","maxReportFields","maxStackFrames","maxSteps","maxStdioChunks","maxStdioBytes","maxTraceExpandedBytes","maxConsoleEvents","maxNetworkEvents","maxDomDepth","maxDomNodes","maxDomTextBytes","maxSourceFiles","maxSourceBytes","maxSourceLinesPerFile","maxImportDepth","maxDiffBytes","maxDiffHunks"];function Vo(r){if(r===null||typeof r!="object")return"policy must be an object";if(typeof r.policyVersion!="string")return"policyVersion must be a string";if(r.policyVersion.length===0)return"policyVersion must not be empty";if(typeof r.workspaceRoot!="string")return"workspaceRoot must be a string";if(r.workspaceRoot.length===0)return"workspaceRoot must not be empty";if(typeof r.includeNetworkBodies!="boolean")return"includeNetworkBodies must be a boolean";if(!Array.isArray(r.sensitiveNames)||r.sensitiveNames.some(t=>typeof t!="string"||t.length===0))return"sensitiveNames must be an array of non-empty strings";if(r.sensitiveNames.some(t=>t.trim()!==t))return"sensitiveNames must not contain surrounding whitespace";for(let t of Dx){let e=r[t];if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)return`${t} must be a positive safe integer`}if(!Number.isSafeInteger(r.maxNetworkBodyBytes)||r.maxNetworkBodyBytes<0||r.includeNetworkBodies&&r.maxNetworkBodyBytes===0)return"maxNetworkBodyBytes must be positive when network bodies are enabled"}var Lx={button:"button",nav:"navigation",main:"main",header:"banner",footer:"contentinfo",form:"form",table:"table",img:"img",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",ul:"list",ol:"list",li:"listitem",section:"region",article:"article",dialog:"dialog",select:"combobox",textarea:"textbox"},Mx={button:"button",submit:"button",reset:"button",checkbox:"checkbox",radio:"radio",range:"slider",text:"textbox",search:"searchbox",email:"textbox",tel:"textbox",url:"textbox",password:"textbox"},$x=new Set(["script","style","head","title","meta","link"]);function $e(r){let t=r[0];return typeof t=="string"?t.toLowerCase():void 0}function De(r){let t=r[1];if(typeof t!="object"||t===null||Array.isArray(t))return{};let e={};for(let[n,i]of Object.entries(t))typeof i=="string"&&(e[n.toLowerCase()]=i);return e}function Le(r){let t=typeof r[1]=="object"&&r[1]!==null&&!Array.isArray(r[1]);return r.slice(t?2:1)}function wt(r,t=0){let e=$e(r);if(e===void 0||$x.has(e)||t>12)return"";let n=[];for(let i of Le(r))typeof i=="string"?n.push(i):Array.isArray(i)&&n.push(wt(i,t+1));return n.join(" ").replace(/\s+/g," ").trim()}function Yt(r){let t=De(r),e=t.role;if(e!==void 0&&e.length>0)return e.toLowerCase();let n=$e(r);if(n!==void 0)return n==="a"?t.href===void 0?void 0:"link":n==="input"?Mx[(t.type??"text").toLowerCase()]:Lx[n]}function es(r){let t=De(r),e=t["aria-label"]??t.alt??t.title;return e!==void 0&&e.trim().length>0?e.trim():wt(r)}function op(r){return r.replace(/\s+/g," ").trim()}function Qi(r,t,e){let n=op(r),i=op(t);return e?n===i:n.toLowerCase().includes(i.toLowerCase())}var _x=new Set(["input","textarea","select"]);function cp(r){let t=[];for(let e of Le(r))if(typeof e=="string")t.push(e);else if(Array.isArray(e)){let n=$e(e);if(n!==void 0&&_x.has(n))continue;t.push(wt(e))}return t.join(" ").replace(/\s+/g," ").trim()}function Fx(r,t){let e,n=i=>{if(e===void 0){if($e(i)==="label"&&De(i).for===t){e=cp(i);return}for(let s of Le(i))Array.isArray(s)&&n(s)}};return n(r),e}function dp(r,t){let e=De(r),n=[];for(let s of["aria-label","placeholder","title"]){let a=e[s];a!==void 0&&a.trim().length>0&&n.push(a.trim())}for(let s=t.path.length-1;s>=0;s-=1){let a=up(t.root,t.path.slice(0,s));if(a===void 0)break;if($e(a)==="label"){n.push(cp(a));break}}let i=e.id;if(i!==void 0){let s=Fx(t.root,i);s!==void 0&&n.push(s)}return n}var jx=`"((?:[^"\\\\]|\\\\.)*)"|'((?:[^'\\\\]|\\\\.)*)'`;function Bx(r){return r.replace(/\\(.)/g,"$1")}function Zi(r){let t=new RegExp(`^(?:${jx})([is])?$`).exec(r.trim());if(t===null)return;let e=t[1]??t[2];if(e!==void 0)return{value:Bx(e),caseSensitive:t[3]!=="i"}}function Vx(r){let t=/^\[\s*([\w:-]+)\s*=\s*(.+?)\s*\]$/.exec(r.trim());if(t===null)return;let e=t[1]?.toLowerCase(),n=Zi(t[2]??"");if(!(e===void 0||n===void 0))return{describe:`[${e}]`,matches:i=>{let s=De(i)[e];return s!==void 0&&Qi(s,n.value,n.caseSensitive)}}}function zx(r,t){if(r==="role"){let e=/^([\w-]+)(?:\[(.*)\])?$/.exec(t.trim()),n=e?.[1]?.toLowerCase();if(n===void 0)return;let i=e?.[2];if(i===void 0||i.trim()==="")return{describe:`role=${n}`,matches:o=>Yt(o)===n};let s=/^name\s*=\s*(.+)$/.exec(i.trim()),a=s===null?void 0:Zi(s[1]??"");return a===void 0?void 0:{describe:`role=${n}[name]`,matches:(o,d)=>Yt(o)===n&&[es(o),...dp(o,d)].some(c=>Qi(c,a.value,a.caseSensitive))}}if(r==="label"){let e=Zi(t);return e===void 0?void 0:{describe:"label",matches:(n,i)=>dp(n,i).some(s=>Qi(s,e.value,e.caseSensitive))}}if(r==="text"){let e=Zi(t);if(e===void 0)return;let n=i=>Qi(wt(i),e.value,e.caseSensitive);return{describe:"text",matches:i=>n(i)&&!Le(i).some(s=>Array.isArray(s)&&n(s))}}if(r==="testid"||r==="attr")return Vx(t)}function Hx(r){let t=r.match(/^[A-Za-z][\w-]*|#[\w-]+|\.[\w-]+|\[[^\]]*\]/g);if(t===null||t.join("")!==r)return;let e=[];for(let n of t)if(n.startsWith("#")){let i=n.slice(1);e.push(s=>De(s).id===i)}else if(n.startsWith(".")){let i=n.slice(1);e.push(s=>(De(s).class??"").split(/\s+/).includes(i))}else if(n.startsWith("[")){let i=/^\[\s*([\w:-]+)\s*(?:=\s*["']?([^"'\]]*)["']?)?\s*\]$/.exec(n),s=i?.[1]?.toLowerCase();if(s===void 0)return;let a=i?.[2];e.push(o=>{let d=De(o)[s];return d===void 0?!1:a===void 0||a===""?!0:d===a})}else{let i=n.toLowerCase();e.push(s=>$e(s)===i)}return{describe:r,matches:n=>e.every(i=>i(n))}}function qx(r){let t=r.trim(),e=/^internal:([\w-]+)=([\s\S]+)$/.exec(t);if(e!==null)return zx(e[1]??"",e[2]??"");let n=/^role=([\w-]+)$/.exec(t);if(n!==null){let i=n[1]?.toLowerCase();return i===void 0?void 0:{describe:t,matches:s=>Yt(s)===i}}return Hx(t)}function Ux(r){let t=[],e="",n;for(let i=0;i<r.length;i+=1){let s=r[i];if(s!==void 0){if(n!==void 0){if(s==="\\"){e+=s+(r[i+1]??""),i+=1;continue}s===n&&(n=void 0),e+=s;continue}if(s==='"'||s==="'"){n=s,e+=s;continue}if(s===">"&&r[i+1]===">"){t.push(e),e="",i+=1;continue}e+=s}}return t.push(e),t.map(i=>i.trim()).filter(i=>i.length>0)}function Gx(r){if(/^(?:internal:|role=)/.test(r))return[r];let t=[],e="",n=0,i;for(let s of r){if(i!==void 0){s===i&&(i=void 0),e+=s;continue}if((s==='"'||s==="'")&&(i=s),(s==="["||s==="(")&&(n+=1),(s==="]"||s===")")&&(n=Math.max(0,n-1)),n===0&&(s===" "||s===">")){e.trim()!==""&&t.push(e.trim()),e="";continue}e+=s}return e.trim()!==""&&t.push(e.trim()),t.length===0?[r]:t}function lp(r,t){let e=[{node:r,path:t}];return Le(r).forEach((n,i)=>{Array.isArray(n)&&e.push(...lp(n,[...t,i]))}),e}function up(r,t){let e=r;for(let n of t){let i=Le(e)[n];if(!Array.isArray(i))return;e=i}return e}function An(r,t){if(!Array.isArray(r))return{kind:"unsupported",reason:"snapshot root is not an element"};let e=Ux(t).flatMap(Gx);if(e.length===0)return{kind:"unsupported",reason:"empty selector"};let n=[{node:r,path:[]}];for(let i of e){if(i===".."){let o=new Map;for(let d of n){if(d.path.length===0)continue;let c=d.path.slice(0,-1),l=up(r,c);l!==void 0&&o.set(c.join("."),{node:l,path:c})}n=[...o.values()];continue}let s=qx(i);if(s===void 0)return{kind:"unsupported",reason:i};let a=new Map;for(let o of n)for(let d of lp(o.node,o.path))s.matches(d.node,{root:r,path:d.path})&&a.set(d.path.join("."),d);if(n=[...a.values()],n.length===0)break}return{kind:"resolved",matches:n}}var Kx=/\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001B]*(?:\u0007|\u001B\\))/g;function ut(r){return r.replace(Kx,"")}function oe(r,t,e,n){let i=ut(r),s=[];for(let a of[...new Set(n.map(o=>o.toLowerCase()))].sort()){let o=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),d=new RegExp(`(["']?${o}["']?\\s*[:=]\\s*)(?:"[^"\\r\\n]*"|'[^'\\r\\n]*'|[^,;&}\\r\\n]*?(?=\\s+(?:and\\s+)?[A-Za-z_$][\\w$.-]*\\s*[:=]|\\s*$|[,;&}]))`,"gim"),c=0;if(i=i.replace(d,(l,u)=>(c+=1,`${u}[REDACTED]`)),c===0){let l=new RegExp(`(${o}\\s*[:=]\\s*)\\S+`,"gi");i=i.replace(l,(u,p)=>(c+=1,`${p}[REDACTED]`))}c>0&&s.push({redactionId:$("red",[t,e,a]),ruleId:`sensitive-name:${a}`,channel:t,locator:e,action:"mask",count:c})}return{value:i,records:s}}function Sn(r,t){let e=r.toLowerCase();return t.map(n=>n.toLowerCase()).sort().find(n=>e===n||e.includes(n))}function ts(r,t,e,n){let i=[],s=new Map;for(let o of r){let d=Sn(o.name,n);if(d===void 0){i.push(o);continue}s.set(d,(s.get(d)??0)+1)}let a=[...s.entries()].sort(([o],[d])=>o.localeCompare(d)).map(([o,d])=>({redactionId:$("red",[t,e,`header:${o}`]),ruleId:`sensitive-header:${o}`,channel:t,locator:e,action:"remove",count:d}));return{value:i,records:a}}function Ot(r,t,e,n){let i;try{i=new URL(r)}catch{return oe(r,t,e,n)}let s=[];(i.username!==""||i.password!=="")&&(i.username="",i.password="",s.push({redactionId:$("red",[t,e,"url-userinfo"]),ruleId:"url-userinfo",channel:t,locator:e,action:"remove",count:1}));let a=new Map;for(let o of[...i.searchParams.keys()]){let d=Sn(o,n);d!==void 0&&(i.searchParams.set(o,"[REDACTED]"),a.set(d,(a.get(d)??0)+1))}for(let[o,d]of[...a.entries()].sort(([c],[l])=>c.localeCompare(l)))s.push({redactionId:$("red",[t,e,`query:${o}`]),ruleId:`sensitive-query:${o}`,channel:t,locator:e,action:"mask",count:d});return{value:i.toString(),records:s}}var Wx=new Set(["value","data-value","content","__playwright_value_","__playwright_checked_","__playwright_selected_"]),pp=["type","name","id","autocomplete","placeholder","aria-label"];function zo(r,t,e,n){if(r==="")return{value:r,records:[]};let i=t.filter(s=>pp.includes(s.name.toLowerCase())).map(s=>Sn(s.value,n)).find(s=>s!==void 0);return i===void 0?{value:r,records:[]}:{value:"[REDACTED]",records:[{redactionId:$("red",["dom",e,`text:${i}`]),ruleId:`sensitive-element-text:${i}`,channel:"dom",locator:e,action:"mask",count:1}]}}function Ho(r,t,e){let n=r.filter(o=>pp.includes(o.name.toLowerCase())).map(o=>Sn(o.value,e)).find(o=>o!==void 0),i=[],s=new Map;for(let o of r){let d=Sn(o.name,e),c=n!==void 0&&Wx.has(o.name.toLowerCase())?n:void 0,l=d??c;if(l===void 0||o.value===""){i.push(o);continue}i.push({name:o.name,value:"[REDACTED]"});let u=d===void 0?`sensitive-element:${l}`:`sensitive-field:${l}`;s.set(u,(s.get(u)??0)+1)}let a=[...s.entries()].sort(([o],[d])=>o.localeCompare(d)).map(([o,d])=>({redactionId:$("red",["dom",t,o]),ruleId:o,channel:"dom",locator:t,action:"mask",count:d}));return{value:i,records:a}}function Jx(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function _(r){return typeof r=="string"?r:void 0}function ke(r){return typeof r=="number"&&Number.isFinite(r)?r:void 0}function fp(r){return typeof r=="boolean"?r:void 0}function fe(r){return Jx(r)?r:void 0}function He(r){return Array.isArray(r)?r:void 0}function _e(r){try{return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}function rs(r){let t=[];return r.split(/\r?\n/).forEach((e,n)=>{let i=e.trim();if(i.length!==0)try{t.push({line:n+1,value:JSON.parse(i),parsed:!0})}catch{t.push({line:n+1,value:void 0,parsed:!1})}}),t}function ge(r,t){let e;try{e=typeof r=="string"?r:JSON.stringify(r)??""}catch{return"[unserializable]"}let n=ut(e).replace(/\s+/g," ").trim(),i=Buffer.from(n,"utf8");if(i.byteLength<=t)return n;let s=t;for(;s>0&&((i[s]??0)&192)===128;)s-=1;return`${i.subarray(0,s).toString("utf8")}\u2026`}var mp=new Set(["script","style","noscript","template","head"]),hp=120,Xx=200,Yx={__playwright_value_:"value",__playwright_checked_:"checked",__playwright_selected_:"selected"},Qx=new Set(["button","link","textbox","searchbox","checkbox","radio","combobox","listbox","option","menuitem","tab","switch","slider","spinbutton","heading","dialog","img","cell","row"]),yp=["data-testid","data-test-id","data-test","data-qa","data-cy"],Zx=new Set(["internal","role","testid","data","name","text","label","attr","has","nth","visible","true","false","exact","css","xpath","and","the"]);function ev(r){let t=[];for(let[e,n]of Object.entries(De(r))){let i=Yx[e];if(i!==void 0){t.push({name:i,value:ge(n,hp)});continue}e.startsWith("__playwright")||/^on[a-z]+$/.test(e)||t.push({name:e,value:ge(n,hp)})}return t.sort((e,n)=>e.name.localeCompare(n.name))}function gp(r,t){let e,n=(i,s)=>{if(e===void 0){if(De(i).__playwright_target__===t){e={node:i,path:s};return}Le(i).forEach((a,o)=>{Array.isArray(a)&&n(a,[...s,o])})}};return n(r,[]),e}function tv(r){return Le(r).filter(t=>typeof t=="string").join(" ").replace(/\s+/g," ").trim()}function En(r,t,e){let n=[],i=[],s=0,a=0,o=!1,d=(c,l)=>{if(o)return;let u=$e(c);if(u===void 0||mp.has(u))return;if(l>e.maxDepth||a>=e.maxNodes){o=!0;return}let p=`${t}/${a}`,f=ev(c),h=Ho(f,p,e.sensitiveNames),g=zo(ge(tv(c),Xx),f,p,e.sensitiveNames);i.push(...h.records,...g.records);let m=h.value.map(x=>` ${x.name}="${x.value}"`).join(""),y=`${" ".repeat(l)}<${u}${m}>${g.value===""?"":` ${g.value}`}`,w=Buffer.byteLength(y,"utf8")+1;if(s+w>e.maxBytes){o=!0;return}n.push(y),s+=w,a+=1;for(let x of Le(c))Array.isArray(x)&&d(x,l+1)};return d(r,0),{text:n.join(`
15
+ `),redactions:i,nodes:a,truncated:o}}function Cn(r,t=[],e){let n=De(r),i=Yt(r),s=es(r),a=ge(s===""&&e!==void 0?e:s,80),o=[i===void 0?`<${$e(r)??"?"}>`:i];a!==""&&o.push(JSON.stringify(a));for(let c of[...new Set([...t,...yp,"id","name"])]){let l=n[c];l!==void 0&&l!==""&&o.push(`${c}=${ge(l,60)}`)}let d=n.placeholder;return d!==void 0&&d!==""&&o.push(`placeholder=${JSON.stringify(ge(d,60))}`),o.join(" ")}function Nr(r){let t=r.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(e=>e.length>=3&&!Zx.has(e));return[...new Set(t)]}function rv(r){return/(?:^|>>\s*)(?:internal:)?role=([\w-]+)/.exec(r)?.[1]?.toLowerCase()}function nv(r){return[...r.matchAll(/\[\s*([\w:-]+)\s*=/g)].map(t=>t[1]?.toLowerCase()).filter(t=>t!==void 0&&t!=="name")}function ns(r,t,e,n,i,s){let a=Nr(t),o=rv(t),d=nv(t),c=new Set(e.map(v=>v.path.join("."))),l=[],u=0,p=new Map,f=v=>{if($e(v)==="label"){let I=De(v).for;I!==void 0&&p.set(I,wt(v))}for(let I of Le(v))Array.isArray(I)&&f(I)};f(r);let h=(v,I,R)=>{let E=$e(v);if(E===void 0||mp.has(E))return;let A=De(v),O=(A.id===void 0?void 0:p.get(A.id))??R,j=Yt(v),V=d.some(C=>A[C]!==void 0)||yp.some(C=>A[C]!==void 0);if(j!==void 0&&Qx.has(j)||V){let C=Cn(v,d,O),M=`${C} ${ge(wt(v),200)}`.toLowerCase(),z=c.has(I.join(".")),k=(z?100:0)+(o!==void 0&&j===o?2:0)+a.filter(T=>M.includes(T)).length*3;l.push({line:`${z?"match: ":""}${C}`,score:k,order:u++})}let P=E==="label"?wt(v):R;Le(v).forEach((C,M)=>{Array.isArray(C)&&h(C,[...I,M],P)})};h(r,[],void 0);let g=[...l].sort((v,I)=>I.score-v.score||v.order-I.order),m=[],y=[],w=0,x=g.length>i.maxItems;for(let v of g.slice(0,i.maxItems)){let I=oe(v.line,"dom",n,s),R=Buffer.byteLength(I.value,"utf8")+1;if(w+R>i.maxBytes){x=!0;break}y.push(...I.records),m.push(I.value),w+=R}return{text:m.join(`
16
+ `),redactions:y,nodes:m.length,truncated:x}}import{open as ov}from"node:fs/promises";import{realpath as wp,stat as iv}from"node:fs/promises";import{isAbsolute as vp,relative as sv,resolve as av,sep as bp}from"node:path";function xp(r,t){let e=sv(r,t);if(e==="")return"";if(!(e===".."||e.startsWith(`..${bp}`)||vp(e)))return e.split(bp).join("/")}async function Nn(r,t){if(t.includes("\0"))return{kind:"unauthorized",message:"Path contains a NUL byte."};let e;try{e=await wp(r)}catch{return{kind:"unreadable",message:"Authorized root could not be resolved."}}let n=vp(t)?t:av(e,t);if(xp(e,n)===void 0)return{kind:"unauthorized",message:"Path escapes the authorized root."};let i;try{i=await wp(n)}catch(a){return a.code==="ENOENT"?{kind:"unavailable",message:"Authorized artifact does not exist."}:{kind:"unreadable",message:"Authorized artifact could not be resolved."}}let s=xp(e,i);if(s===void 0)return{kind:"unauthorized",message:"Resolved path escapes the authorized root."};try{if(!(await iv(i)).isFile())return{kind:"unreadable",message:"Authorized artifact is not a regular file."}}catch{return{kind:"unreadable",message:"Authorized artifact could not be inspected."}}return{kind:"authorized",absolutePath:i,relativePath:s}}function qo(r){return r.length===0||r.includes("\0")||r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/.test(r)?!1:r.split("/").every(e=>e!==".."&&e!==".")}async function W(r,t,e){let n=await Nn(r,t);if(n.kind!=="authorized")return n;let i;try{i=await ov(n.absolutePath,"r");let s=await i.stat();if(s.size>e)return{kind:"over-budget",message:`Artifact exceeds the ${e}-byte limit.`,relativePath:n.relativePath};let a=new Uint8Array(s.size),o=0;for(;o<a.byteLength;){let d=await i.read(a,o,a.byteLength-o,o);if(d.bytesRead===0)break;o+=d.bytesRead}return o!==a.byteLength?{kind:"unreadable",message:"Artifact changed or ended while it was being read.",relativePath:n.relativePath}:{kind:"read",bytes:a,sha256:Te(a),relativePath:n.relativePath}}catch{return{kind:"unreadable",message:"Authorized artifact could not be read.",relativePath:n.relativePath}}finally{await i?.close()}}import{createRequire as dv}from"module";var cv=dv("/"),Mr,lv,uv;try{Mr=cv("worker_threads"),lv=Mr.Worker,uv=Mr.isMarkedAsUntransferable}catch{}var Ee=Uint8Array,Or=Uint16Array,pv=Int32Array,kp=new Ee([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ip=new Ee([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),fv=new Ee([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Pp=function(r,t){for(var e=new Or(31),n=0;n<31;++n)e[n]=t+=1<<r[n-1];for(var i=new pv(e[30]),n=1;n<30;++n)for(var s=e[n];s<e[n+1];++s)i[s]=s-e[n]<<5|n;return{b:e,r:i}},Mr=Pp(kp,2),Rp=Mr.b,hv=Mr.r;Rp[28]=258,hv[258]=28;var Tp=Pp(Ip,0),mv=Tp.b,r1=Tp.r,Wo=new Or(32768);for(ne=0;ne<32768;++ne)bt=(ne&43690)>>1|(ne&21845)<<1,bt=(bt&52428)>>2|(bt&13107)<<2,bt=(bt&61680)>>4|(bt&3855)<<4,Wo[ne]=((bt&65280)>>8|(bt&255)<<8)>>1;var bt,ne,Dn=(function(r,t,e){for(var n=r.length,i=0,s=new Or(t);i<n;++i)r[i]&&++s[r[i]-1];var a=new Or(t);for(i=1;i<t;++i)a[i]=a[i-1]+s[i-1]<<1;var o;if(e){o=new Or(1<<t);var d=15-t;for(i=0;i<n;++i)if(r[i])for(var c=i<<4|r[i],l=t-r[i],u=a[r[i]-1]++<<l,p=u|(1<<l)-1;u<=p;++u)o[Wo[u]>>d]=c}else for(o=new Or(n),i=0;i<n;++i)r[i]&&(o[i]=Wo[a[r[i]-1]++]>>15-r[i]);return o}),Mn=new Ee(288);for(ne=0;ne<144;++ne)Mn[ne]=8;var ne;for(ne=144;ne<256;++ne)Mn[ne]=9;var ne;for(ne=256;ne<280;++ne)Mn[ne]=7;var ne;for(ne=280;ne<288;++ne)Mn[ne]=8;var ne,Ap=new Ee(32);for(ne=0;ne<32;++ne)Ap[ne]=5;var ne;var yv=Dn(Mn,9,1);var gv=Dn(Ap,5,1),Uo=function(r){for(var t=r[0],e=1;e<r.length;++e)r[e]>t&&(t=r[e]);return t},rt=function(r,t,e){var n=t/8|0;return(r[n]|r[n+1]<<8)>>(t&7)&e},Go=function(r,t){var e=t/8|0;return(r[e]|r[e+1]<<8|r[e+2]<<16)>>(t&7)},wv=function(r){return(r+7)/8|0},Ln=function(r,t,e){return(t==null||t<0)&&(t=0),(e==null||e>r.length)&&(e=r.length),new Ee(r.subarray(t,e))};var bv=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ie=function(r,t,e){var n=new Error(t||bv[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,Ie),!e)throw n;return n},xv=function(r,t,e,n){var i=r.length,s=n?n.length:0;if(!i||t.f&&!t.l)return e||new Ee(0);var a=!e,o=a||t.i!=2,d=t.i;a&&(e=new Ee(i*3));var c=function(on){var dn=e.length;if(on>dn){var cn=new Ee(Math.max(dn*2,on));cn.set(e),e=cn}},l=t.f||0,u=t.p||0,p=t.b||0,f=t.l,h=t.d,g=t.m,m=t.n,y=i*8;do{if(!f){l=rt(r,u,1);var w=rt(r,u+1,3);if(u+=3,w)if(w==1)f=yv,h=gv,g=9,m=5;else if(w==2){var R=rt(r,u,31)+257,E=rt(r,u+10,15)+4,A=R+rt(r,u+5,31)+1;u+=14;for(var O=new Ee(A),j=new Ee(19),V=0;V<E;++V)j[fv[V]]=rt(r,u+V*3,7);u+=E*3;for(var P=Uo(j),C=(1<<P)-1,M=Dn(j,P,1),V=0;V<A;){var z=M[rt(r,u,C)];u+=z&15;var x=z>>4;if(x<16)O[V++]=x;else{var k=0,T=0;for(x==16?(T=3+rt(r,u,3),u+=2,k=O[V-1]):x==17?(T=3+rt(r,u,7),u+=3):x==18&&(T=11+rt(r,u,127),u+=7);T--;)O[V++]=k}}var L=O.subarray(0,R),q=O.subarray(R);g=Uo(L),m=Uo(q),f=Dn(L,g,1),h=Dn(q,m,1)}else Ie(1);else{var x=wv(u)+4,v=r[x-4]|r[x-3]<<8,I=x+v;if(I>i){d&&Ie(0);break}o&&c(p+v),e.set(r.subarray(x,I),p),t.b=p+=v,t.p=u=I*8,t.f=l;continue}if(u>y){d&&Ie(0);break}}o&&c(p+131072);for(var Q=(1<<g)-1,ie=(1<<m)-1,de=u;;de=u){var k=f[Go(r,u)&Q],K=k>>4;if(u+=k&15,u>y){d&&Ie(0);break}if(k||Ie(2),K<256)e[p++]=K;else if(K==256){de=u,f=null;break}else{var ve=K-254;if(K>264){var V=K-257,Re=kp[V];ve=rt(r,u,(1<<Re)-1)+Rp[V],u+=Re}var mt=h[Go(r,u)&ie],St=mt>>4;mt||Ie(3),u+=mt&15;var q=mv[St];if(St>3){var Re=Ip[St];q+=Go(r,u)&(1<<Re)-1,u+=Re}if(u>y){d&&Ie(0);break}o&&c(p+131072);var sn=p+ve;if(p<q){var an=s-q,ki=Math.min(q,sn);for(an+p<0&&Ie(3);p<ki;++p)e[p]=n[an+p]}for(;p<sn;++p)e[p]=e[p-q]}}t.l=f,t.p=de,t.b=p,t.f=l,f&&(l=1,t.m=g,t.d=h,t.n=m)}while(!l);return p!=e.length&&a?Ln(e,0,p):e.subarray(0,p)};var On=new Ee(0);var Dr=function(r,t){return r[t]|r[t+1]<<8},Lr=function(r,t){return(r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24)>>>0},Ko=function(r,t){return Lr(r,t)+Lr(r,t+4)*4294967296};var vv=(function(){function r(t,e){typeof t=="function"&&(e=t,t={}),this.ondata=e;var n=t&&t.dictionary&&t.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new Ee(32768),this.p=new Ee(0),n&&this.o.set(n)}return r.prototype.e=function(t){if(this.ondata||Ie(5),this.d&&Ie(4),!this.p.length)this.p=t;else if(t.length){var e=new Ee(this.p.length+t.length);e.set(this.p),e.set(t,this.p.length),this.p=e}},r.prototype.c=function(t){this.s.i=+(this.d=t||!1);var e=this.s.b,n=xv(this.p,this.s,this.o);this.ondata(Ln(n,e,this.s.b),this.d),this.o=Ln(n,this.s.b-32768),this.s.b=this.o.length,this.p=Ln(this.p,this.s.p/8|0),this.s.p&=7},r.prototype.push=function(t,e){this.e(t),this.c(e)},r})();var Jo=typeof TextDecoder<"u"&&new TextDecoder,kv=0;try{Jo.decode(On,{stream:!0}),kv=1}catch{}var Iv=function(r){for(var t="",e=0;;){var n=r[e++],i=(n>127)+(n>223)+(n>239);if(e+i>r.length)return{s:t,r:Ln(r,e-1)};i?i==3?(n=((n&15)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,t+=String.fromCharCode(55296|n>>10,56320|n&1023)):i&1?t+=String.fromCharCode((n&31)<<6|r[e++]&63):t+=String.fromCharCode((n&15)<<12|(r[e++]&63)<<6|r[e++]&63):t+=String.fromCharCode(n)}};function Pv(r,t){if(t){for(var e="",n=0;n<r.length;n+=16384)e+=String.fromCharCode.apply(null,r.subarray(n,n+16384));return e}else{if(Jo)return Jo.decode(r);var i=Iv(r),s=i.s,e=i.r;return e.length&&Ie(8),s}}var Rv=function(r,t,e,n,i,s,a){var o=i==4294967295,d=s==4294967295,c=a==4294967295,l=t+e,u=o+d+c;if(n&&u){for(;t+4<l;t+=4+Dr(r,t+2))if(Dr(r,t)==1)return[o?Ko(r,t+4+8*d):i,d?Ko(r,t+4):s,c?Ko(r,t+4+8*(d+o)):a,1];n<2&&Ie(13)}return[i,s,a,0]};var Tv=(function(){function r(){}return r.prototype.push=function(t,e){this.ondata(null,t,e)},r.compression=0,r})();var Sp=(function(){function r(){var t=this;this.i=new vv(function(e,n){t.ondata(null,e,n)})}return r.prototype.push=function(t,e){try{this.i.push(t,e)}catch(n){this.ondata(n,null,e)}},r.compression=8,r})();var Ep=(function(){function r(t){this.onfile=t,this.k=[],this.o={0:Tv},this.p=On}return r.prototype.push=function(t,e){var n=this;if(this.onfile||Ie(5),this.p||Ie(4),this.c>0){var i=Math.min(this.c,t.length),s=t.subarray(0,i);if(this.c-=i,this.d?this.d.push(s,!this.c):this.k[0].push(s),t=t.subarray(i),t.length)return this.push(t,e)}else{var a=0,o=0,d=void 0,c=void 0;this.p.length?t.length?(c=new Ee(this.p.length+t.length),c.set(this.p),c.set(t,this.p.length)):c=this.p:c=t;for(var l=c.length,u=this.c,p=u&&this.d,f=function(){var y=Lr(c,o);if(y==67324752){a=1,d=o,h.d=null,h.c=0;var w=Dr(c,o+6),x=Dr(c,o+8),v=w&2048,I=w&8,R=Dr(c,o+26),E=Dr(c,o+28);if(l>o+30+R+E){var A=[];h.k.unshift(A),a=2;var O=Lr(c,o+18),j=Lr(c,o+22),V=Pv(c.subarray(o+30,o+=30+R),!v),P=Rv(c,o,E,2,O,j,0),C=P[0],M=P[1],z=P[3];I&&(C=-1-z),o+=E,h.c=C;var k,T={name:V,compression:x,start:function(){if(T.ondata||Ie(5),!C)T.ondata(null,On,!0);else{var L=n.o[x];L||T.ondata(Ie(14,"unknown compression type "+x,1),null,!1),k=C<0?new L(V):new L(V,C,M),k.ondata=function(de,K,ve){T.ondata(de,K,ve)};for(var q=0,Q=A;q<Q.length;q++){var ie=Q[q];k.push(ie,!1)}n.k[0]==A&&n.c?n.d=k:k.push(On,!0)}},terminate:function(){k&&k.terminate&&k.terminate()}};C>=0&&(T.size=C,T.originalSize=M),h.onfile(T)}return"break"}else if(u){if(y==134695760)return d=o+=12+(u==-2&&8),a=3,h.c=0,"break";if(y==33639248)return d=o-=4,a=3,h.c=0,"break"}},h=this;o<l-4;++o){var g=f();if(g==="break")break}if(this.p=On,u<0){var m=a?c.subarray(0,d-12-(u==-2&&8)-(Lr(c,d-16)==134695760&&4)):c.subarray(0,o);p?p.push(m,!!a):this.k[+(a==2)].push(m)}if(a&2)return this.push(c.subarray(o),e);this.p=c.subarray(o)}e&&(this.c&&Ie(13),this.p=null)},r.prototype.register=function(t){this.o[t.compression]=t},r})();var Cp=65536;function Av(r,t){let e=new Uint8Array(t),n=0;for(let i of r)e.set(i,n),n+=i.length;return e}function is(r,t,e){if(r.byteLength===0)return{kind:"unreadable",message:"Archive is empty."};if(r[0]!==80||r[1]!==75)return{kind:"unreadable",message:"Archive does not begin with a ZIP signature."};let n=new Map,i=[],s=0,a=0,o,d=new Set,c=new Ep;c.register(Sp),c.onfile=l=>{let u=l.name,p=typeof l.originalSize=="number"&&l.originalSize>0,f=l.originalSize??0;if(!qo(u)){i.push({entry:u,reason:"unsafe-entry-name",declaredBytes:f});return}if(!e(u))return;if(d.has(u)){i.push({entry:u,reason:"duplicate-selected-name",declaredBytes:f});return}if(s>=t.maxEntries){i.push({entry:u,reason:"entry-budget-exceeded",declaredBytes:f});return}let h=t.maxExpandedBytes-a;if(p&&f>h){i.push({entry:u,reason:"expanded-budget-exceeded",declaredBytes:f});return}s+=1,d.add(u);let g=[],m=0,y=!1;l.ondata=(w,x,v)=>{if(o!==void 0||y)return;if(w!==null){o=`Archive entry ${u} could not be inflated.`;return}m+=x.length;let I=p&&m>f;if(I||m>h){y=!0,g.length=0,i.push({entry:u,reason:I?"declared-size-mismatch":"expanded-budget-exceeded",declaredBytes:f});return}if(g.push(x.slice()),v){if(p&&m!==f){g.length=0,y=!0,i.push({entry:u,reason:"declared-size-mismatch",declaredBytes:f});return}a+=m,n.set(u,Av(g,m))}},l.start()};try{for(let l=0;l<r.byteLength;l+=Cp){let u=Math.min(l+Cp,r.byteLength);if(c.push(r.subarray(l,u),u===r.byteLength),o!==void 0)break}}catch{return{kind:"unreadable",message:"Archive could not be read as a ZIP container."}}return o!==void 0?{kind:"unreadable",message:o}:{kind:"read",contents:{entries:n,skipped:i}}}var Np=256,Op={before:"before",action:"action",input:"action",after:"after"};function Xo(r){return Array.isArray(r)&&typeof r[0]=="string"}function Sv(r){return Array.isArray(r)&&Array.isArray(r[0])&&typeof r[0][0]=="number"&&typeof r[0][1]=="number"}function Dp(r){let t=r[1],e=typeof t=="object"&&t!==null&&!Array.isArray(t);return r.slice(e?2:1)}function Ev(r){let t=_(r.snapshotName),e=_(r.callId),n=Op[_(r.phase)??""];if(t!==void 0){let i=t.indexOf("@");i>0&&(n??=Op[t.slice(0,i)],e??=t.slice(i+1))}return{...e===void 0?{}:{callId:e},...n===void 0?{}:{phase:n},...t===void 0?{}:{name:t}}}var ss=class{frames=new Map;literals=new Map;byCall=new Map;add(t,e,n){let i=fe(n.snapshot);if(i===void 0||i.html===void 0)return;let s=Ev(i),a=_(i.frameId)??_(i.pageId)??"unknown-frame",o=`${t}
17
+ ${a}`,d=this.frames.get(o)??[],c=_(i.frameUrl),l={entry:t,line:e,frameId:a,index:d.length,snapshotId:s.name??(s.callId===void 0?`${t}#line=${e}`:`${s.phase??"snapshot"}@${s.callId}`),...s.callId===void 0?{}:{callId:s.callId},...s.phase===void 0?{}:{phase:s.phase},...c===void 0?{}:{frameUrl:c},isMainFrame:fp(i.isMainFrame)??!0,html:i.html};if(d.push(l),this.frames.set(o,d),l.callId!==void 0){let u=this.byCall.get(l.callId)??[];u.push(l),this.byCall.set(l.callId,u)}return l}forCall(t){return this.byCall.get(t)??[]}get size(){let t=0;for(let e of this.frames.values())t+=e.length;return t}literalNodes(t){let e=this.literals.get(t);if(e!==void 0)return e;let n=[],i=(s,a)=>{if(typeof s=="string"){n.push(s);return}if(!(!Xo(s)||a>Np)){for(let o of Dp(s))i(o,a+1);n.push(s)}};return i(t.html,0),this.literals.set(t,n),n}rebuild(t,e){let n=this.frames.get(`${t.entry}
18
+ ${t.frameId}`)??[],i=0,s=!1,a=(d,c,l)=>{if(i>=e||l>Np){s=!0;return}if(typeof d=="string")return i+=1,d;if(Sv(d)){let[h,g]=d[0],m=c-h,y=n[m];if(h<1||y===void 0)return;let w=this.literalNodes(y)[g];return w===void 0?void 0:a(w,m,l)}if(!Xo(d))return;i+=1;let u=d[1],p=typeof u=="object"&&u!==null&&!Array.isArray(u)?u:{},f=[];for(let h of Dp(d)){let g=a(h,c,l+1);g!==void 0&&f.push(g)}return[d[0],p,...f]},o=a(t.html,t.index,0);return{...Xo(o)?{root:o}:{},truncated:s,nodes:i}}};var Qt=["trace","console","network","dom","accessibility"],Yo=/(?:^|\/)(?:\d+-)?(?:trace|test)\.trace$/,as=/(?:^|\/)(?:\d+-)?trace\.network$/,Qo=/(?:^|\/)(?:\d+-)?trace\.stacks$/,Zt=512,td=2e3,Fp=200,Cv=2,Zo=5e4,ed=25,Nv=new Set(["screencast-frame","object","resource","input"]),ee={failure:5,failedCall:4,significant:3,context:2,ordinary:1,afterFailure:0};function Ov(r,t){switch(t){case"console":return r.maxConsoleEvents;case"network":return r.maxNetworkEvents;case"dom":case"accessibility":return r.maxDomNodes;default:return r.maxTraceEvents}}function se(r,t,e,n,i,s){r.omissions.push({omissionId:$("omi",[r.input.attemptId,t,e,i??"",n]),channel:t,reason:e,message:n,...i===void 0?{}:{locator:i},...s===void 0?{}:{cap:s}})}function os(r,t,e,n,i,s,a){let o=r.channels[t].artifact,d=he(r.runId,o.artifactId,e,n,i);r.evidence.push({evidenceId:d,kind:e,artifactId:o.artifactId,logicalTestId:r.input.logicalTestId,attemptId:r.input.attemptId,locator:n,observation:i,availability:i.length===0?"empty":"present",redactionIds:s.map(c=>c.redactionId)}),r.redactions.push(...s),r.priorities.set(d,a),r.channels[t].included+=1}function $n(r,t,e,n){let i=oe(n,t,e,r.policy.sensitiveNames);return{value:i.value,records:i.records}}function Lp(r){let t=He(r);if(t===void 0)return[];let e=[];for(let n of t){let i=fe(n),s=_(i?.name);s!==void 0&&e.push({name:s,value:_(i?.value)??""})}return e}function Dv(r){let t=_(r.type);if(t==="console")return{type:_(r.messageType)??"log",text:_(r.text)??ge(r.args,td)};if(t!=="event"||!(_(r.class)==="ConsoleMessage"||_(r.method)==="console"))return;let n=fe(r.params);return{type:_(n?.type)??_(n?.messageType)??"log",text:_(n?.text)??ge(n,td)}}function _n(r){let t=fe(r.error);return _(t?.message)??_(fe(t?.error)?.message)}function jp(r){return r===void 0?"unknown":_(r.apiName)??([_(r.class),_(r.method)].filter(Boolean).join(".")||"unknown")}function Lv(r){let t=fe(r?.params);return _(t?.selector)}function Mv(r,t){let e=_(r.type),n=jp(e==="after"?t??r:r),i=_(r.title),s=r.params===void 0?"":` params=${ge(r.params,Zt)}`,a=_n(r),o=a===void 0?"":` error=${ge(a,Zt)}`;switch(e){case"before":return`action started: ${n}${i===void 0?"":` "${ge(i,120)}"`}${s}`;case"after":return`action finished: ${n}${o}`;case"action":return`action: ${n}${s}${o}`;case"log":return`log: ${ge(r.message,Zt)}`;case"error":return`error: ${ge(r.message,Zt)}`;case"stdout":case"stderr":return`${e}: ${ge(r.text,Zt)}`;case"context-options":return`context options: ${ge({browserName:_(r.browserName),platform:_(r.platform),playwrightVersion:_(r.playwrightVersion),sdkLanguage:_(r.sdkLanguage)},Zt)}`;case"event":return`event: ${n}${s}`;default:return}}function $v(r){return ke(r.startTime)??ke(r.endTime)??ke(r.time)}function _v(r,t,e){let n=_e(e);if(n===void 0){r.channels.trace.failed=!0,se(r,"trace","unreadable",`${t} is not valid UTF-8.`,t);return}let i=rs(n);i.length===0&&(r.channels.trace.parsed=!0);let s=new Set;for(let a of i){let o=`${t}#line=${a.line}`;if(!a.parsed){r.channels.trace.failed=!0,se(r,"trace","parse-failed",`${o} is not valid JSON.`,o);continue}let d=fe(a.value),c=_(d?.type);if(d===void 0||c===void 0){r.channels.trace.failed=!0,se(r,"trace","unrecognized",`${o} is not a typed trace event.`,o);continue}if(r.channels.trace.parsed=!0,c==="frame-snapshot"){r.snapshots.add(t,a.line,d)===void 0&&se(r,"dom","unrecognized",`${o} does not carry a readable frame snapshot.`,o);continue}if(c==="resource-snapshot"){Vp(r,t,a.line,d,new Map);continue}let l=$v(d);if(c==="error"){l!==void 0&&r.errorTimes.push(l);for(let y of He(d.stack)??[]){if(r.seeds.length>=Fp)break;let w=fe(y),x=_(w?.file),v=ke(w?.line);if(x===void 0||v===void 0)continue;let I=ke(w?.column);r.seeds.push({file:x,line:v,...I===void 0?{}:{column:I},origin:`${t}#line=${a.line}:error`,logicalTestId:r.input.logicalTestId,attemptId:r.input.attemptId})}}let u=Dv(d);if(u!==void 0){let y=$n(r,"console",o,`console.${u.type}: ${ge(u.text,td)}`);r.candidates.push({channel:"console",kind:"console-event",locator:{type:"trace-event",entry:t,line:a.line,eventType:"console",...l===void 0?{}:{timestamp:l}},locatorText:o,observation:y.value,redactions:y.records,order:r.candidates.length,...l===void 0?{}:{time:l},error:u.type==="error"||u.type==="warning"});continue}if(Nv.has(c))continue;let p=_(d.callId),f=p===void 0?void 0:`${t}
19
+ ${p}`;if(f!==void 0&&p!==void 0){if(c==="before")r.actions.set(f,{callId:p,entry:t,before:{line:a.line,event:d}});else if(c==="after"){let y=r.actions.get(f)??{callId:p,entry:t};y.after={line:a.line,event:d},r.actions.set(f,y);let w=ke(d.endTime);_n(d)!==void 0&&w!==void 0&&r.errorTimes.push(w)}}let h=f===void 0?void 0:r.actions.get(f)?.before,g=Mv(d,h?.event);if(g===void 0){s.add(c);continue}let m=$n(r,"trace",o,g);r.candidates.push({channel:"trace",kind:"trace-event",locator:{type:"trace-event",entry:t,line:a.line,eventType:c,...p===void 0?{}:{eventId:p},...l===void 0?{}:{timestamp:l}},locatorText:o,observation:m.value,redactions:m.records,order:r.candidates.length,...l===void 0?{}:{time:l},...p===void 0?{}:{callId:p},error:c==="error"||_n(d)!==void 0})}for(let a of[...s].sort())se(r,"trace","unrecognized",`Trace event type ${a} is not interpreted by this adapter.`,t)}function Fv(r){let t=[];for(let e of r.actions.values()){let n=Lv(e.before?.event);if(n===void 0||e.before===void 0||_(e.before.event.class)==="Test")continue;let i=e.after!==void 0&&_n(e.after.event)!==void 0,s=e.after===void 0;!i&&!s||t.push({callId:e.callId,entry:e.entry,selector:n,apiName:jp(e.before.event),time:ke(e.before.event.startTime)??0,unfinished:s})}return t.sort((e,n)=>n.time-e.time||e.callId.localeCompare(n.callId))}function jv(r){let t={after:3,action:2,before:1};return[...r].filter(e=>e.isMainFrame||r.length===1).sort((e,n)=>(t[n.phase??"before"]??0)-(t[e.phase??"before"]??0)||n.line-e.line)[0]}function Bv(r,t){let e=jv(r.snapshots.forCall(t.callId)),n=`${t.apiName} on ${t.selector}`;if(e===void 0){se(r,"dom","unavailable",`No DOM snapshot was recorded for the failed ${n}.`,`${t.entry}#${t.callId}`);return}let i=r.snapshots.rebuild(e,Zo),s=`${e.entry}#${e.snapshotId}`;if(i.root===void 0){se(r,"dom","unreadable",`Snapshot ${e.snapshotId} could not be rebuilt.`,s);return}i.truncated&&se(r,"dom","budget-exceeded",`Snapshot ${e.snapshotId} was rebuilt only up to ${Zo} nodes.`,s,Zo);let a={maxDepth:r.policy.maxDomDepth,maxNodes:r.policy.maxDomNodes,maxBytes:r.policy.maxDomTextBytes,sensitiveNames:r.policy.sensitiveNames},o=gp(i.root,t.callId),d=An(i.root,t.selector),c=d.kind==="resolved"?d.matches:void 0,l=o!==void 0&&(c===void 0||c.length<=1)?[o]:c??[],u=e.phase??"snapshot";if(l.length===1&&l[0]!==void 0){let h=l[0],g=En(h.node,s,a);os(r,"dom","dom-subtree",{type:"dom-node",snapshotId:e.snapshotId,nodePath:h.path},`${u} snapshot of the element targeted by the failed ${n}:
20
+ ${g.text}`,g.redactions,ee.failure),g.truncated&&se(r,"dom","budget-exceeded",`The target subtree in ${e.snapshotId} was cut at ${a.maxDepth} levels, ${a.maxNodes} elements, or ${a.maxBytes} bytes.`,s,a.maxNodes);let m=$n(r,"accessibility",s,Cn(h.node));os(r,"accessibility","accessibility-node",{type:"dom-node",snapshotId:e.snapshotId,nodePath:h.path},`target of the failed ${t.apiName}: ${m.value}`,m.records,ee.failure);return}let p=d.kind==="unsupported"?`uses a selector form (${d.reason}) the local DOM adapter does not evaluate`:`matched ${l.length} elements`,f=ns(i.root,t.selector,l,s,{maxItems:ed,maxBytes:a.maxBytes},r.policy.sensitiveNames);os(r,"dom","dom-candidates",{type:"dom-node",snapshotId:e.snapshotId,nodePath:[]},`In the ${u} snapshot of the failed ${n}, the locator ${p}. Elements most like it, best first:
21
+ ${f.text}`,f.redactions,ee.failure),f.truncated&&se(r,"dom","budget-exceeded",`Only the ${ed} closest candidates in ${e.snapshotId} were listed.`,s,ed)}function Vv(r,t){let e=new Set(t.map(s=>s.callId));for(let s of r.actions.values())s.after!==void 0&&_n(s.after.event)!==void 0&&e.add(s.callId);let n=r.errorTimes.length>0?Math.min(...r.errorTimes):t.length>0?Math.min(...t.map(s=>s.time)):void 0,i=s=>s.error?s.channel==="trace"?ee.failedCall+.95:ee.significant:s.callId!==void 0&&e.has(s.callId)?ee.failedCall:n!==void 0&&s.time!==void 0&&s.time>n+1?ee.afterFailure:s.channel==="trace"?ee.context:ee.ordinary;for(let s of["trace","console","network"]){let a=r.candidates.filter(l=>l.channel===s),o=Ov(r.policy,s),d=a.map(l=>({candidate:l,priority:i(l)})).sort((l,u)=>u.priority-l.priority||u.candidate.order-l.candidate.order),c=d.slice(0,o).sort((l,u)=>l.candidate.order-u.candidate.order);for(let{candidate:l,priority:u}of c){let p=a.length===0?0:l.order/(a.length*25);os(r,s,l.kind,l.locator,l.observation,l.redactions,u+p)}d.length>o&&se(r,s,"budget-exceeded",`Kept the ${o} ${s} observations closest to the failure; ${d.length-o} earlier or less relevant ones were not included.`,d[o]?.candidate.locatorText,o)}}function Bp(r){let t=fe(r.snapshot)??r,e=fe(t.response),n=fe(e?.content);return _(n?._sha1)??_(n?.sha1)}function Vp(r,t,e,n,i){let s=fe(n.snapshot)??n,a=fe(s.request),o=_(a?.url),d=`${t}#line=${e}`;if(o===void 0){se(r,"network","unrecognized",`${d} has no request URL.`,d);return}let c=Ot(o,"network",d,r.policy.sensitiveNames),l=ts(Lp(a?.headers),"network",`${d}/request-headers`,r.policy.sensitiveNames),u=fe(s.response),p=ts(Lp(u?.headers),"network",`${d}/response-headers`,r.policy.sensitiveNames),f=_(a?.method)??"GET",h=ke(u?.status),g=fe(u?.content),m=[`${f} ${c.value}`,h===void 0||h<=0?"-> (no response)":`-> ${h} ${_(u?.statusText)??""}`.trim()],y=_(g?.mimeType),w=ke(g?.size);(y!==void 0||w!==void 0)&&m.push(`(${y??"unknown"}, ${w??"unknown"} bytes)`);let x=_(g?.text)??_(u?.body),v=Bp(n);if(x===void 0&&v!==void 0&&r.policy.includeNetworkBodies){let C=i.get(v)??i.get(`resources/${v}`);C===void 0?se(r,"network","unavailable",`Referenced response resource ${v} was not present in the trace archive.`,d):C.byteLength>r.policy.maxNetworkBodyBytes?se(r,"network","budget-exceeded",`Referenced response resource ${v} exceeds the network body byte limit.`,d,r.policy.maxNetworkBodyBytes):(x=_e(C),x===void 0&&se(r,"network","irrelevant",`Referenced response resource ${v} is not textual UTF-8.`,d))}let I=y?.toLowerCase()??"",R=I.startsWith("image/")||I.startsWith("audio/")||I.startsWith("video/")||I.includes("multipart")||I.includes("octet-stream"),E=[];if(r.policy.includeNetworkBodies)if(x!==void 0&&!R){let C=$n(r,"network",`${d}/body`,ge(x,r.policy.maxNetworkBodyBytes));E.push(...C.records),m.push(`body=${C.value}`)}else x!==void 0&&R&&se(r,"network","irrelevant","Response body omitted because it is binary or multipart.",d);else(x!==void 0||g!==void 0)&&se(r,"network","policy-disabled","Response body withheld because includeNetworkBodies is disabled.",d);let A=ke(s.time);A!==void 0&&m.push(`time=${A}ms`);let O=_(s._failureText);O!==void 0&&m.push(`failure=${ge(O,Zt)}`);let j=$n(r,"network",d,m.join(" ")),V=_(s._requestref)??$("req",[f,c.value,String(e)]),P=ke(s._monotonicTime);r.candidates.push({channel:"network",kind:"network-event",locator:{type:"network-request",requestId:V,eventIndex:e},locatorText:d,observation:j.value,redactions:[...j.records,...E,...c.records,...l.records,...p.records],order:r.candidates.length,...P===void 0?{}:{time:P},error:O!==void 0||h!==void 0&&(h>=400||h<=0)})}function zv(r,t,e){let n=_e(e);if(n===void 0){r.channels.trace.failed=!0,se(r,"trace","unreadable",`${t} is not valid UTF-8.`,t);return}let i;try{i=JSON.parse(n),r.channels.trace.parsed=!0}catch{r.channels.trace.failed=!0,se(r,"trace","parse-failed",`${t} is not valid JSON.`,t);return}let s=fe(i),a=He(s?.files)??[],o=He(s?.stacks)??[];for(let d of o){let c=He(d),l=_(c?.[0])??"unknown";for(let u of He(c?.[1])??[]){if(r.seeds.length>=Fp)return;let p=He(u),f=ke(p?.[0]),h=ke(p?.[1]);if(f===void 0||h===void 0)continue;let g=_(a[f]);if(g===void 0)continue;let m=ke(p?.[2]);r.seeds.push({file:g,line:h,...m===void 0?{}:{column:m},origin:`${t}:${l}`,logicalTestId:r.input.logicalTestId,attemptId:r.input.attemptId})}}}function Mp(r,t,e,n){let i={};for(let s of Qt)i[s]={artifact:{artifactId:we(r,s,`${t.attemptId}:${t.attachmentId}`),channel:s,availability:e,...n.path===void 0?{}:{path:n.path},...n.sha256===void 0?{}:{sha256:n.sha256},format:n.format??"playwright-trace-zip",...n.producerVersion===void 0?{}:{producerVersion:n.producerVersion},attemptId:t.attemptId,warnings:n.warnings},included:0,parsed:!1,failed:!1};return i}function $p(r,t,e,n){return{runId:r,policy:t,input:e,channels:n,evidence:[],redactions:[],omissions:[],seeds:[],priorities:new Map,candidates:[],actions:new Map,snapshots:new ss,errorTimes:[]}}function _p(r,t){return{artifacts:r,evidence:[],redactions:[],omissions:t,seeds:[],priorities:new Map,failedSelectors:[]}}async function zp(r,t,e,n){let i=await W(n,e.path,t.maxArtifactBytes);if(i.kind!=="read"){let f=i.kind==="unavailable"?"unavailable":"unreadable",h=i.kind==="over-budget"?"budget-exceeded":i.kind==="unauthorized"?"unauthorized-path":i.kind,g=Mp(r,e,f,{warnings:[i.message]}),m=$p(r,t,e,g);for(let y of Qt)se(m,y,h,i.message,e.path);return _p(Qt.map(y=>g[y].artifact),m.omissions)}let a=is(i.bytes,{maxEntries:t.maxTraceEntries,maxExpandedBytes:t.maxTraceExpandedBytes},f=>Yo.test(f)||as.test(f)||Qo.test(f)),o=e.info?.producerVersion===void 0,d=Mp(r,e,"present",{path:i.relativePath,sha256:i.sha256,warnings:o?["Trace producer version was not supplied; adapter compatibility is unverified."]:[],...e.info?.producerVersion===void 0?{}:{producerVersion:e.info.producerVersion},...e.info?.format===void 0?{}:{format:e.info.format}}),c=$p(r,t,e,d);if(a.kind!=="read"){let f=a.message;for(let h of Qt)se(c,h,"unreadable",f,i.relativePath);return _p(Qt.map(h=>({...d[h].artifact,availability:"unreadable",warnings:[f]})),c.omissions)}o&&se(c,"trace","unrecognized","Trace producer version was not supplied; parsed evidence is not version-qualified.",i.relativePath);let l=new Set;if(t.includeNetworkBodies){for(let[f,h]of a.contents.entries){if(!as.test(f))continue;let g=_e(h);if(g!==void 0)for(let m of rs(g)){let y=fe(m.value);if(y===void 0)continue;let w=Bp(y);w!==void 0&&(l.add(w),l.add(`resources/${w}`))}}if(l.size>0){let f=is(i.bytes,{maxEntries:t.maxTraceEntries,maxExpandedBytes:t.maxTraceExpandedBytes},h=>Yo.test(h)||as.test(h)||Qo.test(h)||l.has(h));f.kind==="read"?a=f:se(c,"network","unreadable",f.message,i.relativePath)}}for(let f of a.contents.skipped){let h=f.reason==="unsafe-entry-name"?"unauthorized-path":"budget-exceeded";se(c,"trace",h,`Archive entry ${f.entry} was not read (${f.reason}, ${f.declaredBytes} declared bytes).`,`${i.relativePath}!${f.entry}`)}let u=[...a.contents.entries.keys()].sort();for(let f of u.filter(h=>Qo.test(h)))zv(c,f,a.contents.entries.get(f));for(let f of u.filter(h=>Yo.test(h)))_v(c,f,a.contents.entries.get(f));for(let f of u.filter(h=>as.test(h))){let h=_e(a.contents.entries.get(f));if(h===void 0){c.channels.network.failed=!0,se(c,"network","unreadable",`${f} is not valid UTF-8.`,f);continue}let g=rs(h);g.length===0&&(c.channels.network.parsed=!0);for(let m of g){if(!m.parsed){c.channels.network.failed=!0,se(c,"network","parse-failed",`${f}#line=${m.line} is not valid JSON.`,`${f}#line=${m.line}`);continue}let y=fe(m.value);if(y===void 0){c.channels.network.failed=!0,se(c,"network","unrecognized",`${f}#line=${m.line} is not a network record.`,`${f}#line=${m.line}`);continue}c.channels.network.parsed=!0,Vp(c,f,m.line,y,a.contents.entries)}}let p=Fv(c);Vv(c,p);for(let f of p.slice(0,Cv))Bv(c,f);if(p.length===0&&c.snapshots.size>0&&se(c,"dom","irrelevant","No failed action targeted an element, so no DOM snapshot was examined.",i.relativePath),u.length===0)for(let f of Qt)d[f].failed=!0,se(c,f,"unreadable","Archive contained no Playwright trace, network, or stacks entry.",i.relativePath);return{artifacts:Qt.map(f=>{let h=d[f],g=h.included>0?"present":h.failed&&!h.parsed?"unreadable":"empty";return{...h.artifact,availability:g}}),evidence:c.evidence,redactions:c.redactions,omissions:c.omissions,seeds:c.seeds,priorities:c.priorities,failedSelectors:p.map(f=>ut(f.selector))}}var Hv="application/vnd.kwikqa.capture+json",Hp=["trace","console","network","dom","accessibility"],qp=25,qv=2,Uv=25,rd=600,Gv=new Set(["type","setValue","addValue","keys"]),Kv=new Set(["get","find","contains","$","$$","within"]),Wv=/pass|secret|token|otp|pin\b|card|cvv|cvc|ssn|credential|auth/i;function nd(r){return r.name==="kwikqa-capture"||r.contentType.toLowerCase().split(";")[0]?.trim()===Hv}function xt(r,t=""){return typeof r=="string"?r:t}function Jv(r){if(typeof r!="object"||r===null||Array.isArray(r))return;let t=r;if(t.schema!=="kwikqa-capture"||String(t.schemaVersion??"").split(".")[0]!=="1")return;let e=t.framework==="webdriverio"?"webdriverio":"cypress",n=i=>Array.isArray(t[i])?t[i].filter(s=>typeof s=="object"&&s!==null&&!Array.isArray(s)):[];return{framework:e,url:xt(t.url),title:xt(t.title),...Array.isArray(t.dom)?{dom:t.dom}:{},domTruncated:t.domTruncated===!0,commands:n("commands").map(i=>({name:xt(i.name),...typeof i.displayName=="string"?{displayName:i.displayName}:{},message:xt(i.message),state:xt(i.state),...typeof i.error=="string"?{error:i.error}:{},...typeof i.repeated=="number"?{repeated:i.repeated}:{}})),console:n("console").map(i=>({level:xt(i.level,"log"),text:xt(i.text)})),network:n("network").map(i=>({message:xt(i.message),state:xt(i.state),...typeof i.url=="string"?{url:i.url}:{}}))}}function Xv(r){let t=/^([A-Z]+)\s+(\d{3})\s+(\S+)/.exec(r.trim());if(t!==null)return{method:t[1]??"GET",status:Number(t[2]),url:t[3]??""};let e=/^([A-Z]+)\s+(\S+)\s+(\S+)$/.exec(r.trim());return e!==null&&/^https?:|^\//.test(e[3]??"")?{method:e[1]??"GET",url:e[3]??"",failure:e[2]??"failed"}:{method:"",url:r}}function Yv(r){for(let t of Le(r))if(Array.isArray(t)&&$e(t)==="body")return t;return r}function Qv(r){let t=/^([a-z][\w-]*)\*?=/i.exec(r);return t!==null&&!r.includes("[")?t[1]??r:r}async function Up(r,t,e,n){let{attachment:i}=e,s=`${e.attemptId}.attachments[${i.sourceIndex}]`,a=Object.fromEntries(Hp.map(k=>[k,we(r,k,`${e.attemptId}:${i.attachmentId}`)])),o=[],d=[],c=[],l=new Map,u=[],p=(k,T,L,q)=>{c.push({omissionId:$("omi",[e.attemptId,k,T,s,L]),channel:k,reason:T,message:L,locator:s,...q===void 0?{}:{cap:q}})},f=(k,T={})=>Hp.map(L=>({artifactId:a[L],channel:L,availability:k(L),format:"kwikqa-capture",attemptId:e.attemptId,warnings:[],...T}));if(i.path===void 0)return p("dom","unavailable","The failure capture attachment has no path."),{artifacts:f(()=>"unavailable"),evidence:o,redactions:d,omissions:c,priorities:l,failedSelectors:u};let h=await W(n,i.path,t.maxArtifactBytes);if(h.kind!=="read"){let k=h.kind==="over-budget"?"budget-exceeded":h.kind==="unauthorized"?"unauthorized-path":h.kind;return p("dom",k,h.message),{artifacts:f(()=>h.kind==="unavailable"?"unavailable":"unreadable",{path:i.path,warnings:[h.message]}),evidence:o,redactions:d,omissions:c,priorities:l,failedSelectors:u}}let g=Te(h.bytes),m=_e(h.bytes),y;try{y=m===void 0?void 0:Jv(JSON.parse(m))}catch{y=void 0}if(y===void 0)return p("dom","unrecognized","The failure capture is not a KwikQA capture."),{artifacts:f(()=>"unreadable",{path:h.relativePath,sha256:g}),evidence:o,redactions:d,omissions:c,priorities:l,failedSelectors:u};let w=(k,T,L,q,Q,ie)=>{let de=he(r,a[k],T,L,q);o.push({evidenceId:de,kind:T,artifactId:a[k],logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:L,observation:q,availability:"present",redactionIds:Q.map(K=>K.redactionId)}),d.push(...Q),l.set(de,ie)},x=(k,T,L)=>oe(ut(T),k,L,t.sensitiveNames),v=y.framework==="cypress"?"cy":"browser",I=y.commands.filter(k=>k.name!==""&&k.state!=="pending"),R=I.findIndex(k=>k.state==="failed"),E=R<0?I.length:R+1,A=Math.max(0,E-qp);A>0&&p("trace","budget-exceeded",`Kept the ${E-A} commands up to the failure; ${A} earlier ones were left out.`,qp);let O="";I.slice(A,Math.min(I.length,E+3)).forEach((k,T)=>{let L=A+T,q=k.state==="failed",de=Gv.has(k.name)&&(Wv.test(O)||t.sensitiveNames.some(St=>O.toLowerCase().includes(St.toLowerCase())))?`<${k.message.length} typed characters, not shown>`:k.message;Kv.has(k.name)&&k.message!==""&&(O=k.message),q&&O!==""&&u.push(O.split(",")[0]?.trim()??O);let ve=k.repeated===void 0?"":` (x${k.repeated})`,Re=`${q?"command failed":L>=E?"command after the failure":"command"}: ${v}.${k.displayName??k.name}(${de.slice(0,rd)})${ve}${k.error===void 0?"":` error=${k.error.slice(0,rd)}`}`,mt=x("trace",Re,`${s}#commands[${L}]`);w("trace","trace-event",{type:"trace-event",entry:`${i.attachmentId}#commands`,line:L+1,eventType:q?"command-failed":"command"},mt.value,mt.records,q?ee.failure:L>=E?ee.afterFailure:ee.context+(L-A)/1e3)}),I.length===0&&p("trace","unavailable","The capture recorded no commands."),y.console.slice(0,t.maxConsoleEvents).forEach((k,T)=>{let L=k.level==="pageerror"?"uncaught page error":`console.${k.level}`,q=x("console",`${L}: ${k.text.slice(0,rd)}`,`${s}#console[${T}]`);w("console","console-event",{type:"trace-event",entry:`${i.attachmentId}#console`,line:T+1,eventType:"console"},q.value,q.records,k.level==="error"||k.level==="pageerror"?ee.significant:ee.ordinary)}),y.console.length>t.maxConsoleEvents&&p("console","budget-exceeded",`Kept ${t.maxConsoleEvents} of ${y.console.length} console messages.`,t.maxConsoleEvents),y.network.slice(0,t.maxNetworkEvents).forEach((k,T)=>{let L=Xv(k.message),q=Ot(k.url??L.url,"network",`${s}#network[${T}]`,t.sensitiveNames),Q=L.status!==void 0?`-> ${L.status}`:L.failure!==void 0?`failure=${L.failure}`:`(${k.state})`,ie=`${L.method===""?"request":L.method} ${q.value} ${Q}`,de=(L.status??0)>=400||L.failure!==void 0;w("network","network-event",{type:"network-request",requestId:`${i.attachmentId}#${T}`,eventIndex:T},ie,q.records,de?ee.significant:ee.ordinary)}),y.network.length>t.maxNetworkEvents&&p("network","budget-exceeded",`Kept ${t.maxNetworkEvents} of ${y.network.length} network responses.`,t.maxNetworkEvents);let j=y.dom,V=`${i.attachmentId}#dom`,P=Ot(y.url,"dom",`${s}#url`,t.sensitiveNames);d.push(...P.records);let C=`the page ${P.value}${y.title===""?"":` ("${y.title.slice(0,120)}")`} when the attempt failed`,M={maxDepth:t.maxDomDepth,maxNodes:t.maxDomNodes,maxBytes:t.maxDomTextBytes,sensitiveNames:t.sensitiveNames};if(j===void 0)p("dom","unavailable","The capture recorded no DOM.");else{y.domTruncated&&p("dom","budget-exceeded","The page was larger than the capture's node limit; later nodes were not recorded.");let k=[...new Set([...u,...e.focus])].map(Qv).filter(T=>T!=="").slice(0,qv);for(let T of k){let L=An(j,T),q=L.kind==="resolved"?L.matches:[];if(q.length===1&&q[0]!==void 0){let de=q[0],K=En(de.node,`${s}#dom`,M);w("dom","dom-subtree",{type:"dom-node",snapshotId:V,nodePath:de.path},`In ${C}, the element ${T} selects:
22
+ ${K.text}`,K.redactions,ee.failure);let ve=x("accessibility",Cn(de.node),`${s}#a11y`);w("accessibility","accessibility-node",{type:"dom-node",snapshotId:V,nodePath:de.path},`element selected by ${T}: ${ve.value}`,ve.records,ee.failure);continue}let Q=L.kind==="unsupported"?`uses a selector form (${L.reason}) the local DOM adapter does not evaluate`:`matched ${q.length} elements`,ie=ns(j,T,q,`${s}#dom`,{maxItems:Uv,maxBytes:M.maxBytes},t.sensitiveNames);w("dom","dom-candidates",{type:"dom-node",snapshotId:V,nodePath:[]},`In ${C}, the selector ${T} ${Q}. Elements most like it, best first:
23
+ ${ie.text}`,ie.redactions,ee.failure)}if(k.length===0){let T=En(Yv(j),`${s}#dom`,M);w("dom","dom-subtree",{type:"dom-node",snapshotId:V,nodePath:[]},`Outline of ${C}:
24
+ ${T.text}`,T.redactions,ee.significant),T.truncated&&p("dom","budget-exceeded",`The page outline was cut at ${M.maxNodes} elements or ${M.maxBytes} bytes.`,M.maxNodes)}}let z=new Set(o.map(k=>k.artifactId));return{artifacts:f(k=>z.has(a[k])?"present":"empty",{path:h.relativePath,sha256:g}),evidence:o,redactions:d,omissions:c,priorities:l,failedSelectors:u}}import{execFile as ak}from"node:child_process";import{isAbsolute as ok,relative as dk,resolve as cd,sep as Kp}from"node:path";import{promisify as ck}from"node:util";import{execFile as Zv}from"node:child_process";import{promisify as ek}from"node:util";import{isAbsolute as tk,relative as id,resolve as ds,sep as sd}from"node:path";var rk=ek(Zv),nk=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/,ik=1e4;function cs(r){let t=[],e,n,i=()=>{if(n===void 0||e===void 0)return;let[,s,a,o,d]=n.header;t.push({path:e,oldStart:Number.parseInt(s??"0",10),oldLines:a===void 0?1:Number.parseInt(a,10),newStart:Number.parseInt(o??"0",10),newLines:d===void 0?1:Number.parseInt(d,10),body:n.lines.join(`
25
+ `)}),n=void 0};for(let s of r.split(/\r?\n/)){if(s.startsWith("diff --git ")){i(),e=void 0;continue}if(s.startsWith("+++ ")){i();let o=s.slice(4).trim();e=o==="/dev/null"?void 0:o.replace(/^b\//,"");continue}let a=nk.exec(s);if(a!==null){i(),n={header:a,lines:[s]};continue}n!==void 0&&n.lines.push(s)}return i(),t}function er(r,t,e,n){return{omissionId:$("omi",["diff",r,e??"",t]),channel:"diff",reason:r,message:t,...e===void 0?{}:{locator:e},...n===void 0?{}:{cap:n}}}async function sk(r,t,e){let n=["-C",r,"--no-optional-locks","-c","core.quotePath=false","diff","--no-color","--no-ext-diff","--no-renames","--unified=3","HEAD","--",...t];try{return{text:(await rk("git",n,{timeout:ik,maxBuffer:e,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}}catch(i){let s=i;if(s.code==="ENOENT")return{error:"git executable was not found."};let a=(s.stderr??s.message??"").trim().split(`
26
+ `)[0]??"";return{error:a===""?"git diff failed.":a}}}async function Gp(r,t,e,n){let i=we(r,"diff",n.gitRoot??t.workspaceRoot),s=(v,I=[])=>({artifactId:i,channel:"diff",availability:v,...n.gitRoot===void 0?{}:{path:n.gitRoot},format:"git-unified-diff",warnings:I});if(!n.authorized)return{artifacts:[s("unavailable")],evidence:[],redactions:[],omissions:[er("policy-disabled","Current-diff selection was not authorized for this run.")]};if(n.gitRoot===void 0)return{artifacts:[s("unavailable")],evidence:[],redactions:[],omissions:[er("unavailable","The workspace has no containing git repository root.")]};let a=ds(n.workspaceRoot??n.gitRoot),o=ds(n.gitRoot),d=id(o,a);if(d===".."||d.startsWith(`..${sd}`))return{artifacts:[s("unavailable")],evidence:[],redactions:[],omissions:[er("unauthorized-path","The authorized workspace is outside the configured git root.",a)]};let c=[...new Set(e.map(v=>{let I=tk(v)?ds(v):ds(a,v),R=id(o,I).split(sd).join("/");return R===""||R.startsWith("../")||R===".."?void 0:R}).filter(v=>v!==void 0))].sort();if(c.length===0)return{artifacts:[s("empty")],evidence:[],redactions:[],omissions:[er("irrelevant","No evidence-bearing file was eligible for diff selection.")]};let l=Math.max(t.maxDiffBytes*4,1e6),u=await sk(o,c,l);if("error"in u)return{artifacts:[s("unreadable",[u.error])],evidence:[],redactions:[],omissions:[er("unreadable",u.error,n.gitRoot)]};let p=a===o?"":`${id(o,a).split(sd).join("/")}/`,f=cs(u.text).map(v=>({...v,path:p!==""&&v.path.startsWith(p)?v.path.slice(p.length):v.path}));if(f.length===0)return{artifacts:[s("empty")],evidence:[],redactions:[],omissions:[]};let h=[],g=[],m=[],y=0,w=!1,x=!1;for(let v of f){if(h.length>=t.maxDiffHunks){w||(w=!0,m.push(er("budget-exceeded",`Reached the ${t.maxDiffHunks}-hunk limit; later hunks were not included.`,v.path,t.maxDiffHunks)));break}let I=`${v.path}@${v.newStart}`,R=oe(v.body,"diff",I,t.sensitiveNames),E=Buffer.byteLength(R.value,"utf8");if(y+E>t.maxDiffBytes){x||(x=!0,m.push(er("budget-exceeded",`Reached the ${t.maxDiffBytes}-byte diff limit; later hunks were not included.`,v.path,t.maxDiffBytes)));break}y+=E,g.push(...R.records);let A={type:"diff-hunk",path:v.path,oldStart:v.oldStart,oldLines:v.oldLines,newStart:v.newStart,newLines:v.newLines};h.push({evidenceId:he(r,i,"diff-hunk",A,R.value),kind:"diff-hunk",artifactId:i,locator:A,observation:R.value,availability:"present",redactionIds:R.records.map(O=>O.redactionId)})}return{artifacts:[s("present")],evidence:h,redactions:g,omissions:m}}var lk=ck(ak),uk=1e4,pk=4e6,fk=16,nf=3,hk=120,Wp=50,Jp=20,Xp=30,ad=12,Yp=24e3,od=40,sf=20,Qp=120,af=1440*60*1e3,mk=new Set(["alert","article","button","cell","checkbox","combobox","dialog","false","heading","hidden","img","link","list","listitem","main","menu","menuitem","navigation","null","option","radio","region","row","status","tab","table","textbox","true","undefined","visible"]),of=/\.(?:[cm]?[jt]sx?|vue|svelte|astro|html?|css|scss|sass|less|json|ya?ml|py|rb|php|java|kt|cs|go|rs|swift|erb|hbs|ejs|pug|liquid|twig|jinja2?|properties|po|xliff|xlf|strings|resx)$/i,df=/(?:^|\/)(?:node_modules|dist|build|out|coverage|vendor|\.next|\.nuxt|\.svelte-kit|\.kwikqa|__snapshots__|test-results|playwright-report|\.git)\/|(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|composer\.lock|Gemfile\.lock|Cargo\.lock|poetry\.lock)$|\.min\.[cm]?js$|\.map$/,yk=/\u001b\[[0-9;]*m/g,Zp=/"([^"\n]{3,120})"|'([^'\n]{3,120})'|`([^`\n]{3,120})`/g,gk=/^\s*(?:Expected|Received)(?: string| pattern| value)?:\s*(.+)$/gm,wk=/^(?:[A-Z]+|request) (\S+) (?:-> (\d{3})|failure=)/;function bk(r){let t=r.trim();return/^(["'`])(.*)\1$/.exec(t)?.[2]??t}function ef(r){let t=r.trim();if(!(t.length<nf||t.length>hk)&&!mk.has(t.toLowerCase())&&!(/^[\d\s.,:%$-]+$/.test(t)&&!/^[$€£]?\d+[.,]\d+$/.test(t))&&!/^(?:\/|[A-Za-z]:\\|file:)|\.(?:spec|test|cy)\.[cm]?[jt]sx?\b|node_modules|:\d+:\d+/.test(t))return t}function dd(r){let t=[];for(let e of r.matchAll(/\[[\w-]+[~|^$*]?=\s*["']?([^"'\]]+)["']?\]/g))t.push(e[1]??"");for(let e of r.matchAll(/[#.]([A-Za-z][\w-]{2,})/g))t.push(e[1]??"");return t}var xk=8;function vk(r){let t=r.trim().split(/\s+/);if(t.length<3)return[];let e=[];for(let n=0;n+1<t.length;n+=1){let i=`${t[n]} ${t[n+1]}`;(i.match(new RegExp("\\p{L}","gu"))??[]).length>=xk&&e.push(i)}return e}function kk(r){let t;try{t=new URL(r,"http://localhost").pathname}catch{return}if(/\.(?:js|css|png|jpe?g|gif|svg|ico|woff2?|map)$/i.test(t))return;let e=[];for(let i of t.split("/").filter(Boolean)){if(/^\d+$|^[0-9a-f-]{16,}$|^[0-9a-f]{8,}$/i.test(i))break;e.push(i)}let n=`/${e.join("/")}`;return e.length===0?void 0:n}function cf(r,t,e=[]){let n=[],i=[];for(let c of r){for(let l of t(c)){for(let u of l.matchAll(Zp)){let p=u[1]??u[2]??u[3]??"";n.push(p,...dd(p))}/[('"`]/.test(l)||n.push(...dd(l))}for(let l of c.errors){let u=(l.message??"").replace(yk,"");for(let f of u.matchAll(gk)){let h=bk(f[1]??"");n.push(h),i.push(h)}let p=u.split(`
27
27
  `).slice(0,6).join(`
28
- `);for(let f of p.matchAll(Kp)){let h=f[1]??f[2]??f[3]??"",g=/^[[#.]/.test(h)?nd(h):[];n.push(...g.length>0?g:[h]),g.length===0&&i.push(h)}}}let s=[];for(let c of e){let l=lk.exec(c);if(l===null)continue;let u=l[2]===void 0?void 0:Number(l[2]);if(u!==void 0&&u<400)continue;let p=hk(l[1]??"");p!==void 0&&p.length>=Yp&&s.push(p)}let a=c=>[...new Set(c)].sort((l,u)=>u.length-l.length||l.localeCompare(u)),o=a([...n.map(Wp).filter(c=>c!==void 0),...s]),d=a(i.flatMap(fk).map(Wp).filter(c=>c!==void 0&&!o.includes(c)));return[...o,...d].slice(0,sk)}function mk(r){return r.map(t=>t.replace(/[.[\]{}()\\*+?^$|]/g,"\\$&")).join("|")}async function Lr(r,t){try{return{text:(await rk("git",["-C",r,"--no-optional-locks","-c","core.quotePath=false",...t],{timeout:nk,maxBuffer:ik,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}}catch(e){let n=e;if(n.code==="ENOENT")return{error:"git executable was not found."};if(n.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{error:"The matching changes are too large to read."};let i=(n.stderr??n.message??"").trim().split(`
29
- `)[0]??"";return{error:i===""?"git failed.":i}}}async function _n(r,t){let e=await Lr(r,t);if("error"in e)return;let n=e.text.trim();return n===""?void 0:n}async function yk(r){let t=await _n(r,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]);if(t!==void 0)return t;for(let e of["main","master","origin/main","origin/master"])if(await _n(r,["rev-parse","--verify","--quiet",`${e}^{commit}`])!==void 0)return e}async function gk(r,t){let e=await _n(r,["rev-parse","--verify","--quiet","HEAD^{commit}"]);if(e===void 0)return;let n=await yk(r),i=n===void 0?void 0:await _n(r,["merge-base","HEAD",n]);if(n!==void 0&&i!==void 0&&i!==e)return{logArgs:[`--max-count=${zp}`,`${i}..HEAD`],description:`the commits on this branch since it left ${n} (at most ${zp})`};let s=Date.parse(t),a=new Date((Number.isNaN(s)?0:s)-qp*Zp).toISOString();return{logArgs:[`--max-count=${Hp}`,`--since=${a}`,"HEAD"],description:`the last ${Hp} commits from the ${qp} days before the run`}}function nf(r,t){let e=Date.parse(t);if(Number.isNaN(e))return"";let n=Math.floor((e-r)/Zp);return n<0?", after the run":n===0?", the day of the run":`, ${n} day${n===1?"":"s"} before the run`}function wk(r,t){let e=r.split(`
30
- `);if(e.length<=rd+1)return r;let[n,...i]=e,s=Math.max(0,i.findIndex(t)),a=Math.max(0,Math.min(s-10,i.length-rd)),o=i.slice(a,a+rd),d=a,c=i.length-a-o.length;return[n??"",...d>0?[`\u2026 ${d} earlier line${d===1?"":"s"} of this hunk left out`]:[],...o,...c>0?[`\u2026 ${c} later line${c===1?"":"s"} of this hunk left out`]:[]].join(`
31
- `)}function sf(r,t,e){let n=id(r,e),i=ek(t,n);if(!(i===""||i===".."||i.startsWith(`..${Vp}`)||Zv(i)))return i.split(Vp).join("/")}function Jp(r,t,e,n,i){let s=a=>(a.startsWith("+")||a.startsWith("-"))&&n.some(o=>a.includes(o));return ss(r).flatMap(a=>{let o=sf(t,e,a.path);return o===void 0||!ef.test(o)||tf.test(o)?[]:a.body.split(`
32
- `).slice(1).some(s)?[{...i===void 0?{}:{commit:i.id},heading:i?.heading??"Uncommitted change",path:o,oldStart:a.oldStart,oldLines:a.oldLines,newStart:a.newStart,newLines:a.newLines,body:wk(a.body,s)}]:[]})}async function bk(r,t,e){let n=await Lr(r,["log","--no-merges","--no-show-signature","--format=%h%x1f%ct%x1f%s",...t.logArgs,"--"]);if("error"in n)return{listed:[],total:0};let i=n.text.split(`
33
- `).filter(a=>a.includes(""));return{listed:i.slice(0,Qp).map(a=>{let[o="",d="0",c=""]=a.split(""),l=c.length>Gp?`${c.slice(0,Gp)}\u2026`:c;return`${o}${nf(Number(d)*1e3,e)}: ${l}`}),total:i.length}}async function xk(r,t){let e=await Lr(r,["diff","--name-only","--no-renames","HEAD","--"]),n=await Lr(r,["ls-files","--others","--exclude-standard","--"]),i=[e,n].flatMap(s=>"error"in s?[]:s.text.split(`
34
- `).filter(a=>a!==""));return[...new Set(i.map(s=>sf(r,t,s)).filter(s=>s!==void 0&&ef.test(s)&&!tf.test(s)))].sort().slice(0,Qp)}var Xp=["--no-color","--no-ext-diff","--no-renames","--unified=3","--src-prefix=a/","--dst-prefix=b/"];function as(r,t,e,n){return{omissionId:$("omi",["changes",r,e??"",t]),channel:"diff",reason:r,message:t,...e===void 0?{}:{locator:e},...n===void 0?{}:{cap:n}}}async function af(r,t,e,n,i){let s=we(r,"diff",`changes:${i.gitRoot??i.workspaceRoot}`),a=(P,O=[])=>({artifactId:s,channel:"diff",availability:P,...i.gitRoot===void 0?{}:{path:i.gitRoot},format:"git-change-search",warnings:O}),o=(P,O)=>({artifacts:[a(P==="irrelevant"?"empty":"unavailable")],evidence:[],redactions:[],omissions:[as(P,O)]});if(!i.authorized)return o("policy-disabled","Recent changes were not included (--no-changes).");if(i.gitRoot===void 0)return o("unavailable","The workspace is not in a git repository, so no changes were searched.");if(n.length===0)return o("irrelevant","The failures name no locator, value, or request path to look for in recent changes.");let d=id(i.gitRoot),c=id(i.workspaceRoot),l=mk(n),u=[];await _n(d,["rev-parse","--is-shallow-repository"])==="true"&&u.push("This is a shallow clone; only the history it has was searched.");let p=[],f=[],h=await Lr(d,["diff",...Xp,`-G${l}`,"HEAD","--"]);"error"in h?f.push(h.error):p.push(...Jp(h.text,d,c,n,void 0));let g=await gk(d,t),m=0;if(g!==void 0){let P=await Lr(d,["log",...Xp,"--no-merges","--no-show-signature","--format=%x1e%h%x1f%ct%x1f%s",`-G${l}`,...g.logArgs,"--"]);if("error"in P)f.push(P.error);else for(let O of P.text.split("").slice(1)){let M=O.indexOf(`
35
- `),[H="",k="0",T=""]=(M===-1?O:O.slice(0,M)).split(""),L=Jp(O.slice(M+1),d,c,n,{id:H,heading:`Commit ${H}${nf(Number(k)*1e3,t)}: ${T}`});L.length>0&&(m+=1),p.push(...L)}}if(f.length>0&&p.length===0)return{artifacts:[a("unreadable",f)],evidence:[],redactions:[],omissions:f.map(P=>as("unreadable",P,i.gitRoot))};let y=[],w=[],x=f.map(P=>as("unreadable",P,i.gitRoot)),v=0;for(let P of p){if(y.length>=td||v>=Up){let k=p.length-y.length;x.push(as("budget-exceeded",`${k} more matching hunk${k===1?" was":"s were"} left out at the ${td}-hunk, ${Up}-byte limit for recent changes.`,void 0,td));break}let O=`${P.commit??"worktree"}:${P.path}@${P.newStart}`,M=ae(`${P.heading}
28
+ `);for(let f of p.matchAll(Zp)){let h=f[1]??f[2]??f[3]??"",g=/^[[#.]/.test(h)?dd(h):[];n.push(...g.length>0?g:[h]),g.length===0&&i.push(h)}}}let s=[];for(let c of e){let l=wk.exec(c);if(l===null)continue;let u=l[2]===void 0?void 0:Number(l[2]);if(u!==void 0&&u<400)continue;let p=kk(l[1]??"");p!==void 0&&p.length>=nf&&s.push(p)}let a=c=>[...new Set(c)].sort((l,u)=>u.length-l.length||l.localeCompare(u)),o=a([...n.map(ef).filter(c=>c!==void 0),...s]),d=a(i.flatMap(vk).map(ef).filter(c=>c!==void 0&&!o.includes(c)));return[...o,...d].slice(0,fk)}function Ik(r){return r.map(t=>t.replace(/[.[\]{}()\\*+?^$|]/g,"\\$&")).join("|")}async function $r(r,t){try{return{text:(await lk("git",["-C",r,"--no-optional-locks","-c","core.quotePath=false",...t],{timeout:uk,maxBuffer:pk,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}}catch(e){let n=e;if(n.code==="ENOENT")return{error:"git executable was not found."};if(n.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{error:"The matching changes are too large to read."};let i=(n.stderr??n.message??"").trim().split(`
29
+ `)[0]??"";return{error:i===""?"git failed.":i}}}async function Fn(r,t){let e=await $r(r,t);if("error"in e)return;let n=e.text.trim();return n===""?void 0:n}async function Pk(r){let t=await Fn(r,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]);if(t!==void 0)return t;for(let e of["main","master","origin/main","origin/master"])if(await Fn(r,["rev-parse","--verify","--quiet",`${e}^{commit}`])!==void 0)return e}async function Rk(r,t){let e=await Fn(r,["rev-parse","--verify","--quiet","HEAD^{commit}"]);if(e===void 0)return;let n=await Pk(r),i=n===void 0?void 0:await Fn(r,["merge-base","HEAD",n]);if(n!==void 0&&i!==void 0&&i!==e)return{logArgs:[`--max-count=${Wp}`,`${i}..HEAD`],description:`the commits on this branch since it left ${n} (at most ${Wp})`};let s=Date.parse(t),a=new Date((Number.isNaN(s)?0:s)-Xp*af).toISOString();return{logArgs:[`--max-count=${Jp}`,`--since=${a}`,"HEAD"],description:`the last ${Jp} commits from the ${Xp} days before the run`}}function lf(r,t){let e=Date.parse(t);if(Number.isNaN(e))return"";let n=Math.floor((e-r)/af);return n<0?", after the run":n===0?", the day of the run":`, ${n} day${n===1?"":"s"} before the run`}function Tk(r,t){let e=r.split(`
30
+ `);if(e.length<=od+1)return r;let[n,...i]=e,s=Math.max(0,i.findIndex(t)),a=Math.max(0,Math.min(s-10,i.length-od)),o=i.slice(a,a+od),d=a,c=i.length-a-o.length;return[n??"",...d>0?[`\u2026 ${d} earlier line${d===1?"":"s"} of this hunk left out`]:[],...o,...c>0?[`\u2026 ${c} later line${c===1?"":"s"} of this hunk left out`]:[]].join(`
31
+ `)}function uf(r,t,e){let n=cd(r,e),i=dk(t,n);if(!(i===""||i===".."||i.startsWith(`..${Kp}`)||ok(i)))return i.split(Kp).join("/")}function tf(r,t,e,n,i){let s=a=>(a.startsWith("+")||a.startsWith("-"))&&n.some(o=>a.includes(o));return cs(r).flatMap(a=>{let o=uf(t,e,a.path);return o===void 0||!of.test(o)||df.test(o)?[]:a.body.split(`
32
+ `).slice(1).some(s)?[{...i===void 0?{}:{commit:i.id},heading:i?.heading??"Uncommitted change",path:o,oldStart:a.oldStart,oldLines:a.oldLines,newStart:a.newStart,newLines:a.newLines,body:Tk(a.body,s)}]:[]})}async function Ak(r,t,e){let n=await $r(r,["log","--no-merges","--no-show-signature","--format=%h%x1f%ct%x1f%s",...t.logArgs,"--"]);if("error"in n)return{listed:[],total:0};let i=n.text.split(`
33
+ `).filter(a=>a.includes(""));return{listed:i.slice(0,sf).map(a=>{let[o="",d="0",c=""]=a.split(""),l=c.length>Qp?`${c.slice(0,Qp)}\u2026`:c;return`${o}${lf(Number(d)*1e3,e)}: ${l}`}),total:i.length}}async function Sk(r,t){let e=await $r(r,["diff","--name-only","--no-renames","HEAD","--"]),n=await $r(r,["ls-files","--others","--exclude-standard","--"]),i=[e,n].flatMap(s=>"error"in s?[]:s.text.split(`
34
+ `).filter(a=>a!==""));return[...new Set(i.map(s=>uf(r,t,s)).filter(s=>s!==void 0&&of.test(s)&&!df.test(s)))].sort().slice(0,sf)}var rf=["--no-color","--no-ext-diff","--no-renames","--unified=3","--src-prefix=a/","--dst-prefix=b/"];function ls(r,t,e,n){return{omissionId:$("omi",["changes",r,e??"",t]),channel:"diff",reason:r,message:t,...e===void 0?{}:{locator:e},...n===void 0?{}:{cap:n}}}async function pf(r,t,e,n,i){let s=we(r,"diff",`changes:${i.gitRoot??i.workspaceRoot}`),a=(P,C=[])=>({artifactId:s,channel:"diff",availability:P,...i.gitRoot===void 0?{}:{path:i.gitRoot},format:"git-change-search",warnings:C}),o=(P,C)=>({artifacts:[a(P==="irrelevant"?"empty":"unavailable")],evidence:[],redactions:[],omissions:[ls(P,C)]});if(!i.authorized)return o("policy-disabled","Recent changes were not included (--no-changes).");if(i.gitRoot===void 0)return o("unavailable","The workspace is not in a git repository, so no changes were searched.");if(n.length===0)return o("irrelevant","The failures name no locator, value, or request path to look for in recent changes.");let d=cd(i.gitRoot),c=cd(i.workspaceRoot),l=Ik(n),u=[];await Fn(d,["rev-parse","--is-shallow-repository"])==="true"&&u.push("This is a shallow clone; only the history it has was searched.");let p=[],f=[],h=await $r(d,["diff",...rf,`-G${l}`,"HEAD","--"]);"error"in h?f.push(h.error):p.push(...tf(h.text,d,c,n,void 0));let g=await Rk(d,t),m=0;if(g!==void 0){let P=await $r(d,["log",...rf,"--no-merges","--no-show-signature","--format=%x1e%h%x1f%ct%x1f%s",`-G${l}`,...g.logArgs,"--"]);if("error"in P)f.push(P.error);else for(let C of P.text.split("").slice(1)){let M=C.indexOf(`
35
+ `),[z="",k="0",T=""]=(M===-1?C:C.slice(0,M)).split(""),L=tf(C.slice(M+1),d,c,n,{id:z,heading:`Commit ${z}${lf(Number(k)*1e3,t)}: ${T}`});L.length>0&&(m+=1),p.push(...L)}}if(f.length>0&&p.length===0)return{artifacts:[a("unreadable",f)],evidence:[],redactions:[],omissions:f.map(P=>ls("unreadable",P,i.gitRoot))};let y=[],w=[],x=f.map(P=>ls("unreadable",P,i.gitRoot)),v=0;for(let P of p){if(y.length>=ad||v>=Yp){let k=p.length-y.length;x.push(ls("budget-exceeded",`${k} more matching hunk${k===1?" was":"s were"} left out at the ${ad}-hunk, ${Yp}-byte limit for recent changes.`,void 0,ad));break}let C=`${P.commit??"worktree"}:${P.path}@${P.newStart}`,M=oe(`${P.heading}
36
36
  ${P.path}
37
- ${P.body}`,"diff",O,e.sensitiveNames);v+=Buffer.byteLength(M.value,"utf8"),w.push(...M.records);let H={type:"diff-hunk",...P.commit===void 0?{}:{commit:P.commit},path:P.path,oldStart:P.oldStart,oldLines:P.oldLines,newStart:P.newStart,newLines:P.newLines};y.push({evidenceId:he(r,s,"diff-hunk",H,M.value),kind:"diff-hunk",artifactId:s,locator:H,observation:M.value,availability:"present",redactionIds:M.records.map(k=>k.redactionId)})}let I=["uncommitted changes",...g===void 0?[]:[g.description]].join(" and "),R=g===void 0?{listed:[],total:0}:await bk(d,g,t),E=await xk(d,c),A=[...R.listed.length===0?[]:[`${R.total>R.listed.length?`The newest ${R.listed.length} of the ${R.total} commits searched`:"Commits searched, newest first"}: ${R.listed.join("; ")}.`],...E.length===0?[]:[`Source files with uncommitted changes: ${E.join(", ")}.`]],N=y.length,B=ae(`Searched ${I} for changed lines containing any of: ${n.map(P=>JSON.stringify(P)).join(", ")}. ${N===0?"No change mentioned them.":`${N} changed hunk${N===1?"":"s"} matched${m>0?`, from ${m} commit${m===1?"":"s"}`:""}${p.some(P=>P.commit===void 0)?" and uncommitted changes":""}.`}${A.map(P=>` ${P}`).join("")} A matching change shows what changed, not who owns the failure.`,"diff","changes:search",e.sensitiveNames);w.push(...B.records);let V={type:"report-field",path:"changes"};return y.push({evidenceId:he(r,s,"change-search",V,B.value),kind:"change-search",artifactId:s,locator:V,observation:B.value,availability:"present",redactionIds:B.records.map(P=>P.redactionId)}),{artifacts:[a(N===0?"empty":"present",u)],evidence:y,redactions:w,omissions:x}}var vk=[137,80,78,71,13,10,26,10];function kk(r){return r<192||r>207?!1:r!==196&&r!==200&&r!==204}function Ik(r){if(r.byteLength<24||vk.some((e,n)=>r[n]!==e))return;let t=new DataView(r.buffer,r.byteOffset,r.byteLength);if(String.fromCharCode(...r.subarray(12,16))==="IHDR")return{width:t.getUint32(16,!1),height:t.getUint32(20,!1)}}function Pk(r){if(r.byteLength<4||r[0]!==255||r[1]!==216)return;let t=new DataView(r.buffer,r.byteOffset,r.byteLength),e=2;for(;e+9<r.byteLength;){if(r[e]!==255){e+=1;continue}let n=r[e+1];if(n===void 0)return;if(n===216||n===1||n>=208&&n<=215){e+=2;continue}let i=t.getUint16(e+2,!1);if(kk(n))return{height:t.getUint16(e+5,!1),width:t.getUint16(e+7,!1)};if(i<2)return;e+=2+i}}function Rk(r){if(r.byteLength<30)return;let t=(i,s)=>String.fromCharCode(...r.subarray(i,s));if(t(0,4)!=="RIFF"||t(8,12)!=="WEBP")return;let e=new DataView(r.buffer,r.byteOffset,r.byteLength),n=t(12,16);if(n==="VP8X"){let i=1+(e.getUint16(24,!0)|e.getUint8(26)<<16),s=1+(e.getUint16(27,!0)|e.getUint8(29)<<16);return{width:i,height:s}}if(n==="VP8 ")return{width:e.getUint16(26,!0)&16383,height:e.getUint16(28,!0)&16383};if(n==="VP8L"){let i=e.getUint32(21,!0);return{width:1+(i&16383),height:1+(i>>14&16383)}}}function df(r){return Ik(r)??Pk(r)??Rk(r)}function Tk(r){let t=r.toLowerCase().split(";")[0]?.trim()??"";if(t.startsWith("image/"))return"screenshot";if(t.startsWith("video/"))return"video"}function of(r,t,e,n,i){return{omissionId:$("omi",[r.attemptId,t,e,i,n]),channel:t,reason:e,message:n,locator:i}}async function cf(r,t,e,n){let{attachment:i}=e,s=Tk(i.contentType);if(s===void 0)return{artifacts:[],evidence:[],redactions:[],omissions:[]};let a=`${e.attemptId}.attachments[${i.sourceIndex}]`,o=we(r,s,`${e.attemptId}:${i.attachmentId}`),d={artifactId:o,channel:s,attemptId:e.attemptId,format:i.contentType},c,l,u;if(i.path!==void 0){let x=await K(n,i.path,t.maxArtifactBytes);x.kind==="read"?(c=x.bytes,l=x.relativePath):u={reason:x.kind==="over-budget"?"budget-exceeded":x.kind==="unauthorized"?"unauthorized-path":x.kind,message:x.message}}else if(i.bodyBase64!==void 0&&i.bodyBase64.length>0){let x=Buffer.from(i.bodyBase64,"base64");x.byteLength>t.maxArtifactBytes?u={reason:"budget-exceeded",message:`Inline attachment exceeds the ${t.maxArtifactBytes}-byte limit.`}:c=new Uint8Array(x)}else u={reason:"unavailable",message:"Attachment supplied neither a path nor a body."};let p=ae(i.name,s,a,t.sensitiveNames);if(c===void 0){let x=u?.reason??"unavailable";return{artifacts:[{...d,availability:x==="unavailable"?"unavailable":"unreadable",...i.path===void 0?{}:{path:i.path},warnings:u===void 0?[]:[u.message]}],evidence:[],redactions:p.records,omissions:[of(e,s,x,u?.message??"Attachment is unavailable.",a)]}}let f=Te(c),h=s==="screenshot"?df(c):void 0,g=[`${s} name=${p.value}`,`contentType=${i.contentType}`,`bytes=${c.byteLength}`,...s==="screenshot"?[h===void 0?"dimensions=unknown":`dimensions=${h.width}x${h.height}`]:[],`sha256=${f}`],m={type:"media",attachmentId:i.attachmentId,sha256:f},y=g.join(" "),w=[];return s==="screenshot"&&h===void 0&&w.push(of(e,s,"unreadable","Image dimensions could not be read from the container header.",a)),{artifacts:[{...d,availability:"present",...l===void 0?{}:{path:l},sha256:f,warnings:[]}],evidence:[{evidenceId:he(r,o,s==="screenshot"?"image-metadata":"video-metadata",m,y),kind:s==="screenshot"?"image-metadata":"video-metadata",artifactId:o,logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:m,observation:y,availability:"present",redactionIds:p.records.map(x=>x.redactionId)}],redactions:p.records,omissions:w}}var Ak=new Set(["textbox","searchbox","combobox","spinbutton"]),Sk=/\s\[(?:ref=[^\]]+|cursor=[^\]]+)\]/g,lf=/^#{1,3}\s+page snapshot\s*$/i,Ek=/^#{1,3}\s+\S/,uf=2;function pf(r){let t=r.contentType.toLowerCase().split(";")[0]?.trim()??"";return r.name==="error-context"?!0:t==="text/markdown"&&(r.path?.endsWith("error-context.md")??!1)}function Ck(r){let t=r.split(/\r?\n/),e=t.some(s=>lf.test(s.trim())),n=!e,i;for(let s=0;s<t.length;s+=1){let o=(t[s]??"").trim();if(i===void 0){if(lf.test(o)){n=!0;continue}if(Ek.test(o)){if(n&&e)break;continue}n&&/^```ya?ml\s*$/i.test(o)&&(i=s+1);continue}if(o==="```")return{scope:e?"page":"element",lines:t.slice(i,s),startLine:i+1,endLine:s}}}function sd(r){return r.length-r.trimStart().length}function ad(r,t,e){let n=[],i=r,s=/^(\s*-\s+)([\w-]+)(\s+"((?:[^"\\]|\\.)*)")(.*?):\s+(.+)$/.exec(i);if(s!==null&&Ak.has(s[2]??"")){let d=(s[4]??"").toLowerCase(),c=[...e].map(l=>l.toLowerCase()).sort().find(l=>d.includes(l));c!==void 0&&(i=`${s[1]}${s[2]}${s[3]}${s[5]}: [REDACTED]`,n.push({redactionId:$("red",["accessibility",t,`field:${c}`]),ruleId:`sensitive-field:${c}`,channel:"accessibility",locator:t,action:"mask",count:1}))}let a=/^(\s*-\s+\/url:\s+)(.+)$/.exec(i);if(a!==null){let d=(a[2]??"").replace(/^"(.*)"$/,"$1"),c=Nt(d,"accessibility",t,e);i=`${a[1]}${c.value}`,n.push(...c.records)}let o=ae(i,"accessibility",t,e);return{value:o.value,records:[...n,...o.records]}}function Nk(r,t,e){if(r.reduce((u,p)=>u+Buffer.byteLength(p,"utf8")+1,0)<=e)return{lines:r,dropped:0};let i=[...new Set(t.flatMap(u=>Er(u)))],s=new Set,a=u=>{s.add(u);let p=sd(r[u]??"");for(let f=u-1;f>=0&&p>0;f-=1){let h=sd(r[f]??"");h<p&&(s.add(f),p=h)}};r.forEach((u,p)=>{let f=u.toLowerCase();if(i.some(h=>f.includes(h)))for(let h=Math.max(0,p-uf);h<=Math.min(r.length-1,p+uf);h+=1)a(h)});let o=[...s].reduce((u,p)=>u+Buffer.byteLength(r[p]??"","utf8")+1,0);for(let u=0;u<r.length&&o<e;u+=1){if(s.has(u))continue;let p=Buffer.byteLength(r[u]??"","utf8")+1;if(o+p>e)break;s.add(u),o+=p}let d=[],c=!1,l=0;for(let u=0;u<r.length;u+=1){if(!s.has(u)){c=!0;continue}let p=r[u]??"",f=Buffer.byteLength(p,"utf8")+1;if(l+f>e){c=!0;break}c&&d.push(`${" ".repeat(sd(p))}\u2026`),c=!1,d.push(p),l+=f}return c&&d.push("\u2026"),{lines:d,dropped:r.length-d.filter(u=>u.trim()!=="\u2026").length}}async function ff(r,t,e,n){let{attachment:i}=e,s=we(r,"accessibility",`${e.attemptId}:${i.attachmentId}`),a=`${e.attemptId}.attachments[${i.sourceIndex}]`,o={artifactId:s,channel:"accessibility",availability:"present",format:"playwright-error-context",attemptId:e.attemptId,warnings:[]},d=(I,R,E)=>({omissionId:$("omi",[e.attemptId,"accessibility",I,a,R]),channel:"accessibility",reason:I,message:R,locator:a,...E===void 0?{}:{cap:E}}),c,l;if(i.path!==void 0){let I=await K(n,i.path,t.maxArtifactBytes);if(I.kind!=="read"){let R=I.kind==="over-budget"?"budget-exceeded":I.kind==="unauthorized"?"unauthorized-path":I.kind;return{artifacts:[{...o,availability:I.kind==="unavailable"?"unavailable":"unreadable",path:i.path,warnings:[I.message]}],evidence:[],redactions:[],omissions:[d(R,I.message)]}}c=I.bytes,l=I.relativePath}else i.bodyBase64!==void 0&&i.bodyBase64.length>0&&(c=new Uint8Array(Buffer.from(i.bodyBase64,"base64")));if(c===void 0)return{artifacts:[{...o,availability:"unavailable"}],evidence:[],redactions:[],omissions:[d("unavailable","The error context attachment has no path or body.")]};let u=Te(c),p={...o,sha256:u,...l===void 0?{}:{path:l}},f=_e(c),h=f===void 0?void 0:Ck(ut(f));if(h===void 0||h.lines.every(I=>I.trim()===""))return{artifacts:[{...p,availability:f===void 0?"unreadable":"empty"}],evidence:[],redactions:[],omissions:[d(f===void 0?"unreadable":"unrecognized",f===void 0?"The error context is not valid UTF-8.":"The error context has no page snapshot section.")]};let g=[],m=h.lines.map((I,R)=>{let E=ad(I.replace(Sk,""),`${a}#line=${h.startLine+R}`,t.sensitiveNames);return g.push(...E.records),E.value}),y=Nk(m,e.focus,t.maxDomTextBytes),w=[];y.dropped>0&&w.push(d("budget-exceeded",`Kept ${m.length-y.dropped} of ${m.length} page snapshot lines, favouring those that mention the failed locator.`,t.maxDomTextBytes));let x=`${h.scope==="page"?"Accessibility snapshot of the page when the test failed":"Accessibility snapshot of the element the failed assertion checked"}:
37
+ ${P.body}`,"diff",C,e.sensitiveNames);v+=Buffer.byteLength(M.value,"utf8"),w.push(...M.records);let z={type:"diff-hunk",...P.commit===void 0?{}:{commit:P.commit},path:P.path,oldStart:P.oldStart,oldLines:P.oldLines,newStart:P.newStart,newLines:P.newLines};y.push({evidenceId:he(r,s,"diff-hunk",z,M.value),kind:"diff-hunk",artifactId:s,locator:z,observation:M.value,availability:"present",redactionIds:M.records.map(k=>k.redactionId)})}let I=["uncommitted changes",...g===void 0?[]:[g.description]].join(" and "),R=g===void 0?{listed:[],total:0}:await Ak(d,g,t),E=await Sk(d,c),A=[...R.listed.length===0?[]:[`${R.total>R.listed.length?`The newest ${R.listed.length} of the ${R.total} commits searched`:"Commits searched, newest first"}: ${R.listed.join("; ")}.`],...E.length===0?[]:[`Source files with uncommitted changes: ${E.join(", ")}.`]],O=y.length,j=oe(`Searched ${I} for changed lines containing any of: ${n.map(P=>JSON.stringify(P)).join(", ")}. ${O===0?"No change mentioned them.":`${O} changed hunk${O===1?"":"s"} matched${m>0?`, from ${m} commit${m===1?"":"s"}`:""}${p.some(P=>P.commit===void 0)?" and uncommitted changes":""}.`}${A.map(P=>` ${P}`).join("")} A matching change shows what changed, not who owns the failure.`,"diff","changes:search",e.sensitiveNames);w.push(...j.records);let V={type:"report-field",path:"changes"};return y.push({evidenceId:he(r,s,"change-search",V,j.value),kind:"change-search",artifactId:s,locator:V,observation:j.value,availability:"present",redactionIds:j.records.map(P=>P.redactionId)}),{artifacts:[a(O===0?"empty":"present",u)],evidence:y,redactions:w,omissions:x}}var Ek=[137,80,78,71,13,10,26,10];function Ck(r){return r<192||r>207?!1:r!==196&&r!==200&&r!==204}function Nk(r){if(r.byteLength<24||Ek.some((e,n)=>r[n]!==e))return;let t=new DataView(r.buffer,r.byteOffset,r.byteLength);if(String.fromCharCode(...r.subarray(12,16))==="IHDR")return{width:t.getUint32(16,!1),height:t.getUint32(20,!1)}}function Ok(r){if(r.byteLength<4||r[0]!==255||r[1]!==216)return;let t=new DataView(r.buffer,r.byteOffset,r.byteLength),e=2;for(;e+9<r.byteLength;){if(r[e]!==255){e+=1;continue}let n=r[e+1];if(n===void 0)return;if(n===216||n===1||n>=208&&n<=215){e+=2;continue}let i=t.getUint16(e+2,!1);if(Ck(n))return{height:t.getUint16(e+5,!1),width:t.getUint16(e+7,!1)};if(i<2)return;e+=2+i}}function Dk(r){if(r.byteLength<30)return;let t=(i,s)=>String.fromCharCode(...r.subarray(i,s));if(t(0,4)!=="RIFF"||t(8,12)!=="WEBP")return;let e=new DataView(r.buffer,r.byteOffset,r.byteLength),n=t(12,16);if(n==="VP8X"){let i=1+(e.getUint16(24,!0)|e.getUint8(26)<<16),s=1+(e.getUint16(27,!0)|e.getUint8(29)<<16);return{width:i,height:s}}if(n==="VP8 ")return{width:e.getUint16(26,!0)&16383,height:e.getUint16(28,!0)&16383};if(n==="VP8L"){let i=e.getUint32(21,!0);return{width:1+(i&16383),height:1+(i>>14&16383)}}}function hf(r){return Nk(r)??Ok(r)??Dk(r)}function Lk(r){let t=r.toLowerCase().split(";")[0]?.trim()??"";if(t.startsWith("image/"))return"screenshot";if(t.startsWith("video/"))return"video"}function ff(r,t,e,n,i){return{omissionId:$("omi",[r.attemptId,t,e,i,n]),channel:t,reason:e,message:n,locator:i}}async function mf(r,t,e,n){let{attachment:i}=e,s=Lk(i.contentType);if(s===void 0)return{artifacts:[],evidence:[],redactions:[],omissions:[]};let a=`${e.attemptId}.attachments[${i.sourceIndex}]`,o=we(r,s,`${e.attemptId}:${i.attachmentId}`),d={artifactId:o,channel:s,attemptId:e.attemptId,format:i.contentType},c,l,u;if(i.path!==void 0){let x=await W(n,i.path,t.maxArtifactBytes);x.kind==="read"?(c=x.bytes,l=x.relativePath):u={reason:x.kind==="over-budget"?"budget-exceeded":x.kind==="unauthorized"?"unauthorized-path":x.kind,message:x.message}}else if(i.bodyBase64!==void 0&&i.bodyBase64.length>0){let x=Buffer.from(i.bodyBase64,"base64");x.byteLength>t.maxArtifactBytes?u={reason:"budget-exceeded",message:`Inline attachment exceeds the ${t.maxArtifactBytes}-byte limit.`}:c=new Uint8Array(x)}else u={reason:"unavailable",message:"Attachment supplied neither a path nor a body."};let p=oe(i.name,s,a,t.sensitiveNames);if(c===void 0){let x=u?.reason??"unavailable";return{artifacts:[{...d,availability:x==="unavailable"?"unavailable":"unreadable",...i.path===void 0?{}:{path:i.path},warnings:u===void 0?[]:[u.message]}],evidence:[],redactions:p.records,omissions:[ff(e,s,x,u?.message??"Attachment is unavailable.",a)]}}let f=Te(c),h=s==="screenshot"?hf(c):void 0,g=[`${s} name=${p.value}`,`contentType=${i.contentType}`,`bytes=${c.byteLength}`,...s==="screenshot"?[h===void 0?"dimensions=unknown":`dimensions=${h.width}x${h.height}`]:[],`sha256=${f}`],m={type:"media",attachmentId:i.attachmentId,sha256:f},y=g.join(" "),w=[];return s==="screenshot"&&h===void 0&&w.push(ff(e,s,"unreadable","Image dimensions could not be read from the container header.",a)),{artifacts:[{...d,availability:"present",...l===void 0?{}:{path:l},sha256:f,warnings:[]}],evidence:[{evidenceId:he(r,o,s==="screenshot"?"image-metadata":"video-metadata",m,y),kind:s==="screenshot"?"image-metadata":"video-metadata",artifactId:o,logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:m,observation:y,availability:"present",redactionIds:p.records.map(x=>x.redactionId)}],redactions:p.records,omissions:w}}var Mk=new Set(["textbox","searchbox","combobox","spinbutton"]),$k=/\s\[(?:ref=[^\]]+|cursor=[^\]]+)\]/g,yf=/^#{1,3}\s+page snapshot\s*$/i,_k=/^#{1,3}\s+\S/,gf=2;function wf(r){let t=r.contentType.toLowerCase().split(";")[0]?.trim()??"";return r.name==="error-context"?!0:t==="text/markdown"&&(r.path?.endsWith("error-context.md")??!1)}function Fk(r){let t=r.split(/\r?\n/),e=t.some(s=>yf.test(s.trim())),n=!e,i;for(let s=0;s<t.length;s+=1){let o=(t[s]??"").trim();if(i===void 0){if(yf.test(o)){n=!0;continue}if(_k.test(o)){if(n&&e)break;continue}n&&/^```ya?ml\s*$/i.test(o)&&(i=s+1);continue}if(o==="```")return{scope:e?"page":"element",lines:t.slice(i,s),startLine:i+1,endLine:s}}}function ld(r){return r.length-r.trimStart().length}function ud(r,t,e){let n=[],i=r,s=/^(\s*-\s+)([\w-]+)(\s+"((?:[^"\\]|\\.)*)")(.*?):\s+(.+)$/.exec(i);if(s!==null&&Mk.has(s[2]??"")){let d=(s[4]??"").toLowerCase(),c=[...e].map(l=>l.toLowerCase()).sort().find(l=>d.includes(l));c!==void 0&&(i=`${s[1]}${s[2]}${s[3]}${s[5]}: [REDACTED]`,n.push({redactionId:$("red",["accessibility",t,`field:${c}`]),ruleId:`sensitive-field:${c}`,channel:"accessibility",locator:t,action:"mask",count:1}))}let a=/^(\s*-\s+\/url:\s+)(.+)$/.exec(i);if(a!==null){let d=(a[2]??"").replace(/^"(.*)"$/,"$1"),c=Ot(d,"accessibility",t,e);i=`${a[1]}${c.value}`,n.push(...c.records)}let o=oe(i,"accessibility",t,e);return{value:o.value,records:[...n,...o.records]}}function jk(r,t,e){if(r.reduce((u,p)=>u+Buffer.byteLength(p,"utf8")+1,0)<=e)return{lines:r,dropped:0};let i=[...new Set(t.flatMap(u=>Nr(u)))],s=new Set,a=u=>{s.add(u);let p=ld(r[u]??"");for(let f=u-1;f>=0&&p>0;f-=1){let h=ld(r[f]??"");h<p&&(s.add(f),p=h)}};r.forEach((u,p)=>{let f=u.toLowerCase();if(i.some(h=>f.includes(h)))for(let h=Math.max(0,p-gf);h<=Math.min(r.length-1,p+gf);h+=1)a(h)});let o=[...s].reduce((u,p)=>u+Buffer.byteLength(r[p]??"","utf8")+1,0);for(let u=0;u<r.length&&o<e;u+=1){if(s.has(u))continue;let p=Buffer.byteLength(r[u]??"","utf8")+1;if(o+p>e)break;s.add(u),o+=p}let d=[],c=!1,l=0;for(let u=0;u<r.length;u+=1){if(!s.has(u)){c=!0;continue}let p=r[u]??"",f=Buffer.byteLength(p,"utf8")+1;if(l+f>e){c=!0;break}c&&d.push(`${" ".repeat(ld(p))}\u2026`),c=!1,d.push(p),l+=f}return c&&d.push("\u2026"),{lines:d,dropped:r.length-d.filter(u=>u.trim()!=="\u2026").length}}async function bf(r,t,e,n){let{attachment:i}=e,s=we(r,"accessibility",`${e.attemptId}:${i.attachmentId}`),a=`${e.attemptId}.attachments[${i.sourceIndex}]`,o={artifactId:s,channel:"accessibility",availability:"present",format:"playwright-error-context",attemptId:e.attemptId,warnings:[]},d=(I,R,E)=>({omissionId:$("omi",[e.attemptId,"accessibility",I,a,R]),channel:"accessibility",reason:I,message:R,locator:a,...E===void 0?{}:{cap:E}}),c,l;if(i.path!==void 0){let I=await W(n,i.path,t.maxArtifactBytes);if(I.kind!=="read"){let R=I.kind==="over-budget"?"budget-exceeded":I.kind==="unauthorized"?"unauthorized-path":I.kind;return{artifacts:[{...o,availability:I.kind==="unavailable"?"unavailable":"unreadable",path:i.path,warnings:[I.message]}],evidence:[],redactions:[],omissions:[d(R,I.message)]}}c=I.bytes,l=I.relativePath}else i.bodyBase64!==void 0&&i.bodyBase64.length>0&&(c=new Uint8Array(Buffer.from(i.bodyBase64,"base64")));if(c===void 0)return{artifacts:[{...o,availability:"unavailable"}],evidence:[],redactions:[],omissions:[d("unavailable","The error context attachment has no path or body.")]};let u=Te(c),p={...o,sha256:u,...l===void 0?{}:{path:l}},f=_e(c),h=f===void 0?void 0:Fk(ut(f));if(h===void 0||h.lines.every(I=>I.trim()===""))return{artifacts:[{...p,availability:f===void 0?"unreadable":"empty"}],evidence:[],redactions:[],omissions:[d(f===void 0?"unreadable":"unrecognized",f===void 0?"The error context is not valid UTF-8.":"The error context has no page snapshot section.")]};let g=[],m=h.lines.map((I,R)=>{let E=ud(I.replace($k,""),`${a}#line=${h.startLine+R}`,t.sensitiveNames);return g.push(...E.records),E.value}),y=jk(m,e.focus,t.maxDomTextBytes),w=[];y.dropped>0&&w.push(d("budget-exceeded",`Kept ${m.length-y.dropped} of ${m.length} page snapshot lines, favouring those that mention the failed locator.`,t.maxDomTextBytes));let x=`${h.scope==="page"?"Accessibility snapshot of the page when the test failed":"Accessibility snapshot of the element the failed assertion checked"}:
38
38
  ${y.lines.join(`
39
- `)}`,v={type:"attachment-text",attachmentId:i.attachmentId,sha256:u,startLine:h.startLine,endLine:h.endLine};return{artifacts:[p],evidence:[{evidenceId:he(r,s,"page-snapshot",v,x),kind:"page-snapshot",artifactId:s,logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:v,observation:x,availability:"present",redactionIds:g.map(I=>I.redactionId)}],redactions:g,omissions:w}}var Ok=256*1024,Dk=10,hf=200;async function mf(r,t,e,n){let i=we(r.runId,"probe",e),s=(h,g,m=e)=>({omissionId:$("omi",[r.runId,"probe",h,m,g]),channel:"probe",reason:h,message:g,locator:m}),a=await K(n,e,Ok);if(a.kind!=="read")return{artifacts:[{artifactId:i,channel:"probe",availability:"unavailable",warnings:[a.message]}],evidence:[],redactions:[],omissions:[s("unavailable",a.message)]};let o={artifactId:i,channel:"probe",availability:"present",path:a.relativePath,sha256:a.sha256,format:"kwikqa-playwright-cli-probe",warnings:[]},d;try{d=pe(JSON.parse(_e(a.bytes)??""))}catch{d=void 0}if(d===void 0||_(d.schemaVersion)!=="1.0")return{artifacts:[{...o,availability:"unreadable"}],evidence:[],redactions:[],omissions:[s("unrecognized","The probe results are not in a recognized format.")]};let c=pe(d.tool),l=`Playwright CLI ${_(c?.version)??"unknown"}, Playwright ${_(d.playwrightVersion)??"unknown"}`,u=[],p=[],f=[];return He(d.results)?.forEach((h,g)=>{let m=pe(h);if(m===void 0)return;let y=_(m.logicalTestId),w=r.logicalTests.find(P=>P.logicalTestId===y)??r.logicalTests.find(P=>P.title===_(m.title)&&P.location.file===_(m.file)&&P.location.line===ke(m.line)),x=w?.attempts.at(-1),v=`${a.relativePath}#results[${g}]`;for(let P of He(m.issues)??[]){let O=_(P);O!==void 0&&f.push(s("unavailable",`Live probe of "${_(m.title)??"a test"}": ${O}`,v))}let I=(He(m.candidates)??[]).map(P=>pe(P)).filter(P=>P!==void 0).slice(0,Dk);if(w===void 0||I.length===0)return;let R=[],E=[];I.forEach((P,O)=>{let M=ad(`- ${(_(P.element)??"").slice(0,hf)}`,`${v}/candidates[${O}]`,t.sensitiveNames),H=ae((_(P.locator)??"").slice(0,hf),"probe",`${v}/candidates[${O}]/locator`,t.sensitiveNames);p.push(...M.records,...H.records),E.push(...M.records.map(k=>k.redactionId),...H.records.map(k=>k.redactionId)),R.push(`${M.value.replace(/^- /,"")} \u2192 ${H.value}`)});let A=_(m.locator),B=[`Live page paused at ${`${_(m.file)??w.location.file}:${ke(m.failingLine)??"?"}`}, before the failing step (${l}).${A===void 0?"":` The failed locator was ${A}.`} Locators Playwright generated for the elements most like it:`,...R].join(`
40
- `),V={type:"report-field",path:`probe.results[${g}]`};u.push({evidenceId:he(r.runId,i,"locator-suggestion",V,B),kind:"locator-suggestion",artifactId:i,logicalTestId:w.logicalTestId,...x===void 0?{}:{attemptId:x.attemptId},locator:V,observation:B,availability:"present",redactionIds:E})}),{artifacts:[{...o,availability:u.length>0?"present":"empty"}],evidence:u,redactions:p,omissions:f}}var Lk=/(?:\(|\bat\s+|^)((?:[A-Za-z]:)?[^():\s][^():]*?):(\d+):(\d+)\)?\s*$/;function od(r,t,e){let n=[];return r.split(/\r?\n/).forEach((i,s)=>{let a=Lk.exec(i.trim().replace(/webpack:\/\/[^/\s()]*\//g,""));if(a===null)return;let[,o,d,c]=a;o===void 0||d===void 0||c===void 0||n.push({file:o.replace(/^file:\/\//,"").replace(/^(?:\.\/)+/,""),line:Number.parseInt(d,10),column:Number.parseInt(c,10),origin:`${t}#frame=${s+1}`,...e})}),n}function Fn(r,t,e,n,i,s,a){let o=`${n}:${i}`;if(e.reported.has(o))return;e.reported.add(o);let d=`Reached the ${s}-${i} limit; later observations were not included.`;t.push({omissionId:$("omi",[r.runId,n,"budget-exceeded",a,d]),channel:n,reason:"budget-exceeded",message:d,locator:a,cap:s})}function dd(r,t,e){return r===void 0?[]:[{file:r.file,line:r.line??1,...r.column===void 0?{}:{column:r.column},origin:t,...e}]}function cd(r,t,e){let n=[...dd(r.location,`${t}.location`,e)];return r.stack!==void 0&&n.push(...od(r.stack,`${t}.stack`,e)),n}function yf(r,t,e){let n=[];return r.forEach((i,s)=>{let a=`${t}[${s}]`;i.error!==void 0&&n.push(...cd(i.error,a,e)),n.push(...yf(i.steps,`${a}.steps`,e))}),n}function Mk(r){let t=[];for(let e of r.logicalTests){for(let n of e.attempts){let i={logicalTestId:e.logicalTestId,attemptId:n.attemptId};t.push(...dd(n.errorLocation,`${n.attemptId}.errorLocation`,i));for(let s of n.errors)t.push(...cd(s,s.source,i));t.push(...yf(n.steps,`${n.attemptId}.steps`,i))}t.push(...dd(e.location,`${e.logicalTestId}.location`,{logicalTestId:e.logicalTestId}))}for(let e of r.reportErrors)t.push(...cd(e,e.source,{}));return t}function os(r,t,e,n,i,s,a,o,d,c,l){if(c.reportFields>=t.maxReportFields){Fn(r,d,c,"report","field",t.maxReportFields,i);return}c.reportFields+=1;let u=ae(s,e.channel,i,t.sensitiveNames);o.push(...u.records);let p={type:"report-field",path:i};a.push({evidenceId:he(r.runId,e.artifactId,n,p,u.value),kind:n,artifactId:e.artifactId,...l,locator:p,observation:u.value,availability:u.value.length===0?"empty":"present",redactionIds:u.records.map(f=>f.redactionId)})}function ld(r,t,e,n,i,s,a,o,d){let c=[["name",n.name],["message",n.message],["value",n.value],["snippet",n.snippet]];for(let[l,u]of c)u!==void 0&&os(r,t,e,"error-field",`${n.source}.${l}`,u,i,s,a,o,d);n.stack!==void 0&&(os(r,t,e,"error-field",`${n.source}.stack`,n.stack,i,s,a,o,d),n.stack.split(/\r?\n/).forEach((l,u)=>{if(l.trim().length===0)return;let p=`${n.source}.stack#line=${u+1}`;if(o.stackFrames>=t.maxStackFrames){Fn(r,a,o,"report","stack-frame",t.maxStackFrames,p);return}o.stackFrames+=1,os(r,t,e,"stack-frame",p,l,i,s,a,o,d)}))}function gf(r,t,e,n,i,s,a,o,d,c){n.forEach((l,u)=>{let p=`${i}[${u}]`;if(d.steps>=t.maxSteps){Fn(r,o,d,"report","step",t.maxSteps,p);return}d.steps+=1,os(r,t,e,"step",`${p}.title`,l.title,s,a,o,d,c),l.error!==void 0&&ld(r,t,e,l.error,s,a,o,d,c),gf(r,t,e,l.steps,`${p}.steps`,s,a,o,d,c)})}function $k(r){if(r.kind==="text")return r.text;let t=Buffer.from(r.base64,"base64");return`binary stdio: sha256=${Te(t)} bytes=${t.byteLength}`}function wf(r,t){let e={artifactId:we(r.runId,"report",r.artifact.artifactId),channel:"report",availability:r.artifact.availability,...r.artifact.path===void 0?{}:{path:r.artifact.path},...r.artifact.sha256===void 0?{}:{sha256:r.artifact.sha256},...r.artifact.formatVersion===void 0?{}:{producerVersion:r.artifact.formatVersion},warnings:r.artifact.warnings},n=[e],i=[],s=[],a=[],o={reportFields:0,stackFrames:0,steps:0,stdioChunks:0,stdioBytes:0,reported:new Set};r.reportErrors.forEach(d=>{ld(r,t,e,d,i,s,a,o,{})});for(let d of r.logicalTests)for(let c of d.attempts){let l={logicalTestId:d.logicalTestId,attemptId:c.attemptId};c.errors.forEach(u=>{ld(r,t,e,u,i,s,a,o,l)}),gf(r,t,e,c.steps,`${c.attemptId}.steps`,i,s,a,o,l);for(let u of["stdout","stderr"]){let p=c[u],f={artifactId:we(r.runId,u,c.attemptId),channel:u,availability:p.length===0?"empty":"present",attemptId:c.attemptId,warnings:[]};n.push(f);let h=0;p.forEach((g,m)=>{let y=g.kind==="text"?Buffer.byteLength(g.text,"utf8"):Buffer.from(g.base64,"base64").byteLength,w=`${c.attemptId}.${u}[${m}]`;if(o.stdioChunks>=t.maxStdioChunks){Fn(r,a,o,u,"stdio-chunk",t.maxStdioChunks,w),h+=y;return}if(o.stdioBytes+y>t.maxStdioBytes){Fn(r,a,o,u,"stdio-byte",t.maxStdioBytes,w),h+=y;return}o.stdioChunks+=1,o.stdioBytes+=y;let x=$k(g),v=ae(x,u,w,t.sensitiveNames);s.push(...v.records);let I={type:"stdio",stream:u,chunk:m,startByte:h,endByte:h+y};h+=y,i.push({evidenceId:he(r.runId,f.artifactId,"stdio-chunk",I,v.value),kind:"stdio-chunk",artifactId:f.artifactId,...l,locator:I,observation:v.value,availability:x.length===0?"empty":"present",redactionIds:v.records.map(R=>R.redactionId)})})}}return{artifacts:n,evidence:i,redactions:s,omissions:a,seeds:Mk(r)}}var Pf=bi(Pn(),1);import{dirname as _k,extname as If,join as bf}from"node:path/posix";var Fk=new Set(["test","it","describe","suite","step","beforeEach","afterEach","beforeAll","afterAll"]),xf=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],jk=new Set([".js",".mjs",".cjs"]),Bk=[".ts",".tsx",".mts",".cts"];function Vk(r){return r.split("/").includes("node_modules")}function qe(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof r.type=="string"}function jn(r,t,e=new Set){if(!e.has(r)){e.add(r),t(r);for(let n of Object.keys(r)){if(n==="loc")continue;let i=r[n];if(Array.isArray(i))for(let s of i)qe(s)&&jn(s,t,e);else qe(i)&&jn(i,t,e)}}}function er(r){if(qe(r)&&r.type==="Identifier")return typeof r.name=="string"?r.name:void 0}function Mr(r){if(qe(r)){if(r.type==="Identifier"&&typeof r.name=="string")return r.name;if(r.type==="StringLiteral"&&typeof r.value=="string")return r.value}}function Rf(r){if(qe(r)){if(r.type==="Identifier")return typeof r.name=="string"?r.name:void 0;if(r.type==="MemberExpression"){let t=Rf(r.object),e=Mr(r.property);return t===void 0||e===void 0?void 0:`${t}.${e}`}}}function zk(r){let t=Rf(r.callee);if(t===void 0)return;let e=t.split(".").pop()??t;if(!Fk.has(e))return;let i=(Array.isArray(r.arguments)?r.arguments:[])[0];if(!(!qe(i)||i.type!=="StringLiteral"||typeof i.value!="string"))return`${t}("${i.value}")`}function Tf(r){switch(r.type){case"FunctionDeclaration":case"ClassDeclaration":case"TSInterfaceDeclaration":case"TSTypeAliasDeclaration":case"TSEnumDeclaration":case"TSModuleDeclaration":return er(r.id);case"ClassMethod":case"ObjectMethod":case"ClassProperty":case"PropertyDefinition":return Mr(r.key);case"VariableDeclarator":return er(r.id);case"CallExpression":return zk(r);default:return}}function Hk(r,t){let e=r.loc;return e==null?!1:e.start.line<=t&&e.end.line>=t}function qk(r,t){let e;return jn(r,n=>{let i=Tf(n);if(i===void 0||!Hk(n,t))return;let s=n.loc;if(s==null)return;let a={name:i,startLine:s.start.line,endLine:s.end.line};if(e===void 0){e=a;return}let o=a.endLine-a.startLine,d=e.endLine-e.startLine;o<d&&(e=a)}),e}function Uk(r){let t=Tf(r);return t!==void 0&&r.type!=="CallExpression"?[t]:r.type==="VariableDeclaration"&&Array.isArray(r.declarations)?r.declarations.map(e=>qe(e)?er(e.id):void 0).filter(e=>e!==void 0):[]}function Gk(r,t){let e=Array.isArray(r.program)?[]:r.program?.body,n=Array.isArray(e)?e:[],i=[];for(let s of n){if(!qe(s))continue;let a=s.loc;if(a==null)continue;if(s.type==="ExportDefaultDeclaration"&&t.has("default")){i.push({name:"default",startLine:a.start.line,endLine:a.end.line});continue}if(s.type==="ExportNamedDeclaration"&&Array.isArray(s.specifiers))for(let d of s.specifiers){if(!qe(d))continue;let c=Mr(d.exported);c!==void 0&&t.has(c)&&i.push({name:c,startLine:a.start.line,endLine:a.end.line})}let o=s.type==="ExportNamedDeclaration"&&qe(s.declaration)?s.declaration:s;for(let d of Uk(o))t.has(d)&&i.push({name:d,startLine:a.start.line,endLine:a.end.line})}return i}function Kk(r){let t=[];return jn(r,e=>{if(e.type!=="ImportDeclaration"&&e.type!=="ExportNamedDeclaration"&&e.type!=="ExportAllDeclaration")return;let n=qe(e.source)?e.source.value:void 0;if(typeof n!="string")return;let i=[],s;for(let a of Array.isArray(e.specifiers)?e.specifiers:[])if(qe(a)){if(e.type==="ExportNamedDeclaration"){let o=Mr(a.exported),d=Mr(a.local);o!==void 0&&d!==void 0&&i.push({imported:d,local:o})}else if(a.type==="ImportDefaultSpecifier"){let o=er(a.local);o!==void 0&&i.push({imported:"default",local:o})}else if(a.type==="ImportNamespaceSpecifier")s=er(a.local);else if(a.type==="ImportSpecifier"){let o=Mr(a.imported)??er(a.local),d=er(a.local);o!==void 0&&d!==void 0&&i.push({imported:o,local:d})}}t.push({specifier:n,bindings:i,...s===void 0?{}:{namespaceLocal:s},exportStar:e.type==="ExportAllDeclaration"})}),t}function vf(r,t,e){let n=new Set;return jn(r,i=>{let s=i.loc;s==null||s.end.line<t||s.start.line>e||i.type==="Identifier"&&typeof i.name=="string"&&n.add(i.name)}),n}function Wk(r){let t=If(r).toLowerCase();return t===".tsx"?["typescript","jsx"]:[".ts",".mts",".cts"].includes(t)?["typescript"]:["jsx"]}function Jk(r,t){try{return{ast:(0,Pf.parse)(r,{sourceType:"module",allowReturnOutsideFunction:!0,errorRecovery:!1,plugins:Wk(t)})}}catch(e){return{error:e instanceof Error?e.message:"Source could not be parsed."}}}function Xk(r,t){if(!r.startsWith("./")&&!r.startsWith("../"))return[];let e=bf(t,r),n=[e],i=If(e).toLowerCase();if(jk.has(i)){let s=e.slice(0,e.length-i.length);for(let a of Bk)n.push(`${s}${a}`)}if(i===""){for(let s of xf)n.push(`${e}${s}`);for(let s of xf)n.push(bf(e,`index${s}`))}return n}function rt(r,t,e,n,i){r.omissions.push({omissionId:$("omi",["source",t,n,e]),channel:"source",reason:t,message:e,locator:n,...i===void 0?{}:{cap:i}})}async function Af(r,t){let e=await Cn(r.workspaceRoot,t);if(e.kind!=="authorized"){rt(r,e.kind==="unauthorized"?"unauthorized-path":e.kind,e.message,t);return}if(Vk(e.relativePath)){rt(r,"policy-disabled","Dependency source under node_modules is out of scope for evidence.",e.relativePath);return}let n=r.files.get(e.relativePath);if(n!==void 0)return n;if(r.files.size>=r.policy.maxSourceFiles){r.filesReported||(r.filesReported=!0,rt(r,"budget-exceeded",`Reached the ${r.policy.maxSourceFiles}-file source limit; later files were not read.`,e.relativePath,r.policy.maxSourceFiles));return}let i=await K(r.workspaceRoot,e.relativePath,r.policy.maxArtifactBytes);if(i.kind!=="read"){let c=i.kind==="over-budget"?"budget-exceeded":i.kind==="unauthorized"?"unauthorized-path":i.kind;rt(r,c,i.message,e.relativePath);return}let s=_e(i.bytes);if(s===void 0){rt(r,"unreadable","Source file is not valid UTF-8.",i.relativePath);return}let a=Jk(s,i.relativePath);a.error!==void 0&&rt(r,"parse-failed",`Symbol boundaries are unavailable: ${a.error}`,i.relativePath);let o={artifactId:we(r.runId,"source",i.relativePath),channel:"source",availability:"present",path:i.relativePath,sha256:i.sha256,warnings:a.error===void 0?[]:[a.error]},d={relativePath:i.relativePath,sha256:i.sha256,lines:s.split(/\r?\n/),ast:a.ast,artifact:o};return r.files.set(i.relativePath,d),r.artifacts.push(o),d}function kf(r,t,e,n,i){let s=r.policy.maxSourceLinesPerFile,a=Math.max(1,e.startLine),o=Math.min(t.lines.length,e.endLine);if(o<a)return;o-a+1>s&&(o=a+s-1,rt(r,"budget-exceeded",`Symbol context in ${t.relativePath} was truncated to ${s} lines.`,`${t.relativePath}:${a}`,s));let d=`${t.relativePath}:${a}:${o}:${i.logicalTestId??""}:${i.attemptId??""}:${n}`;if(r.emitted.has(d))return;r.emitted.add(d);let c=t.lines.slice(a-1,o).join(`
41
- `),l=ae(c,"source",`${t.relativePath}:${a}-${o}`,r.policy.sensitiveNames),u=Buffer.byteLength(l.value,"utf8");if(r.emittedBytes+u>r.policy.maxSourceBytes){r.bytesReported||(r.bytesReported=!0,rt(r,"budget-exceeded",`Reached the ${r.policy.maxSourceBytes}-byte source limit; later ranges were not included.`,t.relativePath,r.policy.maxSourceBytes));return}r.emittedBytes+=u,r.redactions.push(...l.records);let p=t.lines[o-1]??"",f={type:"source-range",path:t.relativePath,sha256:t.sha256,startLine:a,startColumn:1,endLine:o,endColumn:p.length+1,...e.symbol===void 0?{}:{symbol:e.symbol}},h=`${n}
42
- ${l.value}`;r.evidence.push({evidenceId:he(r.runId,t.artifact.artifactId,"source-range",f,h),kind:"source-range",artifactId:t.artifact.artifactId,...i,locator:f,observation:h,availability:"present",redactionIds:l.records.map(g=>g.redactionId)})}async function Yk(r,t,e){for(let n of Xk(t,e)){let i=await Cn(r.workspaceRoot,n);if(i.kind==="authorized")return await Af(r,i.relativePath)}rt(r,"unavailable",`Relative import ${t} did not resolve to a readable workspace file.`,e)}async function Sf(r,t,e,n){let i={runId:r,policy:t,workspaceRoot:n,files:new Map,artifacts:[],evidence:[],redactions:[],omissions:[],emitted:new Set,traversed:new Set,emittedBytes:0,filesReported:!1,bytesReported:!1},s=new Set,a=[];for(let d of e){let c=`${d.file}:${d.line}:${d.logicalTestId??""}:${d.attemptId??""}:${d.origin}`;if(s.has(c))continue;s.add(c);let l=await Af(i,d.file);if(l===void 0)continue;let u={...d.logicalTestId===void 0?{}:{logicalTestId:d.logicalTestId},...d.attemptId===void 0?{}:{attemptId:d.attemptId}},p=l.ast===void 0?void 0:qk(l.ast,d.line),f=Math.floor(t.maxSourceLinesPerFile/2),h=p??{name:void 0,startLine:Math.max(1,d.line-f),endLine:d.line+f};a.push({file:l,linkage:u,referenced:l.ast===void 0?new Set:vf(l.ast,h.startLine,h.endLine)}),kf(i,l,{startLine:h.startLine,endLine:h.endLine,...p===void 0?{}:{symbol:p.name}},`${l.relativePath}:${d.line} via ${d.origin}`,u)}let o=a;for(let d=1;d<=t.maxImportDepth;d+=1){let c=[];for(let l of o){let u=l.file;if(u.ast!==void 0)for(let p of Kk(u.ast)){let f=new Set(p.bindings.filter(x=>l.referenced.has(x.local)).map(x=>x.imported));if(p.namespaceLocal!==void 0&&l.referenced.has(p.namespaceLocal)){rt(i,"policy-disabled",`Namespace import of ${p.specifier} was not expanded; only named symbols are followed.`,u.relativePath);continue}if(p.exportStar){rt(i,"unrecognized",`Export-star from ${p.specifier} was not expanded because the exported symbol is ambiguous.`,u.relativePath);continue}if(f.size===0||!p.specifier.startsWith("."))continue;let h=await Yk(i,p.specifier,_k(u.relativePath));if(h===void 0||h.ast===void 0)continue;let g=l.linkage,m=`${h.relativePath}:${[...f].sort().join(",")}:${g.logicalTestId??""}:${g.attemptId??""}`;if(i.traversed.has(m))continue;i.traversed.add(m);let y=Gk(h.ast,f),w=new Set;for(let x of y){for(let v of vf(h.ast,x.startLine,x.endLine))w.add(v);kf(i,h,{startLine:x.startLine,endLine:x.endLine,symbol:x.name},`${h.relativePath} exports ${x.name}, imported by ${u.relativePath} (depth ${d})`,g)}c.some(x=>x.file===h&&x.linkage.attemptId===g.attemptId)||c.push({file:h,linkage:g,referenced:w})}}if(o=c,o.length===0)break}return{artifacts:i.artifacts,evidence:i.evidence,redactions:i.redactions,omissions:i.omissions}}var Qk=["report","trace","stdout","stderr","screenshot","video","dom","accessibility","console","network","source","diff","probe"],Zk={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"},eI=["trace","console","network","dom","accessibility"],tI=8,rI=12,nI=5,iI=/\b(?:getBy\w+|locator|frameLocator)\((?:[^()]|\([^()]*\))*\)/g,sI=[/Expected to find element: `([^`]+)`/g,/within the selector: '([^']+)'/g,/expected '<([a-z][\w-]*(?:[#.][\w-]+)*)>'/gi,/\bselector "([^"]+)"/g,/\belement \("([^"]+)"\)/g,/\${1,2}\(`([^`]+)`\)/g];function Bn(r){return Buffer.byteLength(JSON.stringify(r),"utf8")}function ds(r,t){return[...r].sort((e,n)=>t(e).localeCompare(t(n)))}function aI(r){return r.length===0?"unavailable":r.some(t=>t.availability==="present")?"present":r.some(t=>t.availability==="empty")?"empty":r.some(t=>t.availability==="unreadable")?"unreadable":"unavailable"}function oI(r,t,e,n,i){let s=t.filter(l=>l.channel===r),a=new Set(s.map(l=>l.artifactId)),o=e.filter(l=>a.has(l.artifactId)),d=n.filter(l=>l.channel===r),c=i.filter(l=>l.channel===r);return{channel:r,availability:aI(s),examined:o.length+d.length,included:o.length,omitted:d.length,observationBytes:o.reduce((l,u)=>l+Buffer.byteLength(u.observation,"utf8"),0),redactionCount:c.reduce((l,u)=>l+u.count,0),serializedBytes:Bn({artifacts:s,evidence:o,redactions:c,omissions:d})}}function Ef(r,t,e){return{omissionId:$("omi",[r,t,"unavailable",e]),channel:t,reason:"unavailable",message:e,locator:r}}function Cf(r,t){return t?.[r.attachmentId]!==void 0?!0:r.name==="trace"&&r.contentType==="application/zip"}function $r(r){return r.attempts.filter(t=>t.status==="interrupted"?!0:r.status==="unexpected"?t.status!=="skipped":r.status==="flaky"?t.status!=="passed"&&t.status!=="skipped":!1)}function dI(r){return{...r,logicalTests:r.logicalTests.map(t=>({...t,attempts:$r(t)})).filter(t=>t.attempts.length>0)}}function cI(r,t){let e={expected:0,unexpected:0,flaky:0,skipped:0};for(let a of r.logicalTests)e[a.status]+=1;let n=t.logicalTests.reduce((a,o)=>a+o.attempts.length,0),i=[...new Set(r.logicalTests.map(a=>a.projectId))].length,s=r.artifact.formatVersion===void 0?"":` ${r.artifact.formatVersion}`;return[`${Zk[r.framework]}${s} run of ${r.logicalTests.length} tests in ${i} project${i===1?"":"s"}`,`${e.expected} passed, ${e.unexpected} failed, ${e.flaky} flaky, ${e.skipped} skipped`,`evidence covers the ${n} failing attempt${n===1?"":"s"} of ${t.logicalTests.length} test${t.logicalTests.length===1?"":"s"}; passing tests are only counted.`].join("; ")}function Vn(r){let t=r.errors.map(n=>`${n.message??""}
43
- ${n.stack??""}`),e=t.flatMap(n=>sI.flatMap(i=>[...n.matchAll(i)].map(s=>s[1]??"")));return[...new Set([...t.flatMap(n=>n.match(iI)??[]),...e.filter(n=>n!=="")])]}function lI(r,t,e,n,i){let s=r.attemptId===void 0?0:n.get(r.attemptId)??0;if(i.has(r.evidenceId))return Z.afterFailure;switch(r.kind){case"error-field":case"run-summary":case"change-search":return Z.failure;case"locator-suggestion":return Z.failedCall+.95-Math.min(.5,s/1e3);case"page-snapshot":case"dom-subtree":case"dom-candidates":case"accessibility-node":{let o=r.kind==="accessibility-node"?.5:.9;return s<nI?Z.failedCall+o-s/1e3:Z.context+o-Math.min(.8,s/1e3)}default:break}let a=t.get(r.evidenceId);if(a!==void 0)return a;switch(r.kind){case"stack-frame":return/node_modules|node:internal/.test(r.observation)?Z.ordinary:Z.failedCall;case"source-range":{let o=e.get(r.evidenceId)??0;return Z.significant-Math.min(.9,o/100)}case"diff-hunk":return Z.failedCall+.9;case"step":return Z.context;default:return Z.ordinary}}async function cs(r,t,e){let n=$o(e);if(n!==void 0)return{kind:"invalid-policy",message:n};if(e.workspaceRoot!==r.workspace.root)return{kind:"invalid-policy",message:"Evidence policy workspaceRoot must match the normalized run workspace root."};let i=t.artifactRoot??r.workspace.root,s=dI(r),a=wf(s,e),o=[...a.artifacts],d=[...a.evidence],c=[...a.redactions],l=[...a.omissions],u=[...a.seeds],p=new Map,f=a.artifacts.find(A=>A.channel==="report");if(f!==void 0&&r.logicalTests.length>0){let A={type:"report-field",path:"stats"},N=cI(r,s);d.push({evidenceId:he(r.runId,f.artifactId,"run-summary",A,N),kind:"run-summary",artifactId:f.artifactId,locator:A,observation:N,availability:"present",redactionIds:[]})}for(let A of s.logicalTests)for(let N of A.attempts){let B=0,V=0,P=0,O=[...Vn(N)];for(let M of N.attachments){if(!Cf(M,t.tracePaths))continue;let H=t.tracePaths?.[M.attachmentId]??M.path;if(H===void 0){l.push(Ef(N.attemptId,"trace","Trace attachment supplied no path; inline trace bodies are not read."));continue}B+=1;let k=await $p(r.runId,e,{attachmentId:M.attachmentId,logicalTestId:A.logicalTestId,attemptId:N.attemptId,path:H,info:{...r.artifact.formatVersion===void 0?{}:{producerVersion:r.artifact.formatVersion},format:"playwright-trace-zip"}},i);o.push(...k.artifacts),d.push(...k.evidence),c.push(...k.redactions),l.push(...k.omissions),u.push(...k.seeds),O.push(...k.failedSelectors);for(let[T,L]of k.priorities)p.set(T,L)}for(let M of N.attachments){if(!Qo(M))continue;V+=1;let H=await jp(r.runId,e,{logicalTestId:A.logicalTestId,attemptId:N.attemptId,attachment:M,focus:O},i);o.push(...H.artifacts),d.push(...H.evidence),c.push(...H.redactions),l.push(...H.omissions),O.push(...H.failedSelectors);for(let[k,T]of H.priorities)p.set(k,T)}for(let M of N.attachments){if(Cf(M,t.tracePaths)||Qo(M))continue;if(pf(M)){P+=1;let k=await ff(r.runId,e,{logicalTestId:A.logicalTestId,attemptId:N.attemptId,attachment:M,focus:O},i);o.push(...k.artifacts),d.push(...k.evidence),c.push(...k.redactions),l.push(...k.omissions);continue}let H=await cf(r.runId,e,{logicalTestId:A.logicalTestId,attemptId:N.attemptId,attachment:M},i);o.push(...H.artifacts),d.push(...H.evidence),c.push(...H.redactions),l.push(...H.omissions)}if(B===0&&V===0){let M=r.framework==="playwright"?"Attempt produced no trace attachment.":"Attempt has no KwikQA failure capture; run `kwikqa analyze --capture` to record the page.";for(let H of eI)H==="accessibility"&&P>0||l.push(Ef(N.attemptId,H,M))}}if(t.probePath!==void 0){let A=await mf(s,e,t.probePath,r.workspace.root);o.push(...A.artifacts),d.push(...A.evidence),c.push(...A.redactions),l.push(...A.omissions)}let h=await Sf(r.runId,e,u,r.workspace.root);o.push(...h.artifacts),d.push(...h.evidence),c.push(...h.redactions),l.push(...h.omissions);let g=new Map(h.evidence.map((A,N)=>[A.evidenceId,N])),m=h.artifacts.map(A=>A.path).filter(A=>A!==void 0),y=await Bp(r.runId,e,m,{authorized:t.includeCurrentDiff===!0,workspaceRoot:r.workspace.root,...r.workspace.gitRoot===void 0?{}:{gitRoot:r.workspace.gitRoot}});o.push(...y.artifacts),d.push(...y.evidence),c.push(...y.redactions),l.push(...y.omissions);let w=await af(r.runId,r.createdAt,e,rf(s.logicalTests.flatMap(A=>A.attempts),Vn,d.filter(A=>A.kind==="network-event").map(A=>A.observation)),{authorized:t.includeChangeHistory===!0,workspaceRoot:r.workspace.root,...r.workspace.gitRoot===void 0?{}:{gitRoot:r.workspace.gitRoot}});o.push(...w.artifacts),d.push(...w.evidence),c.push(...w.redactions),l.push(...w.omissions);let x=ds(o,A=>A.artifactId),v=new Map(x.map(A=>[A.artifactId,A.channel])),I=(A,N,B)=>{let V=ds(A,T=>T.evidenceId),P=ds(N,T=>T.redactionId),O=ds(B,T=>T.omissionId),M=Qk.map(T=>oI(T,x,V,O,P)),H=T=>{let L={schemaVersion:"1.2",runId:r.runId,framework:r.framework,createdAt:r.createdAt,workspace:r.workspace,sourceHashes:r.sourceHashes,policy:e,artifacts:x,evidence:V,redactions:P,omissions:O,accounting:M,totals:{artifacts:x.length,evidence:V.length,redactions:P.length,omissions:O.length,serializedBytes:T}};return{...L,packetHash:Sr(L)}},k=H(0);for(let T=0;T<tI;T+=1){let L=Bn(k);if(k.totals.serializedBytes===L)break;k=H(L)}return k},R=I(d,c,l),E=Bn(R);if(E>e.maxPacketBytes){let A=new Set(d.flatMap(k=>k.redactionIds)),N=new Map(d.map(k=>[k.evidenceId,k])),B=new Map(s.logicalTests.flatMap(k=>k.attempts).map((k,T)=>[k.attemptId,T])),V=new Set,P=new Set;for(let k of[...d].sort((T,L)=>(B.get(T.attemptId??"")??0)-(B.get(L.attemptId??"")??0)||T.evidenceId.localeCompare(L.evidenceId))){if(k.kind==="error-field"||k.kind==="run-summary"||k.kind==="change-search")continue;let T=`${k.kind}
44
- ${k.observation}`;P.has(T)?V.add(k.evidenceId):P.add(T)}let O=d.map(k=>({item:k,priority:lI(k,p,g,B,V)})).filter(k=>k.priority<Z.failure).sort((k,T)=>k.priority-T.priority||k.item.evidenceId.localeCompare(T.item.evidenceId)),M=new Set,H=0;for(let k=0;k<rI&&E>e.maxPacketBytes;k+=1){let T=E-e.maxPacketBytes*.97;for(;T>0&&H<O.length;){let Y=O[H++];if(Y===void 0)break;M.add(Y.item.evidenceId),T-=Bn(Y.item)+64}let L=d.filter(Y=>!M.has(Y.evidenceId)),j=new Set(L.flatMap(Y=>Y.redactionIds)),se=c.filter(Y=>!A.has(Y.redactionId)||j.has(Y.redactionId)),fe=new Map;for(let Y of M){let ve=N.get(Y),Re=ve===void 0?void 0:v.get(ve.artifactId);Re!==void 0&&fe.set(Re,(fe.get(Re)??0)+1)}let ue=[...fe.entries()].map(([Y,ve])=>{let Re=`Dropped ${ve} lower-priority ${Y} observation${ve===1?"":"s"} to fit the ${e.maxPacketBytes}-byte packet budget; observations closest to the failure were kept.`;return{omissionId:$("omi",[r.runId,Y,"budget-exceeded","packet",Re]),channel:Y,reason:"budget-exceeded",message:Re,locator:"packet",cap:e.maxPacketBytes}});if(R=I(L,se,[...l,...ue]),E=Bn(R),H>=O.length)break}}return E>e.maxPacketBytes?{kind:"budget-exceeded",message:`Even the evidence closest to the failure is ${E} bytes, exceeding maxPacketBytes=${e.maxPacketBytes}; raise the explicit policy limit or narrow the authorized inputs.`}:{kind:"built",packet:R}}import{spawn as Mf}from"node:child_process";var uI=["KWIKQA_TOKEN","KWIKQA_API_URL","OPENROUTER_API_KEY"],Of=256*1024,pI=8e3;function ls(r,t={}){let e={...r,...t};for(let n of uI)delete e[n];return e}function Df(r){return r.pid===void 0||r.exitCode!==null||r.signalCode!==null}function Lf(r,t){if(r.pid!==void 0)try{process.kill(-r.pid,t)}catch{r.kill(t)}}async function fI(r,t){if(!Df(r)){if(process.platform==="win32"){await new Promise(e=>{let n=Mf("taskkill",["/pid",String(r.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("exit",()=>e()),n.on("error",()=>e())});return}Lf(r,"SIGINT"),await Promise.race([t,new Promise(e=>setTimeout(e,pI))]),Df(r)||Lf(r,"SIGKILL")}}function ud(r,t,e){let n=Mf(r,[...t],{cwd:e.cwd,env:e.env,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),i="",s=o=>{i+=o.toString("utf8"),i.length>Of&&(i=i.slice(-Of))};n.stdout?.on("data",s),n.stderr?.on("data",s);let a=new Promise(o=>{n.on("exit",d=>o(d??void 0)),n.on("error",()=>o(void 0))});return{child:n,output:()=>i,exited:a,stop:async()=>{await fI(n,a),await Promise.race([a,new Promise(o=>setTimeout(o,2e3))])}}}async function us(r,t,e){let n=ud(r,t,e),i=!1,s=setTimeout(()=>{i=!0,n.stop()},e.timeoutMs),a=await n.exited;return clearTimeout(s),{...a===void 0?{}:{exitCode:a},timedOut:i,output:n.output()}}async function $f(r,t,e){let n=Date.now()+e,i=!1;for(r.exited.then(()=>{i=!0});Date.now()<n;){let s=t.exec(r.output());if(s!==null)return s;if(i)return t.exec(r.output())??void 0;await new Promise(a=>setTimeout(a,100))}}var jf="1.0",pd=[1,59],bI=5,xI=6e4,vI=3e4,kI=12e4,II=new Set(["generic","text","list","group","none","presentation"]),PI=new Set(["banner","navigation","main","contentinfo","complementary","region","form","search"]);function fd(r){let[t=0,e=0]=r.split(".").map(n=>Number.parseInt(n,10));return t>pd[0]||t===pd[0]&&e>=pd[1]}async function Ff(r){try{let t=JSON.parse(await hI(tr(r,"package.json"),"utf8"));return t.name==="@playwright/cli"&&typeof t.version=="string"?t.version:void 0}catch{return}}async function Bf(r,t){try{let n=yI(tr(r,"package.json")).resolve("@playwright/cli/package.json"),i=_f(n),s=await Ff(i);if(s!==void 0)return{entryPath:tr(i,"playwright-cli.js"),version:s,source:"project"}}catch{}let e=process.platform==="win32"?["playwright-cli.cmd"]:["playwright-cli"];for(let n of(t.PATH??"").split(gI).filter(Boolean))for(let i of e){let s=tr(n,i);try{let a=process.platform==="win32"?tr(n,"node_modules","@playwright","cli"):_f(await mI(s)),o=await Ff(a);if(o!==void 0)return{entryPath:tr(a,"playwright-cli.js"),version:o,source:"path"}}catch{}}}function hd(r){return r.split(/\r?\n/).filter(t=>!/[║╔╚═]/.test(t)).join(`
45
- `)}function Vf(r){return/```yaml\r?\n([\s\S]*?)\r?\n```/.exec(hd(r))?.[1]?.split(/\r?\n/)}function zf(r){let t=hd(r).split(/\r?\n/),e=t.findIndex(n=>n.trim()==="### Result");if(!(e<0))return t.slice(e+1).map(n=>n.trim()).find(n=>n!==""&&!n.startsWith("###"))}function RI(r){return/getByRole\(\s*['"]([\w-]+)['"]/.exec(r??"")?.[1]?.toLowerCase()}function Hf(r){return r.trim().replace(/^-\s+/,"").replace(/\s\[(?:ref|cursor)=[^\]]+\]/g,"").replace(/:$/,"").trim()}function qf(r,t,e=bI){let n=Er(t??""),i=RI(t);return r.map((a,o)=>{let d=/\[ref=(e\d+)\]/.exec(a)?.[1],c=Hf(a),l=/^([\w-]+)/.exec(c)?.[1]?.toLowerCase()??"";if(d===void 0||II.has(l))return;let u=c.toLowerCase(),p=n.filter(f=>u.includes(f)).length*3+(i!==void 0&&l===i?2:0);if(!(PI.has(l)&&p===0))return{ref:d,element:c,score:p,order:o}}).filter(a=>a!==void 0).sort((a,o)=>o.score-a.score||a.order-o.order).slice(0,e).map(({ref:a,element:o})=>({ref:a,element:o}))}async function Uf(r){let{target:t}=r,e=[],n={logicalTestId:t.logicalTestId,title:t.title,file:t.file,line:t.line,...t.failingLine===void 0?{}:{failingLine:t.failingLine},...t.locator===void 0?{}:{locator:t.locator}};if(t.failingLine===void 0)return{...n,candidates:[],issues:["The report does not say which line failed."]};let i=ls(r.env,{PLAYWRIGHT_HTML_OPEN:"never"}),s=ud(r.playwright.executable,[...r.playwright.nodeArguments,"test",`${t.file}:${t.line}`,...t.project===void 0?[]:[`--project=${t.project}`],...r.configPath===void 0?[]:[`--config=${r.configPath}`],"--debug=cli","--timeout=0","--retries=0","--workers=1","--reporter=line"],{cwd:r.workspaceRoot,env:i}),a=(c,l=vI)=>us(process.execPath,[r.cli.entryPath,...c],{cwd:r.scratchDirectory,env:i,timeoutMs:l}),o,d=[];try{if(o=(await $f(s,/playwright-cli attach ([\w-]+)/,xI))?.[1],o===void 0)return e.push("The test did not stop in the debugger."),{...n,candidates:d,issues:e};if((await a(["attach",o])).exitCode!==0)return e.push("Playwright CLI could not attach to the paused test."),{...n,candidates:d,issues:e};let u=wI(t.file)?t.file:tr(r.workspaceRoot,t.file),p=await a([`-s=${o}`,"pause-at",`${u}:${t.failingLine}`],kI);if(p.exitCode!==0||!/### Paused/.test(p.output))return e.push(`The test did not reach line ${t.failingLine}.`),{...n,candidates:d,issues:e};let f=Vf((await a([`-s=${o}`,"snapshot"])).output);if(f===void 0)return e.push("Playwright CLI returned no page snapshot."),{...n,candidates:d,issues:e};for(let h of qf(f,t.locator)){let g=zf((await a([`-s=${o}`,"generate-locator",h.ref])).output);g!==void 0&&d.push({element:h.element,locator:g})}return d.length===0&&e.push("No locator could be generated for any candidate."),{...n,candidates:d,issues:e}}catch(c){return e.push(`The probe stopped: ${c instanceof Error?c.message:String(c)}`),{...n,candidates:d,issues:e}}finally{o!==void 0&&await a([`-s=${o}`,"detach"],1e4).catch(()=>{}),await s.stop()}}import{mkdir as rm,rm as tm}from"node:fs/promises";import{dirname as oT,join as Kr,relative as dT,resolve as cT}from"node:path";import{createHash as TI}from"node:crypto";function md(r,t){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError("canonical JSON cannot contain non-finite numbers");return r}if(Array.isArray(r))return r.map(e=>md(e,t));if(typeof r!="object")throw new TypeError(`canonical JSON cannot contain ${typeof r}`);if(t.has(r))throw new TypeError("canonical JSON cannot contain cycles");t.add(r);try{let e=r,n={};for(let i of Object.keys(e).sort()){let s=e[i];if(s===void 0)throw new TypeError(`canonical JSON cannot contain undefined at ${JSON.stringify(i)}`);n[i]=md(s,t)}return n}finally{t.delete(r)}}function de(r){return JSON.stringify(md(r,new Set))}function C(r){return TI("sha256").update(de(r),"utf8").digest("hex")}function Gf(r){let t=new Map;for(let e of r){if(t.has(e.logicalTestId))throw new Error("Logical test observation is duplicated.");t.set(e.logicalTestId,e.status)}return t}function Kf(r){return r!==void 0&&r!=="passed"}function yd(r){let t=new Set(r.targetLogicalTestIds);if(t.size===0||t.size!==r.targetLogicalTestIds.length)throw new Error("Target logical test identities must be unique and nonempty.");let e=Gf(r.baseline),n=[],i=new Set;for(let l of r.blockingReasons??[]){if(l.length===0)throw new Error("Blocking validation reasons must be nonempty.");n.push({classification:"incomplete-check",message:l})}for(let l of[...r.commands].sort((u,p)=>u.commandId.localeCompare(p.commandId))){if(!l.required)continue;if(l.timing==="post-patch")for(let p of l.expectedLogicalTestIds)i.add(p);if(!l.fresh){n.push({classification:"incomplete-check",commandId:l.commandId,message:"Required command evidence is not fresh."});continue}if(l.status==="unavailable"){n.push({classification:"unavailable-check",commandId:l.commandId,message:"Required command was unavailable."});continue}if(l.status==="incomplete"){n.push({classification:"incomplete-check",commandId:l.commandId,message:"Required command did not produce authoritative evidence."});continue}if(l.timing==="baseline")continue;let u=Gf(l.observations);for(let p of l.expectedLogicalTestIds){let f=u.get(p);if(f===void 0){n.push({classification:"incomplete-check",logicalTestId:p,commandId:l.commandId,message:"An expected logical test is missing from post-patch evidence."});continue}if(t.has(p)){n.push({classification:f==="passed"?"fixed-target-failure":"still-failing-target",logicalTestId:p,commandId:l.commandId,message:f==="passed"?"The original target failure is fixed.":"The original target remains non-passing."});continue}let h=e.get(p);f!=="passed"&&n.push({classification:Kf(h)?"unchanged-pre-existing-failure":"newly-introduced-failure",logicalTestId:p,commandId:l.commandId,message:Kf(h)?"An affected test remains non-passing from its baseline.":"An affected test newly became non-passing."})}}for(let l of[...t].sort())i.has(l)||n.push({classification:"incomplete-check",logicalTestId:l,message:"No fresh focused evidence covers the target logical test."});let s=n.sort((l,u)=>`${l.classification}\0${l.logicalTestId??""}\0${l.commandId??""}`.localeCompare(`${u.classification}\0${u.logicalTestId??""}\0${u.commandId??""}`)),a=new Set(s.map(l=>l.classification)),o=[...t].every(l=>s.some(u=>u.classification==="fixed-target-failure"&&u.logicalTestId===l)),c={schemaVersion:"1.0",status:a.has("incomplete-check")?"incomplete":a.has("unavailable-check")?"unavailable":!o||a.has("still-failing-target")||a.has("unchanged-pre-existing-failure")||a.has("newly-introduced-failure")||r.commands.some(l=>l.required&&l.status==="failed")?"failed":"passed",classifications:s};return{...c,summaryHash:C(c)}}var fs="1.1",gd="1.0",hs="1.1";var ms="1.0",Ot=/^[a-z][a-z0-9_-]{0,63}$/,_r=32*1024*1024,rr=16*1024*1024,Hn="report.json",Jf=["playwright-focused","playwright-affected","playwright-project","playwright-suite","cypress-focused","cypress-affected","cypress-project","cypress-suite","webdriverio-focused","webdriverio-affected","webdriverio-project","webdriverio-suite"];function Fr(r){return Jf.includes(r)}var be=/^[a-f0-9]{64}$/,qn=Ot;function Ce(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Xf(r){return Array.isArray(r)&&r.every(t=>typeof t=="string")}function zn(r,t=!0){return Xf(r)&&(t||r.length>0)&&r.every(e=>e.length>0&&!e.includes("\0"))&&new Set(r).size===r.length}function Ae(r,t){let e=Object.keys(r).sort(),n=[...t].sort();return e.length===n.length&&e.every((i,s)=>i===n[s])}function AI(r){if(!Ce(r))return!1;let t=["outputDirectory","maxArtifacts","maxArtifactBytes"];return r.reportFile!==void 0&&t.push("reportFile"),Ae(r,t)&&typeof r.outputDirectory=="string"&&r.outputDirectory.length>0&&!r.outputDirectory.includes("\0")&&(r.reportFile===void 0||typeof r.reportFile=="string"&&r.reportFile.length>0&&!r.reportFile.includes("\0"))&&Number.isInteger(r.maxArtifacts)&&r.maxArtifacts>0&&Number.isInteger(r.maxArtifactBytes)&&r.maxArtifactBytes>0&&r.maxArtifactBytes<=_r}function SI(r){if(!Ce(r))return!1;let t=["kind","path","detail"];return r.sha256!==void 0&&t.push("sha256"),Ae(r,t)&&["package-root","package-manifest","package-entry","configuration","pnp-loader","source-graph","scope-escalation"].includes(String(r.kind))&&typeof r.path=="string"&&r.path.length>0&&!r.path.includes("\0")&&typeof r.detail=="string"&&r.detail.length>0&&(r.sha256===void 0||typeof r.sha256=="string"&&be.test(r.sha256))}function Yf(r){return!Ce(r)||!qn.test(String(r.commandId))||!Ae(r,["commandId","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","artifactPolicy","resolutionEvidence"])||!(Fr(String(r.kind))||["parse","format","typecheck","lint"].includes(String(r.kind)))||r.timing!=="baseline"&&r.timing!=="post-patch"||typeof r.executable!="string"||r.executable.length===0||!Xf(r.args)||r.args.some(t=>t.includes("\0"))||typeof r.workingDirectory!="string"||r.workingDirectory.length===0||r.workingDirectory.includes("\0")||!Number.isInteger(r.timeoutMs)||r.timeoutMs<=0||r.required!==!0||typeof r.purpose!="string"||r.purpose.length===0||!zn(r.logicalTestIds)||!zn(r.projectIds)||!Ce(r.environmentDelta)||!AI(r.artifactPolicy)||!Array.isArray(r.resolutionEvidence)||!r.resolutionEvidence.every(SI)?!1:Object.entries(r.environmentDelta).every(([t,e])=>/^[A-Z][A-Z0-9_]*$/.test(t)&&typeof e=="string"&&!e.includes("\0"))}function wd(r){return Ce(r)&&Ae(r,["path","sourceSha256","resultSha256"])&&typeof r.path=="string"&&r.path.length>0&&!r.path.includes("\0")&&typeof r.sourceSha256=="string"&&be.test(r.sourceSha256)&&typeof r.resultSha256=="string"&&be.test(r.resultSha256)}function EI(r){return Ce(r)&&Ae(r,["baselineId","commandId","logicalTestIds","reason"])&&/^baseline_[a-f0-9]{24}$/.test(String(r.baselineId))&&qn.test(String(r.commandId))&&zn(r.logicalTestIds,!1)&&typeof r.reason=="string"&&r.reason.length>0}function CI(r){if(!Ce(r))return!1;let t=["code","message"];return r.path!==void 0&&t.push("path"),Ae(r,t)&&["ambiguous-package-root","ambiguous-configuration","budget-exceeded","cancelled","entry-outside-workspace","invalid-artifact","invalid-command","malformed-manifest","missing-browser","missing-configuration","missing-dependency","missing-test-identity","package-mismatch","parse-failed","report-incomplete","resolution-failed","spawn-failed","symlink-escape","timeout","unsupported-layout"].includes(String(r.code))&&typeof r.message=="string"&&r.message.length>0&&(r.path===void 0||typeof r.path=="string"&&!r.path.includes("\0"))}function Qf(r){return C({purpose:"kwikqa-validation-baseline",...r})}function ys(r){return C({purpose:"kwikqa-validation-run",...r})}function ps(r){return typeof r=="string"&&r.length>0&&Number.isFinite(Date.parse(r))}function NI(r){if(!Ce(r)||typeof r.kind!="string")return!1;if(r.kind==="exit")return Ae(r,["kind","exitCode"])&&Number.isInteger(r.exitCode);if(r.kind==="signal")return Ae(r,["kind","signal"])&&typeof r.signal=="string";if(r.kind==="spawn-error"){let t=["kind",...r.code===void 0?[]:["code"]];return Ae(r,t)&&(r.code===void 0||typeof r.code=="string")}return(r.kind==="timeout"||r.kind==="cancelled")&&Ae(r,["kind"])}function Wf(r){return Ce(r)&&Ae(r,["path","sha256","storedSha256","observedBytes","storedBytes","truncated","redacted"])&&typeof r.path=="string"&&r.path.length>0&&typeof r.sha256=="string"&&be.test(r.sha256)&&typeof r.storedSha256=="string"&&be.test(r.storedSha256)&&Number.isInteger(r.observedBytes)&&r.observedBytes>=0&&Number.isInteger(r.storedBytes)&&r.storedBytes>=0&&typeof r.truncated=="boolean"&&typeof r.redacted=="boolean"}function OI(r){return Ce(r)&&Ae(r,["path","sha256","bytes"])&&typeof r.path=="string"&&r.path.length>0&&typeof r.sha256=="string"&&be.test(r.sha256)&&Number.isInteger(r.bytes)&&r.bytes>=0}function bd(r){if(!xd(r))throw new Error("Validation command record is malformed or failed integrity validation.");return r}function DI(r){if(!Ce(r))return!1;let t=["classification",...r.logicalTestId===void 0?[]:["logicalTestId"],...r.commandId===void 0?[]:["commandId"],"message"];return Ae(r,t)&&["fixed-target-failure","still-failing-target","unchanged-pre-existing-failure","newly-introduced-failure","unavailable-check","incomplete-check"].includes(String(r.classification))&&(r.logicalTestId===void 0||typeof r.logicalTestId=="string"&&r.logicalTestId.length>0)&&(r.commandId===void 0||typeof r.commandId=="string"&&qn.test(r.commandId))&&typeof r.message=="string"&&r.message.length>0}function xd(r){if(!Ce(r))return!1;let t=r,{recordHash:e,...n}=t;return Ae(r,["schemaVersion","validationRunId","commandId","commandHash","planHash","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","startedAt","durationMs","termination","stdout","stderr","artifacts","status","recordHash"])&&t.schemaVersion===gd&&/^vld_[a-f0-9]{24}$/.test(t.validationRunId)&&qn.test(t.commandId)&&be.test(t.commandHash)&&be.test(t.planHash)&&t.required===!0&&Yf({commandId:t.commandId,kind:t.kind,timing:t.timing,required:t.required,executable:t.executable,args:t.args,workingDirectory:t.workingDirectory,environmentDelta:t.environmentDelta,timeoutMs:t.timeoutMs,purpose:t.purpose,logicalTestIds:t.logicalTestIds,projectIds:t.projectIds,artifactPolicy:{outputDirectory:"artifacts",maxArtifacts:1,maxArtifactBytes:1},resolutionEvidence:[]})&&ps(t.startedAt)&&Number.isInteger(t.durationMs)&&t.durationMs>=0&&NI(t.termination)&&Wf(t.stdout)&&Wf(t.stderr)&&Array.isArray(t.artifacts)&&t.artifacts.every(OI)&&["blocked","passed","failed","unavailable","incomplete"].includes(t.status)&&be.test(e)&&C(n)===e}function Un(r){if(!Ce(r))throw new Error("Baseline manifest is not an object.");let t=r,{baselineHash:e,...n}=t;if(!Ae(r,["schemaVersion","planHash","repositoryFingerprint","targetHashes","commandRecords","logicalTestOutcomes","capturedAt","baselineHash"])||t.schemaVersion!==gd||!be.test(t.planHash)||!be.test(t.repositoryFingerprint)||!Array.isArray(t.targetHashes)||!t.targetHashes.every(wd)||!Array.isArray(t.commandRecords)||!t.commandRecords.every(xd)||!Ce(t.logicalTestOutcomes)||!Object.entries(t.logicalTestOutcomes).every(([i,s])=>i.length>0&&typeof s=="string"&&["passed","failed","skipped","interrupted"].includes(s))||!ps(t.capturedAt)||!be.test(e)||Qf(n)!==e)throw new Error("Baseline manifest is malformed or failed integrity validation.");return t}function Dt(r){if(!Ce(r))throw new Error("Validation run manifest is not an object.");let t=r,{manifestHash:e,...n}=t;if(!Ae(r,["schemaVersion","validationRunId","transactionId","planHash","repositoryFingerprint","targetHashes","requiredCommandIds","status","commandRecords","classifications","startedAt","completedAt","manifestHash"])||t.schemaVersion!==hs||!/^vld_[a-f0-9]{24}$/.test(t.validationRunId)||!/^txn_[a-f0-9]{24}$/.test(t.transactionId)||!be.test(t.planHash)||!be.test(t.repositoryFingerprint)||!Array.isArray(t.targetHashes)||!t.targetHashes.every(wd)||!zn(t.requiredCommandIds,!1)||!t.requiredCommandIds.every(i=>qn.test(i))||!Array.isArray(t.commandRecords)||!t.commandRecords.every(xd)||!Array.isArray(t.classifications)||!t.classifications.every(DI)||!["blocked","passed","failed","unavailable","incomplete"].includes(t.status)||!ps(t.startedAt)||!ps(t.completedAt)||Date.parse(t.completedAt)<Date.parse(t.startedAt)||!be.test(e)||ys(n)!==e)throw new Error("Validation run manifest is malformed or failed integrity validation.");if(new Set(t.targetHashes.map(i=>i.path)).size!==t.targetHashes.length||new Set(t.commandRecords.map(i=>i.commandId)).size!==t.commandRecords.length||t.commandRecords.some(i=>i.validationRunId!==t.validationRunId||i.planHash!==t.planHash))throw new Error("Validation run manifest contains inconsistent evidence.");if(!LI(t))throw new Error("Validation run manifest status is inconsistent with its evidence.");return t}function LI(r){let t=new Set(r.requiredCommandIds),e=new Set(r.commandRecords.map(i=>i.commandId)),n=new Set(r.classifications.map(i=>i.classification));if(r.commandRecords.some(i=>!t.has(i.commandId)||i.timing!=="post-patch")||r.requiredCommandIds.some(i=>!e.has(i)&&!r.classifications.some(s=>s.classification==="incomplete-check"&&s.commandId===i)))return!1;switch(r.status){case"passed":return r.classifications.length>0&&[...n].every(i=>i==="fixed-target-failure")&&e.size===t.size&&r.commandRecords.every(i=>i.status==="passed");case"incomplete":return n.has("incomplete-check");case"unavailable":return!n.has("incomplete-check")&&n.has("unavailable-check");case"failed":return!n.has("incomplete-check")&&!n.has("unavailable-check");default:return!0}}function gs(r){return C({purpose:"kwikqa-resolved-validation-plan",...r})}function nr(r){if(!Ce(r))throw new Error("Resolved validation plan is not an object.");if(!Ae(r,["schemaVersion","policyVersion","status",...r.transactionId===void 0?[]:["transactionId"],"proposalHash","targetLogicalTestIds","targetHashes","advisoryPlanHash","repositoryFingerprint","commands","baselineRequirements","unresolvedReasons","planHash"]))throw new Error("Resolved validation plan contains unknown or missing fields.");let t=r,{planHash:e,...n}=t;if(t.schemaVersion!==fs||t.policyVersion!==ms||t.status!=="resolved"&&t.status!=="unavailable"||!be.test(t.proposalHash)||!zn(t.targetLogicalTestIds,!1)||!be.test(t.advisoryPlanHash)||!be.test(t.repositoryFingerprint)||!Array.isArray(t.commands)||!t.commands.every(Yf)||t.transactionId!==void 0&&!/^txn_[a-f0-9]{24}$/.test(t.transactionId)||!Array.isArray(t.targetHashes)||!t.targetHashes.every(wd)||!Array.isArray(t.baselineRequirements)||!t.baselineRequirements.every(EI)||!Array.isArray(t.unresolvedReasons)||!t.unresolvedReasons.every(CI)||!be.test(e)||gs(n)!==e)throw new Error("Resolved validation plan is malformed or failed integrity validation.");if(new Set(t.commands.map(s=>s.commandId)).size!==t.commands.length)throw new Error("Resolved validation plan contains duplicate command ids.");if(new Set(t.targetHashes.map(s=>s.path)).size!==t.targetHashes.length)throw new Error("Resolved validation plan contains duplicate targets.");if(new Set(t.baselineRequirements.map(s=>s.baselineId)).size!==t.baselineRequirements.length)throw new Error("Resolved validation plan contains duplicate baseline ids.");let i=new Map(t.commands.map(s=>[s.commandId,s]));if(t.baselineRequirements.some(s=>{let a=i.get(s.commandId);return a===void 0||a.timing!=="baseline"}))throw new Error("Resolved validation plan baseline references are invalid.");if(t.status==="resolved"&&t.unresolvedReasons.length>0||t.status==="unavailable"&&t.unresolvedReasons.length===0)throw new Error("Resolved validation plan status is inconsistent.");return t}var nh=bi(Pn(),1);import{readdir as MI,realpath as th}from"node:fs/promises";import{extname as $I,isAbsolute as rh,join as _I,relative as FI,resolve as jI,sep as Zf}from"node:path";import{dirname as BI,extname as Pd,join as eh}from"node:path/posix";var vd=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],ih=new Set(vd),VI=new Set([".js",".mjs",".cjs"]),zI=[".ts",".tsx",".mts",".cts"],HI=/(?:^|\/)(?:[^/]+\.)?(?:spec|test|cy|e2e)\.(?:[cm]?[jt]sx?)$/i,qI=new Set([".git",".kwikqa","node_modules",".yarn",".pnpm-store","coverage","dist","build","out","test-results","playwright-report"]);function Gn(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof r.type=="string"}function kd(r,t,e=new Set){if(!e.has(r)){e.add(r),t(r);for(let[n,i]of Object.entries(r))if(n!=="loc")if(Array.isArray(i))for(let s of i)Gn(s)&&kd(s,t,e);else Gn(i)&&kd(i,t,e)}}function UI(r){let t=Pd(r).toLowerCase();return t===".tsx"?["typescript","jsx"]:[".ts",".mts",".cts"].includes(t)?["typescript"]:["jsx"]}function ws(r){return Gn(r)&&r.type==="StringLiteral"&&typeof r.value=="string"?r.value:void 0}function GI(r,t){try{let e=(0,nh.parse)(r,{sourceType:"unambiguous",allowReturnOutsideFunction:!0,errorRecovery:!1,plugins:UI(t)}),n=new Set,i=!1;return kd(e,s=>{if(s.type==="ImportDeclaration"||s.type==="ExportNamedDeclaration"||s.type==="ExportAllDeclaration"){let c=ws(s.source);c!==void 0&&n.add(c),s.type==="ExportAllDeclaration"&&(i=!0);return}if(s.type==="ImportExpression"){let c=ws(s.source);c===void 0?i=!0:n.add(c);return}if(s.type!=="CallExpression")return;let a=s.callee,o=Array.isArray(s.arguments)?s.arguments:[];if(Gn(a)&&a.type==="Import"){let c=ws(o[0]);c===void 0?i=!0:n.add(c);return}if(!Gn(a)||a.type!=="Identifier"||a.name!=="require")return;let d=ws(o[0]);d===void 0?i=!0:n.add(d)}),{imports:[...n].sort(),ambiguous:i}}catch{return{code:"parse-failed",message:"Source could not be parsed for validation discovery.",path:t}}}function Id(r){return r.length===0||r.includes("\0")||r.includes("\\")||rh(r)?!1:r.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function KI(r,t){return r.split("/").some(n=>qI.has(n))?!0:t.some(n=>r===n||r.startsWith(`${n}/`))}function WI(r,t){let e=FI(r,t);if(!(e===""||e===".."||e.startsWith(`..${Zf}`)||rh(e)))return e.split(Zf).join("/")}async function JI(r,t,e){let n=await th(r),i=[],s=!1;async function a(o){if(s)return;let d=(await MI(o,{withFileTypes:!0})).sort((c,l)=>c.name.localeCompare(l.name,"en"));for(let c of d){if(c.isSymbolicLink())continue;let l=_I(o,c.name),u=WI(n,l);if(!(u===void 0||KI(u,t))){if(c.isDirectory())await a(l);else if(c.isFile()&&ih.has($I(c.name).toLowerCase())){if(i.length>=e){s=!0;return}i.push(u)}}}}return await a(n),{files:i.sort(),exhausted:s}}function XI(r,t){if(!r.startsWith("./")&&!r.startsWith("../"))return[];let e=eh(t,r),n=[e],i=Pd(e).toLowerCase();if(VI.has(i)){let s=e.slice(0,e.length-i.length);for(let a of zI)n.push(`${s}${a}`)}if(i===""){for(let s of vd)n.push(`${e}${s}`);for(let s of vd)n.push(eh(e,`index${s}`))}return n.filter(Id)}function YI(r,t,e){return XI(r,BI(t)).find(n=>e.has(n))}async function QI(r){let t=[],e=await JI(r.workspaceRoot,r.ignoredPaths??[],r.limits.maxFiles);e.exhausted&&t.push({code:"budget-exceeded",message:"Source file discovery exceeded its file limit."});let n=new Set(e.files),i=new Map,s=0,a=0,o=!e.exhausted,d=e.exhausted;for(let u of e.files){let p=await K(r.workspaceRoot,u,r.limits.maxFileBytes);if(p.kind!=="read"||p.relativePath!==u){o=!1,t.push({code:"unsafe-path",message:"Source could not be safely read.",path:u});continue}if(s+=p.bytes.byteLength,s>r.limits.maxTotalBytes){o=!1,d=!0,t.push({code:"budget-exceeded",message:"Source discovery exceeded its total byte limit."});break}let f=GI(new TextDecoder("utf-8",{fatal:!0}).decode(p.bytes),u);if("code"in f){o=!1,t.push(f),i.set(u,{path:u,imports:[],ambiguous:!0});continue}let h=[],g=f.ambiguous;for(let m of f.imports){if(!m.startsWith("./")&&!m.startsWith("../"))continue;let y=YI(m,u,n);if(y===void 0){g=!0,o=!1,t.push({code:"unresolved-local-import",message:`Local import ${JSON.stringify(m)} could not be resolved safely.`,path:u});continue}if(a+=1,a>r.limits.maxImportEdges){o=!1,d=!0,t.push({code:"budget-exceeded",message:"Import graph exceeded its edge limit."});break}h.push(y)}if(i.set(u,{path:u,imports:[...new Set(h)].sort(),ambiguous:g}),g&&(o=!1,t.push({code:"dynamic-import",message:"Module contains an import flow that cannot be bounded.",path:u})),d)break}let c=new Map;for(let u of i.values())for(let p of u.imports){let f=c.get(p)??[];f.push(u.path),c.set(p,f)}let l=new Map([...c].map(([u,p])=>[u,[...new Set(p)].sort()]));return{modules:i,reverse:l,edges:Math.min(a,r.limits.maxImportEdges),complete:o,exhausted:d,reasons:t}}function sh(r,t){return t.filter(e=>r===e.testDirectory||r.startsWith(`${e.testDirectory}/`)).sort((e,n)=>n.testDirectory.length-e.testDirectory.length||e.id.localeCompare(n.id))}function ZI(r,t,e){let n=new Set,i=[];for(let s of[...r.map(a=>a.path),...t]){let o=sh(s,e)[0];o!==void 0&&!n.has(o.id)&&(n.add(o.id),i.push(o))}return i.sort((s,a)=>s.id.localeCompare(a.id))}function eP(r,t,e){let n=new Set,i=new Set(r),s=[...r].sort(),a=!0;for(let o=0;s.length>0;o+=1){if(o>=e){a=!1;break}let d=[];for(let c of s){t.modules.get(c)?.ambiguous===!0&&(a=!1);for(let u of t.reverse.get(c)??[])HI.test(u)&&n.add(u),i.has(u)||(i.add(u),d.push(u))}s=[...new Set(d)].sort()}return{tests:[...n].sort(),complete:a}}async function bs(r,t){for(let e of t){let n=await K(r,e,1e6);if(n.kind==="read"&&n.relativePath===e)return e}}async function ah(r,t){let e=[];t.some(o=>ih.has(Pd(o).toLowerCase()))&&e.push({kind:"parse",tool:"kwikqa-babel",required:!0});let n=await bs(r,["biome.json","biome.jsonc"]),i=await bs(r,[".prettierrc",".prettierrc.json","prettier.config.js","prettier.config.cjs","prettier.config.mjs"]);n!==void 0?(e.push({kind:"format",tool:"biome",configPath:n,required:!0}),e.push({kind:"lint",tool:"biome",configPath:n,required:!0})):i!==void 0&&e.push({kind:"format",tool:"prettier",configPath:i,required:!0});let s=await bs(r,["tsconfig.json"]);s!==void 0&&e.push({kind:"typecheck",tool:"typescript",configPath:s,required:!0});let a=await bs(r,["eslint.config.js","eslint.config.mjs","eslint.config.cjs",".eslintrc.json"]);return n===void 0&&a!==void 0&&e.push({kind:"lint",tool:"eslint",configPath:a,required:!0}),e}function tP(r,t,e){return r.some(n=>n.class==="playwright-config"||n.class==="framework-config")?t.length===1?"project":"suite":e?"affected":t.length===1?"project":"suite"}async function Rd(r){let t=await ah(r.workspaceRoot,r.targets.map(u=>u.path));if(r.targets.length===0||!Id(r.originalTestPath)||r.targets.some(u=>!Id(u.path))||r.limits.maxFiles<=0||r.limits.maxFileBytes<=0||r.limits.maxTotalBytes<=0||r.limits.maxImportEdges<=0||r.limits.maxImportDepth<=0)return{status:"unavailable",scope:"unavailable",testPaths:[],projectIds:[],staticChecks:t,indexedFiles:0,importEdges:0,completeGraph:!1,reasons:[{code:"unsafe-path",message:"Discovery input is unsafe or unbounded."}]};let e=await th(r.workspaceRoot).catch(()=>{});if(e===void 0||jI(e,r.originalTestPath)===e)return{status:"unavailable",scope:"unavailable",testPaths:[],projectIds:[],staticChecks:t,indexedFiles:0,importEdges:0,completeGraph:!1,reasons:[{code:"unsafe-path",message:"Workspace could not be resolved safely."}]};let n=await QI(r),i=r.targets.filter(u=>u.class!=="spec");if(i.length===0)return{status:"resolved",scope:"focused",testPaths:[r.originalTestPath],projectIds:sh(r.originalTestPath,r.projects).slice(0,1).map(u=>u.id),staticChecks:t,indexedFiles:n.modules.size,importEdges:n.edges,completeGraph:n.complete,reasons:[]};let s=eP(i.map(u=>u.path),n,r.limits.maxImportDepth),a=n.complete&&s.complete&&!n.exhausted,o=ZI(r.targets,s.tests,r.projects),d=tP(r.targets,o,a),c=d==="affected"?[...new Set([r.originalTestPath,...s.tests])].sort():d==="project"?[...new Set([r.originalTestPath,...s.tests])].sort():[r.originalTestPath],l=[...n.reasons];return d==="suite"&&r.projects.length>0&&o.length!==1&&l.push({code:"ambiguous-project",message:"Shared impact could not be partitioned to exactly one project; full-suite validation is required."}),{status:"resolved",scope:d,testPaths:c,projectIds:o.map(u=>u.id),staticChecks:t,indexedFiles:n.modules.size,importEdges:n.edges,completeGraph:a,reasons:l}}import{spawn as oP}from"node:child_process";import{createHash as Ps,randomUUID as dP}from"node:crypto";import{lstat as Wn,mkdir as Kn,readdir as cP,readFile as lP,realpath as Rs}from"node:fs/promises";import{isAbsolute as gh,join as Ge,relative as Ts,resolve as uP,sep as As}from"node:path";import{createHash as rP,randomUUID as vs}from"node:crypto";import{constants as jr}from"node:fs";import{chmod as nP,link as iP,lstat as kt,mkdir as ch,open as xs,readFile as lh,realpath as vt,rename as Sd,rm as oh,unlink as Td}from"node:fs/promises";import{dirname as Ad,isAbsolute as sP,join as Lt,relative as uh,resolve as Ed,sep as ph}from"node:path";var aP=/^txn_[a-f0-9]{24}$/;function ir(r,t){let e=uh(r,t);return e===""||!sP(e)&&e!==".."&&!e.startsWith(`..${ph}`)}async function Br(r){if(process.platform==="win32")return;let t=await xs(r,"r");try{await t.sync()}finally{await t.close()}}function dh(r){return rP("sha256").update(r).digest("hex")}function fh(){return`txn_${vs().replaceAll("-","").slice(0,24)}`}function sr(r){return aP.test(r)}async function ks(r){let t=await vt(r),e=Ed(t,".kwikqa","transactions");if(!ir(t,e))throw new Error("Transaction path escapes workspace.");return{root:t,transactionsDirectory:e}}async function Fe(r,t){let e=await vt(r),n=e;for(let i of t){if(!/^[A-Za-z0-9_.-]+$/.test(i)||i==="."||i==="..")throw new Error("Unsafe transaction directory segment.");let s=Lt(n,i),a=await kt(s).catch(d=>{if(d.code!=="ENOENT")throw d});if(a===void 0)await ch(s,{mode:448}),await Br(n);else if(!a.isDirectory()||a.isSymbolicLink())throw new Error("Transaction directory contains an unsafe path.");let o=await vt(s);if(!ir(e,o))throw new Error("Transaction directory escapes workspace.");n=o}return n}async function hh(r,t,e){if(!/^\.staging-[a-f0-9]{24}$/.test(t)||!sr(e))throw new Error("Transaction publication name is invalid.");let n=await ks(r),i=await vt(n.transactionsDirectory),s=Lt(i,t),a=Lt(i,e),o=await kt(s);if(!o.isDirectory()||o.isSymbolicLink())throw new Error("Transaction staging directory is unsafe.");if(await kt(a).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Transaction already exists.");await Sd(s,a),await Br(i)}async function me(r,t,e){let n=await vt(Ad(r)),i=Ed(n,r.slice(Ad(r).length+1));if(!ir(n,i))throw new Error("Write target escapes its directory.");if(!e.replace&&await kt(i).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Durable record already exists.");let s=Lt(n,`.kwikqa-${vs()}.tmp`),a=await xs(s,"wx",e.mode),o=!1;try{await a.writeFile(t),await a.sync(),await a.close(),e.replace?await Sd(s,i):(await iP(s,i),await Td(s)),o=!0,await Br(n)}finally{await a.close().catch(()=>{}),o||await Td(s).catch(()=>{})}}async function Is(r,t,e,n){let i=await vt(r),s=Ed(i,t);if(!ir(i,s))throw new Error("Target escapes workspace.");let a=await kt(s);if(!a.isFile()||a.isSymbolicLink())throw new Error("Target is not a regular file.");let o=await vt(Ad(s)),d=await vt(s);if(!ir(i,o)||!ir(i,d))throw new Error("Target escapes workspace.");if(uh(i,d).split(ph).join("/")!==t)throw new Error("Target canonical path changed during final authorization.");let l=await xs(d,jr.O_RDONLY|jr.O_NOFOLLOW);try{let g=await l.stat();if(!g.isFile()||g.dev!==a.dev||g.ino!==a.ino)throw new Error("Target changed during final authorization.");let m=await l.readFile();if(dh(m)!==e)throw new Error("Target content changed during final authorization.")}finally{await l.close()}let u=Lt(o,`.kwikqa-target-${vs()}.tmp`),p=a.mode&511,f=await xs(u,jr.O_CREAT|jr.O_EXCL|jr.O_WRONLY|jr.O_NOFOLLOW,p),h=!1;try{await f.writeFile(n),await f.sync(),await f.close(),await nP(u,p);let g=await vt(s);if(g!==d||!ir(i,g))throw new Error("Target path changed before replacement.");let m=await lh(g),y=await kt(g);if(!y.isFile()||y.isSymbolicLink()||y.dev!==a.dev||y.ino!==a.ino||dh(m)!==e)throw new Error("Target changed before replacement.");await Sd(u,g),h=!0,await Br(o)}finally{await f.close().catch(()=>{}),h||await Td(u).catch(()=>{})}}async function Ue(r,t){let e=await Fe(r,[".kwikqa","transactions"]),n=Lt(e,".lock"),i=vs();await ch(n,{mode:448});let s=await kt(n);try{await me(Lt(n,"owner.json"),`${JSON.stringify({...t,nonce:i})}
46
- `,{mode:384,replace:!1})}catch(a){let o=await kt(n).catch(()=>{});throw o?.dev===s.dev&&o.ino===s.ino&&await oh(n,{recursive:!0,force:!0}).catch(()=>{}),a}return await Br(e),{release:async()=>{let a=await kt(n).catch(()=>{});if(a===void 0||a.dev!==s.dev||a.ino!==s.ino||a.isSymbolicLink())throw new Error("Workspace lock ownership changed before release.");if(JSON.parse(await lh(Lt(n,"owner.json"),"utf8")).nonce!==i)throw new Error("Workspace lock ownership changed before release.");await oh(n,{recursive:!0,force:!1}),await Br(e)}}}var pP=/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTH)/i,fP=["authorization","cookie","password","passwd","secret","token","api_key","private_key"];function Cd(r,t){let e=Ts(r,t);return e===""||!gh(e)&&e!==".."&&!e.startsWith(`..${As}`)}function hP(r){return/^[a-f0-9]{64}$/.test(r)}function mP(r){let t=nr(r.plan),e=t.commands.find(n=>n.commandId===r.commandId);if(!/^txn_[a-f0-9]{24}$/.test(r.transactionId)||t.status!=="resolved"||!hP(t.planHash)||!Ot.test(r.commandId)||e===void 0||e.executable!==process.execPath||!gh(e.workingDirectory)||e.args.some(n=>n.includes("\0"))||!Number.isInteger(e.timeoutMs)||e.timeoutMs<=0||!Number.isInteger(r.limits.maxStreamBytes)||r.limits.maxStreamBytes<=0||r.limits.maxStreamBytes>rr||!Number.isInteger(r.limits.maxTotalStreamBytes)||r.limits.maxTotalStreamBytes<r.limits.maxStreamBytes||!Number.isInteger(r.limits.terminationGraceMs)||r.limits.terminationGraceMs<0)throw new Error("Validation command or execution limits are invalid.");for(let[n,i]of Object.entries(e.environmentDelta))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n)||i.includes("\0"))throw new Error("Validation environment delta is invalid.");return e}async function yP(r,t){let e=await Rs(r.workspaceRoot),n=uP(e,".kwikqa","transactions",r.transactionId);if(!Cd(e,n))throw new Error("Validation transaction escapes workspace.");let i=await Wn(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Validation transaction is unsafe.");let s=r.validationRunId??`vld_${dP().replaceAll("-","").slice(0,24)}`;if(!/^vld_[a-f0-9]{24}$/.test(s))throw new Error("Validation run id is invalid.");let a=Ge(n,"validation");await Kn(a,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let o=await Wn(a);if(!o.isDirectory()||o.isSymbolicLink())throw new Error("Validation directory is unsafe.");let d=Ge(a,s);await Kn(d,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let c=await Wn(d);if(!c.isDirectory()||c.isSymbolicLink())throw new Error("Validation run directory is unsafe.");let l=Ge(d,"commands");await Kn(l,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let u=await Wn(l);if(!u.isDirectory()||u.isSymbolicLink())throw new Error("Validation commands directory is unsafe.");let p=Ge(l,t.commandId);return await Kn(p,{mode:448}),await Kn(Ge(p,"artifacts"),{mode:448}),{root:d,commandDirectory:p,runId:s}}var Ss=class{constructor(t,e){this.cap=t;this.consumeGlobal=e}cap;consumeGlobal;#e=Ps("sha256");#r=[];#t=0;#n=0;add(t){this.#e.update(t),this.#t+=t.byteLength;let e=Math.max(0,this.cap-this.#n),n=this.consumeGlobal(Math.min(e,t.byteLength));n>0&&(this.#r.push(t.subarray(0,n)),this.#n+=n)}finish(){return{text:Buffer.concat(this.#r).toString("utf8"),observed:this.#t,hash:this.#e.digest("hex"),truncated:this.#n<this.#t}}};function mh(r,t){let e=Buffer.from(r,"utf8");if(e.byteLength<=t)return{text:r,truncated:!1};let n=t;for(;n>0&&(e[n]??0)>=128&&(e[n]??0)<192;)n-=1;return{text:e.subarray(0,n).toString("utf8"),truncated:!0}}function yh(r){return Object.fromEntries(Object.entries(r).sort(([t],[e])=>t.localeCompare(e)).map(([t,e])=>[t,pP.test(t)?"[REDACTED]":e]))}function gP(r){return r.kind==="timeout"||r.kind==="cancelled"?"incomplete":r.kind==="spawn-error"?"unavailable":r.kind==="signal"?"incomplete":r.exitCode===0?"passed":"failed"}function wP(r){return new Promise(t=>setTimeout(t,r))}async function bP(r,t,e,n){let i=await cP(t,{withFileTypes:!0}),s=[],a=0;for(let o of i.sort((d,c)=>d.name.localeCompare(c.name))){if(!o.isFile()||o.isSymbolicLink())throw new Error("Validation artifact output contains an unsafe entry.");let d=Ge(t,o.name),c=await Wn(d),l=await Rs(d);if(!c.isFile()||c.isSymbolicLink()||!Cd(t,l)||c.mtimeMs+1<n)throw new Error("Validation artifact is stale or unsafe.");let u=await lP(l);if(a+=u.byteLength,s.push({path:Ts(r,l).split(As).join("/"),sha256:Ps("sha256").update(u).digest("hex"),bytes:u.byteLength}),s.length>e.artifactPolicy.maxArtifacts||a>e.artifactPolicy.maxArtifactBytes)throw new Error("Validation artifact policy limit was exceeded.")}if(e.artifactPolicy.reportFile!==void 0&&!s.some(o=>o.path.split("/").at(-1)===e.artifactPolicy.reportFile))throw new Error("Required validation report artifact is missing.");return s}async function Nd(r){let t=mP(r),e=await Rs(r.workspaceRoot),n=await Rs(t.workingDirectory);if(!Cd(e,n))throw new Error("Validation working directory escapes workspace.");for(let j of t.resolutionEvidence){if(j.sha256===void 0)continue;let se=await K(e,j.path,16*1024*1024);if(se.kind!=="read"||se.sha256!==j.sha256)throw new Error("Validation resolution evidence changed after approval.")}let i=await yP(r,t),s=r.now??(()=>new Date),a=s(),o=r.limits.maxTotalStreamBytes,d=j=>{let se=Math.min(j,o);return o-=se,se},c=new Ss(r.limits.maxStreamBytes,d),l=new Ss(r.limits.maxStreamBytes,d),u=Ge(i.commandDirectory,"artifacts"),p={...r.inheritedEnvironment??process.env,...t.environmentDelta,...t.kind.startsWith("playwright-")?{PLAYWRIGHT_JSON_OUTPUT_NAME:Ge(u,t.artifactPolicy.reportFile??Hn)}:{},...Fr(t.kind)&&!t.kind.startsWith("playwright-")?{KWIKQA_REPORT_DIR:u}:{}},f=oP(t.executable,[...t.args],{cwd:t.workingDirectory,env:p,shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"]});f.stdout.on("data",j=>c.add(j)),f.stderr.on("data",j=>l.add(j));let h,g,m=j=>{h===void 0&&(h=j,f.kill(),g=setTimeout(()=>f.kill("SIGKILL"),r.limits.terminationGraceMs))},y=()=>m("cancelled");r.signal?.addEventListener("abort",y,{once:!0}),r.signal?.aborted&&m("cancelled");let w=setTimeout(()=>m("timeout"),t.timeoutMs),x=await new Promise(j=>{let se=!1;f.once("error",fe=>{se||(se=!0,j({kind:"spawn-error",...fe.code===void 0?{}:{code:fe.code}}))}),f.once("close",(fe,ue)=>{se||(se=!0,j(h!==void 0?{kind:h}:ue!==null?{kind:"signal",signal:ue}:{kind:"exit",exitCode:fe??1}))})});w!==void 0&&clearTimeout(w),g!==void 0&&clearTimeout(g),r.signal?.removeEventListener("abort",y),await wP(0);let v=r.sensitiveNames??fP,I=c.finish(),R=l.finish(),E=ae(I.text,"report","validation:stdout",v).value,A=mh(E,r.limits.maxStreamBytes),N=ae(R.text,"report","validation:stderr",v).value,B=mh(N,r.limits.maxStreamBytes),V=A.text,P=B.text,O=Ge(i.commandDirectory,"stdout.log"),M=Ge(i.commandDirectory,"stderr.log");await me(O,V,{mode:384,replace:!1}),await me(M,P,{mode:384,replace:!1});let H=await bP(i.root,u,t,a.getTime()),k=s(),T={schemaVersion:"1.0",validationRunId:i.runId,commandId:t.commandId,commandHash:C(t),planHash:r.plan.planHash,kind:t.kind,timing:t.timing,required:t.required,executable:t.executable,args:t.args,workingDirectory:t.workingDirectory,environmentDelta:yh(t.environmentDelta),timeoutMs:t.timeoutMs,purpose:t.purpose,logicalTestIds:t.logicalTestIds,projectIds:t.projectIds,startedAt:a.toISOString(),durationMs:Math.max(0,k.getTime()-a.getTime()),termination:x,stdout:{path:Ts(i.root,O).split(As).join("/"),observedBytes:I.observed,storedBytes:Buffer.byteLength(V),sha256:I.hash,storedSha256:Ps("sha256").update(V).digest("hex"),truncated:I.truncated||A.truncated,redacted:E!==I.text},stderr:{path:Ts(i.root,M).split(As).join("/"),observedBytes:R.observed,storedBytes:Buffer.byteLength(P),sha256:R.hash,storedSha256:Ps("sha256").update(P).digest("hex"),truncated:R.truncated||B.truncated,redacted:N!==R.text},artifacts:H,status:gP(x)},L={...T,recordHash:C(T)};return await me(Ge(i.commandDirectory,"command.json"),`${de({commandId:t.commandId,planHash:r.plan.planHash,executable:t.executable,args:t.args,workingDirectory:t.workingDirectory,environmentDelta:yh(t.environmentDelta)})}
47
- `,{mode:384,replace:!1}),await me(Ge(i.commandDirectory,"result.json"),`${de(L)}
48
- `,{mode:384,replace:!1}),{directory:i.root,record:L}}import{realpath as $P}from"node:fs/promises";import{join as _P}from"node:path";import{createHash as xP}from"node:crypto";import{readdir as vP,readFile as Es}from"node:fs/promises";import{join as It}from"node:path";var Jn="1.0";function wh(r){let t=JSON.parse(r);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("Journal record is not an object.");return t}function kP(r){if(r.schemaVersion!==Jn||typeof r.transactionId!="string"||!sr(r.transactionId)||typeof r.manifestHash!="string"||!Array.isArray(r.targets)||r.preview===null||typeof r.preview!="object"||r.authorization===null||typeof r.authorization!="object"||r.config===null||typeof r.config!="object"||typeof r.maxTargetBytes!="number"||typeof r.createdAt!="string")throw new Error("Transaction manifest is malformed.");let t=r,{manifestHash:e,...n}=t;if(C(n)!==e)throw new Error("Transaction manifest integrity check failed.");return t}function IP(r){let t=new Set(["prepared","applying","applied","validating","rolling-back","rolled-back","completed","conflicted"]);if(r.schemaVersion!==Jn||typeof r.transactionId!="string"||!sr(r.transactionId)||typeof r.manifestHash!="string"||typeof r.stateHash!="string"||typeof r.phase!="string"||!t.has(r.phase)||!Number.isInteger(r.revision)||r.revision<1||typeof r.updatedAt!="string"||!Array.isArray(r.history))throw new Error("Transaction state is malformed.");let e=r,{stateHash:n,...i}=e;if(C(i)!==n||e.history.length!==e.revision)throw new Error("Transaction state integrity check failed.");for(let[s,a]of e.history.entries())if(a===null||typeof a!="object"||a.sequence!==s+1||typeof a.type!="string"||a.type.length===0||typeof a.at!="string"||!t.has(a.phase)||a.path!==void 0&&typeof a.path!="string"||a.message!==void 0&&typeof a.message!="string"||a.planHash!==void 0&&typeof a.planHash!="string"||a.validationRunId!==void 0&&typeof a.validationRunId!="string"||a.validationManifestHash!==void 0&&typeof a.validationManifestHash!="string")throw new Error("Transaction history is malformed.");if(e.history.at(-1)?.phase!==e.phase)throw new Error("Transaction state phase does not match its history.");return e}function PP(r){return C({purpose:"kwikqa-transaction-target",path:r}).slice(0,32)}function bh(r){return xP("sha256").update(r).digest("hex")}async function xh(r){if(!sr(r.transactionId))throw new Error("Transaction id is invalid.");let t=`.staging-${r.transactionId.slice(4)}`,e=await Fe(r.workspaceRoot,[".kwikqa","transactions",t]);await Fe(r.workspaceRoot,[".kwikqa","transactions",t,"preimages"]),await Fe(r.workspaceRoot,[".kwikqa","transactions",t,"results"]);let n=[];for(let c of r.targets){let l=PP(c.path),u=`preimages/${l}.bin`,p=`results/${l}.bin`;await me(It(e,u),c.sourceBytes,{mode:384,replace:!1}),await me(It(e,p),c.resultBytes,{mode:384,replace:!1}),n.push({id:l,path:c.path,sourceSha256:c.sourceSha256,resultSha256:c.resultSha256,preimageFile:u,resultFile:p,preimageBytes:c.sourceBytes.byteLength,resultBytes:c.resultBytes.byteLength})}let i={schemaVersion:Jn,transactionId:r.transactionId,preview:r.preview,authorization:r.authorization,config:r.config,maxTargetBytes:r.maxTargetBytes,targets:n,createdAt:r.now},s={...i,manifestHash:C(i)};await me(It(e,"manifest.json"),`${de(s)}
49
- `,{mode:384,replace:!1});let a={sequence:1,type:"prepared",at:r.now,phase:"prepared"},o={schemaVersion:Jn,transactionId:r.transactionId,manifestHash:s.manifestHash,phase:"prepared",revision:1,updatedAt:r.now,history:[a]},d={...o,stateHash:C(o)};return await me(It(e,"state.json"),`${de(d)}
50
- `,{mode:384,replace:!1}),await hh(r.workspaceRoot,t,r.transactionId),xe(r.workspaceRoot,r.transactionId)}async function xe(r,t){if(!sr(t))throw new Error("Transaction id is invalid.");let e=await ks(r),n=await Fe(e.root,[".kwikqa","transactions",t]),i=kP(wh(await Es(It(n,"manifest.json"),"utf8"))),s=IP(wh(await Es(It(n,"state.json"),"utf8")));if(i.transactionId!==t||s.transactionId!==t||s.manifestHash!==i.manifestHash)throw new Error("Transaction identity mismatch.");let a=new Map,o=new Map;for(let d of i.targets){if(!/^[a-f0-9]{32}$/.test(d.id)||d.preimageFile!==`preimages/${d.id}.bin`||d.resultFile!==`results/${d.id}.bin`)throw new Error("Transaction target record is malformed.");let c=await Es(It(n,d.preimageFile)),l=await Es(It(n,d.resultFile));if(c.byteLength!==d.preimageBytes||l.byteLength!==d.resultBytes||bh(c)!==d.sourceSha256||bh(l)!==d.resultSha256)throw new Error("Transaction target bytes are malformed.");a.set(d.path,c),o.set(d.path,l)}return{directory:n,manifest:i,state:s,preimages:a,results:o}}function RP(r,t){return t==="conflicted"?r!=="completed"&&r!=="rolled-back":{prepared:["applying","rolling-back"],applying:["applying","applied","rolling-back"],applied:["validating","rolling-back"],validating:["completed","rolling-back"],"rolling-back":["rolling-back","rolled-back","applying"],"rolled-back":[],completed:[],conflicted:[]}[r].includes(t)}async function Be(r){let t=await xe(r.transaction.manifest.preview.workspace.workspaceRoot,r.transaction.manifest.transactionId);if(t.state.revision!==r.transaction.state.revision)throw new Error("Transaction state changed concurrently.");if(!RP(t.state.phase,r.phase))throw new Error("Transaction phase transition is not permitted.");let e={sequence:t.state.history.length+1,type:r.type,at:r.now,phase:r.phase,...r.path===void 0?{}:{path:r.path},...r.message===void 0?{}:{message:r.message},...r.planHash===void 0?{}:{planHash:r.planHash},...r.validationRunId===void 0?{}:{validationRunId:r.validationRunId},...r.validationManifestHash===void 0?{}:{validationManifestHash:r.validationManifestHash}},n={schemaVersion:Jn,transactionId:t.manifest.transactionId,manifestHash:t.manifest.manifestHash,phase:r.phase,revision:t.state.revision+1,updatedAt:r.now,history:[...t.state.history,e]},i={...n,stateHash:C(n)};return await me(It(t.directory,"state.json"),`${de(i)}
51
- `,{mode:384,replace:!0}),xe(t.manifest.preview.workspace.workspaceRoot,t.manifest.transactionId)}async function Xn(r){let t=await ks(r);return(await vP(t.transactionsDirectory,{withFileTypes:!0}).catch(n=>{if(n.code==="ENOENT")return[];throw n})).filter(n=>n.isDirectory()&&!n.isSymbolicLink()&&sr(n.name)).map(n=>n.name).sort()}import{createHash as TP}from"node:crypto";import{lstat as kh,readFile as Ih,realpath as Cs}from"node:fs/promises";import{isAbsolute as AP,relative as SP,resolve as Ph,sep as EP}from"node:path";var CP=2*1024*1024,Os=4*1024*1024;function Ns(r,t){let e=SP(r,t);return e===""||!AP(e)&&e!==".."&&!e.startsWith(`..${EP}`)}async function ar(r,t,e){let n=await Cs(r),i=Ph(n,t);if(!Ns(n,i))throw new Error("Validation evidence path escapes its run.");let s=await kh(i),a=await Cs(i);if(!s.isFile()||s.isSymbolicLink()||!Ns(n,a)||s.size>e)throw new Error("Validation evidence file is unsafe or unbounded.");return JSON.parse(await Ih(a,"utf8"))}async function Od(r,t){if(!Ot.test(t))throw new Error("Validation command id is invalid.");return bd(await ar(r,`commands/${t}/result.json`,CP))}async function vh(r,t,e,n,i){let s=Ph(r,t);if(!Ns(r,s))return!1;let a=await kh(s).catch(()=>{}),o=await Cs(s).catch(()=>{});if(a===void 0||o===void 0||!a.isFile()||a.isSymbolicLink()||!Ns(r,o)||a.size>i||a.size!==e)return!1;let d=await Ih(o).catch(()=>{});return d!==void 0&&d.byteLength===e&&TP("sha256").update(d).digest("hex")===n}async function Dd(r,t,e){let n=await Cs(r);for(let i of[t.stdout,t.stderr])if(!await vh(n,i.path,i.storedBytes,i.storedSha256,rr))return!1;for(let i of t.artifacts)if(!await vh(n,i.path,i.bytes,i.sha256,e))return!1;return!0}async function Rh(r,t,e){try{let n=await Od(r,t.commandId);return C(n)===C(t)&&await Dd(r,t,e)}catch{return!1}}import{createHash as NP}from"node:crypto";import{lstat as Ah,readFile as Sh,realpath as Ds}from"node:fs/promises";import{isAbsolute as OP,relative as DP,resolve as Eh,sep as LP}from"node:path";function Ls(r,t){let e=DP(r,t);return e===""||!OP(e)&&e!==".."&&!e.startsWith(`..${LP}`)}function MP(r){return r.status==="expected"?"passed":r.status==="skipped"?"skipped":r.attempts.some(t=>t.status==="interrupted")?"interrupted":"failed"}var Th={passed:0,skipped:1,interrupted:2,failed:3};function Ch(r){let t=new Map;for(let e of r){let n=MP(e),i=t.get(e.logicalTestId);(i===void 0||Th[n]>Th[i])&&t.set(e.logicalTestId,n)}return[...t].map(([e,n])=>({logicalTestId:e,status:n})).sort((e,n)=>e.logicalTestId.localeCompare(n.logicalTestId))}async function Ld(r){if(!Number.isInteger(r.maxBytes)||r.maxBytes<=0)throw new Error("Validation report byte limit is invalid.");let t=await Ds(r.runDirectory).catch(()=>{});if(t===void 0)return{kind:"incomplete",reason:"Validation run directory is unavailable."};let e=Eh(t,r.artifact.path);if(!Ls(t,e))return{kind:"incomplete",reason:"Validation report path escapes its run directory."};let n=await Ah(e).catch(()=>{}),i=await Ds(e).catch(()=>{});if(n===void 0||i===void 0||!n.isFile()||n.isSymbolicLink()||!Ls(t,i)||n.size>r.maxBytes||n.size!==r.artifact.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unsafe."};let s=await Sh(i).catch(()=>{});if(s===void 0||s.byteLength>r.maxBytes||s.byteLength!==r.artifact.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unbounded."};let a=vr(s,{workspaceRoot:r.workspaceRoot,...r.gitRoot===void 0?{}:{gitRoot:r.gitRoot},reportPath:r.artifact.path});if(a.kind!=="parsed")return{kind:"incomplete",reason:`Validation report could not be parsed: ${a.diagnostic.reasonCode}.`};if(a.run.usability!=="analysis-ready")return{kind:"incomplete",reason:`Validation report is not analysis-ready: ${a.run.usability}.`};if(a.run.sourceHashes.report!==r.artifact.sha256)return{kind:"incomplete",reason:"Validation report content hash does not match its record."};let o=Ch(a.run.logicalTests),d=new Set(o.map(c=>c.logicalTestId));return r.expectedLogicalTestIds.some(c=>!d.has(c))?{kind:"incomplete",reason:"Validation report omits an expected logical test."}:{kind:"observed",reportSha256:a.run.sourceHashes.report,observations:o}}var Ms=/^(?:cypress|wdio)-[^/]*\.json$/;async function Md(r){if(!Number.isInteger(r.maxBytes)||r.maxBytes<=0)throw new Error("Validation report byte limit is invalid.");let t=await Ds(r.runDirectory).catch(()=>{});if(t===void 0)return{kind:"incomplete",reason:"Validation run directory is unavailable."};let e=r.artifacts.filter(d=>Ms.test(d.path.split("/").at(-1)??""));if(e.length===0)return{kind:"incomplete",reason:"The test run wrote no KwikQA report."};let n=[],i=0;for(let d of e){let c=Eh(t,d.path);if(!Ls(t,c))return{kind:"incomplete",reason:"Validation report path escapes its run directory."};let l=await Ah(c).catch(()=>{}),u=await Ds(c).catch(()=>{});if(l===void 0||u===void 0||!l.isFile()||l.isSymbolicLink()||!Ls(t,u)||l.size!==d.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unsafe."};if(i+=l.size,i>r.maxBytes)return{kind:"incomplete",reason:"Validation reports exceed their byte limit."};let p=await Sh(u).catch(()=>{});if(p===void 0||p.byteLength!==d.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unbounded."};if(NP("sha256").update(p).digest("hex")!==d.sha256)return{kind:"incomplete",reason:"Validation report content hash does not match its record."};n.push({path:u,bytes:p})}let s=Gi(n,{workspaceRoot:r.workspaceRoot,...r.gitRoot===void 0?{}:{gitRoot:r.gitRoot}});if(s.kind!=="parsed")return{kind:"incomplete",reason:`Validation report could not be parsed: ${s.diagnostic.reasonCode}.`};if(s.run.artifact.format!=="kwikqa-json")return{kind:"incomplete",reason:"Validation report was not written by KwikQA's reporter."};if(s.run.usability==="interrupted"||s.run.usability==="zero-tests")return{kind:"incomplete",reason:`Validation report is not analysis-ready: ${s.run.usability}.`};let a=Ch(s.run.logicalTests),o=new Set(a.map(d=>d.logicalTestId));return r.expectedLogicalTestIds.some(d=>!o.has(d))?{kind:"incomplete",reason:"Validation report omits an expected logical test."}:{kind:"observed",reportSha256:s.run.sourceHashes.report,observations:a}}var FP=/^txn_[a-f0-9]{24}$/,jP=/^vld_[a-f0-9]{24}$/,BP=new Set(["rolling-back","rolled-back","conflicted"]);function VP(r){return r.length>0&&Number.isFinite(Date.parse(r))}function zP(r){return r.commands.filter(t=>t.required&&t.timing==="post-patch").sort((t,e)=>t.commandId.localeCompare(e.commandId))}function HP(r,t){let e=new Set(r);return e.size===r.length&&r.length===t.length&&t.every(n=>e.has(n))}function qP(r,t,e){let n=r.manifest.preview.authoritativeValidation,i=new Map(n.requiredCommands.map(s=>[s.commandId,s.commandHash]));return n.planHash===t.planHash&&n.repositoryFingerprint===t.repositoryFingerprint&&C(n.targetHashes)===C(t.targetHashes)&&HP(n.requiredCommandIds,e.map(s=>s.commandId))&&e.every(s=>i.get(s.commandId)===C(s))}async function UP(r,t){for(let e of t.manifest.targets){let n=await K(r,e.path,Math.max(1,e.resultBytes)).catch(()=>{});if(n?.kind!=="read"||n.relativePath!==e.path||n.sha256!==e.resultSha256)return!1}return!0}function GP(r){return r===void 0?[]:Object.entries(r.logicalTestOutcomes).map(([t,e])=>({logicalTestId:t,status:e})).sort((t,e)=>t.logicalTestId.localeCompare(e.logicalTestId))}async function KP(r,t,e,n,i,s){let a={classification:{commandId:i.commandId,required:!0,timing:"post-patch",status:"incomplete",fresh:!0,expectedLogicalTestIds:i.logicalTestIds,observations:[]}},o=await Od(e,i.commandId).catch(()=>{});if(o===void 0||o.validationRunId!==r.validationRunId||o.planHash!==n.planHash||o.commandId!==i.commandId||o.commandHash!==C(i)||o.timing!=="post-patch"||!await Dd(e,o,i.artifactPolicy.maxArtifactBytes))return a;let d=[],c=o.status==="blocked"?"incomplete":o.status;if(Fr(i.kind)&&!i.kind.startsWith("playwright-")&&o.status!=="unavailable"){let l=await Md({workspaceRoot:t,...r.gitRoot===void 0?{}:{gitRoot:r.gitRoot},runDirectory:e,artifacts:o.artifacts,expectedLogicalTestIds:i.logicalTestIds,maxBytes:r.reportMaxBytes});l.kind==="observed"?d=l.observations:c="incomplete"}else if(i.kind.startsWith("playwright-")&&o.status!=="unavailable"){let l=i.artifactPolicy.reportFile??Hn,u=o.artifacts.find(p=>p.path.split("/").at(-1)===l);if(u===void 0)c="incomplete";else{let p=await Ld({workspaceRoot:t,...r.gitRoot===void 0?{}:{gitRoot:r.gitRoot},runDirectory:e,artifact:u,expectedLogicalTestIds:i.logicalTestIds,maxBytes:r.reportMaxBytes});p.kind==="observed"?d=p.observations:c="incomplete"}}return{record:o,classification:{commandId:i.commandId,required:!0,timing:"post-patch",status:c,fresh:Date.parse(o.startedAt)>=s&&!o.stdout.truncated&&!o.stderr.truncated,expectedLogicalTestIds:i.logicalTestIds,observations:d}}}async function WP(r,t,e,n){let i=await xe(t,r.transactionId),s=i.manifest.preview.authoritativeValidation,a=i.state.history,o=a.findLastIndex(I=>I.type==="validation-started"),d=a[o],c=zP(e);if(d===void 0||d.validationRunId!==r.validationRunId||d.planHash!==e.planHash||!qP(i,e,c))throw new Error("Validation run does not match the durable transaction approval.");if(s.baselineManifestHash!==n?.baselineHash||n!==void 0&&(n.planHash!==e.planHash||n.repositoryFingerprint!==e.repositoryFingerprint||C(n.targetHashes)!==C(e.targetHashes)))throw new Error("Required validation baseline is missing or mismatched.");let l=await Fe(t,[".kwikqa","transactions",r.transactionId,"validation",r.validationRunId]),u=await ar(l,"manifest.json",Os).catch(I=>{if(I.code!=="ENOENT")throw I});if(u!==void 0){let I=Dt(u);if(I.transactionId!==r.transactionId||I.validationRunId!==r.validationRunId||I.planHash!==e.planHash)throw new Error("Validation run was already finalized for different evidence.");return{directory:l,manifest:I}}let p=[],f=i.state.phase;if(f==="validating")await UP(t,i)||p.push("Applied validation targets changed before the run was finalized.");else if(BP.has(f)&&!a.slice(o+1).some(I=>I.type==="validation-passed"))p.push("The transaction left validation before M6 accepted this run.");else throw new Error("Validation run cannot be finalized from the current transaction phase.");let h=Date.parse(d.at),g=r.completedAt??new Date().toISOString();if(Date.parse(g)<h)throw new Error("Validation completion precedes command execution.");let m=[],y=[];for(let I of c){let R=await KP(r,t,l,e,I,h);R.record!==void 0&&m.push(R.record),y.push(R.classification)}let w=yd({targetLogicalTestIds:e.targetLogicalTestIds,baseline:GP(n),commands:y,blockingReasons:p}),x={schemaVersion:hs,validationRunId:r.validationRunId,transactionId:r.transactionId,planHash:e.planHash,repositoryFingerprint:e.repositoryFingerprint,targetHashes:e.targetHashes,requiredCommandIds:c.map(I=>I.commandId),status:w.status,commandRecords:m,classifications:w.classifications,startedAt:d.at,completedAt:g},v=Dt({...x,manifestHash:ys(x)});return await me(_P(l,"manifest.json"),`${de(v)}
52
- `,{mode:384,replace:!1}),{directory:l,manifest:v}}async function $d(r){if(!FP.test(r.transactionId)||!jP.test(r.validationRunId)||!Number.isInteger(r.reportMaxBytes)||r.reportMaxBytes<=0||r.completedAt!==void 0&&!VP(r.completedAt))throw new Error("Validation finalization identity, timestamp, or limits are invalid.");let t=nr(r.plan);if(t.status!=="resolved")throw new Error("Unavailable validation plan cannot be finalized.");if(t.transactionId!==void 0&&t.transactionId!==r.transactionId)throw new Error("Validation plan is bound to another transaction.");let e=r.baseline===void 0?void 0:Un(r.baseline),n=await $P(r.workspaceRoot),i=await Ue(n,{operation:"finalize-validation",transactionId:r.transactionId,validationRunId:r.validationRunId});try{return await WP(r,n,t,e)}finally{await i.release().catch(()=>{})}}import{fileURLToPath as lR}from"node:url";import{execFile as JP}from"node:child_process";import{lstat as _s,realpath as nt}from"node:fs/promises";import{createRequire as XP}from"node:module";import{dirname as Pt,isAbsolute as Dh,join as _d,relative as YP,resolve as Lh,sep as QP}from"node:path";import{fileURLToPath as ZP}from"node:url";import{promisify as eR}from"node:util";var tR=eR(JP),Mh=128*1024,rR=64*1024,nR=/^[a-f0-9]{64}$/,Nh={"@playwright/test":{entryRequests:["@playwright/test/cli"]},cypress:{entryRequests:["cypress/bin/cypress"],bin:"cypress"},"@wdio/cli":{entryRequests:["@wdio/cli/bin/wdio.js"],bin:"wdio"},"@biomejs/biome":{entryRequests:["@biomejs/biome/bin/biome"]},prettier:{entryRequests:["prettier/bin/prettier.cjs","prettier/bin/prettier.js"]},typescript:{entryRequests:["typescript/bin/tsc"],bin:"tsc"},eslint:{entryRequests:["eslint/bin/eslint.js"]}};function Vr(r,t){let e=YP(r,t);return e===""||!Dh(e)&&e!==".."&&!e.startsWith(`..${QP}`)}function $s(r,t,e){return{code:r,message:t,...e===void 0?{}:{path:e}}}function iR(r,t){let e=new TextDecoder("utf-8",{fatal:!0}).decode(r),n=JSON.parse(e);if(n===null||typeof n!="object"||Array.isArray(n))throw new Error("Package manifest is not an object.");let i=n;if(i.name!==t||typeof i.version!="string"||i.version.trim().length===0)throw new Error("Package identity does not match the requested tool.");return{name:i.name,version:i.version}}async function sR(r,t){let e=await nt(r),n=Dh(t)?t:Lh(e,t),i=await nt(n).catch(()=>n);if(!Vr(e,i))return;let s=i;for((await _s(s).catch(()=>{}))?.isFile()&&(s=Pt(s));Vr(e,s);){let o=_d(s,"package.json"),d=await _s(o).catch(()=>{});if(d?.isFile()&&!d.isSymbolicLink())return o;if(s===e)break;s=Pt(s)}}async function aR(r,t){let e=await nt(r),n=Pt(t);for(;Vr(e,n);){let i=_d(n,".pnp.cjs"),s=await _s(i).catch(()=>{});if(s?.isFile()&&!s.isSymbolicLink())return i;if(n===e)break;n=Pt(n)}}async function Oh(r,t,e){let n=Pt(r);for(;;){let i=_d(n,"node_modules",...t.split("/"),"package.json");if(await _s(i).catch(()=>{})!==void 0){let o=await nt(i),d=await K(Pt(o),o,Mh).catch(()=>{}),l=(d?.kind==="read"?JSON.parse(new TextDecoder().decode(d.bytes)):void 0)?.bin,u=typeof l=="string"?l:typeof l=="object"&&l!==null?l[e]:void 0;if(typeof u!="string")throw new Error("Package declares no CLI entry.");let p=await nt(Lh(Pt(o),u));return{manifestPath:o,entryPath:p}}let a=Pt(n);if(a===n)throw new Error("Package is not installed.");n=a}}async function oR(r,t){let e=XP(r),n=Nh[t].bin,i;try{i=await nt(e.resolve(`${t}/package.json`))}catch(a){if(n===void 0)throw a;return Oh(r,t,n)}let s;for(let a of Nh[t].entryRequests)try{s=await nt(e.resolve(a));break}catch{}if(s===void 0){if(n!==void 0)return Oh(r,t,n);throw new Error("Package CLI entry could not be resolved.")}return{manifestPath:i,entryPath:s}}async function Fd(r,t){let e=await nt(t),n=await K(r,e,16*1024*1024);if(n.kind!=="read")throw new Error("PnP loader is not an authorized repository-local regular file.");return{path:e,relativePath:n.relativePath,sha256:n.sha256}}async function dR(r,t,e,n){let i=ZP(new URL("./pnp-resolver.mjs",import.meta.url)),{stdout:s}=await tR(process.execPath,[i,r,t.path,t.sha256,e,n],{encoding:"utf8",maxBuffer:rR,timeout:1e4,windowsHide:!0,env:{PATH:process.env.PATH??""}}),a=JSON.parse(s);if(a===null||typeof a!="object"||Array.isArray(a))throw new Error("PnP resolver output is malformed.");let o=a;if(typeof o.manifestPath!="string"||typeof o.entryPath!="string"||o.loaderSha256!==t.sha256)throw new Error("PnP resolver output is incomplete or has the wrong loader identity.");let d=await Fd(r,t.path);if(d.path!==t.path||d.relativePath!==t.relativePath||d.sha256!==t.sha256)throw new Error("PnP loader identity changed during resolution.");return{manifestPath:await nt(o.manifestPath),entryPath:await nt(o.entryPath)}}async function cR(r){let t=await K(r.root,r.paths.manifestPath,r.maxManifestBytes),e=await K(r.root,r.paths.entryPath,16*1024*1024);if(t.kind!=="read"||e.kind!=="read")throw new Error("Resolved package files are not authorized repository-local regular files.");let n=iR(t.bytes,r.packageName),i=Pt(r.paths.manifestPath);if(!Vr(i,r.paths.entryPath))throw new Error("Package CLI entry escapes its package root.");let s=[],a=[];if(r.loader!==void 0){let o=await Fd(r.root,r.loader.path);if(o.path!==r.loader.path||o.relativePath!==r.loader.relativePath||o.sha256!==r.loader.sha256)throw new Error("PnP loader identity changed before tool authorization completed.");a.push("--require",r.loader.path),s.push({kind:"pnp-loader",path:r.loader.relativePath,sha256:r.loader.sha256,detail:"Repository-local Yarn Plug'n'Play loader."})}return a.push(r.paths.entryPath),{packageName:r.packageName,packageVersion:n.version,packageRoot:i,packageManifest:r.paths.manifestPath,packageManifestSha256:t.sha256,entryPath:r.paths.entryPath,entrySha256:e.sha256,executable:process.execPath,nodeArguments:a,packageManagerLayout:r.layout,resolutionEvidence:[{kind:"package-root",path:i,detail:`Canonical repository-local ${r.packageName} package root.`},{kind:"package-manifest",path:t.relativePath,sha256:t.sha256,detail:`${n.name}@${n.version}`},{kind:"package-entry",path:e.relativePath,sha256:e.sha256,detail:"JavaScript CLI entry executed directly through the current Node runtime."},...s]}}async function Yn(r){try{let t=await nt(r.workspaceRoot),e=await sR(t,r.ownerPath);if(e===void 0)return{kind:"unavailable",reasons:[$s("ambiguous-package-root","No owning repository package was found.")]};let n=r.maxManifestBytes??Mh;if(!Number.isInteger(n)||n<=0)return{kind:"unavailable",reasons:[$s("budget-exceeded","Package manifest byte limit is invalid.")]};let i,s="node-modules",a;try{i=await oR(e,r.packageName)}catch{let d=await aR(t,e);if(d===void 0)throw new Error("No repository-local dependency resolution succeeded.");a=await Fd(t,d),s="pnp",i=await dR(t,a,e,r.packageName)}return!Vr(t,i.manifestPath)||!Vr(t,i.entryPath)?{kind:"unavailable",reasons:[$s("entry-outside-workspace","Resolved package files are outside the canonical workspace.")]}:{kind:"resolved",tool:await cR({root:t,packageName:r.packageName,paths:i,maxManifestBytes:n,layout:s,...a===void 0?{}:{loader:a}})}}catch{return{kind:"unavailable",reasons:[$s("missing-dependency",`Repository-local ${r.packageName} could not be resolved safely. No installation or global fallback was attempted.`)]}}}function Qn(r){if(r.tool.executable!==process.execPath||r.args.some(i=>i.includes("\0"))||r.workingDirectory.includes("\0")||!Number.isInteger(r.timeoutMs)||r.timeoutMs<=0)throw new Error("Resolved validation command is invalid.");let t=[...r.tool.nodeArguments,...r.args],e=[...r.tool.resolutionEvidence,...r.extraEvidence??[]],n=C({packageManifestSha256:r.tool.packageManifestSha256,entrySha256:r.tool.entrySha256,resolutionEvidence:e,kind:r.kind,timing:r.timing,executable:r.tool.executable,args:t,workingDirectory:r.workingDirectory,environmentDelta:r.environmentDelta,timeoutMs:r.timeoutMs,purpose:r.purpose,logicalTestIds:r.logicalTestIds,projectIds:r.projectIds,artifactPolicy:r.artifactPolicy});if(!nR.test(n))throw new Error("Command identity could not be constructed.");return{commandId:`cmd_${n.slice(0,24)}`,kind:r.kind,timing:r.timing,required:!0,executable:r.tool.executable,args:t,workingDirectory:r.workingDirectory,environmentDelta:r.environmentDelta,timeoutMs:r.timeoutMs,purpose:r.purpose,logicalTestIds:r.logicalTestIds,projectIds:r.projectIds,artifactPolicy:r.artifactPolicy,resolutionEvidence:e}}function jd(r,t){return C({purpose:"kwikqa-validation-repository-fingerprint",evidence:r,targetHashes:t})}var uR=/^[a-f0-9]{64}$/,Vd=3,pR=/^rps_[a-f0-9]{24}$/,Bd=lR(new URL("./parse-check.mjs",import.meta.url));function fR(r,t){switch(r.tool){case"biome":return t.biome;case"prettier":return t.prettier;case"typescript":return t.typescript;case"eslint":return t.eslint;case"kwikqa-babel":return}}function hR(r,t){return t==="unavailable"?void 0:`${r}-${t}`}var $h={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"};function mR(r,t){let e=["test"];if(t==="focused"?e.push(`${r.originalTest.path}:${r.originalTest.line}`,`--repeat-each=${Vd}`):t==="affected"&&e.push(...r.discovery.testPaths),t!=="suite")for(let n of r.discovery.projectIds)n!==""&&e.push(`--project=${n}`);return r.originalTest.configPath!==void 0&&e.push(`--config=${r.originalTest.configPath}`),e.push("--reporter=json",`--output=${r.artifactRoot}`,"--trace=retain-on-failure","--retries=0"),e}function yR(r,t){let e=t.targets.map(n=>n.path);switch(r.tool){case"biome":return r.kind==="format"?["format",...e]:["lint",...e];case"prettier":return["--check",...e];case"typescript":return["--noEmit","--pretty","false",...r.configPath?["--project",r.configPath]:[]];case"eslint":return e;case"kwikqa-babel":return[]}}function Fs(r){return{code:"resolution-failed",message:r}}function zd(r){if(!Number.isInteger(r.timeoutMs)||r.timeoutMs<=0||r.originalTest.line<=0||r.originalTest.logicalTestId.trim().length===0||r.originalTest.projectId.trim().length===0)throw new Error("Validation preparation input is invalid.");let t=C(r.advisoryPlan),e=[...new Set(r.affectedLogicalTestIds??[])].sort(),n=[...r.discovery.reasons.map(y=>({code:y.code==="budget-exceeded"?"budget-exceeded":"resolution-failed",message:y.message,...y.path===void 0?{}:{path:y.path}}))],i=[],s=[],a=r.framework??"playwright",o=r.tools[a],d=hR(a,r.discovery.scope),c=a==="playwright"?void 0:r.frameworkRun,l=()=>c?.args??mR(r,r.discovery.scope),u=c?.evidence??[],p=c?.workingDirectory??r.workspaceRoot;if(r.discovery.status!=="resolved"||d===void 0||o===void 0||a!=="playwright"&&c===void 0)n.push(Fs(`Repository-local ${$h[a]} validation could not be resolved.`));else{let y=[r.originalTest.logicalTestId,...(r.companionLogicalTestIds??[]).filter(x=>x!==r.originalTest.logicalTestId)],w=a!=="playwright"&&r.discovery.scope==="focused"?Vd:1;for(let x=1;x<=w;x+=1)i.push(Qn({tool:o,kind:d,timing:"post-patch",args:l(),workingDirectory:p,environmentDelta:{},timeoutMs:r.timeoutMs,purpose:`Run the approved risk-based ${$h[a]} validation scope${w>1?` (run ${x} of ${w})`:""}.`,logicalTestIds:r.discovery.scope==="focused"?[...new Set(y)].sort():e,projectIds:r.discovery.projectIds,artifactPolicy:{outputDirectory:r.artifactRoot,...a==="playwright"?{reportFile:"report.json"}:{},maxArtifacts:100,maxArtifactBytes:32*1024*1024},extraEvidence:u}));if(r.discovery.scope!=="focused"){(e.length===0||!e.includes(r.originalTest.logicalTestId))&&n.push(Fs("Shared validation scope lacks complete canonical affected-test identities."));let x=Qn({tool:o,kind:d,timing:"baseline",args:l(),workingDirectory:p,environmentDelta:{},timeoutMs:r.timeoutMs,purpose:"Capture required affected-test outcomes before shared-source mutation.",logicalTestIds:e,projectIds:r.discovery.projectIds,artifactPolicy:{outputDirectory:`${r.artifactRoot}-baseline`,...a==="playwright"?{reportFile:"report.json"}:{},maxArtifacts:100,maxArtifactBytes:32*1024*1024},extraEvidence:u});i.push(x);let v=`baseline_${C({commandId:x.commandId}).slice(0,24)}`;s.push({baselineId:v,commandId:x.commandId,logicalTestIds:e,reason:"Shared test support requires a pre-patch affected-test baseline."})}else r.originalTest.environmentEquivalent||n.push(Fs("Original failure evidence is not environment-equivalent to validation."))}for(let y of r.discovery.staticChecks){if(y.tool==="kwikqa-babel"){let x=C({purpose:"kwikqa-parse-check-command",executable:process.execPath,shim:Bd,paths:r.proposal.targets.map(v=>v.path),workingDirectory:r.workspaceRoot});i.push({commandId:`cmd_${x.slice(0,24)}`,kind:"parse",timing:"post-patch",required:!0,executable:process.execPath,args:[Bd,...r.proposal.targets.map(v=>v.path)],workingDirectory:r.workspaceRoot,environmentDelta:{},timeoutMs:r.timeoutMs,purpose:"Parse every changed JavaScript or TypeScript source file.",logicalTestIds:[],projectIds:r.discovery.projectIds,artifactPolicy:{outputDirectory:r.artifactRoot,maxArtifacts:1,maxArtifactBytes:1e6},resolutionEvidence:[{kind:"configuration",path:Bd,detail:"KwikQA-owned Babel parse-only validation shim."}]});continue}let w=fR(y,r.tools);if(w===void 0){n.push(Fs(`Required ${y.tool} check could not be resolved locally.`));continue}i.push(Qn({tool:w,kind:y.kind,timing:"post-patch",args:yR(y,r.proposal),workingDirectory:r.workspaceRoot,environmentDelta:{},timeoutMs:r.timeoutMs,purpose:`Run required ${y.kind} validation.`,logicalTestIds:[],projectIds:r.discovery.projectIds,artifactPolicy:{outputDirectory:r.artifactRoot,maxArtifacts:10,maxArtifactBytes:8*1024*1024}}))}let f=i.flatMap(y=>y.resolutionEvidence),h=r.proposal.targets.map(y=>({path:y.path,sourceSha256:y.sourceSha256,resultSha256:y.resultSha256})),g={schemaVersion:fs,policyVersion:ms,status:n.length===0?"resolved":"unavailable",proposalHash:r.proposal.proposalHash,targetLogicalTestIds:[r.originalTest.logicalTestId],targetHashes:h,advisoryPlanHash:t,repositoryFingerprint:jd(f,h),commands:[...i].sort((y,w)=>y.commandId.localeCompare(w.commandId)),baselineRequirements:[...s].sort((y,w)=>y.baselineId.localeCompare(w.baselineId)),unresolvedReasons:n},m={...g,planHash:gs(g)};return{plan:m,requiredBaselineCommands:m.commands.filter(y=>y.timing==="baseline")}}function Hd(r){if(r.plan.status!=="resolved"||!uR.test(r.plan.planHash)||!pR.test(r.repairSessionId)||r.attemptOrdinal!==1&&r.attemptOrdinal!==2)throw new Error("Only a resolved plan can become application execution authority.");let t=r.plan.baselineRequirements.map(i=>i.baselineId),e;if(t.length>0){if(r.baseline===void 0)throw new Error("Required pre-application baseline is missing.");e=Un(r.baseline);let i=new Map(r.plan.baselineRequirements.map(s=>[s.commandId,s]));if(e.planHash!==r.plan.planHash||e.repositoryFingerprint!==r.plan.repositoryFingerprint||C(e.targetHashes)!==C(r.plan.targetHashes)||e.commandRecords.length!==i.size||e.commandRecords.some(s=>{let a=i.get(s.commandId);return a===void 0||s.planHash!==r.plan.planHash||s.timing!=="baseline"||s.status!=="passed"||s.termination.kind!=="exit"||s.termination.exitCode!==0||s.stdout.truncated||s.stderr.truncated||a.logicalTestIds.some(o=>e?.logicalTestOutcomes[o]===void 0)}))throw new Error("Required pre-application baseline does not match the resolved plan.")}let n=r.plan.commands.filter(i=>i.timing==="post-patch"&&i.required).sort((i,s)=>i.commandId.localeCompare(s.commandId));return{schemaVersion:"1.0",policyVersion:"1.0",planHash:r.plan.planHash,repositoryFingerprint:r.plan.repositoryFingerprint,targetHashes:r.plan.targetHashes,advisoryPlanHash:C(r.advisoryPlan),...e===void 0?{}:{baselineManifestHash:e.baselineHash},requiredBaselineIds:t,requiredCommandIds:n.map(i=>i.commandId),requiredCommands:n.map(i=>({commandId:i.commandId,commandHash:C(i)})),repairSessionId:r.repairSessionId,attemptOrdinal:r.attemptOrdinal}}import{randomUUID as $R}from"node:crypto";import{lstat as ri,mkdir as Zd,readFile as _R,realpath as FR,rm as jR}from"node:fs/promises";import{isAbsolute as BR,join as Ur,relative as VR,resolve as zR,sep as HR}from"node:path";import{realpath as Hr}from"node:fs/promises";import{realpath as zr}from"node:fs/promises";var Ke=/^[a-f0-9]{64}$/,gR=/^rps_[a-f0-9]{24}$/;function _h(r){let t=r.map(e=>e.trim());return t.every(e=>e.length>0)&&new Set(t).size===r.length}function wR(r){return{kind:"rejected",reasons:r}}function Bh(r){return r.length>0&&Number.isFinite(Date.parse(r))}function js(r){return Number.isFinite(r)&&r>0}function bR(r){let{proposalHash:t,...e}=r;return Ke.test(t)&&C(e)===t}function xR(r){let t=[];(!bR(r)||C(r.diff)!==r.diffHash)&&t.push({code:"invalid-proposal",message:"Proposal and diff integrity hashes must match their canonical contents."}),(r.targets.length===0||r.changedFiles!==r.targets.length||r.targets.some(i=>!Ke.test(i.sourceSha256)||!Ke.test(i.resultSha256)||i.sourceSha256===i.resultSha256))&&t.push({code:"invalid-proposal",message:"Proposal targets and their source/result hashes must be complete and consistent."});let e=new Set,n=new Map;for(let i of r.targets){let s=i.path.toLocaleLowerCase("en-US"),a=n.get(s);(e.has(i.path)||a!==void 0&&a!==i.path)&&t.push({code:"invalid-proposal",message:"Proposal targets may not duplicate or case-collide.",path:i.path}),e.add(i.path),n.set(s,i.path)}return(r.replacements.length===0||r.replacements.some(i=>!e.has(i.path)))&&t.push({code:"invalid-proposal",message:"Every approved replacement must resolve to an approved proposal target."}),t}function vR(r){let t=xR(r.proposal);(r.context.workspace.workspaceRoot.length===0||r.context.workspace.gitRoot.length===0||r.context.snapshot.workspaceRoot!==r.context.workspace.workspaceRoot||r.context.snapshot.gitRoot!==r.context.workspace.gitRoot)&&t.push({code:"invalid-workspace",message:"Confirmed workspace and git roots must match the repository snapshot identity."}),(!Number.isInteger(r.context.maxTargetBytes)||r.context.maxTargetBytes<=0||r.context.config.schemaVersion.length===0)&&t.push({code:"invalid-configuration",message:"Application configuration and target byte limit must be explicit and bounded."}),(r.interactiveSession.sessionId.trim().length===0||!Bh(r.previewedAt))&&t.push({code:"invalid-preview",message:"An interactive session identity and valid preview timestamp are required."});let e=r.costBounds;(!Number.isInteger(e.maxRequestTokens)||!Number.isInteger(e.maxRunTokens)||!js(e.maxRequestTokens)||!js(e.maxRunTokens)||!js(e.maxRequestDollars)||!js(e.maxRunDollars)||e.maxRequestTokens>e.maxRunTokens||e.maxRequestDollars>e.maxRunDollars)&&t.push({code:"invalid-preview",message:"Approved request and run token/dollar bounds must be positive and internally consistent."});let n=new Set;for(let s of r.payloadManifests){if(!Ke.test(s.manifestHash)||!Ke.test(s.payloadHash)||!Ke.test(s.packetHash)||s.model.trim().length===0||s.provider.trim().length===0||s.promptVersion.trim().length===0||s.outputSchemaVersion.trim().length===0||n.has(s.manifestHash)){t.push({code:"invalid-preview",message:"Model payload manifest references must be sanitized, complete, and unique."});break}n.add(s.manifestHash)}(r.scopes.baseline.some(s=>s.trim().length===0)||r.scopes.validation.some(s=>s.trim().length===0))&&t.push({code:"invalid-preview",message:"Baseline and validation scopes may not contain empty entries."});let i=r.authoritativeValidation;return(i.schemaVersion!=="1.0"||i.policyVersion!=="1.0"||!Ke.test(i.planHash)||!Ke.test(i.repositoryFingerprint)||!Ke.test(i.advisoryPlanHash)||i.targetHashes.length!==r.proposal.targets.length||i.targetHashes.some((s,a)=>{let o=r.proposal.targets[a];return o===void 0||s.path!==o.path||s.sourceSha256!==o.sourceSha256||s.resultSha256!==o.resultSha256})||i.baselineManifestHash!==void 0&&!Ke.test(i.baselineManifestHash)||!gR.test(i.repairSessionId)||i.attemptOrdinal!==1&&i.attemptOrdinal!==2||!_h(i.requiredBaselineIds)||!_h(i.requiredCommandIds)||i.requiredCommandIds.length===0||i.requiredCommands.length!==i.requiredCommandIds.length||i.requiredCommands.some((s,a)=>s.commandId!==i.requiredCommandIds[a]||!Ke.test(s.commandHash))||i.requiredBaselineIds.length>0&&i.baselineManifestHash===void 0)&&t.push({code:"invalid-preview",message:"Authoritative validation approval metadata is incomplete or inconsistent."}),t}function qd(r){return C({purpose:"kwikqa-approved-application",...r})}function Ud(r){let t=vR(r);if(t.length>0)return wR(t);let e={schemaVersion:"2.0",bindingVersion:"2.0",proposal:r.proposal,workspace:r.context.workspace,checkoutPristine:r.context.snapshot.dirtyPaths.length===0,validationPlan:r.proposal.validationPlan,scopes:r.scopes,authoritativeValidation:r.authoritativeValidation,payloadManifests:r.payloadManifests,costBounds:r.costBounds,previewedAt:r.previewedAt,interactiveSession:r.interactiveSession};return{kind:"preview-ready",preview:{...e,bindingHash:qd(e)}}}function Bs(r,t,e,n){return C({purpose:"kwikqa-interactive-application-authorization",previewBindingHash:r.bindingHash,authorizationId:t,authorizedAt:e,interactiveSession:n})}function Gd(r,t){let{bindingHash:e,...n}=r;return Ke.test(e)&&qd(n)===e&&t.authorizationId.trim().length>0&&Bh(t.authorizedAt)&&t.bindingHash===Bs(r,t.authorizationId,t.authorizedAt,t.interactiveSession)&&t.interactiveSession.sessionId===r.interactiveSession.sessionId}import{realpath as Vs}from"node:fs/promises";import{isAbsolute as AR,relative as SR,sep as ER}from"node:path";import{createHash as kR}from"node:crypto";function IR(r){return kR("sha256").update(r,"utf8").digest("hex")}function Kd(r,t,e){let n=[],i=[];for(let o of e){if(o.oldText.length===0||o.newText===o.oldText||o.rationale.trim().length===0||o.expectedEffect.trim().length===0||o.evidenceIds.length===0){n.push({code:"invalid-replacement",message:"Replacement fields must be meaningful, cited, and non-no-op.",path:r});continue}if(o.oldText===t){n.push({code:"invalid-replacement",message:"A replacement may not rewrite the complete file.",path:r});continue}let d=t.indexOf(o.oldText);if(d<0||t.indexOf(o.oldText,d+1)>=0){n.push({code:"non-unique-match",message:"Replacement preimage must occur exactly once.",path:r});continue}i.push({start:d,end:d+o.oldText.length,newText:o.newText})}let s=[...i].sort((o,d)=>o.start-d.start);for(let o=1;o<s.length;o+=1){let d=s[o-1],c=s[o];d!==void 0&&c!==void 0&&c.start<d.end&&n.push({code:"overlapping-replacement",message:"Exact replacements overlap in the original source.",path:r})}if(n.length>0)return{kind:"rejected",reasons:n};let a=t;for(let o of[...s].sort((d,c)=>c.start-d.start))a=`${a.slice(0,o.start)}${o.newText}${a.slice(o.end)}`;return{kind:"applied",result:a,resultSha256:IR(a)}}function Vh(r){let t=[],e=[];for(let n of r){let i=Kd(n.path,n.source,n.replacements);if(i.kind==="rejected"){t.push(...i.reasons);continue}e.push({...n,result:i.result,resultSha256:i.resultSha256})}return t.length>0?{kind:"rejected",reasons:t}:{kind:"applied",targets:e}}import{isAbsolute as PR}from"node:path";function RR(r){return r.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function zh(r,t){let e=RR(r).replaceAll("**/","\0").replaceAll("**","").replaceAll("*","[^/]*").replaceAll("\0","(?:.*/)?").replaceAll("",".*");return new RegExp(`^${e}$`).test(t)}function Zn(r){return r.length===0||r.includes("\0")||r.includes("\\")||PR(r)||/^[A-Za-z]:/.test(r)?!0:r.split("/").some(t=>t===""||t==="."||t==="..")}function ei(r,t){let e=r.toLowerCase(),n=e.split("/").at(-1)??e;return e.includes("/node_modules/")||e.startsWith("node_modules/")||e.includes("/src/")||e.startsWith("src/")||new Set(["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"]).has(n)?!0:t.generatedPaths.some(i=>zh(i,r))}function ti(r,t){return t.find(e=>zh(e.pattern,r))}function TR(r){try{return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}async function Hh(r,t,e,n){let i=[],s=new Map;for(let l of e){if(Zn(l.path)){i.push({code:"unauthorized-target",message:"Target path is not a safe repository-relative path.",path:l.path});continue}let u=s.get(l.path)??[];u.push(l),s.set(l.path,u)}if(i.length>0)return{kind:"rejected",reasons:i};let a=new Set(t.dirtyPaths.map(l=>l.replaceAll("\\","/").toLocaleLowerCase("en-US"))),o=new Set,d=new Map,c=[];for(let[l,u]of[...s].sort(([p],[f])=>p.localeCompare(f))){let p=ti(l,r.editablePaths);if(p===void 0||ei(l,r)){i.push({code:"unauthorized-target",message:"Target is outside the configured test-support repair boundary.",path:l});continue}if(a.has(l.toLocaleLowerCase("en-US"))){i.push({code:"dirty-target-file",message:"Already-dirty target files are read-only.",path:l});continue}let f=await K(t.workspaceRoot,l,n);if(f.kind!=="read"){i.push({code:f.kind==="unauthorized"?"unauthorized-target":"unreadable-target",message:f.message,...f.relativePath===void 0?{path:l}:{path:f.relativePath}});continue}if(f.relativePath!==l){i.push({code:"unauthorized-target",message:"Target path does not match its canonical repository-relative path.",path:l});continue}let h=f.relativePath.toLocaleLowerCase("en-US"),g=d.get(h);if(o.has(f.relativePath)||g!==void 0&&g!==f.relativePath){i.push({code:"unauthorized-target",message:"Target aliases or case-collides with another target.",path:l});continue}o.add(f.relativePath),d.set(h,f.relativePath);let m=TR(f.bytes);if(m===void 0){i.push({code:"unreadable-target",message:"Target is not valid UTF-8.",path:l});continue}if(u.some(y=>y.sourceSha256!==void 0&&y.sourceSha256!==f.sha256)){i.push({code:"source-hash-mismatch",message:"Target source hash differs from the proposed preimage.",path:l});continue}c.push({path:f.relativePath,class:p.class,source:m,sourceSha256:f.sha256,replacements:u})}return i.length>0?{kind:"rejected",reasons:i}:{kind:"authorized",targets:c}}function CR(r,t){let e=SR(r,t);return e===""||!AR(e)&&e!==".."&&!e.startsWith(`..${ER}`)}function NR(r){try{return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}async function qh(r){if(!Number.isInteger(r.maxTargetBytes)||r.maxTargetBytes<=0||r.maxTargetBytes>1e6)return{kind:"rejected",code:"invalid-limit",message:"Target limit is invalid."};let t,e,n,i;try{[t,e,n,i]=await Promise.all([Vs(r.workspaceRoot),Vs(r.gitRoot),Vs(r.approvedWorkspaceRoot),Vs(r.approvedGitRoot)])}catch{return{kind:"rejected",code:"workspace-mismatch",message:"Workspace roots are unreadable."}}if(t!==n||e!==i||!CR(t,e))return{kind:"rejected",code:"workspace-mismatch",message:"Current and approved canonical workspace identities differ."};let s=new Set(r.dirtyPaths.map(c=>c.replaceAll("\\","/").toLocaleLowerCase("en-US"))),a=new Map;for(let c of r.proposal.replacements){let l=a.get(c.path)??[];l.push(c),a.set(c.path,l)}let o=new Set,d=[];for(let c of r.proposal.targets){let l=c.path.toLocaleLowerCase("en-US");if(o.has(l)||Zn(c.path))return{kind:"rejected",code:"unsafe-target",message:"Target aliases, case-collides, or has an unsafe path.",path:c.path};o.add(l);let u=ti(c.path,r.config.editablePaths);if(u===void 0||u.class!==c.class||ei(c.path,r.config))return{kind:"rejected",code:"unauthorized-target",message:"Target is outside the approved repair boundary.",path:c.path};if(s.has(l))return{kind:"rejected",code:"dirty-target-file",message:"An approved target is currently dirty.",path:c.path};let p=await K(t,c.path,r.maxTargetBytes);if(p.kind!=="read"||p.relativePath!==c.path)return{kind:"rejected",code:"unreadable-target",message:"Target could not be read through its canonical authorized path.",path:c.path};if(p.sha256!==c.sourceSha256)return{kind:"rejected",code:"source-hash-mismatch",message:"Target no longer matches the approved preimage.",path:c.path};let f=NR(p.bytes);if(f===void 0)return{kind:"rejected",code:"unreadable-target",message:"Target is not valid UTF-8.",path:c.path};let h=a.get(c.path)??[],g=Kd(c.path,f,h);if(g.kind!=="applied"||g.resultSha256!==c.resultSha256)return{kind:"rejected",code:"result-hash-mismatch",message:"Approved replacements no longer derive the approved result.",path:c.path};d.push({path:c.path,source:f,sourceBytes:p.bytes,sourceSha256:p.sha256,result:g.result,resultBytes:new TextEncoder().encode(g.result),resultSha256:g.resultSha256,replacements:h})}return{kind:"verified",workspaceRoot:t,gitRoot:e,targets:d,nonPristine:r.dirtyPaths.length>0}}var OR=new Set(["completed","rolled-back","conflicted"]);function or(r,t,e){return{code:r,message:t,...e===void 0?{}:{path:e}}}function Pe(r){return{schemaVersion:"2.0",transactionId:r.manifest.transactionId,authorizationId:r.manifest.authorization.authorizationId,approvalBindingHash:r.manifest.preview.bindingHash,proposalHash:r.manifest.preview.proposal.proposalHash,diffHash:r.manifest.preview.proposal.diffHash,workspace:r.manifest.preview.workspace,phase:r.state.phase,revision:r.state.revision,targets:r.manifest.targets.map(t=>({path:t.path,sourceSha256:t.sourceSha256,resultSha256:t.resultSha256,preimageBytes:t.preimageBytes,resultBytes:t.resultBytes})),validationPlan:r.manifest.preview.validationPlan,authoritativeValidation:r.manifest.preview.authoritativeValidation,createdAt:r.manifest.createdAt,updatedAt:r.state.updatedAt}}async function DR(r){return(await Promise.all((await Xn(r)).map(e=>xe(r,e)))).filter(e=>!OR.has(e.state.phase))}async function Uh(r,t,e,n){let i=await K(r,t,e);return i.kind==="read"&&i.relativePath===t&&i.sha256===n}async function Wd(r){return LR(r,{})}async function LR(r,t){if(!Gd(r.preview,r.authorization))return{kind:"rejected",reasons:[or("authorization-mismatch","Authorization does not match this exact preview.")]};let e=r.now??new Date().toISOString(),n;try{let[i,s,a,o,d,c]=await Promise.all([zr(r.context.workspace.workspaceRoot),zr(r.context.snapshot.workspaceRoot),zr(r.preview.workspace.workspaceRoot),zr(r.context.workspace.gitRoot),zr(r.context.snapshot.gitRoot),zr(r.preview.workspace.gitRoot)]);if(i!==s||i!==a||o!==d||o!==c)return{kind:"rejected",reasons:[or("invalid-workspace","Application workspace identity changed.")]};let l=a;n=await Ue(l,{operation:"apply",authorizationId:r.authorization.authorizationId,at:e});let u=await DR(l);if(u.length>0)return{kind:"recovery-required",reasons:[or("transaction-blocked","A nonterminal transaction must be recovered before another application.")],transaction:Pe(u[0])};if((await Promise.all((await Xn(l)).map(m=>xe(l,m)))).some(m=>m.manifest.authorization.authorizationId===r.authorization.authorizationId))return{kind:"rejected",reasons:[or("authorization-replayed","Authorization has already been consumed.")]};let f=await qh({workspaceRoot:r.context.snapshot.workspaceRoot,gitRoot:r.context.snapshot.gitRoot,approvedWorkspaceRoot:r.preview.workspace.workspaceRoot,approvedGitRoot:r.preview.workspace.gitRoot,config:r.context.config,dirtyPaths:r.context.snapshot.dirtyPaths,proposal:r.preview.proposal,maxTargetBytes:r.context.maxTargetBytes});if(f.kind!=="verified")return{kind:"rejected",reasons:[or(f.code==="dirty-target-file"?"dirty-target-file":f.code==="source-hash-mismatch"?"source-hash-mismatch":f.code==="result-hash-mismatch"?"result-hash-mismatch":"unsafe-target",f.message,f.path)]};let h=fh(),g=await xh({workspaceRoot:f.workspaceRoot,transactionId:h,preview:r.preview,authorization:r.authorization,config:r.context.config,maxTargetBytes:r.context.maxTargetBytes,targets:f.targets,now:e});await t.failpoint?.("journal-prepared"),g=await Be({transaction:g,phase:"applying",type:"application-started",now:e}),await t.failpoint?.("phase-applying");for(let m of g.manifest.targets){if(!await Uh(f.workspaceRoot,m.path,r.context.maxTargetBytes,m.sourceSha256))return{kind:"recovery-required",reasons:[or("source-hash-mismatch","Target changed immediately before mutation.",m.path)],transaction:Pe(g)};g=await Be({transaction:g,phase:"applying",type:"target-write-intent",path:m.path,now:e}),await t.failpoint?.(`before-target:${m.path}`);let w=g.results.get(m.path);if(w===void 0)throw new Error("Journal result bytes are unavailable.");if(await Is(f.workspaceRoot,m.path,m.sourceSha256,w),await t.failpoint?.(`after-target:${m.path}`),!await Uh(f.workspaceRoot,m.path,r.context.maxTargetBytes,m.resultSha256))throw new Error("Applied target hash could not be verified.");g=await Be({transaction:g,phase:"applying",type:"target-write-complete",path:m.path,now:e})}return g=await Be({transaction:g,phase:"applied",type:"application-complete",now:e}),await t.failpoint?.("phase-applied"),{kind:"applied",transaction:Pe(g)}}catch{return{kind:"failed",reasons:[or("application-failed","Application stopped safely; inspect transaction discovery before continuing.")]}}finally{await n?.release().catch(()=>{})}}var Kh=new Set(["completed","rolled-back","conflicted"]);function Mt(r,t){return{code:"transaction-conflict",message:r,...t===void 0?{}:{path:t}}}async function Xd(r,t){let e=r.manifest.targets.find(i=>i.path===t);if(e===void 0)return"conflict";let n=await K(r.manifest.preview.workspace.workspaceRoot,t,r.manifest.maxTargetBytes);return n.kind!=="read"||n.relativePath!==t?"conflict":n.sha256===e.sourceSha256?"preimage":n.sha256===e.resultSha256?"applied":"conflict"}async function zs(r,t){let e=await xe(r,t),n=await Promise.all(e.manifest.targets.map(async i=>({path:i.path,classification:await Xd(e,i.path)})));return{transactionId:t,phase:e.state.phase,targets:n}}async function Yd(r){try{let t=await Promise.all((await Xn(r)).map(n=>zs(r,n))),e=t.filter(n=>!Kh.has(n.phase));return e.some(n=>n.targets.some(i=>i.classification==="conflict"))?{kind:"conflicted",transactions:e}:e.length===0?{kind:"clear",transactions:t}:{kind:"recovery-required",transactions:e}}catch{return{kind:"failed",reasons:[Mt("Transaction discovery failed closed because a journal is unreadable.")]}}}async function Jd(r,t,e){return r.state.phase==="conflicted"?r:Be({transaction:r,phase:"conflicted",type:"conflict-detected",message:e,now:t})}async function Gh(r){let t=await Promise.all(r.manifest.targets.map(async e=>[e.path,await Xd(r,e.path)]));return new Map(t)}async function MR(r,t,e,n,i){let s;try{let[a,o,d,c]=await Promise.all([Hr(r.workspace.workspaceRoot),Hr(r.snapshot.workspaceRoot),Hr(r.workspace.gitRoot),Hr(r.snapshot.gitRoot)]);if(a!==o||d!==c)return{kind:"rejected",reasons:[Mt("Recovery workspace identity differs.")]};s=await Ue(a,{operation:e,transactionId:t,at:n});let l=await xe(a,t);if(await Hr(l.manifest.preview.workspace.workspaceRoot)!==a||await Hr(l.manifest.preview.workspace.gitRoot)!==d)return{kind:"rejected",reasons:[Mt("Recovery workspace identity differs.")]};if(Kh.has(l.state.phase))return e==="rollback"&&l.state.phase==="rolled-back"?{kind:"rolled-back",transaction:Pe(l)}:{kind:"rejected",reasons:[Mt("Terminal transaction cannot perform this recovery operation.")],transaction:Pe(l)};let u=await Gh(l),p=[...u].find(([,g])=>g==="conflict");if(p!==void 0)return l=await Jd(l,n,"Current target bytes match neither recorded preimage nor applied image."),{kind:"conflicted",reasons:[Mt("Developer or unknown target bytes prohibit automatic recovery.",p[0])],transaction:Pe(l)};e==="rollback"&&(l=await Be({transaction:l,phase:"rolling-back",type:"rollback-started",now:n}),await i?.("phase-rolling-back"));for(let g of l.manifest.targets){let m=u.get(g.path);if(!(e==="resume"&&m==="preimage"||e==="rollback"&&m==="applied"))continue;let w=e==="resume"?"resume":"rollback";if(await i?.(`before-${w}-target:${g.path}`),await Xd(l,g.path)!==m)return l=await Jd(l,n,"Target changed after recovery classification."),{kind:"conflicted",reasons:[Mt("Target changed immediately before recovery mutation.",g.path)],transaction:Pe(l)};let v=e==="resume"?l.results.get(g.path):l.preimages.get(g.path);if(v===void 0)throw new Error("Recovery bytes are unavailable.");await Is(a,g.path,e==="resume"?g.sourceSha256:g.resultSha256,v),await i?.(`after-${w}-target:${g.path}`),l=await Be({transaction:l,phase:e==="resume"?"applying":"rolling-back",type:`${e}-target-complete`,path:g.path,now:n})}let f=await Gh(l),h=e==="resume"?"applied":"preimage";return[...f.values()].some(g=>g!==h)?(l=await Jd(l,n,"Recovery result hashes did not verify."),{kind:"conflicted",reasons:[Mt("Recovery completed with an unknown target state.")],transaction:Pe(l)}):(l=await Be({transaction:l,phase:e==="resume"?"applied":"rolled-back",type:e==="resume"?"resume-complete":"rollback-complete",now:n}),{kind:e==="resume"?"resumed":"rolled-back",transaction:Pe(l)})}catch{return{kind:"failed",reasons:[Mt("Recovery stopped safely; rediscover transaction state.")]}}finally{await s?.release().catch(()=>{})}}async function Qd(r,t,e=new Date().toISOString()){return MR(r,t,"rollback",e)}var Wh=/^rps_[a-f0-9]{24}$/,Hs=/^[a-f0-9]{64}$/,qR=new Set(["rolling-back","rolled-back","conflicted"]);function UR(r,t){let e=VR(r,t);return e===""||!BR(e)&&e!==".."&&!e.startsWith(`..${HR}`)}function qr(r){return r.length>0&&Number.isFinite(Date.parse(r))}function Jh(r){if(r.ordinal!==1&&r.ordinal!==2||!Hs.test(r.proposalHash)||!/^txn_[a-f0-9]{24}$/.test(r.transactionId)||r.validationManifestHash!==void 0&&!Hs.test(r.validationManifestHash)||!qr(r.recordedAt))throw new Error("Repair attempt record is malformed.")}function GR(r){let{sessionHash:t,...e}=r;if(r.schemaVersion!=="1.0"||!Wh.test(r.repairSessionId)||r.originalRunId.trim().length===0||!Hs.test(r.originalPacketHash)||r.maxAttempts!==2||!qr(r.createdAt)||!qr(r.updatedAt)||!Number.isInteger(r.revision)||r.revision<1||r.attempts.length>2||C(e)!==t)throw new Error("Repair session integrity check failed.");r.attempts.forEach(Jh);for(let[n,i]of r.attempts.entries())if(i.ordinal!==n+1)throw new Error("Repair attempt order is malformed.");return r}async function qs(r){let t=await FR(r),e=zR(t,".kwikqa");if(!UR(t,e))throw new Error("Repair session directory escapes workspace.");await Zd(e,{mode:448}).catch(a=>{if(a.code!=="EEXIST")throw a});let n=await ri(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Repair session path is unsafe.");let i=Ur(e,"repair-sessions");await Zd(i,{mode:448}).catch(a=>{if(a.code!=="EEXIST")throw a});let s=await ri(i);if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Repair session path is unsafe.");return i}function Us(r){return{...r,sessionHash:C(r)}}function ec(r){return{schemaVersion:r.schemaVersion,repairSessionId:r.repairSessionId,originalRunId:r.originalRunId,originalPacketHash:r.originalPacketHash,maxAttempts:r.maxAttempts,attempts:r.attempts,state:r.state,createdAt:r.createdAt,updatedAt:r.updatedAt,revision:r.revision}}async function tc(r){if(r.originalRunId.trim().length===0||!Hs.test(r.originalPacketHash))throw new Error("Original repair evidence identity is invalid.");let t=r.now??new Date().toISOString();if(!qr(t))throw new Error("Repair session timestamp is invalid.");let e=`rps_${$R().replaceAll("-","").slice(0,24)}`,n=Us({schemaVersion:"1.0",repairSessionId:e,originalRunId:r.originalRunId,originalPacketHash:r.originalPacketHash,maxAttempts:2,attempts:[],state:"first-attempt",createdAt:t,updatedAt:t,revision:1}),i=await qs(r.workspaceRoot);return await me(Ur(i,`${e}.json`),`${de(n)}
53
- `,{mode:384,replace:!1}),n}async function $t(r,t){if(!Wh.test(t))throw new Error("Repair session id is invalid.");let e=await qs(r),n=Ur(e,`${t}.json`),i=await ri(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("Repair session record is unsafe.");let s=JSON.parse(await _R(n,"utf8"));if(s===null||typeof s!="object"||Array.isArray(s))throw new Error("Repair session record is malformed.");return GR(s)}async function rc(r,t){let e=await qs(r),n=Ur(e,`${t}.lock`);await Zd(n,{mode:448});let i=await ri(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Repair session lock is unsafe.");return{release:async()=>{let s=await ri(n);if(s.dev!==i.dev||s.ino!==i.ino||s.isSymbolicLink())throw new Error("Repair session lock ownership changed.");await jR(n,{recursive:!0,force:!1})}}}async function nc(r,t,e){let n=await $t(r,t.repairSessionId);if(n.revision!==t.revision||n.sessionHash!==t.sessionHash)throw new Error("Repair session changed concurrently.");let i=await qs(r);return await me(Ur(i,`${t.repairSessionId}.json`),`${de(e)}
54
- `,{mode:384,replace:!0}),$t(r,t.repairSessionId)}async function ic(r,t,e){Jh(e);let n=await rc(r,t);try{let i=await $t(r,t);if(i.state==="repaired"||i.state==="stopped")throw new Error("Terminal repair session cannot accept another attempt.");if(e.ordinal!==i.attempts.length+1||e.ordinal>i.maxAttempts)throw new Error("Repair session attempt limit or ordering was violated.");if(e.ordinal===1&&i.state!=="first-attempt"||e.ordinal===2&&i.state!=="retry-approval-required")throw new Error("Repair session is not ready for this attempt.");let s=e.recordedAt,a=Us({...ec(i),attempts:[...i.attempts,e],state:e.ordinal===1?"first-attempt":"second-attempt",updatedAt:s,revision:i.revision+1});return await nc(r,i,a)}finally{await n.release()}}function KR(r,t){let e=r.status;if(e==="blocked")throw new Error("A blocked validation run has no attempt outcome.");let n=t.state.history,i=n.findLastIndex(d=>d.type==="validation-started"),s=n[i];if(s===void 0||s.validationRunId!==r.validationRunId||s.planHash!==r.planHash)throw new Error("Validation run was not started for this transaction approval.");let a=n.slice(i+1).find(d=>d.type==="validation-passed"),o=t.state.phase;if(a!==void 0){if(o!=="completed"||e!=="passed"||a.validationRunId!==r.validationRunId||a.planHash!==r.planHash||a.validationManifestHash!==r.manifestHash)throw new Error("Validation outcome does not match the durable transaction state.");return"passed"}if(o==="validating"){if(e==="passed")throw new Error("A passing validation run must be completed by M6, or rolled back, before it is recorded.");return e}if(qR.has(o))return e==="passed"?"incomplete":e;throw new Error("Validation outcome does not match the durable transaction state.")}async function Gs(r){if(!/^vld_[a-f0-9]{24}$/.test(r.validationRunId))throw new Error("Validation run id is invalid.");let t=r.now??new Date().toISOString();if(!qr(t))throw new Error("Repair session timestamp is invalid.");let e=await rc(r.workspaceRoot,r.repairSessionId),n;try{n=await Ue(r.workspaceRoot,{operation:"record-repair-validation",repairSessionId:r.repairSessionId,validationRunId:r.validationRunId});let i=await $t(r.workspaceRoot,r.repairSessionId),s=i.attempts.at(-1);if(s===void 0||s.ordinal!==r.ordinal)throw new Error("Repair attempt cannot be finalized from its current state.");let a=await xe(r.workspaceRoot,s.transactionId),o=a.manifest.preview.authoritativeValidation,d=Ur(a.directory,"validation",r.validationRunId),c=Dt(await ar(d,"manifest.json",Os)),l=new Map(o.requiredCommands.map(g=>[g.commandId,g.commandHash]));if(c.transactionId!==s.transactionId||c.validationRunId!==r.validationRunId||c.planHash!==o.planHash||c.repositoryFingerprint!==o.repositoryFingerprint||C(c.targetHashes)!==C(o.targetHashes)||c.requiredCommandIds.length!==l.size||c.requiredCommandIds.some(g=>!l.has(g))||c.commandRecords.some(g=>l.get(g.commandId)!==g.commandHash)||o.repairSessionId!==i.repairSessionId||o.attemptOrdinal!==s.ordinal||a.manifest.preview.proposal.proposalHash!==s.proposalHash)throw new Error("Validation manifest does not match the repair attempt authority.");for(let g of c.commandRecords)if(!await Rh(d,g,_r))throw new Error("Validation manifest command evidence failed verification.");let u=KR(c,a);if(s.outcome!=="applied"){if(s.validationManifestHash===c.manifestHash&&s.outcome===u)return{session:i};throw new Error("Repair attempt was already finalized with different evidence.")}let p={...s,validationManifestHash:c.manifestHash,outcome:u,recordedAt:t},f=u==="passed"?"repaired":"rollback-required",h=Us({...ec(i),attempts:[...i.attempts.slice(0,-1),p],state:f,updatedAt:t,revision:i.revision+1});return{session:await nc(r.workspaceRoot,i,h)}}finally{await n?.release(),await e.release()}}async function sc(r){if(!/^txn_[a-f0-9]{24}$/.test(r.proof.transactionId)||r.proof.phase!=="rolled-back"||!Number.isInteger(r.proof.transactionRevision)||r.proof.transactionRevision<1)throw new Error("Repair rollback proof is invalid.");let t=r.now??new Date().toISOString();if(!qr(t))throw new Error("Repair session timestamp is invalid.");let e=await rc(r.workspaceRoot,r.repairSessionId),n;try{n=await Ue(r.workspaceRoot,{operation:"confirm-repair-rollback",repairSessionId:r.repairSessionId,transactionId:r.proof.transactionId});let i=await $t(r.workspaceRoot,r.repairSessionId),s=i.attempts.at(-1);if(i.state!=="rollback-required"||s===void 0||s.ordinal!==r.ordinal||s.transactionId!==r.proof.transactionId||s.validationManifestHash===void 0||s.outcome==="passed"||s.outcome==="applied")throw new Error("Repair session does not match the rolled-back attempt.");let a=await xe(r.workspaceRoot,s.transactionId),o=a.manifest.preview.authoritativeValidation;if(a.state.phase!=="rolled-back"||a.state.revision!==r.proof.transactionRevision||o.repairSessionId!==i.repairSessionId||o.attemptOrdinal!==s.ordinal||a.manifest.preview.proposal.proposalHash!==s.proposalHash)throw new Error("Repair rollback proof does not match the durable transaction.");let d=await zs(r.workspaceRoot,s.transactionId);if(d.phase!=="rolled-back"||d.targets.some(f=>f.classification!=="preimage"))throw new Error("Durable rollback could not be verified from recorded preimages.");let c=r.ordinal===1?"retry-approval-required":"stopped",l=Us({...ec(i),state:c,updatedAt:t,revision:i.revision+1}),u=await nc(r.workspaceRoot,i,l);if(c!=="retry-approval-required")return{session:u};let p={repairSessionId:u.repairSessionId,failedTransactionId:s.transactionId,failedValidationManifestHash:s.validationManifestHash,nextAttemptOrdinal:2};return{session:u,retry:{...p,handoffHash:C(p)}}}finally{await n?.release(),await e.release()}}import{basename as sT,dirname as Zh,join as Gr,relative as uc,resolve as Rt,sep as aT}from"node:path";import{createHash as WR}from"node:crypto";import{lstat as JR,mkdir as XR,readFile as Xh,realpath as ac,rename as YR,writeFile as QR}from"node:fs/promises";import{isAbsolute as ZR,join as Yh,relative as oc,sep as Qh}from"node:path";import{fileURLToPath as eT}from"node:url";var tT=".kwikqa/runtime",rT=["cypress-reporter.cjs","cypress-capture.js","wdio-reporter.mjs","wdio-capture.mjs"];async function nT(r){return Xh(eT(new URL(`./${r}`,import.meta.url)),"utf8")}function iT(r,t){let e=oc(r,t);return e===""||!ZR(e)&&e!==".."&&!e.startsWith(`..${Qh}`)}async function Ks(r,t){let e=await ac(r),n=e;for(let i of t.split("/").filter(s=>s!=="")){if(i==="."||i==="..")throw new Error("Unsafe KwikQA directory.");n=Yh(n,i);let s=await JR(n).catch(()=>{});if(s===void 0)await XR(n);else if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`${oc(e,n)} must be a real directory inside the workspace.`)}if(!iT(e,await ac(n)))throw new Error("KwikQA directory escapes workspace.");return n}async function dc(r,t){let e=`${r}.${process.pid}.tmp`;await QR(e,t,{mode:420}),await YR(e,r)}function cc(r){return WR("sha256").update(r,"utf8").digest("hex")}async function Ws(r){let t=await ac(r),e=await Ks(t,tT),n={};for(let i of rT){let s=await nT(i),a=Yh(e,i);await Xh(a,"utf8").catch(()=>{})!==s&&await dc(a,s),n[i]={path:a,relativePath:oc(t,a).split(Qh).join("/"),sha256:cc(s)}}return n}function pc(r){return r.split(aT).join("/")}function ni(r,t){let e=pc(uc(r,t));return e.startsWith(".")?e:`./${e}`}async function lc(r,t,e){return await dc(t,e),{path:t,relativePath:pc(uc(r,t)),sha256:cc(e)}}async function Js(r){let t=r.workspaceRoot,e=r.configFile===void 0?t:Zh(Rt(t,r.configFile)),n=["video=false","screenshotOnRunFailure=true",`screenshotsFolder=${Rt(t,r.screenshotsDirectory)}`,...r.noRetries?["retries=0"]:[]],i=[];if(r.capture!==void 0){let a=await Ks(t,r.capture.directory),o=await lc(t,Gr(a,"kwikqa-settings.js"),`// Generated by KwikQA for one run.
55
- globalThis.__kwikqaCapture = ${JSON.stringify({directory:pc(uc(e,Gr(a,"pages"))),...r.capture.only===void 0?{}:{only:[...r.capture.only].sort()}})};
56
- `),d=[`import ${JSON.stringify(ni(a,o.path))};`,`import ${JSON.stringify(ni(a,r.runtime["cypress-capture.js"].path))};`,...r.capture.supportFile===null||r.capture.supportFile===void 0?[]:[`import ${JSON.stringify(ni(a,Rt(t,r.capture.supportFile)))};`]],c=await lc(t,Gr(a,"kwikqa-support.js"),`// Generated by KwikQA: its failure capture, then the project's support file.
39
+ `)}`,v={type:"attachment-text",attachmentId:i.attachmentId,sha256:u,startLine:h.startLine,endLine:h.endLine};return{artifacts:[p],evidence:[{evidenceId:he(r,s,"page-snapshot",v,x),kind:"page-snapshot",artifactId:s,logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:v,observation:x,availability:"present",redactionIds:g.map(I=>I.redactionId)}],redactions:g,omissions:w}}var Bk=256*1024,Vk=10,xf=200;async function vf(r,t,e,n){let i=we(r.runId,"probe",e),s=(h,g,m=e)=>({omissionId:$("omi",[r.runId,"probe",h,m,g]),channel:"probe",reason:h,message:g,locator:m}),a=await W(n,e,Bk);if(a.kind!=="read")return{artifacts:[{artifactId:i,channel:"probe",availability:"unavailable",warnings:[a.message]}],evidence:[],redactions:[],omissions:[s("unavailable",a.message)]};let o={artifactId:i,channel:"probe",availability:"present",path:a.relativePath,sha256:a.sha256,format:"kwikqa-playwright-cli-probe",warnings:[]},d;try{d=fe(JSON.parse(_e(a.bytes)??""))}catch{d=void 0}if(d===void 0||_(d.schemaVersion)!=="1.0")return{artifacts:[{...o,availability:"unreadable"}],evidence:[],redactions:[],omissions:[s("unrecognized","The probe results are not in a recognized format.")]};let c=fe(d.tool),l=`Playwright CLI ${_(c?.version)??"unknown"}, Playwright ${_(d.playwrightVersion)??"unknown"}`,u=[],p=[],f=[];return He(d.results)?.forEach((h,g)=>{let m=fe(h);if(m===void 0)return;let y=_(m.logicalTestId),w=r.logicalTests.find(P=>P.logicalTestId===y)??r.logicalTests.find(P=>P.title===_(m.title)&&P.location.file===_(m.file)&&P.location.line===ke(m.line)),x=w?.attempts.at(-1),v=`${a.relativePath}#results[${g}]`;for(let P of He(m.issues)??[]){let C=_(P);C!==void 0&&f.push(s("unavailable",`Live probe of "${_(m.title)??"a test"}": ${C}`,v))}let I=(He(m.candidates)??[]).map(P=>fe(P)).filter(P=>P!==void 0).slice(0,Vk);if(w===void 0||I.length===0)return;let R=[],E=[];I.forEach((P,C)=>{let M=ud(`- ${(_(P.element)??"").slice(0,xf)}`,`${v}/candidates[${C}]`,t.sensitiveNames),z=oe((_(P.locator)??"").slice(0,xf),"probe",`${v}/candidates[${C}]/locator`,t.sensitiveNames);p.push(...M.records,...z.records),E.push(...M.records.map(k=>k.redactionId),...z.records.map(k=>k.redactionId)),R.push(`${M.value.replace(/^- /,"")} \u2192 ${z.value}`)});let A=_(m.locator),j=[`Live page paused at ${`${_(m.file)??w.location.file}:${ke(m.failingLine)??"?"}`}, before the failing step (${l}).${A===void 0?"":` The failed locator was ${A}.`} Locators Playwright generated for the elements most like it:`,...R].join(`
40
+ `),V={type:"report-field",path:`probe.results[${g}]`};u.push({evidenceId:he(r.runId,i,"locator-suggestion",V,j),kind:"locator-suggestion",artifactId:i,logicalTestId:w.logicalTestId,...x===void 0?{}:{attemptId:x.attemptId},locator:V,observation:j,availability:"present",redactionIds:E})}),{artifacts:[{...o,availability:u.length>0?"present":"empty"}],evidence:u,redactions:p,omissions:f}}var zk=/(?:\(|\bat\s+|^)((?:[A-Za-z]:)?[^():\s][^():]*?):(\d+):(\d+)\)?\s*$/;function pd(r,t,e){let n=[];return r.split(/\r?\n/).forEach((i,s)=>{let a=zk.exec(i.trim().replace(/webpack:\/\/[^/\s()]*\//g,""));if(a===null)return;let[,o,d,c]=a;o===void 0||d===void 0||c===void 0||n.push({file:o.replace(/^file:\/\//,"").replace(/^(?:\.\/)+/,""),line:Number.parseInt(d,10),column:Number.parseInt(c,10),origin:`${t}#frame=${s+1}`,...e})}),n}function jn(r,t,e,n,i,s,a){let o=`${n}:${i}`;if(e.reported.has(o))return;e.reported.add(o);let d=`Reached the ${s}-${i} limit; later observations were not included.`;t.push({omissionId:$("omi",[r.runId,n,"budget-exceeded",a,d]),channel:n,reason:"budget-exceeded",message:d,locator:a,cap:s})}function fd(r,t,e){return r===void 0?[]:[{file:r.file,line:r.line??1,...r.column===void 0?{}:{column:r.column},origin:t,...e}]}function hd(r,t,e){let n=[...fd(r.location,`${t}.location`,e)];return r.stack!==void 0&&n.push(...pd(r.stack,`${t}.stack`,e)),n}function kf(r,t,e){let n=[];return r.forEach((i,s)=>{let a=`${t}[${s}]`;i.error!==void 0&&n.push(...hd(i.error,a,e)),n.push(...kf(i.steps,`${a}.steps`,e))}),n}function Hk(r){let t=[];for(let e of r.logicalTests){for(let n of e.attempts){let i={logicalTestId:e.logicalTestId,attemptId:n.attemptId};t.push(...fd(n.errorLocation,`${n.attemptId}.errorLocation`,i));for(let s of n.errors)t.push(...hd(s,s.source,i));t.push(...kf(n.steps,`${n.attemptId}.steps`,i))}t.push(...fd(e.location,`${e.logicalTestId}.location`,{logicalTestId:e.logicalTestId}))}for(let e of r.reportErrors)t.push(...hd(e,e.source,{}));return t}function us(r,t,e,n,i,s,a,o,d,c,l){if(c.reportFields>=t.maxReportFields){jn(r,d,c,"report","field",t.maxReportFields,i);return}c.reportFields+=1;let u=oe(s,e.channel,i,t.sensitiveNames);o.push(...u.records);let p={type:"report-field",path:i};a.push({evidenceId:he(r.runId,e.artifactId,n,p,u.value),kind:n,artifactId:e.artifactId,...l,locator:p,observation:u.value,availability:u.value.length===0?"empty":"present",redactionIds:u.records.map(f=>f.redactionId)})}function md(r,t,e,n,i,s,a,o,d){let c=[["name",n.name],["message",n.message],["value",n.value],["snippet",n.snippet]];for(let[l,u]of c)u!==void 0&&us(r,t,e,"error-field",`${n.source}.${l}`,u,i,s,a,o,d);n.stack!==void 0&&(us(r,t,e,"error-field",`${n.source}.stack`,n.stack,i,s,a,o,d),n.stack.split(/\r?\n/).forEach((l,u)=>{if(l.trim().length===0)return;let p=`${n.source}.stack#line=${u+1}`;if(o.stackFrames>=t.maxStackFrames){jn(r,a,o,"report","stack-frame",t.maxStackFrames,p);return}o.stackFrames+=1,us(r,t,e,"stack-frame",p,l,i,s,a,o,d)}))}function If(r,t,e,n,i,s,a,o,d,c){n.forEach((l,u)=>{let p=`${i}[${u}]`;if(d.steps>=t.maxSteps){jn(r,o,d,"report","step",t.maxSteps,p);return}d.steps+=1,us(r,t,e,"step",`${p}.title`,l.title,s,a,o,d,c),l.error!==void 0&&md(r,t,e,l.error,s,a,o,d,c),If(r,t,e,l.steps,`${p}.steps`,s,a,o,d,c)})}function qk(r){if(r.kind==="text")return r.text;let t=Buffer.from(r.base64,"base64");return`binary stdio: sha256=${Te(t)} bytes=${t.byteLength}`}function Pf(r,t){let e={artifactId:we(r.runId,"report",r.artifact.artifactId),channel:"report",availability:r.artifact.availability,...r.artifact.path===void 0?{}:{path:r.artifact.path},...r.artifact.sha256===void 0?{}:{sha256:r.artifact.sha256},...r.artifact.formatVersion===void 0?{}:{producerVersion:r.artifact.formatVersion},warnings:r.artifact.warnings},n=[e],i=[],s=[],a=[],o={reportFields:0,stackFrames:0,steps:0,stdioChunks:0,stdioBytes:0,reported:new Set};r.reportErrors.forEach(d=>{md(r,t,e,d,i,s,a,o,{})});for(let d of r.logicalTests)for(let c of d.attempts){let l={logicalTestId:d.logicalTestId,attemptId:c.attemptId};c.errors.forEach(u=>{md(r,t,e,u,i,s,a,o,l)}),If(r,t,e,c.steps,`${c.attemptId}.steps`,i,s,a,o,l);for(let u of["stdout","stderr"]){let p=c[u],f={artifactId:we(r.runId,u,c.attemptId),channel:u,availability:p.length===0?"empty":"present",attemptId:c.attemptId,warnings:[]};n.push(f);let h=0;p.forEach((g,m)=>{let y=g.kind==="text"?Buffer.byteLength(g.text,"utf8"):Buffer.from(g.base64,"base64").byteLength,w=`${c.attemptId}.${u}[${m}]`;if(o.stdioChunks>=t.maxStdioChunks){jn(r,a,o,u,"stdio-chunk",t.maxStdioChunks,w),h+=y;return}if(o.stdioBytes+y>t.maxStdioBytes){jn(r,a,o,u,"stdio-byte",t.maxStdioBytes,w),h+=y;return}o.stdioChunks+=1,o.stdioBytes+=y;let x=qk(g),v=oe(x,u,w,t.sensitiveNames);s.push(...v.records);let I={type:"stdio",stream:u,chunk:m,startByte:h,endByte:h+y};h+=y,i.push({evidenceId:he(r.runId,f.artifactId,"stdio-chunk",I,v.value),kind:"stdio-chunk",artifactId:f.artifactId,...l,locator:I,observation:v.value,availability:x.length===0?"empty":"present",redactionIds:v.records.map(R=>R.redactionId)})})}}return{artifacts:n,evidence:i,redactions:s,omissions:a,seeds:Hk(r)}}var Cf=Ii(Rn(),1);import{dirname as Uk,extname as Ef,join as Rf}from"node:path/posix";var Gk=new Set(["test","it","describe","suite","step","beforeEach","afterEach","beforeAll","afterAll"]),Tf=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Kk=new Set([".js",".mjs",".cjs"]),Wk=[".ts",".tsx",".mts",".cts"];function Jk(r){return r.split("/").includes("node_modules")}function qe(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof r.type=="string"}function Bn(r,t,e=new Set){if(!e.has(r)){e.add(r),t(r);for(let n of Object.keys(r)){if(n==="loc")continue;let i=r[n];if(Array.isArray(i))for(let s of i)qe(s)&&Bn(s,t,e);else qe(i)&&Bn(i,t,e)}}}function tr(r){if(qe(r)&&r.type==="Identifier")return typeof r.name=="string"?r.name:void 0}function _r(r){if(qe(r)){if(r.type==="Identifier"&&typeof r.name=="string")return r.name;if(r.type==="StringLiteral"&&typeof r.value=="string")return r.value}}function Nf(r){if(qe(r)){if(r.type==="Identifier")return typeof r.name=="string"?r.name:void 0;if(r.type==="MemberExpression"){let t=Nf(r.object),e=_r(r.property);return t===void 0||e===void 0?void 0:`${t}.${e}`}}}function Xk(r){let t=Nf(r.callee);if(t===void 0)return;let e=t.split(".").pop()??t;if(!Gk.has(e))return;let i=(Array.isArray(r.arguments)?r.arguments:[])[0];if(!(!qe(i)||i.type!=="StringLiteral"||typeof i.value!="string"))return`${t}("${i.value}")`}function Of(r){switch(r.type){case"FunctionDeclaration":case"ClassDeclaration":case"TSInterfaceDeclaration":case"TSTypeAliasDeclaration":case"TSEnumDeclaration":case"TSModuleDeclaration":return tr(r.id);case"ClassMethod":case"ObjectMethod":case"ClassProperty":case"PropertyDefinition":return _r(r.key);case"VariableDeclarator":return tr(r.id);case"CallExpression":return Xk(r);default:return}}function Yk(r,t){let e=r.loc;return e==null?!1:e.start.line<=t&&e.end.line>=t}function Qk(r,t){let e;return Bn(r,n=>{let i=Of(n);if(i===void 0||!Yk(n,t))return;let s=n.loc;if(s==null)return;let a={name:i,startLine:s.start.line,endLine:s.end.line};if(e===void 0){e=a;return}let o=a.endLine-a.startLine,d=e.endLine-e.startLine;o<d&&(e=a)}),e}function Zk(r){let t=Of(r);return t!==void 0&&r.type!=="CallExpression"?[t]:r.type==="VariableDeclaration"&&Array.isArray(r.declarations)?r.declarations.map(e=>qe(e)?tr(e.id):void 0).filter(e=>e!==void 0):[]}function eI(r,t){let e=Array.isArray(r.program)?[]:r.program?.body,n=Array.isArray(e)?e:[],i=[];for(let s of n){if(!qe(s))continue;let a=s.loc;if(a==null)continue;if(s.type==="ExportDefaultDeclaration"&&t.has("default")){i.push({name:"default",startLine:a.start.line,endLine:a.end.line});continue}if(s.type==="ExportNamedDeclaration"&&Array.isArray(s.specifiers))for(let d of s.specifiers){if(!qe(d))continue;let c=_r(d.exported);c!==void 0&&t.has(c)&&i.push({name:c,startLine:a.start.line,endLine:a.end.line})}let o=s.type==="ExportNamedDeclaration"&&qe(s.declaration)?s.declaration:s;for(let d of Zk(o))t.has(d)&&i.push({name:d,startLine:a.start.line,endLine:a.end.line})}return i}function tI(r){let t=[];return Bn(r,e=>{if(e.type!=="ImportDeclaration"&&e.type!=="ExportNamedDeclaration"&&e.type!=="ExportAllDeclaration")return;let n=qe(e.source)?e.source.value:void 0;if(typeof n!="string")return;let i=[],s;for(let a of Array.isArray(e.specifiers)?e.specifiers:[])if(qe(a)){if(e.type==="ExportNamedDeclaration"){let o=_r(a.exported),d=_r(a.local);o!==void 0&&d!==void 0&&i.push({imported:d,local:o})}else if(a.type==="ImportDefaultSpecifier"){let o=tr(a.local);o!==void 0&&i.push({imported:"default",local:o})}else if(a.type==="ImportNamespaceSpecifier")s=tr(a.local);else if(a.type==="ImportSpecifier"){let o=_r(a.imported)??tr(a.local),d=tr(a.local);o!==void 0&&d!==void 0&&i.push({imported:o,local:d})}}t.push({specifier:n,bindings:i,...s===void 0?{}:{namespaceLocal:s},exportStar:e.type==="ExportAllDeclaration"})}),t}function Af(r,t,e){let n=new Set;return Bn(r,i=>{let s=i.loc;s==null||s.end.line<t||s.start.line>e||i.type==="Identifier"&&typeof i.name=="string"&&n.add(i.name)}),n}function rI(r){let t=Ef(r).toLowerCase();return t===".tsx"?["typescript","jsx"]:[".ts",".mts",".cts"].includes(t)?["typescript"]:["jsx"]}function nI(r,t){try{return{ast:(0,Cf.parse)(r,{sourceType:"module",allowReturnOutsideFunction:!0,errorRecovery:!1,plugins:rI(t)})}}catch(e){return{error:e instanceof Error?e.message:"Source could not be parsed."}}}function iI(r,t){if(!r.startsWith("./")&&!r.startsWith("../"))return[];let e=Rf(t,r),n=[e],i=Ef(e).toLowerCase();if(Kk.has(i)){let s=e.slice(0,e.length-i.length);for(let a of Wk)n.push(`${s}${a}`)}if(i===""){for(let s of Tf)n.push(`${e}${s}`);for(let s of Tf)n.push(Rf(e,`index${s}`))}return n}function nt(r,t,e,n,i){r.omissions.push({omissionId:$("omi",["source",t,n,e]),channel:"source",reason:t,message:e,locator:n,...i===void 0?{}:{cap:i}})}async function Df(r,t){let e=await Nn(r.workspaceRoot,t);if(e.kind!=="authorized"){nt(r,e.kind==="unauthorized"?"unauthorized-path":e.kind,e.message,t);return}if(Jk(e.relativePath)){nt(r,"policy-disabled","Dependency source under node_modules is out of scope for evidence.",e.relativePath);return}let n=r.files.get(e.relativePath);if(n!==void 0)return n;if(r.files.size>=r.policy.maxSourceFiles){r.filesReported||(r.filesReported=!0,nt(r,"budget-exceeded",`Reached the ${r.policy.maxSourceFiles}-file source limit; later files were not read.`,e.relativePath,r.policy.maxSourceFiles));return}let i=await W(r.workspaceRoot,e.relativePath,r.policy.maxArtifactBytes);if(i.kind!=="read"){let c=i.kind==="over-budget"?"budget-exceeded":i.kind==="unauthorized"?"unauthorized-path":i.kind;nt(r,c,i.message,e.relativePath);return}let s=_e(i.bytes);if(s===void 0){nt(r,"unreadable","Source file is not valid UTF-8.",i.relativePath);return}let a=nI(s,i.relativePath);a.error!==void 0&&nt(r,"parse-failed",`Symbol boundaries are unavailable: ${a.error}`,i.relativePath);let o={artifactId:we(r.runId,"source",i.relativePath),channel:"source",availability:"present",path:i.relativePath,sha256:i.sha256,warnings:a.error===void 0?[]:[a.error]},d={relativePath:i.relativePath,sha256:i.sha256,lines:s.split(/\r?\n/),ast:a.ast,artifact:o};return r.files.set(i.relativePath,d),r.artifacts.push(o),d}function Sf(r,t,e,n,i){let s=r.policy.maxSourceLinesPerFile,a=Math.max(1,e.startLine),o=Math.min(t.lines.length,e.endLine);if(o<a)return;o-a+1>s&&(o=a+s-1,nt(r,"budget-exceeded",`Symbol context in ${t.relativePath} was truncated to ${s} lines.`,`${t.relativePath}:${a}`,s));let d=`${t.relativePath}:${a}:${o}:${i.logicalTestId??""}:${i.attemptId??""}:${n}`;if(r.emitted.has(d))return;r.emitted.add(d);let c=t.lines.slice(a-1,o).join(`
41
+ `),l=oe(c,"source",`${t.relativePath}:${a}-${o}`,r.policy.sensitiveNames),u=Buffer.byteLength(l.value,"utf8");if(r.emittedBytes+u>r.policy.maxSourceBytes){r.bytesReported||(r.bytesReported=!0,nt(r,"budget-exceeded",`Reached the ${r.policy.maxSourceBytes}-byte source limit; later ranges were not included.`,t.relativePath,r.policy.maxSourceBytes));return}r.emittedBytes+=u,r.redactions.push(...l.records);let p=t.lines[o-1]??"",f={type:"source-range",path:t.relativePath,sha256:t.sha256,startLine:a,startColumn:1,endLine:o,endColumn:p.length+1,...e.symbol===void 0?{}:{symbol:e.symbol}},h=`${n}
42
+ ${l.value}`;r.evidence.push({evidenceId:he(r.runId,t.artifact.artifactId,"source-range",f,h),kind:"source-range",artifactId:t.artifact.artifactId,...i,locator:f,observation:h,availability:"present",redactionIds:l.records.map(g=>g.redactionId)})}async function sI(r,t,e){for(let n of iI(t,e)){let i=await Nn(r.workspaceRoot,n);if(i.kind==="authorized")return await Df(r,i.relativePath)}nt(r,"unavailable",`Relative import ${t} did not resolve to a readable workspace file.`,e)}async function Lf(r,t,e,n){let i={runId:r,policy:t,workspaceRoot:n,files:new Map,artifacts:[],evidence:[],redactions:[],omissions:[],emitted:new Set,traversed:new Set,emittedBytes:0,filesReported:!1,bytesReported:!1},s=new Set,a=[];for(let d of e){let c=`${d.file}:${d.line}:${d.logicalTestId??""}:${d.attemptId??""}:${d.origin}`;if(s.has(c))continue;s.add(c);let l=await Df(i,d.file);if(l===void 0)continue;let u={...d.logicalTestId===void 0?{}:{logicalTestId:d.logicalTestId},...d.attemptId===void 0?{}:{attemptId:d.attemptId}},p=l.ast===void 0?void 0:Qk(l.ast,d.line),f=Math.floor(t.maxSourceLinesPerFile/2),h=p??{name:void 0,startLine:Math.max(1,d.line-f),endLine:d.line+f};a.push({file:l,linkage:u,referenced:l.ast===void 0?new Set:Af(l.ast,h.startLine,h.endLine)}),Sf(i,l,{startLine:h.startLine,endLine:h.endLine,...p===void 0?{}:{symbol:p.name}},`${l.relativePath}:${d.line} via ${d.origin}`,u)}let o=a;for(let d=1;d<=t.maxImportDepth;d+=1){let c=[];for(let l of o){let u=l.file;if(u.ast!==void 0)for(let p of tI(u.ast)){let f=new Set(p.bindings.filter(x=>l.referenced.has(x.local)).map(x=>x.imported));if(p.namespaceLocal!==void 0&&l.referenced.has(p.namespaceLocal)){nt(i,"policy-disabled",`Namespace import of ${p.specifier} was not expanded; only named symbols are followed.`,u.relativePath);continue}if(p.exportStar){nt(i,"unrecognized",`Export-star from ${p.specifier} was not expanded because the exported symbol is ambiguous.`,u.relativePath);continue}if(f.size===0||!p.specifier.startsWith("."))continue;let h=await sI(i,p.specifier,Uk(u.relativePath));if(h===void 0||h.ast===void 0)continue;let g=l.linkage,m=`${h.relativePath}:${[...f].sort().join(",")}:${g.logicalTestId??""}:${g.attemptId??""}`;if(i.traversed.has(m))continue;i.traversed.add(m);let y=eI(h.ast,f),w=new Set;for(let x of y){for(let v of Af(h.ast,x.startLine,x.endLine))w.add(v);Sf(i,h,{startLine:x.startLine,endLine:x.endLine,symbol:x.name},`${h.relativePath} exports ${x.name}, imported by ${u.relativePath} (depth ${d})`,g)}c.some(x=>x.file===h&&x.linkage.attemptId===g.attemptId)||c.push({file:h,linkage:g,referenced:w})}}if(o=c,o.length===0)break}return{artifacts:i.artifacts,evidence:i.evidence,redactions:i.redactions,omissions:i.omissions}}var aI=["report","trace","stdout","stderr","screenshot","video","dom","accessibility","console","network","source","diff","probe"],oI={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"},dI=["trace","console","network","dom","accessibility"],cI=8,lI=12,uI=5,pI=/\b(?:getBy\w+|locator|frameLocator)\((?:[^()]|\([^()]*\))*\)/g,fI=[/Expected to find element: `([^`]+)`/g,/within the selector: '([^']+)'/g,/expected '<([a-z][\w-]*(?:[#.][\w-]+)*)>'/gi,/\bselector "([^"]+)"/g,/\belement \("([^"]+)"\)/g,/\${1,2}\(`([^`]+)`\)/g];function Vn(r){return Buffer.byteLength(JSON.stringify(r),"utf8")}function ps(r,t){return[...r].sort((e,n)=>t(e).localeCompare(t(n)))}function hI(r){return r.length===0?"unavailable":r.some(t=>t.availability==="present")?"present":r.some(t=>t.availability==="empty")?"empty":r.some(t=>t.availability==="unreadable")?"unreadable":"unavailable"}function mI(r,t,e,n,i){let s=t.filter(l=>l.channel===r),a=new Set(s.map(l=>l.artifactId)),o=e.filter(l=>a.has(l.artifactId)),d=n.filter(l=>l.channel===r),c=i.filter(l=>l.channel===r);return{channel:r,availability:hI(s),examined:o.length+d.length,included:o.length,omitted:d.length,observationBytes:o.reduce((l,u)=>l+Buffer.byteLength(u.observation,"utf8"),0),redactionCount:c.reduce((l,u)=>l+u.count,0),serializedBytes:Vn({artifacts:s,evidence:o,redactions:c,omissions:d})}}function Mf(r,t,e){return{omissionId:$("omi",[r,t,"unavailable",e]),channel:t,reason:"unavailable",message:e,locator:r}}function $f(r,t){return t?.[r.attachmentId]!==void 0?!0:r.name==="trace"&&r.contentType==="application/zip"}function Fr(r){return r.attempts.filter(t=>t.status==="interrupted"?!0:r.status==="unexpected"?t.status!=="skipped":r.status==="flaky"?t.status!=="passed"&&t.status!=="skipped":!1)}function yI(r){return{...r,logicalTests:r.logicalTests.map(t=>({...t,attempts:Fr(t)})).filter(t=>t.attempts.length>0)}}function gI(r,t){let e={expected:0,unexpected:0,flaky:0,skipped:0};for(let a of r.logicalTests)e[a.status]+=1;let n=t.logicalTests.reduce((a,o)=>a+o.attempts.length,0),i=[...new Set(r.logicalTests.map(a=>a.projectId))].length,s=r.artifact.formatVersion===void 0?"":` ${r.artifact.formatVersion}`;return[`${oI[r.framework]}${s} run of ${r.logicalTests.length} tests in ${i} project${i===1?"":"s"}`,`${e.expected} passed, ${e.unexpected} failed, ${e.flaky} flaky, ${e.skipped} skipped`,`evidence covers the ${n} failing attempt${n===1?"":"s"} of ${t.logicalTests.length} test${t.logicalTests.length===1?"":"s"}; passing tests are only counted.`].join("; ")}function zn(r){let t=r.errors.map(n=>`${n.message??""}
43
+ ${n.stack??""}`),e=t.flatMap(n=>fI.flatMap(i=>[...n.matchAll(i)].map(s=>s[1]??"")));return[...new Set([...t.flatMap(n=>n.match(pI)??[]),...e.filter(n=>n!=="")])]}function wI(r,t,e,n,i){let s=r.attemptId===void 0?0:n.get(r.attemptId)??0;if(i.has(r.evidenceId))return ee.afterFailure;switch(r.kind){case"error-field":case"run-summary":case"change-search":return ee.failure;case"locator-suggestion":return ee.failedCall+.95-Math.min(.5,s/1e3);case"page-snapshot":case"dom-subtree":case"dom-candidates":case"accessibility-node":{let o=r.kind==="accessibility-node"?.5:.9;return s<uI?ee.failedCall+o-s/1e3:ee.context+o-Math.min(.8,s/1e3)}default:break}let a=t.get(r.evidenceId);if(a!==void 0)return a;switch(r.kind){case"stack-frame":return/node_modules|node:internal/.test(r.observation)?ee.ordinary:ee.failedCall;case"source-range":{let o=e.get(r.evidenceId)??0;return ee.significant-Math.min(.9,o/100)}case"diff-hunk":return ee.failedCall+.9;case"step":return ee.context;default:return ee.ordinary}}async function fs(r,t,e){let n=Vo(e);if(n!==void 0)return{kind:"invalid-policy",message:n};if(e.workspaceRoot!==r.workspace.root)return{kind:"invalid-policy",message:"Evidence policy workspaceRoot must match the normalized run workspace root."};let i=t.artifactRoot??r.workspace.root,s=yI(r),a=Pf(s,e),o=[...a.artifacts],d=[...a.evidence],c=[...a.redactions],l=[...a.omissions],u=[...a.seeds],p=new Map,f=a.artifacts.find(A=>A.channel==="report");if(f!==void 0&&r.logicalTests.length>0){let A={type:"report-field",path:"stats"},O=gI(r,s);d.push({evidenceId:he(r.runId,f.artifactId,"run-summary",A,O),kind:"run-summary",artifactId:f.artifactId,locator:A,observation:O,availability:"present",redactionIds:[]})}for(let A of s.logicalTests)for(let O of A.attempts){let j=0,V=0,P=0,C=[...zn(O)];for(let M of O.attachments){if(!$f(M,t.tracePaths))continue;let z=t.tracePaths?.[M.attachmentId]??M.path;if(z===void 0){l.push(Mf(O.attemptId,"trace","Trace attachment supplied no path; inline trace bodies are not read."));continue}j+=1;let k=await zp(r.runId,e,{attachmentId:M.attachmentId,logicalTestId:A.logicalTestId,attemptId:O.attemptId,path:z,info:{...r.artifact.formatVersion===void 0?{}:{producerVersion:r.artifact.formatVersion},format:"playwright-trace-zip"}},i);o.push(...k.artifacts),d.push(...k.evidence),c.push(...k.redactions),l.push(...k.omissions),u.push(...k.seeds),C.push(...k.failedSelectors);for(let[T,L]of k.priorities)p.set(T,L)}for(let M of O.attachments){if(!nd(M))continue;V+=1;let z=await Up(r.runId,e,{logicalTestId:A.logicalTestId,attemptId:O.attemptId,attachment:M,focus:C},i);o.push(...z.artifacts),d.push(...z.evidence),c.push(...z.redactions),l.push(...z.omissions),C.push(...z.failedSelectors);for(let[k,T]of z.priorities)p.set(k,T)}for(let M of O.attachments){if($f(M,t.tracePaths)||nd(M))continue;if(wf(M)){P+=1;let k=await bf(r.runId,e,{logicalTestId:A.logicalTestId,attemptId:O.attemptId,attachment:M,focus:C},i);o.push(...k.artifacts),d.push(...k.evidence),c.push(...k.redactions),l.push(...k.omissions);continue}let z=await mf(r.runId,e,{logicalTestId:A.logicalTestId,attemptId:O.attemptId,attachment:M},i);o.push(...z.artifacts),d.push(...z.evidence),c.push(...z.redactions),l.push(...z.omissions)}if(j===0&&V===0){let M=r.framework==="playwright"?"Attempt produced no trace attachment.":"Attempt has no KwikQA failure capture; run `kwikqa analyze --capture` to record the page.";for(let z of dI)z==="accessibility"&&P>0||l.push(Mf(O.attemptId,z,M))}}if(t.probePath!==void 0){let A=await vf(s,e,t.probePath,r.workspace.root);o.push(...A.artifacts),d.push(...A.evidence),c.push(...A.redactions),l.push(...A.omissions)}let h=await Lf(r.runId,e,u,r.workspace.root);o.push(...h.artifacts),d.push(...h.evidence),c.push(...h.redactions),l.push(...h.omissions);let g=new Map(h.evidence.map((A,O)=>[A.evidenceId,O])),m=h.artifacts.map(A=>A.path).filter(A=>A!==void 0),y=await Gp(r.runId,e,m,{authorized:t.includeCurrentDiff===!0,workspaceRoot:r.workspace.root,...r.workspace.gitRoot===void 0?{}:{gitRoot:r.workspace.gitRoot}});o.push(...y.artifacts),d.push(...y.evidence),c.push(...y.redactions),l.push(...y.omissions);let w=await pf(r.runId,r.createdAt,e,cf(s.logicalTests.flatMap(A=>A.attempts),zn,d.filter(A=>A.kind==="network-event").map(A=>A.observation)),{authorized:t.includeChangeHistory===!0,workspaceRoot:r.workspace.root,...r.workspace.gitRoot===void 0?{}:{gitRoot:r.workspace.gitRoot}});o.push(...w.artifacts),d.push(...w.evidence),c.push(...w.redactions),l.push(...w.omissions);let x=ps(o,A=>A.artifactId),v=new Map(x.map(A=>[A.artifactId,A.channel])),I=(A,O,j)=>{let V=ps(A,T=>T.evidenceId),P=ps(O,T=>T.redactionId),C=ps(j,T=>T.omissionId),M=aI.map(T=>mI(T,x,V,C,P)),z=T=>{let L={schemaVersion:"1.2",runId:r.runId,framework:r.framework,createdAt:r.createdAt,workspace:r.workspace,sourceHashes:r.sourceHashes,policy:e,artifacts:x,evidence:V,redactions:P,omissions:C,accounting:M,totals:{artifacts:x.length,evidence:V.length,redactions:P.length,omissions:C.length,serializedBytes:T}};return{...L,packetHash:Cr(L)}},k=z(0);for(let T=0;T<cI;T+=1){let L=Vn(k);if(k.totals.serializedBytes===L)break;k=z(L)}return k},R=I(d,c,l),E=Vn(R);if(E>e.maxPacketBytes){let A=new Set(d.flatMap(k=>k.redactionIds)),O=new Map(d.map(k=>[k.evidenceId,k])),j=new Map(s.logicalTests.flatMap(k=>k.attempts).map((k,T)=>[k.attemptId,T])),V=new Set,P=new Set;for(let k of[...d].sort((T,L)=>(j.get(T.attemptId??"")??0)-(j.get(L.attemptId??"")??0)||T.evidenceId.localeCompare(L.evidenceId))){if(k.kind==="error-field"||k.kind==="run-summary"||k.kind==="change-search")continue;let T=`${k.kind}
44
+ ${k.observation}`;P.has(T)?V.add(k.evidenceId):P.add(T)}let C=d.map(k=>({item:k,priority:wI(k,p,g,j,V)})).filter(k=>k.priority<ee.failure).sort((k,T)=>k.priority-T.priority||k.item.evidenceId.localeCompare(T.item.evidenceId)),M=new Set,z=0;for(let k=0;k<lI&&E>e.maxPacketBytes;k+=1){let T=E-e.maxPacketBytes*.97;for(;T>0&&z<C.length;){let K=C[z++];if(K===void 0)break;M.add(K.item.evidenceId),T-=Vn(K.item)+64}let L=d.filter(K=>!M.has(K.evidenceId)),q=new Set(L.flatMap(K=>K.redactionIds)),Q=c.filter(K=>!A.has(K.redactionId)||q.has(K.redactionId)),ie=new Map;for(let K of M){let ve=O.get(K),Re=ve===void 0?void 0:v.get(ve.artifactId);Re!==void 0&&ie.set(Re,(ie.get(Re)??0)+1)}let de=[...ie.entries()].map(([K,ve])=>{let Re=`Dropped ${ve} lower-priority ${K} observation${ve===1?"":"s"} to fit the ${e.maxPacketBytes}-byte packet budget; observations closest to the failure were kept.`;return{omissionId:$("omi",[r.runId,K,"budget-exceeded","packet",Re]),channel:K,reason:"budget-exceeded",message:Re,locator:"packet",cap:e.maxPacketBytes}});if(R=I(L,Q,[...l,...de]),E=Vn(R),z>=C.length)break}}return E>e.maxPacketBytes?{kind:"budget-exceeded",message:`Even the evidence closest to the failure is ${E} bytes, exceeding maxPacketBytes=${e.maxPacketBytes}; raise the explicit policy limit or narrow the authorized inputs.`}:{kind:"built",packet:R}}import{spawn as Vf}from"node:child_process";var bI=["KWIKQA_TOKEN","KWIKQA_API_URL","OPENROUTER_API_KEY"],Ff=256*1024,xI=8e3;function hs(r,t={}){let e={...r,...t};for(let n of bI)delete e[n];return e}function jf(r){return r.pid===void 0||r.exitCode!==null||r.signalCode!==null}function Bf(r,t){if(r.pid!==void 0)try{process.kill(-r.pid,t)}catch{r.kill(t)}}async function vI(r,t){if(!jf(r)){if(process.platform==="win32"){await new Promise(e=>{let n=Vf("taskkill",["/pid",String(r.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("exit",()=>e()),n.on("error",()=>e())});return}Bf(r,"SIGINT"),await Promise.race([t,new Promise(e=>setTimeout(e,xI))]),jf(r)||Bf(r,"SIGKILL")}}function yd(r,t,e){let n=Vf(r,[...t],{cwd:e.cwd,env:e.env,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),i="",s=o=>{i+=o.toString("utf8"),i.length>Ff&&(i=i.slice(-Ff))};n.stdout?.on("data",s),n.stderr?.on("data",s);let a=new Promise(o=>{n.on("exit",d=>o(d??void 0)),n.on("error",()=>o(void 0))});return{child:n,output:()=>i,exited:a,stop:async()=>{await vI(n,a),await Promise.race([a,new Promise(o=>setTimeout(o,2e3))])}}}async function ms(r,t,e){let n=yd(r,t,e),i=!1,s=setTimeout(()=>{i=!0,n.stop()},e.timeoutMs),a=await n.exited;return clearTimeout(s),{...a===void 0?{}:{exitCode:a},timedOut:i,output:n.output()}}async function zf(r,t,e){let n=Date.now()+e,i=!1;for(r.exited.then(()=>{i=!0});Date.now()<n;){let s=t.exec(r.output());if(s!==null)return s;if(i)return t.exec(r.output())??void 0;await new Promise(a=>setTimeout(a,100))}}var Uf="1.0",gd=[1,59],AI=5,SI=6e4,EI=3e4,CI=12e4,NI=new Set(["generic","text","list","group","none","presentation"]),OI=new Set(["banner","navigation","main","contentinfo","complementary","region","form","search"]);function wd(r){let[t=0,e=0]=r.split(".").map(n=>Number.parseInt(n,10));return t>gd[0]||t===gd[0]&&e>=gd[1]}async function qf(r){try{let t=JSON.parse(await kI(rr(r,"package.json"),"utf8"));return t.name==="@playwright/cli"&&typeof t.version=="string"?t.version:void 0}catch{return}}async function Gf(r,t){try{let n=PI(rr(r,"package.json")).resolve("@playwright/cli/package.json"),i=Hf(n),s=await qf(i);if(s!==void 0)return{entryPath:rr(i,"playwright-cli.js"),version:s,source:"project"}}catch{}let e=process.platform==="win32"?["playwright-cli.cmd"]:["playwright-cli"];for(let n of(t.PATH??"").split(RI).filter(Boolean))for(let i of e){let s=rr(n,i);try{let a=process.platform==="win32"?rr(n,"node_modules","@playwright","cli"):Hf(await II(s)),o=await qf(a);if(o!==void 0)return{entryPath:rr(a,"playwright-cli.js"),version:o,source:"path"}}catch{}}}function bd(r){return r.split(/\r?\n/).filter(t=>!/[║╔╚═]/.test(t)).join(`
45
+ `)}function Kf(r){return/```yaml\r?\n([\s\S]*?)\r?\n```/.exec(bd(r))?.[1]?.split(/\r?\n/)}function Wf(r){let t=bd(r).split(/\r?\n/),e=t.findIndex(n=>n.trim()==="### Result");if(!(e<0))return t.slice(e+1).map(n=>n.trim()).find(n=>n!==""&&!n.startsWith("###"))}function DI(r){return/getByRole\(\s*['"]([\w-]+)['"]/.exec(r??"")?.[1]?.toLowerCase()}function Jf(r){return r.trim().replace(/^-\s+/,"").replace(/\s\[(?:ref|cursor)=[^\]]+\]/g,"").replace(/:$/,"").trim()}function Xf(r,t,e=AI){let n=Nr(t??""),i=DI(t);return r.map((a,o)=>{let d=/\[ref=(e\d+)\]/.exec(a)?.[1],c=Jf(a),l=/^([\w-]+)/.exec(c)?.[1]?.toLowerCase()??"";if(d===void 0||NI.has(l))return;let u=c.toLowerCase(),p=n.filter(f=>u.includes(f)).length*3+(i!==void 0&&l===i?2:0);if(!(OI.has(l)&&p===0))return{ref:d,element:c,score:p,order:o}}).filter(a=>a!==void 0).sort((a,o)=>o.score-a.score||a.order-o.order).slice(0,e).map(({ref:a,element:o})=>({ref:a,element:o}))}async function Yf(r){let{target:t}=r,e=[],n={logicalTestId:t.logicalTestId,title:t.title,file:t.file,line:t.line,...t.failingLine===void 0?{}:{failingLine:t.failingLine},...t.locator===void 0?{}:{locator:t.locator}};if(t.failingLine===void 0)return{...n,candidates:[],issues:["The report does not say which line failed."]};let i=hs(r.env,{PLAYWRIGHT_HTML_OPEN:"never"}),s=yd(r.playwright.executable,[...r.playwright.nodeArguments,"test",`${t.file}:${t.line}`,...t.project===void 0?[]:[`--project=${t.project}`],...r.configPath===void 0?[]:[`--config=${r.configPath}`],"--debug=cli","--timeout=0","--retries=0","--workers=1","--reporter=line"],{cwd:r.workspaceRoot,env:i}),a=(c,l=EI)=>ms(process.execPath,[r.cli.entryPath,...c],{cwd:r.scratchDirectory,env:i,timeoutMs:l}),o,d=[];try{if(o=(await zf(s,/playwright-cli attach ([\w-]+)/,SI))?.[1],o===void 0)return e.push("The test did not stop in the debugger."),{...n,candidates:d,issues:e};if((await a(["attach",o])).exitCode!==0)return e.push("Playwright CLI could not attach to the paused test."),{...n,candidates:d,issues:e};let u=TI(t.file)?t.file:rr(r.workspaceRoot,t.file),p=await a([`-s=${o}`,"pause-at",`${u}:${t.failingLine}`],CI);if(p.exitCode!==0||!/### Paused/.test(p.output))return e.push(`The test did not reach line ${t.failingLine}.`),{...n,candidates:d,issues:e};let f=Kf((await a([`-s=${o}`,"snapshot"])).output);if(f===void 0)return e.push("Playwright CLI returned no page snapshot."),{...n,candidates:d,issues:e};for(let h of Xf(f,t.locator)){let g=Wf((await a([`-s=${o}`,"generate-locator",h.ref])).output);g!==void 0&&d.push({element:h.element,locator:g})}return d.length===0&&e.push("No locator could be generated for any candidate."),{...n,candidates:d,issues:e}}catch(c){return e.push(`The probe stopped: ${c instanceof Error?c.message:String(c)}`),{...n,candidates:d,issues:e}}finally{o!==void 0&&await a([`-s=${o}`,"detach"],1e4).catch(()=>{}),await s.stop()}}import{mkdir as lm,rm as cm}from"node:fs/promises";import{dirname as pT,join as Wr,relative as fT,resolve as hT}from"node:path";import{createHash as LI}from"node:crypto";function xd(r,t){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError("canonical JSON cannot contain non-finite numbers");return r}if(Array.isArray(r))return r.map(e=>xd(e,t));if(typeof r!="object")throw new TypeError(`canonical JSON cannot contain ${typeof r}`);if(t.has(r))throw new TypeError("canonical JSON cannot contain cycles");t.add(r);try{let e=r,n={};for(let i of Object.keys(e).sort()){let s=e[i];if(s===void 0)throw new TypeError(`canonical JSON cannot contain undefined at ${JSON.stringify(i)}`);n[i]=xd(s,t)}return n}finally{t.delete(r)}}function le(r){return JSON.stringify(xd(r,new Set))}function N(r){return LI("sha256").update(le(r),"utf8").digest("hex")}function Qf(r){let t=new Map;for(let e of r){if(t.has(e.logicalTestId))throw new Error("Logical test observation is duplicated.");t.set(e.logicalTestId,e.status)}return t}function Zf(r){return r!==void 0&&r!=="passed"}function vd(r){let t=new Set(r.targetLogicalTestIds);if(t.size===0||t.size!==r.targetLogicalTestIds.length)throw new Error("Target logical test identities must be unique and nonempty.");let e=Qf(r.baseline),n=[],i=new Set;for(let l of r.blockingReasons??[]){if(l.length===0)throw new Error("Blocking validation reasons must be nonempty.");n.push({classification:"incomplete-check",message:l})}for(let l of[...r.commands].sort((u,p)=>u.commandId.localeCompare(p.commandId))){if(!l.required)continue;if(l.timing==="post-patch")for(let p of l.expectedLogicalTestIds)i.add(p);if(!l.fresh){n.push({classification:"incomplete-check",commandId:l.commandId,message:"Required command evidence is not fresh."});continue}if(l.status==="unavailable"){n.push({classification:"unavailable-check",commandId:l.commandId,message:"Required command was unavailable."});continue}if(l.status==="incomplete"){n.push({classification:"incomplete-check",commandId:l.commandId,message:"Required command did not produce authoritative evidence."});continue}if(l.timing==="baseline")continue;let u=Qf(l.observations);for(let p of l.expectedLogicalTestIds){let f=u.get(p);if(f===void 0){n.push({classification:"incomplete-check",logicalTestId:p,commandId:l.commandId,message:"An expected logical test is missing from post-patch evidence."});continue}if(t.has(p)){n.push({classification:f==="passed"?"fixed-target-failure":"still-failing-target",logicalTestId:p,commandId:l.commandId,message:f==="passed"?"The original target failure is fixed.":"The original target remains non-passing."});continue}let h=e.get(p);f!=="passed"&&n.push({classification:Zf(h)?"unchanged-pre-existing-failure":"newly-introduced-failure",logicalTestId:p,commandId:l.commandId,message:Zf(h)?"An affected test remains non-passing from its baseline.":"An affected test newly became non-passing."})}}for(let l of[...t].sort())i.has(l)||n.push({classification:"incomplete-check",logicalTestId:l,message:"No fresh focused evidence covers the target logical test."});let s=n.sort((l,u)=>`${l.classification}\0${l.logicalTestId??""}\0${l.commandId??""}`.localeCompare(`${u.classification}\0${u.logicalTestId??""}\0${u.commandId??""}`)),a=new Set(s.map(l=>l.classification)),o=[...t].every(l=>s.some(u=>u.classification==="fixed-target-failure"&&u.logicalTestId===l)),c={schemaVersion:"1.0",status:a.has("incomplete-check")?"incomplete":a.has("unavailable-check")?"unavailable":!o||a.has("still-failing-target")||a.has("unchanged-pre-existing-failure")||a.has("newly-introduced-failure")||r.commands.some(l=>l.required&&l.status==="failed")?"failed":"passed",classifications:s};return{...c,summaryHash:N(c)}}var gs="1.1",kd="1.0",ws="1.1";var bs="1.0",Dt=/^[a-z][a-z0-9_-]{0,63}$/,jr=32*1024*1024,nr=16*1024*1024,qn="report.json",th=["playwright-focused","playwright-affected","playwright-project","playwright-suite","cypress-focused","cypress-affected","cypress-project","cypress-suite","webdriverio-focused","webdriverio-affected","webdriverio-project","webdriverio-suite"];function Br(r){return th.includes(r)}var be=/^[a-f0-9]{64}$/,Un=Dt;function Ce(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function rh(r){return Array.isArray(r)&&r.every(t=>typeof t=="string")}function Hn(r,t=!0){return rh(r)&&(t||r.length>0)&&r.every(e=>e.length>0&&!e.includes("\0"))&&new Set(r).size===r.length}function Ae(r,t){let e=Object.keys(r).sort(),n=[...t].sort();return e.length===n.length&&e.every((i,s)=>i===n[s])}function MI(r){if(!Ce(r))return!1;let t=["outputDirectory","maxArtifacts","maxArtifactBytes"];return r.reportFile!==void 0&&t.push("reportFile"),Ae(r,t)&&typeof r.outputDirectory=="string"&&r.outputDirectory.length>0&&!r.outputDirectory.includes("\0")&&(r.reportFile===void 0||typeof r.reportFile=="string"&&r.reportFile.length>0&&!r.reportFile.includes("\0"))&&Number.isInteger(r.maxArtifacts)&&r.maxArtifacts>0&&Number.isInteger(r.maxArtifactBytes)&&r.maxArtifactBytes>0&&r.maxArtifactBytes<=jr}function $I(r){if(!Ce(r))return!1;let t=["kind","path","detail"];return r.sha256!==void 0&&t.push("sha256"),Ae(r,t)&&["package-root","package-manifest","package-entry","configuration","pnp-loader","source-graph","scope-escalation"].includes(String(r.kind))&&typeof r.path=="string"&&r.path.length>0&&!r.path.includes("\0")&&typeof r.detail=="string"&&r.detail.length>0&&(r.sha256===void 0||typeof r.sha256=="string"&&be.test(r.sha256))}function nh(r){return!Ce(r)||!Un.test(String(r.commandId))||!Ae(r,["commandId","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","artifactPolicy","resolutionEvidence"])||!(Br(String(r.kind))||["parse","format","typecheck","lint"].includes(String(r.kind)))||r.timing!=="baseline"&&r.timing!=="post-patch"||typeof r.executable!="string"||r.executable.length===0||!rh(r.args)||r.args.some(t=>t.includes("\0"))||typeof r.workingDirectory!="string"||r.workingDirectory.length===0||r.workingDirectory.includes("\0")||!Number.isInteger(r.timeoutMs)||r.timeoutMs<=0||r.required!==!0||typeof r.purpose!="string"||r.purpose.length===0||!Hn(r.logicalTestIds)||!Hn(r.projectIds)||!Ce(r.environmentDelta)||!MI(r.artifactPolicy)||!Array.isArray(r.resolutionEvidence)||!r.resolutionEvidence.every($I)?!1:Object.entries(r.environmentDelta).every(([t,e])=>/^[A-Z][A-Z0-9_]*$/.test(t)&&typeof e=="string"&&!e.includes("\0"))}function Id(r){return Ce(r)&&Ae(r,["path","sourceSha256","resultSha256"])&&typeof r.path=="string"&&r.path.length>0&&!r.path.includes("\0")&&typeof r.sourceSha256=="string"&&be.test(r.sourceSha256)&&typeof r.resultSha256=="string"&&be.test(r.resultSha256)}function _I(r){return Ce(r)&&Ae(r,["baselineId","commandId","logicalTestIds","reason"])&&/^baseline_[a-f0-9]{24}$/.test(String(r.baselineId))&&Un.test(String(r.commandId))&&Hn(r.logicalTestIds,!1)&&typeof r.reason=="string"&&r.reason.length>0}function FI(r){if(!Ce(r))return!1;let t=["code","message"];return r.path!==void 0&&t.push("path"),Ae(r,t)&&["ambiguous-package-root","ambiguous-configuration","budget-exceeded","cancelled","entry-outside-workspace","invalid-artifact","invalid-command","malformed-manifest","missing-browser","missing-configuration","missing-dependency","missing-test-identity","package-mismatch","parse-failed","report-incomplete","resolution-failed","spawn-failed","symlink-escape","timeout","unsupported-layout"].includes(String(r.code))&&typeof r.message=="string"&&r.message.length>0&&(r.path===void 0||typeof r.path=="string"&&!r.path.includes("\0"))}function ih(r){return N({purpose:"kwikqa-validation-baseline",...r})}function xs(r){return N({purpose:"kwikqa-validation-run",...r})}function ys(r){return typeof r=="string"&&r.length>0&&Number.isFinite(Date.parse(r))}function jI(r){if(!Ce(r)||typeof r.kind!="string")return!1;if(r.kind==="exit")return Ae(r,["kind","exitCode"])&&Number.isInteger(r.exitCode);if(r.kind==="signal")return Ae(r,["kind","signal"])&&typeof r.signal=="string";if(r.kind==="spawn-error"){let t=["kind",...r.code===void 0?[]:["code"]];return Ae(r,t)&&(r.code===void 0||typeof r.code=="string")}return(r.kind==="timeout"||r.kind==="cancelled")&&Ae(r,["kind"])}function eh(r){return Ce(r)&&Ae(r,["path","sha256","storedSha256","observedBytes","storedBytes","truncated","redacted"])&&typeof r.path=="string"&&r.path.length>0&&typeof r.sha256=="string"&&be.test(r.sha256)&&typeof r.storedSha256=="string"&&be.test(r.storedSha256)&&Number.isInteger(r.observedBytes)&&r.observedBytes>=0&&Number.isInteger(r.storedBytes)&&r.storedBytes>=0&&typeof r.truncated=="boolean"&&typeof r.redacted=="boolean"}function BI(r){return Ce(r)&&Ae(r,["path","sha256","bytes"])&&typeof r.path=="string"&&r.path.length>0&&typeof r.sha256=="string"&&be.test(r.sha256)&&Number.isInteger(r.bytes)&&r.bytes>=0}function Pd(r){if(!Rd(r))throw new Error("Validation command record is malformed or failed integrity validation.");return r}function VI(r){if(!Ce(r))return!1;let t=["classification",...r.logicalTestId===void 0?[]:["logicalTestId"],...r.commandId===void 0?[]:["commandId"],"message"];return Ae(r,t)&&["fixed-target-failure","still-failing-target","unchanged-pre-existing-failure","newly-introduced-failure","unavailable-check","incomplete-check"].includes(String(r.classification))&&(r.logicalTestId===void 0||typeof r.logicalTestId=="string"&&r.logicalTestId.length>0)&&(r.commandId===void 0||typeof r.commandId=="string"&&Un.test(r.commandId))&&typeof r.message=="string"&&r.message.length>0}function Rd(r){if(!Ce(r))return!1;let t=r,{recordHash:e,...n}=t;return Ae(r,["schemaVersion","validationRunId","commandId","commandHash","planHash","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","startedAt","durationMs","termination","stdout","stderr","artifacts","status","recordHash"])&&t.schemaVersion===kd&&/^vld_[a-f0-9]{24}$/.test(t.validationRunId)&&Un.test(t.commandId)&&be.test(t.commandHash)&&be.test(t.planHash)&&t.required===!0&&nh({commandId:t.commandId,kind:t.kind,timing:t.timing,required:t.required,executable:t.executable,args:t.args,workingDirectory:t.workingDirectory,environmentDelta:t.environmentDelta,timeoutMs:t.timeoutMs,purpose:t.purpose,logicalTestIds:t.logicalTestIds,projectIds:t.projectIds,artifactPolicy:{outputDirectory:"artifacts",maxArtifacts:1,maxArtifactBytes:1},resolutionEvidence:[]})&&ys(t.startedAt)&&Number.isInteger(t.durationMs)&&t.durationMs>=0&&jI(t.termination)&&eh(t.stdout)&&eh(t.stderr)&&Array.isArray(t.artifacts)&&t.artifacts.every(BI)&&["blocked","passed","failed","unavailable","incomplete"].includes(t.status)&&be.test(e)&&N(n)===e}function Gn(r){if(!Ce(r))throw new Error("Baseline manifest is not an object.");let t=r,{baselineHash:e,...n}=t;if(!Ae(r,["schemaVersion","planHash","repositoryFingerprint","targetHashes","commandRecords","logicalTestOutcomes","capturedAt","baselineHash"])||t.schemaVersion!==kd||!be.test(t.planHash)||!be.test(t.repositoryFingerprint)||!Array.isArray(t.targetHashes)||!t.targetHashes.every(Id)||!Array.isArray(t.commandRecords)||!t.commandRecords.every(Rd)||!Ce(t.logicalTestOutcomes)||!Object.entries(t.logicalTestOutcomes).every(([i,s])=>i.length>0&&typeof s=="string"&&["passed","failed","skipped","interrupted"].includes(s))||!ys(t.capturedAt)||!be.test(e)||ih(n)!==e)throw new Error("Baseline manifest is malformed or failed integrity validation.");return t}function Lt(r){if(!Ce(r))throw new Error("Validation run manifest is not an object.");let t=r,{manifestHash:e,...n}=t;if(!Ae(r,["schemaVersion","validationRunId","transactionId","planHash","repositoryFingerprint","targetHashes","requiredCommandIds","status","commandRecords","classifications","startedAt","completedAt","manifestHash"])||t.schemaVersion!==ws||!/^vld_[a-f0-9]{24}$/.test(t.validationRunId)||!/^txn_[a-f0-9]{24}$/.test(t.transactionId)||!be.test(t.planHash)||!be.test(t.repositoryFingerprint)||!Array.isArray(t.targetHashes)||!t.targetHashes.every(Id)||!Hn(t.requiredCommandIds,!1)||!t.requiredCommandIds.every(i=>Un.test(i))||!Array.isArray(t.commandRecords)||!t.commandRecords.every(Rd)||!Array.isArray(t.classifications)||!t.classifications.every(VI)||!["blocked","passed","failed","unavailable","incomplete"].includes(t.status)||!ys(t.startedAt)||!ys(t.completedAt)||Date.parse(t.completedAt)<Date.parse(t.startedAt)||!be.test(e)||xs(n)!==e)throw new Error("Validation run manifest is malformed or failed integrity validation.");if(new Set(t.targetHashes.map(i=>i.path)).size!==t.targetHashes.length||new Set(t.commandRecords.map(i=>i.commandId)).size!==t.commandRecords.length||t.commandRecords.some(i=>i.validationRunId!==t.validationRunId||i.planHash!==t.planHash))throw new Error("Validation run manifest contains inconsistent evidence.");if(!zI(t))throw new Error("Validation run manifest status is inconsistent with its evidence.");return t}function zI(r){let t=new Set(r.requiredCommandIds),e=new Set(r.commandRecords.map(i=>i.commandId)),n=new Set(r.classifications.map(i=>i.classification));if(r.commandRecords.some(i=>!t.has(i.commandId)||i.timing!=="post-patch")||r.requiredCommandIds.some(i=>!e.has(i)&&!r.classifications.some(s=>s.classification==="incomplete-check"&&s.commandId===i)))return!1;switch(r.status){case"passed":return r.classifications.length>0&&[...n].every(i=>i==="fixed-target-failure")&&e.size===t.size&&r.commandRecords.every(i=>i.status==="passed");case"incomplete":return n.has("incomplete-check");case"unavailable":return!n.has("incomplete-check")&&n.has("unavailable-check");case"failed":return!n.has("incomplete-check")&&!n.has("unavailable-check");default:return!0}}function vs(r){return N({purpose:"kwikqa-resolved-validation-plan",...r})}function ir(r){if(!Ce(r))throw new Error("Resolved validation plan is not an object.");if(!Ae(r,["schemaVersion","policyVersion","status",...r.transactionId===void 0?[]:["transactionId"],"proposalHash","targetLogicalTestIds","targetHashes","advisoryPlanHash","repositoryFingerprint","commands","baselineRequirements","unresolvedReasons","planHash"]))throw new Error("Resolved validation plan contains unknown or missing fields.");let t=r,{planHash:e,...n}=t;if(t.schemaVersion!==gs||t.policyVersion!==bs||t.status!=="resolved"&&t.status!=="unavailable"||!be.test(t.proposalHash)||!Hn(t.targetLogicalTestIds,!1)||!be.test(t.advisoryPlanHash)||!be.test(t.repositoryFingerprint)||!Array.isArray(t.commands)||!t.commands.every(nh)||t.transactionId!==void 0&&!/^txn_[a-f0-9]{24}$/.test(t.transactionId)||!Array.isArray(t.targetHashes)||!t.targetHashes.every(Id)||!Array.isArray(t.baselineRequirements)||!t.baselineRequirements.every(_I)||!Array.isArray(t.unresolvedReasons)||!t.unresolvedReasons.every(FI)||!be.test(e)||vs(n)!==e)throw new Error("Resolved validation plan is malformed or failed integrity validation.");if(new Set(t.commands.map(s=>s.commandId)).size!==t.commands.length)throw new Error("Resolved validation plan contains duplicate command ids.");if(new Set(t.targetHashes.map(s=>s.path)).size!==t.targetHashes.length)throw new Error("Resolved validation plan contains duplicate targets.");if(new Set(t.baselineRequirements.map(s=>s.baselineId)).size!==t.baselineRequirements.length)throw new Error("Resolved validation plan contains duplicate baseline ids.");let i=new Map(t.commands.map(s=>[s.commandId,s]));if(t.baselineRequirements.some(s=>{let a=i.get(s.commandId);return a===void 0||a.timing!=="baseline"}))throw new Error("Resolved validation plan baseline references are invalid.");if(t.status==="resolved"&&t.unresolvedReasons.length>0||t.status==="unavailable"&&t.unresolvedReasons.length===0)throw new Error("Resolved validation plan status is inconsistent.");return t}var ch=Ii(Rn(),1);import{readdir as HI,realpath as oh}from"node:fs/promises";import{extname as qI,isAbsolute as dh,join as UI,relative as GI,resolve as KI,sep as sh}from"node:path";import{dirname as WI,extname as Ed,join as ah}from"node:path/posix";var Td=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],lh=new Set(Td),JI=new Set([".js",".mjs",".cjs"]),XI=[".ts",".tsx",".mts",".cts"],YI=/(?:^|\/)(?:[^/]+\.)?(?:spec|test|cy|e2e)\.(?:[cm]?[jt]sx?)$/i,QI=new Set([".git",".kwikqa","node_modules",".yarn",".pnpm-store","coverage","dist","build","out","test-results","playwright-report"]);function Kn(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof r.type=="string"}function Ad(r,t,e=new Set){if(!e.has(r)){e.add(r),t(r);for(let[n,i]of Object.entries(r))if(n!=="loc")if(Array.isArray(i))for(let s of i)Kn(s)&&Ad(s,t,e);else Kn(i)&&Ad(i,t,e)}}function ZI(r){let t=Ed(r).toLowerCase();return t===".tsx"?["typescript","jsx"]:[".ts",".mts",".cts"].includes(t)?["typescript"]:["jsx"]}function ks(r){return Kn(r)&&r.type==="StringLiteral"&&typeof r.value=="string"?r.value:void 0}function eP(r,t){try{let e=(0,ch.parse)(r,{sourceType:"unambiguous",allowReturnOutsideFunction:!0,errorRecovery:!1,plugins:ZI(t)}),n=new Set,i=!1;return Ad(e,s=>{if(s.type==="ImportDeclaration"||s.type==="ExportNamedDeclaration"||s.type==="ExportAllDeclaration"){let c=ks(s.source);c!==void 0&&n.add(c),s.type==="ExportAllDeclaration"&&(i=!0);return}if(s.type==="ImportExpression"){let c=ks(s.source);c===void 0?i=!0:n.add(c);return}if(s.type!=="CallExpression")return;let a=s.callee,o=Array.isArray(s.arguments)?s.arguments:[];if(Kn(a)&&a.type==="Import"){let c=ks(o[0]);c===void 0?i=!0:n.add(c);return}if(!Kn(a)||a.type!=="Identifier"||a.name!=="require")return;let d=ks(o[0]);d===void 0?i=!0:n.add(d)}),{imports:[...n].sort(),ambiguous:i}}catch{return{code:"parse-failed",message:"Source could not be parsed for validation discovery.",path:t}}}function Sd(r){return r.length===0||r.includes("\0")||r.includes("\\")||dh(r)?!1:r.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function tP(r,t){return r.split("/").some(n=>QI.has(n))?!0:t.some(n=>r===n||r.startsWith(`${n}/`))}function rP(r,t){let e=GI(r,t);if(!(e===""||e===".."||e.startsWith(`..${sh}`)||dh(e)))return e.split(sh).join("/")}async function nP(r,t,e){let n=await oh(r),i=[],s=!1;async function a(o){if(s)return;let d=(await HI(o,{withFileTypes:!0})).sort((c,l)=>c.name.localeCompare(l.name,"en"));for(let c of d){if(c.isSymbolicLink())continue;let l=UI(o,c.name),u=rP(n,l);if(!(u===void 0||tP(u,t))){if(c.isDirectory())await a(l);else if(c.isFile()&&lh.has(qI(c.name).toLowerCase())){if(i.length>=e){s=!0;return}i.push(u)}}}}return await a(n),{files:i.sort(),exhausted:s}}function iP(r,t){if(!r.startsWith("./")&&!r.startsWith("../"))return[];let e=ah(t,r),n=[e],i=Ed(e).toLowerCase();if(JI.has(i)){let s=e.slice(0,e.length-i.length);for(let a of XI)n.push(`${s}${a}`)}if(i===""){for(let s of Td)n.push(`${e}${s}`);for(let s of Td)n.push(ah(e,`index${s}`))}return n.filter(Sd)}function sP(r,t,e){return iP(r,WI(t)).find(n=>e.has(n))}async function aP(r){let t=[],e=await nP(r.workspaceRoot,r.ignoredPaths??[],r.limits.maxFiles);e.exhausted&&t.push({code:"budget-exceeded",message:"Source file discovery exceeded its file limit."});let n=new Set(e.files),i=new Map,s=0,a=0,o=!e.exhausted,d=e.exhausted;for(let u of e.files){let p=await W(r.workspaceRoot,u,r.limits.maxFileBytes);if(p.kind!=="read"||p.relativePath!==u){o=!1,t.push({code:"unsafe-path",message:"Source could not be safely read.",path:u});continue}if(s+=p.bytes.byteLength,s>r.limits.maxTotalBytes){o=!1,d=!0,t.push({code:"budget-exceeded",message:"Source discovery exceeded its total byte limit."});break}let f=eP(new TextDecoder("utf-8",{fatal:!0}).decode(p.bytes),u);if("code"in f){o=!1,t.push(f),i.set(u,{path:u,imports:[],ambiguous:!0});continue}let h=[],g=f.ambiguous;for(let m of f.imports){if(!m.startsWith("./")&&!m.startsWith("../"))continue;let y=sP(m,u,n);if(y===void 0){g=!0,o=!1,t.push({code:"unresolved-local-import",message:`Local import ${JSON.stringify(m)} could not be resolved safely.`,path:u});continue}if(a+=1,a>r.limits.maxImportEdges){o=!1,d=!0,t.push({code:"budget-exceeded",message:"Import graph exceeded its edge limit."});break}h.push(y)}if(i.set(u,{path:u,imports:[...new Set(h)].sort(),ambiguous:g}),g&&(o=!1,t.push({code:"dynamic-import",message:"Module contains an import flow that cannot be bounded.",path:u})),d)break}let c=new Map;for(let u of i.values())for(let p of u.imports){let f=c.get(p)??[];f.push(u.path),c.set(p,f)}let l=new Map([...c].map(([u,p])=>[u,[...new Set(p)].sort()]));return{modules:i,reverse:l,edges:Math.min(a,r.limits.maxImportEdges),complete:o,exhausted:d,reasons:t}}function uh(r,t){return t.filter(e=>r===e.testDirectory||r.startsWith(`${e.testDirectory}/`)).sort((e,n)=>n.testDirectory.length-e.testDirectory.length||e.id.localeCompare(n.id))}function oP(r,t,e){let n=new Set,i=[];for(let s of[...r.map(a=>a.path),...t]){let o=uh(s,e)[0];o!==void 0&&!n.has(o.id)&&(n.add(o.id),i.push(o))}return i.sort((s,a)=>s.id.localeCompare(a.id))}function dP(r,t,e){let n=new Set,i=new Set(r),s=[...r].sort(),a=!0;for(let o=0;s.length>0;o+=1){if(o>=e){a=!1;break}let d=[];for(let c of s){t.modules.get(c)?.ambiguous===!0&&(a=!1);for(let u of t.reverse.get(c)??[])YI.test(u)&&n.add(u),i.has(u)||(i.add(u),d.push(u))}s=[...new Set(d)].sort()}return{tests:[...n].sort(),complete:a}}async function Is(r,t){for(let e of t){let n=await W(r,e,1e6);if(n.kind==="read"&&n.relativePath===e)return e}}async function ph(r,t){let e=[];t.some(o=>lh.has(Ed(o).toLowerCase()))&&e.push({kind:"parse",tool:"kwikqa-babel",required:!0});let n=await Is(r,["biome.json","biome.jsonc"]),i=await Is(r,[".prettierrc",".prettierrc.json","prettier.config.js","prettier.config.cjs","prettier.config.mjs"]);n!==void 0?(e.push({kind:"format",tool:"biome",configPath:n,required:!0}),e.push({kind:"lint",tool:"biome",configPath:n,required:!0})):i!==void 0&&e.push({kind:"format",tool:"prettier",configPath:i,required:!0});let s=await Is(r,["tsconfig.json"]);s!==void 0&&e.push({kind:"typecheck",tool:"typescript",configPath:s,required:!0});let a=await Is(r,["eslint.config.js","eslint.config.mjs","eslint.config.cjs",".eslintrc.json"]);return n===void 0&&a!==void 0&&e.push({kind:"lint",tool:"eslint",configPath:a,required:!0}),e}function cP(r,t,e){return r.some(n=>n.class==="playwright-config"||n.class==="framework-config")?t.length===1?"project":"suite":e?"affected":t.length===1?"project":"suite"}async function Cd(r){let t=await ph(r.workspaceRoot,r.targets.map(u=>u.path));if(r.targets.length===0||!Sd(r.originalTestPath)||r.targets.some(u=>!Sd(u.path))||r.limits.maxFiles<=0||r.limits.maxFileBytes<=0||r.limits.maxTotalBytes<=0||r.limits.maxImportEdges<=0||r.limits.maxImportDepth<=0)return{status:"unavailable",scope:"unavailable",testPaths:[],projectIds:[],staticChecks:t,indexedFiles:0,importEdges:0,completeGraph:!1,reasons:[{code:"unsafe-path",message:"Discovery input is unsafe or unbounded."}]};let e=await oh(r.workspaceRoot).catch(()=>{});if(e===void 0||KI(e,r.originalTestPath)===e)return{status:"unavailable",scope:"unavailable",testPaths:[],projectIds:[],staticChecks:t,indexedFiles:0,importEdges:0,completeGraph:!1,reasons:[{code:"unsafe-path",message:"Workspace could not be resolved safely."}]};let n=await aP(r),i=r.targets.filter(u=>u.class!=="spec");if(i.length===0)return{status:"resolved",scope:"focused",testPaths:[r.originalTestPath],projectIds:uh(r.originalTestPath,r.projects).slice(0,1).map(u=>u.id),staticChecks:t,indexedFiles:n.modules.size,importEdges:n.edges,completeGraph:n.complete,reasons:[]};let s=dP(i.map(u=>u.path),n,r.limits.maxImportDepth),a=n.complete&&s.complete&&!n.exhausted,o=oP(r.targets,s.tests,r.projects),d=cP(r.targets,o,a),c=d==="affected"?[...new Set([r.originalTestPath,...s.tests])].sort():d==="project"?[...new Set([r.originalTestPath,...s.tests])].sort():[r.originalTestPath],l=[...n.reasons];return d==="suite"&&r.projects.length>0&&o.length!==1&&l.push({code:"ambiguous-project",message:"Shared impact could not be partitioned to exactly one project; full-suite validation is required."}),{status:"resolved",scope:d,testPaths:c,projectIds:o.map(u=>u.id),staticChecks:t,indexedFiles:n.modules.size,importEdges:n.edges,completeGraph:a,reasons:l}}import{spawn as mP}from"node:child_process";import{createHash as Ss,randomUUID as yP}from"node:crypto";import{lstat as Jn,mkdir as Wn,readdir as gP,readFile as wP,realpath as Es}from"node:fs/promises";import{isAbsolute as Ih,join as Ge,relative as Cs,resolve as Ph,sep as Ns}from"node:path";import{createHash as lP,randomUUID as Rs}from"node:crypto";import{constants as Vr}from"node:fs";import{chmod as uP,link as pP,lstat as kt,mkdir as mh,open as Ps,readFile as yh,realpath as vt,rename as Dd,rm as fh,unlink as Nd}from"node:fs/promises";import{dirname as Od,isAbsolute as fP,join as Mt,relative as gh,resolve as Ld,sep as wh}from"node:path";var hP=/^txn_[a-f0-9]{24}$/;function sr(r,t){let e=gh(r,t);return e===""||!fP(e)&&e!==".."&&!e.startsWith(`..${wh}`)}async function zr(r){if(process.platform==="win32")return;let t=await Ps(r,"r");try{await t.sync()}finally{await t.close()}}function hh(r){return lP("sha256").update(r).digest("hex")}function bh(){return`txn_${Rs().replaceAll("-","").slice(0,24)}`}function ar(r){return hP.test(r)}async function Ts(r){let t=await vt(r),e=Ld(t,".kwikqa","transactions");if(!sr(t,e))throw new Error("Transaction path escapes workspace.");return{root:t,transactionsDirectory:e}}async function Fe(r,t){let e=await vt(r),n=e;for(let i of t){if(!/^[A-Za-z0-9_.-]+$/.test(i)||i==="."||i==="..")throw new Error("Unsafe transaction directory segment.");let s=Mt(n,i),a=await kt(s).catch(d=>{if(d.code!=="ENOENT")throw d});if(a===void 0)await mh(s,{mode:448}),await zr(n);else if(!a.isDirectory()||a.isSymbolicLink())throw new Error("Transaction directory contains an unsafe path.");let o=await vt(s);if(!sr(e,o))throw new Error("Transaction directory escapes workspace.");n=o}return n}async function xh(r,t,e){if(!/^\.staging-[a-f0-9]{24}$/.test(t)||!ar(e))throw new Error("Transaction publication name is invalid.");let n=await Ts(r),i=await vt(n.transactionsDirectory),s=Mt(i,t),a=Mt(i,e),o=await kt(s);if(!o.isDirectory()||o.isSymbolicLink())throw new Error("Transaction staging directory is unsafe.");if(await kt(a).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Transaction already exists.");await Dd(s,a),await zr(i)}async function me(r,t,e){let n=await vt(Od(r)),i=Ld(n,r.slice(Od(r).length+1));if(!sr(n,i))throw new Error("Write target escapes its directory.");if(!e.replace&&await kt(i).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Durable record already exists.");let s=Mt(n,`.kwikqa-${Rs()}.tmp`),a=await Ps(s,"wx",e.mode),o=!1;try{await a.writeFile(t),await a.sync(),await a.close(),e.replace?await Dd(s,i):(await pP(s,i),await Nd(s)),o=!0,await zr(n)}finally{await a.close().catch(()=>{}),o||await Nd(s).catch(()=>{})}}async function As(r,t,e,n){let i=await vt(r),s=Ld(i,t);if(!sr(i,s))throw new Error("Target escapes workspace.");let a=await kt(s);if(!a.isFile()||a.isSymbolicLink())throw new Error("Target is not a regular file.");let o=await vt(Od(s)),d=await vt(s);if(!sr(i,o)||!sr(i,d))throw new Error("Target escapes workspace.");if(gh(i,d).split(wh).join("/")!==t)throw new Error("Target canonical path changed during final authorization.");let l=await Ps(d,Vr.O_RDONLY|Vr.O_NOFOLLOW);try{let g=await l.stat();if(!g.isFile()||g.dev!==a.dev||g.ino!==a.ino)throw new Error("Target changed during final authorization.");let m=await l.readFile();if(hh(m)!==e)throw new Error("Target content changed during final authorization.")}finally{await l.close()}let u=Mt(o,`.kwikqa-target-${Rs()}.tmp`),p=a.mode&511,f=await Ps(u,Vr.O_CREAT|Vr.O_EXCL|Vr.O_WRONLY|Vr.O_NOFOLLOW,p),h=!1;try{await f.writeFile(n),await f.sync(),await f.close(),await uP(u,p);let g=await vt(s);if(g!==d||!sr(i,g))throw new Error("Target path changed before replacement.");let m=await yh(g),y=await kt(g);if(!y.isFile()||y.isSymbolicLink()||y.dev!==a.dev||y.ino!==a.ino||hh(m)!==e)throw new Error("Target changed before replacement.");await Dd(u,g),h=!0,await zr(o)}finally{await f.close().catch(()=>{}),h||await Nd(u).catch(()=>{})}}async function Ue(r,t){let e=await Fe(r,[".kwikqa","transactions"]),n=Mt(e,".lock"),i=Rs();await mh(n,{mode:448});let s=await kt(n);try{await me(Mt(n,"owner.json"),`${JSON.stringify({...t,nonce:i})}
46
+ `,{mode:384,replace:!1})}catch(a){let o=await kt(n).catch(()=>{});throw o?.dev===s.dev&&o.ino===s.ino&&await fh(n,{recursive:!0,force:!0}).catch(()=>{}),a}return await zr(e),{release:async()=>{let a=await kt(n).catch(()=>{});if(a===void 0||a.dev!==s.dev||a.ino!==s.ino||a.isSymbolicLink())throw new Error("Workspace lock ownership changed before release.");if(JSON.parse(await yh(Mt(n,"owner.json"),"utf8")).nonce!==i)throw new Error("Workspace lock ownership changed before release.");await fh(n,{recursive:!0,force:!1}),await zr(e)}}}var bP=/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTH)/i,xP=["authorization","cookie","password","passwd","secret","token","api_key","private_key"];function Md(r,t){let e=Cs(r,t);return e===""||!Ih(e)&&e!==".."&&!e.startsWith(`..${Ns}`)}function vP(r){return/^[a-f0-9]{64}$/.test(r)}function kP(r){let t=ir(r.plan),e=t.commands.find(n=>n.commandId===r.commandId);if(!/^txn_[a-f0-9]{24}$/.test(r.transactionId)||t.status!=="resolved"||!vP(t.planHash)||!Dt.test(r.commandId)||e===void 0||e.executable!==process.execPath||!Ih(e.workingDirectory)||e.args.some(n=>n.includes("\0"))||!Number.isInteger(e.timeoutMs)||e.timeoutMs<=0||!Number.isInteger(r.limits.maxStreamBytes)||r.limits.maxStreamBytes<=0||r.limits.maxStreamBytes>nr||!Number.isInteger(r.limits.maxTotalStreamBytes)||r.limits.maxTotalStreamBytes<r.limits.maxStreamBytes||!Number.isInteger(r.limits.terminationGraceMs)||r.limits.terminationGraceMs<0)throw new Error("Validation command or execution limits are invalid.");for(let[n,i]of Object.entries(e.environmentDelta))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n)||i.includes("\0"))throw new Error("Validation environment delta is invalid.");return e}async function IP(r,t){let e=await Es(r.workspaceRoot),n=Ph(e,".kwikqa","transactions",r.transactionId);if(!Md(e,n))throw new Error("Validation transaction escapes workspace.");let i=await Jn(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Validation transaction is unsafe.");let s=r.validationRunId??`vld_${yP().replaceAll("-","").slice(0,24)}`;if(!/^vld_[a-f0-9]{24}$/.test(s))throw new Error("Validation run id is invalid.");let a=Ge(n,"validation");await Wn(a,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let o=await Jn(a);if(!o.isDirectory()||o.isSymbolicLink())throw new Error("Validation directory is unsafe.");let d=Ge(a,s);await Wn(d,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let c=await Jn(d);if(!c.isDirectory()||c.isSymbolicLink())throw new Error("Validation run directory is unsafe.");let l=Ge(d,"commands");await Wn(l,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let u=await Jn(l);if(!u.isDirectory()||u.isSymbolicLink())throw new Error("Validation commands directory is unsafe.");let p=Ge(l,t.commandId);return await Wn(p,{mode:448}),await Wn(Ge(p,"artifacts"),{mode:448}),{root:d,commandDirectory:p,runId:s}}var Os=class{constructor(t,e){this.cap=t;this.consumeGlobal=e}cap;consumeGlobal;#e=Ss("sha256");#r=[];#t=0;#n=0;add(t){this.#e.update(t),this.#t+=t.byteLength;let e=Math.max(0,this.cap-this.#n),n=this.consumeGlobal(Math.min(e,t.byteLength));n>0&&(this.#r.push(t.subarray(0,n)),this.#n+=n)}finish(){return{text:Buffer.concat(this.#r).toString("utf8"),observed:this.#t,hash:this.#e.digest("hex"),truncated:this.#n<this.#t}}};function vh(r,t){let e=Buffer.from(r,"utf8");if(e.byteLength<=t)return{text:r,truncated:!1};let n=t;for(;n>0&&(e[n]??0)>=128&&(e[n]??0)<192;)n-=1;return{text:e.subarray(0,n).toString("utf8"),truncated:!0}}function kh(r){return Object.fromEntries(Object.entries(r).sort(([t],[e])=>t.localeCompare(e)).map(([t,e])=>[t,bP.test(t)?"[REDACTED]":e]))}function PP(r){return r.kind==="timeout"||r.kind==="cancelled"?"incomplete":r.kind==="spawn-error"?"unavailable":r.kind==="signal"?"incomplete":r.exitCode===0?"passed":"failed"}function RP(r){return new Promise(t=>setTimeout(t,r))}async function TP(r,t,e,n){let i=await gP(t,{withFileTypes:!0}),s=[],a=0;for(let o of i.sort((d,c)=>d.name.localeCompare(c.name))){if(!o.isFile()||o.isSymbolicLink())throw new Error("Validation artifact output contains an unsafe entry.");let d=Ge(t,o.name),c=await Jn(d),l=await Es(d);if(!c.isFile()||c.isSymbolicLink()||!Md(t,l)||c.mtimeMs+1<n)throw new Error("Validation artifact is stale or unsafe.");let u=await wP(l);if(a+=u.byteLength,s.push({path:Cs(r,l).split(Ns).join("/"),sha256:Ss("sha256").update(u).digest("hex"),bytes:u.byteLength}),s.length>e.artifactPolicy.maxArtifacts||a>e.artifactPolicy.maxArtifactBytes)throw new Error("Validation artifact policy limit was exceeded.")}if(e.artifactPolicy.reportFile!==void 0&&!s.some(o=>o.path.split("/").at(-1)===e.artifactPolicy.reportFile))throw new Error("Required validation report artifact is missing.");return s}async function $d(r){let t=kP(r),e=await Es(r.workspaceRoot),n=await Es(t.workingDirectory);if(!Md(e,n))throw new Error("Validation working directory escapes workspace.");let i=r.repositoryRoot??e;for(let Q of t.resolutionEvidence){if(Q.sha256===void 0)continue;let ie=await W(i,Ph(e,Q.path),16*1024*1024);if(ie.kind!=="read"||ie.sha256!==Q.sha256)throw new Error("Validation resolution evidence changed after approval.")}let s=await IP(r,t),a=r.now??(()=>new Date),o=a(),d=r.limits.maxTotalStreamBytes,c=Q=>{let ie=Math.min(Q,d);return d-=ie,ie},l=new Os(r.limits.maxStreamBytes,c),u=new Os(r.limits.maxStreamBytes,c),p=Ge(s.commandDirectory,"artifacts"),f={...r.inheritedEnvironment??process.env,...t.environmentDelta,...t.kind.startsWith("playwright-")?{PLAYWRIGHT_JSON_OUTPUT_NAME:Ge(p,t.artifactPolicy.reportFile??qn)}:{},...Br(t.kind)&&!t.kind.startsWith("playwright-")?{KWIKQA_REPORT_DIR:p}:{}},h=mP(t.executable,[...t.args],{cwd:t.workingDirectory,env:f,shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"]});h.stdout.on("data",Q=>l.add(Q)),h.stderr.on("data",Q=>u.add(Q));let g,m,y=Q=>{g===void 0&&(g=Q,h.kill(),m=setTimeout(()=>h.kill("SIGKILL"),r.limits.terminationGraceMs))},w=()=>y("cancelled");r.signal?.addEventListener("abort",w,{once:!0}),r.signal?.aborted&&y("cancelled");let x=setTimeout(()=>y("timeout"),t.timeoutMs),v=await new Promise(Q=>{let ie=!1;h.once("error",de=>{ie||(ie=!0,Q({kind:"spawn-error",...de.code===void 0?{}:{code:de.code}}))}),h.once("close",(de,K)=>{ie||(ie=!0,Q(g!==void 0?{kind:g}:K!==null?{kind:"signal",signal:K}:{kind:"exit",exitCode:de??1}))})});x!==void 0&&clearTimeout(x),m!==void 0&&clearTimeout(m),r.signal?.removeEventListener("abort",w),await RP(0);let I=r.sensitiveNames??xP,R=l.finish(),E=u.finish(),A=oe(R.text,"report","validation:stdout",I).value,O=vh(A,r.limits.maxStreamBytes),j=oe(E.text,"report","validation:stderr",I).value,V=vh(j,r.limits.maxStreamBytes),P=O.text,C=V.text,M=Ge(s.commandDirectory,"stdout.log"),z=Ge(s.commandDirectory,"stderr.log");await me(M,P,{mode:384,replace:!1}),await me(z,C,{mode:384,replace:!1});let k=await TP(s.root,p,t,o.getTime()),T=a(),L={schemaVersion:"1.0",validationRunId:s.runId,commandId:t.commandId,commandHash:N(t),planHash:r.plan.planHash,kind:t.kind,timing:t.timing,required:t.required,executable:t.executable,args:t.args,workingDirectory:t.workingDirectory,environmentDelta:kh(t.environmentDelta),timeoutMs:t.timeoutMs,purpose:t.purpose,logicalTestIds:t.logicalTestIds,projectIds:t.projectIds,startedAt:o.toISOString(),durationMs:Math.max(0,T.getTime()-o.getTime()),termination:v,stdout:{path:Cs(s.root,M).split(Ns).join("/"),observedBytes:R.observed,storedBytes:Buffer.byteLength(P),sha256:R.hash,storedSha256:Ss("sha256").update(P).digest("hex"),truncated:R.truncated||O.truncated,redacted:A!==R.text},stderr:{path:Cs(s.root,z).split(Ns).join("/"),observedBytes:E.observed,storedBytes:Buffer.byteLength(C),sha256:E.hash,storedSha256:Ss("sha256").update(C).digest("hex"),truncated:E.truncated||V.truncated,redacted:j!==E.text},artifacts:k,status:PP(v)},q={...L,recordHash:N(L)};return await me(Ge(s.commandDirectory,"command.json"),`${le({commandId:t.commandId,planHash:r.plan.planHash,executable:t.executable,args:t.args,workingDirectory:t.workingDirectory,environmentDelta:kh(t.environmentDelta)})}
47
+ `,{mode:384,replace:!1}),await me(Ge(s.commandDirectory,"result.json"),`${le(q)}
48
+ `,{mode:384,replace:!1}),{directory:s.root,record:q}}import{realpath as HP}from"node:fs/promises";import{join as qP}from"node:path";import{createHash as AP}from"node:crypto";import{readdir as SP,readFile as Ds}from"node:fs/promises";import{join as It}from"node:path";var Xn="1.0";function Rh(r){let t=JSON.parse(r);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("Journal record is not an object.");return t}function EP(r){if(r.schemaVersion!==Xn||typeof r.transactionId!="string"||!ar(r.transactionId)||typeof r.manifestHash!="string"||!Array.isArray(r.targets)||r.preview===null||typeof r.preview!="object"||r.authorization===null||typeof r.authorization!="object"||r.config===null||typeof r.config!="object"||typeof r.maxTargetBytes!="number"||typeof r.createdAt!="string")throw new Error("Transaction manifest is malformed.");let t=r,{manifestHash:e,...n}=t;if(N(n)!==e)throw new Error("Transaction manifest integrity check failed.");return t}function CP(r){let t=new Set(["prepared","applying","applied","validating","rolling-back","rolled-back","completed","conflicted"]);if(r.schemaVersion!==Xn||typeof r.transactionId!="string"||!ar(r.transactionId)||typeof r.manifestHash!="string"||typeof r.stateHash!="string"||typeof r.phase!="string"||!t.has(r.phase)||!Number.isInteger(r.revision)||r.revision<1||typeof r.updatedAt!="string"||!Array.isArray(r.history))throw new Error("Transaction state is malformed.");let e=r,{stateHash:n,...i}=e;if(N(i)!==n||e.history.length!==e.revision)throw new Error("Transaction state integrity check failed.");for(let[s,a]of e.history.entries())if(a===null||typeof a!="object"||a.sequence!==s+1||typeof a.type!="string"||a.type.length===0||typeof a.at!="string"||!t.has(a.phase)||a.path!==void 0&&typeof a.path!="string"||a.message!==void 0&&typeof a.message!="string"||a.planHash!==void 0&&typeof a.planHash!="string"||a.validationRunId!==void 0&&typeof a.validationRunId!="string"||a.validationManifestHash!==void 0&&typeof a.validationManifestHash!="string")throw new Error("Transaction history is malformed.");if(e.history.at(-1)?.phase!==e.phase)throw new Error("Transaction state phase does not match its history.");return e}function NP(r){return N({purpose:"kwikqa-transaction-target",path:r}).slice(0,32)}function Th(r){return AP("sha256").update(r).digest("hex")}async function Ah(r){if(!ar(r.transactionId))throw new Error("Transaction id is invalid.");let t=`.staging-${r.transactionId.slice(4)}`,e=await Fe(r.workspaceRoot,[".kwikqa","transactions",t]);await Fe(r.workspaceRoot,[".kwikqa","transactions",t,"preimages"]),await Fe(r.workspaceRoot,[".kwikqa","transactions",t,"results"]);let n=[];for(let c of r.targets){let l=NP(c.path),u=`preimages/${l}.bin`,p=`results/${l}.bin`;await me(It(e,u),c.sourceBytes,{mode:384,replace:!1}),await me(It(e,p),c.resultBytes,{mode:384,replace:!1}),n.push({id:l,path:c.path,sourceSha256:c.sourceSha256,resultSha256:c.resultSha256,preimageFile:u,resultFile:p,preimageBytes:c.sourceBytes.byteLength,resultBytes:c.resultBytes.byteLength})}let i={schemaVersion:Xn,transactionId:r.transactionId,preview:r.preview,authorization:r.authorization,config:r.config,maxTargetBytes:r.maxTargetBytes,targets:n,createdAt:r.now},s={...i,manifestHash:N(i)};await me(It(e,"manifest.json"),`${le(s)}
49
+ `,{mode:384,replace:!1});let a={sequence:1,type:"prepared",at:r.now,phase:"prepared"},o={schemaVersion:Xn,transactionId:r.transactionId,manifestHash:s.manifestHash,phase:"prepared",revision:1,updatedAt:r.now,history:[a]},d={...o,stateHash:N(o)};return await me(It(e,"state.json"),`${le(d)}
50
+ `,{mode:384,replace:!1}),await xh(r.workspaceRoot,t,r.transactionId),xe(r.workspaceRoot,r.transactionId)}async function xe(r,t){if(!ar(t))throw new Error("Transaction id is invalid.");let e=await Ts(r),n=await Fe(e.root,[".kwikqa","transactions",t]),i=EP(Rh(await Ds(It(n,"manifest.json"),"utf8"))),s=CP(Rh(await Ds(It(n,"state.json"),"utf8")));if(i.transactionId!==t||s.transactionId!==t||s.manifestHash!==i.manifestHash)throw new Error("Transaction identity mismatch.");let a=new Map,o=new Map;for(let d of i.targets){if(!/^[a-f0-9]{32}$/.test(d.id)||d.preimageFile!==`preimages/${d.id}.bin`||d.resultFile!==`results/${d.id}.bin`)throw new Error("Transaction target record is malformed.");let c=await Ds(It(n,d.preimageFile)),l=await Ds(It(n,d.resultFile));if(c.byteLength!==d.preimageBytes||l.byteLength!==d.resultBytes||Th(c)!==d.sourceSha256||Th(l)!==d.resultSha256)throw new Error("Transaction target bytes are malformed.");a.set(d.path,c),o.set(d.path,l)}return{directory:n,manifest:i,state:s,preimages:a,results:o}}function OP(r,t){return t==="conflicted"?r!=="completed"&&r!=="rolled-back":{prepared:["applying","rolling-back"],applying:["applying","applied","rolling-back"],applied:["validating","rolling-back"],validating:["completed","rolling-back"],"rolling-back":["rolling-back","rolled-back","applying"],"rolled-back":[],completed:[],conflicted:[]}[r].includes(t)}async function Be(r){let t=await xe(r.transaction.manifest.preview.workspace.workspaceRoot,r.transaction.manifest.transactionId);if(t.state.revision!==r.transaction.state.revision)throw new Error("Transaction state changed concurrently.");if(!OP(t.state.phase,r.phase))throw new Error("Transaction phase transition is not permitted.");let e={sequence:t.state.history.length+1,type:r.type,at:r.now,phase:r.phase,...r.path===void 0?{}:{path:r.path},...r.message===void 0?{}:{message:r.message},...r.planHash===void 0?{}:{planHash:r.planHash},...r.validationRunId===void 0?{}:{validationRunId:r.validationRunId},...r.validationManifestHash===void 0?{}:{validationManifestHash:r.validationManifestHash}},n={schemaVersion:Xn,transactionId:t.manifest.transactionId,manifestHash:t.manifest.manifestHash,phase:r.phase,revision:t.state.revision+1,updatedAt:r.now,history:[...t.state.history,e]},i={...n,stateHash:N(n)};return await me(It(t.directory,"state.json"),`${le(i)}
51
+ `,{mode:384,replace:!0}),xe(t.manifest.preview.workspace.workspaceRoot,t.manifest.transactionId)}async function Yn(r){let t=await Ts(r);return(await SP(t.transactionsDirectory,{withFileTypes:!0}).catch(n=>{if(n.code==="ENOENT")return[];throw n})).filter(n=>n.isDirectory()&&!n.isSymbolicLink()&&ar(n.name)).map(n=>n.name).sort()}import{createHash as DP}from"node:crypto";import{lstat as Eh,readFile as Ch,realpath as Ls}from"node:fs/promises";import{isAbsolute as LP,relative as MP,resolve as Nh,sep as $P}from"node:path";var _P=2*1024*1024,$s=4*1024*1024;function Ms(r,t){let e=MP(r,t);return e===""||!LP(e)&&e!==".."&&!e.startsWith(`..${$P}`)}async function or(r,t,e){let n=await Ls(r),i=Nh(n,t);if(!Ms(n,i))throw new Error("Validation evidence path escapes its run.");let s=await Eh(i),a=await Ls(i);if(!s.isFile()||s.isSymbolicLink()||!Ms(n,a)||s.size>e)throw new Error("Validation evidence file is unsafe or unbounded.");return JSON.parse(await Ch(a,"utf8"))}async function _d(r,t){if(!Dt.test(t))throw new Error("Validation command id is invalid.");return Pd(await or(r,`commands/${t}/result.json`,_P))}async function Sh(r,t,e,n,i){let s=Nh(r,t);if(!Ms(r,s))return!1;let a=await Eh(s).catch(()=>{}),o=await Ls(s).catch(()=>{});if(a===void 0||o===void 0||!a.isFile()||a.isSymbolicLink()||!Ms(r,o)||a.size>i||a.size!==e)return!1;let d=await Ch(o).catch(()=>{});return d!==void 0&&d.byteLength===e&&DP("sha256").update(d).digest("hex")===n}async function Fd(r,t,e){let n=await Ls(r);for(let i of[t.stdout,t.stderr])if(!await Sh(n,i.path,i.storedBytes,i.storedSha256,nr))return!1;for(let i of t.artifacts)if(!await Sh(n,i.path,i.bytes,i.sha256,e))return!1;return!0}async function Oh(r,t,e){try{let n=await _d(r,t.commandId);return N(n)===N(t)&&await Fd(r,t,e)}catch{return!1}}import{createHash as FP}from"node:crypto";import{lstat as Lh,readFile as Mh,realpath as _s}from"node:fs/promises";import{isAbsolute as jP,relative as BP,resolve as $h,sep as VP}from"node:path";function Fs(r,t){let e=BP(r,t);return e===""||!jP(e)&&e!==".."&&!e.startsWith(`..${VP}`)}function zP(r){return r.status==="expected"?"passed":r.status==="skipped"?"skipped":r.attempts.some(t=>t.status==="interrupted")?"interrupted":"failed"}var Dh={passed:0,skipped:1,interrupted:2,failed:3};function _h(r){let t=new Map;for(let e of r){let n=zP(e),i=t.get(e.logicalTestId);(i===void 0||Dh[n]>Dh[i])&&t.set(e.logicalTestId,n)}return[...t].map(([e,n])=>({logicalTestId:e,status:n})).sort((e,n)=>e.logicalTestId.localeCompare(n.logicalTestId))}async function jd(r){if(!Number.isInteger(r.maxBytes)||r.maxBytes<=0)throw new Error("Validation report byte limit is invalid.");let t=await _s(r.runDirectory).catch(()=>{});if(t===void 0)return{kind:"incomplete",reason:"Validation run directory is unavailable."};let e=$h(t,r.artifact.path);if(!Fs(t,e))return{kind:"incomplete",reason:"Validation report path escapes its run directory."};let n=await Lh(e).catch(()=>{}),i=await _s(e).catch(()=>{});if(n===void 0||i===void 0||!n.isFile()||n.isSymbolicLink()||!Fs(t,i)||n.size>r.maxBytes||n.size!==r.artifact.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unsafe."};let s=await Mh(i).catch(()=>{});if(s===void 0||s.byteLength>r.maxBytes||s.byteLength!==r.artifact.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unbounded."};let a=Ir(s,{workspaceRoot:r.workspaceRoot,...r.gitRoot===void 0?{}:{gitRoot:r.gitRoot},reportPath:r.artifact.path});if(a.kind!=="parsed")return{kind:"incomplete",reason:`Validation report could not be parsed: ${a.diagnostic.reasonCode}.`};if(a.run.usability!=="analysis-ready")return{kind:"incomplete",reason:`Validation report is not analysis-ready: ${a.run.usability}.`};if(a.run.sourceHashes.report!==r.artifact.sha256)return{kind:"incomplete",reason:"Validation report content hash does not match its record."};let o=_h(a.run.logicalTests),d=new Set(o.map(c=>c.logicalTestId));return r.expectedLogicalTestIds.some(c=>!d.has(c))?{kind:"incomplete",reason:"Validation report omits an expected logical test."}:{kind:"observed",reportSha256:a.run.sourceHashes.report,observations:o}}var js=/^(?:cypress|wdio)-[^/]*\.json$/;async function Bd(r){if(!Number.isInteger(r.maxBytes)||r.maxBytes<=0)throw new Error("Validation report byte limit is invalid.");let t=await _s(r.runDirectory).catch(()=>{});if(t===void 0)return{kind:"incomplete",reason:"Validation run directory is unavailable."};let e=r.artifacts.filter(d=>js.test(d.path.split("/").at(-1)??""));if(e.length===0)return{kind:"incomplete",reason:"The test run wrote no KwikQA report."};let n=[],i=0;for(let d of e){let c=$h(t,d.path);if(!Fs(t,c))return{kind:"incomplete",reason:"Validation report path escapes its run directory."};let l=await Lh(c).catch(()=>{}),u=await _s(c).catch(()=>{});if(l===void 0||u===void 0||!l.isFile()||l.isSymbolicLink()||!Fs(t,u)||l.size!==d.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unsafe."};if(i+=l.size,i>r.maxBytes)return{kind:"incomplete",reason:"Validation reports exceed their byte limit."};let p=await Mh(u).catch(()=>{});if(p===void 0||p.byteLength!==d.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unbounded."};if(FP("sha256").update(p).digest("hex")!==d.sha256)return{kind:"incomplete",reason:"Validation report content hash does not match its record."};n.push({path:u,bytes:p})}let s=Xi(n,{workspaceRoot:r.workspaceRoot,...r.gitRoot===void 0?{}:{gitRoot:r.gitRoot}});if(s.kind!=="parsed")return{kind:"incomplete",reason:`Validation report could not be parsed: ${s.diagnostic.reasonCode}.`};if(s.run.artifact.format!=="kwikqa-json")return{kind:"incomplete",reason:"Validation report was not written by KwikQA's reporter."};if(s.run.usability==="interrupted"||s.run.usability==="zero-tests")return{kind:"incomplete",reason:`Validation report is not analysis-ready: ${s.run.usability}.`};let a=_h(s.run.logicalTests),o=new Set(a.map(d=>d.logicalTestId));return r.expectedLogicalTestIds.some(d=>!o.has(d))?{kind:"incomplete",reason:"Validation report omits an expected logical test."}:{kind:"observed",reportSha256:s.run.sourceHashes.report,observations:a}}var UP=/^txn_[a-f0-9]{24}$/,GP=/^vld_[a-f0-9]{24}$/,KP=new Set(["rolling-back","rolled-back","conflicted"]);function WP(r){return r.length>0&&Number.isFinite(Date.parse(r))}function JP(r){return r.commands.filter(t=>t.required&&t.timing==="post-patch").sort((t,e)=>t.commandId.localeCompare(e.commandId))}function XP(r,t){let e=new Set(r);return e.size===r.length&&r.length===t.length&&t.every(n=>e.has(n))}function YP(r,t,e){let n=r.manifest.preview.authoritativeValidation,i=new Map(n.requiredCommands.map(s=>[s.commandId,s.commandHash]));return n.planHash===t.planHash&&n.repositoryFingerprint===t.repositoryFingerprint&&N(n.targetHashes)===N(t.targetHashes)&&XP(n.requiredCommandIds,e.map(s=>s.commandId))&&e.every(s=>i.get(s.commandId)===N(s))}async function QP(r,t){for(let e of t.manifest.targets){let n=await W(r,e.path,Math.max(1,e.resultBytes)).catch(()=>{});if(n?.kind!=="read"||n.relativePath!==e.path||n.sha256!==e.resultSha256)return!1}return!0}function ZP(r){return r===void 0?[]:Object.entries(r.logicalTestOutcomes).map(([t,e])=>({logicalTestId:t,status:e})).sort((t,e)=>t.logicalTestId.localeCompare(e.logicalTestId))}async function eR(r,t,e,n,i,s){let a={classification:{commandId:i.commandId,required:!0,timing:"post-patch",status:"incomplete",fresh:!0,expectedLogicalTestIds:i.logicalTestIds,observations:[]}},o=await _d(e,i.commandId).catch(()=>{});if(o===void 0||o.validationRunId!==r.validationRunId||o.planHash!==n.planHash||o.commandId!==i.commandId||o.commandHash!==N(i)||o.timing!=="post-patch"||!await Fd(e,o,i.artifactPolicy.maxArtifactBytes))return a;let d=[],c=o.status==="blocked"?"incomplete":o.status;if(Br(i.kind)&&!i.kind.startsWith("playwright-")&&o.status!=="unavailable"){let l=await Bd({workspaceRoot:t,...r.gitRoot===void 0?{}:{gitRoot:r.gitRoot},runDirectory:e,artifacts:o.artifacts,expectedLogicalTestIds:i.logicalTestIds,maxBytes:r.reportMaxBytes});l.kind==="observed"?d=l.observations:c="incomplete"}else if(i.kind.startsWith("playwright-")&&o.status!=="unavailable"){let l=i.artifactPolicy.reportFile??qn,u=o.artifacts.find(p=>p.path.split("/").at(-1)===l);if(u===void 0)c="incomplete";else{let p=await jd({workspaceRoot:t,...r.gitRoot===void 0?{}:{gitRoot:r.gitRoot},runDirectory:e,artifact:u,expectedLogicalTestIds:i.logicalTestIds,maxBytes:r.reportMaxBytes});p.kind==="observed"?d=p.observations:c="incomplete"}}return{record:o,classification:{commandId:i.commandId,required:!0,timing:"post-patch",status:c,fresh:Date.parse(o.startedAt)>=s&&!o.stdout.truncated&&!o.stderr.truncated,expectedLogicalTestIds:i.logicalTestIds,observations:d}}}async function tR(r,t,e,n){let i=await xe(t,r.transactionId),s=i.manifest.preview.authoritativeValidation,a=i.state.history,o=a.findLastIndex(I=>I.type==="validation-started"),d=a[o],c=JP(e);if(d===void 0||d.validationRunId!==r.validationRunId||d.planHash!==e.planHash||!YP(i,e,c))throw new Error("Validation run does not match the durable transaction approval.");if(s.baselineManifestHash!==n?.baselineHash||n!==void 0&&(n.planHash!==e.planHash||n.repositoryFingerprint!==e.repositoryFingerprint||N(n.targetHashes)!==N(e.targetHashes)))throw new Error("Required validation baseline is missing or mismatched.");let l=await Fe(t,[".kwikqa","transactions",r.transactionId,"validation",r.validationRunId]),u=await or(l,"manifest.json",$s).catch(I=>{if(I.code!=="ENOENT")throw I});if(u!==void 0){let I=Lt(u);if(I.transactionId!==r.transactionId||I.validationRunId!==r.validationRunId||I.planHash!==e.planHash)throw new Error("Validation run was already finalized for different evidence.");return{directory:l,manifest:I}}let p=[],f=i.state.phase;if(f==="validating")await QP(t,i)||p.push("Applied validation targets changed before the run was finalized.");else if(KP.has(f)&&!a.slice(o+1).some(I=>I.type==="validation-passed"))p.push("The transaction left validation before M6 accepted this run.");else throw new Error("Validation run cannot be finalized from the current transaction phase.");let h=Date.parse(d.at),g=r.completedAt??new Date().toISOString();if(Date.parse(g)<h)throw new Error("Validation completion precedes command execution.");let m=[],y=[];for(let I of c){let R=await eR(r,t,l,e,I,h);R.record!==void 0&&m.push(R.record),y.push(R.classification)}let w=vd({targetLogicalTestIds:e.targetLogicalTestIds,baseline:ZP(n),commands:y,blockingReasons:p}),x={schemaVersion:ws,validationRunId:r.validationRunId,transactionId:r.transactionId,planHash:e.planHash,repositoryFingerprint:e.repositoryFingerprint,targetHashes:e.targetHashes,requiredCommandIds:c.map(I=>I.commandId),status:w.status,commandRecords:m,classifications:w.classifications,startedAt:d.at,completedAt:g},v=Lt({...x,manifestHash:xs(x)});return await me(qP(l,"manifest.json"),`${le(v)}
52
+ `,{mode:384,replace:!1}),{directory:l,manifest:v}}async function Vd(r){if(!UP.test(r.transactionId)||!GP.test(r.validationRunId)||!Number.isInteger(r.reportMaxBytes)||r.reportMaxBytes<=0||r.completedAt!==void 0&&!WP(r.completedAt))throw new Error("Validation finalization identity, timestamp, or limits are invalid.");let t=ir(r.plan);if(t.status!=="resolved")throw new Error("Unavailable validation plan cannot be finalized.");if(t.transactionId!==void 0&&t.transactionId!==r.transactionId)throw new Error("Validation plan is bound to another transaction.");let e=r.baseline===void 0?void 0:Gn(r.baseline),n=await HP(r.workspaceRoot),i=await Ue(n,{operation:"finalize-validation",transactionId:r.transactionId,validationRunId:r.validationRunId});try{return await tR(r,n,t,e)}finally{await i.release().catch(()=>{})}}import{fileURLToPath as mR}from"node:url";import{execFile as rR}from"node:child_process";import{lstat as Bs,realpath as Ke}from"node:fs/promises";import{createRequire as nR}from"node:module";import{dirname as Pt,isAbsolute as Bh,join as Hd,relative as Vh,resolve as qd,sep as zh}from"node:path";import{fileURLToPath as iR}from"node:url";import{promisify as sR}from"node:util";var aR=sR(rR),Hh=128*1024,oR=64*1024,dR=/^[a-f0-9]{64}$/,Fh={"@playwright/test":{entryRequests:["@playwright/test/cli"]},cypress:{entryRequests:["cypress/bin/cypress"],bin:"cypress"},"@wdio/cli":{entryRequests:["@wdio/cli/bin/wdio.js"],bin:"wdio"},"@biomejs/biome":{entryRequests:["@biomejs/biome/bin/biome"]},prettier:{entryRequests:["prettier/bin/prettier.cjs","prettier/bin/prettier.js"]},typescript:{entryRequests:["typescript/bin/tsc"],bin:"tsc"},eslint:{entryRequests:["eslint/bin/eslint.js"]}};function dr(r,t){let e=Vh(r,t);return e===""||!Bh(e)&&e!==".."&&!e.startsWith(`..${zh}`)}function zd(r,t){return Vh(r,t).split(zh).join("/")}function Qn(r,t,e){return{code:r,message:t,...e===void 0?{}:{path:e}}}function cR(r,t){let e=new TextDecoder("utf-8",{fatal:!0}).decode(r),n=JSON.parse(e);if(n===null||typeof n!="object"||Array.isArray(n))throw new Error("Package manifest is not an object.");let i=n;if(i.name!==t||typeof i.version!="string"||i.version.trim().length===0)throw new Error("Package identity does not match the requested tool.");return{name:i.name,version:i.version}}async function lR(r,t){let e=await Ke(r),n=Bh(t)?t:qd(e,t),i=await Ke(n).catch(()=>n);if(!dr(e,i))return;let s=i;for((await Bs(s).catch(()=>{}))?.isFile()&&(s=Pt(s));dr(e,s);){let o=Hd(s,"package.json"),d=await Bs(o).catch(()=>{});if(d?.isFile()&&!d.isSymbolicLink())return o;if(s===e)break;s=Pt(s)}}async function uR(r,t){let e=await Ke(r),n=Pt(t);for(;dr(e,n);){let i=Hd(n,".pnp.cjs"),s=await Bs(i).catch(()=>{});if(s?.isFile()&&!s.isSymbolicLink())return i;if(n===e)break;n=Pt(n)}}async function jh(r,t,e){let n=Pt(r);for(;;){let i=Hd(n,"node_modules",...t.split("/"),"package.json");if(await Bs(i).catch(()=>{})!==void 0){let o=await Ke(i),d=await W(Pt(o),o,Hh).catch(()=>{}),l=(d?.kind==="read"?JSON.parse(new TextDecoder().decode(d.bytes)):void 0)?.bin,u=typeof l=="string"?l:typeof l=="object"&&l!==null?l[e]:void 0;if(typeof u!="string")throw new Error("Package declares no CLI entry.");let p=await Ke(qd(Pt(o),u));return{manifestPath:o,entryPath:p}}let a=Pt(n);if(a===n)throw new Error("Package is not installed.");n=a}}async function pR(r,t){let e=nR(r),n=Fh[t].bin,i;try{i=await Ke(e.resolve(`${t}/package.json`))}catch(a){if(n===void 0)throw a;return jh(r,t,n)}let s;for(let a of Fh[t].entryRequests)try{s=await Ke(e.resolve(a));break}catch{}if(s===void 0){if(n!==void 0)return jh(r,t,n);throw new Error("Package CLI entry could not be resolved.")}return{manifestPath:i,entryPath:s}}async function Ud(r,t){let e=await Ke(t),n=await W(r,e,16*1024*1024);if(n.kind!=="read")throw new Error("PnP loader is not an authorized repository-local regular file.");return{path:e,relativePath:n.relativePath,sha256:n.sha256}}async function fR(r,t,e,n){let i=iR(new URL("./pnp-resolver.mjs",import.meta.url)),{stdout:s}=await aR(process.execPath,[i,r,t.path,t.sha256,e,n],{encoding:"utf8",maxBuffer:oR,timeout:1e4,windowsHide:!0,env:{PATH:process.env.PATH??""}}),a=JSON.parse(s);if(a===null||typeof a!="object"||Array.isArray(a))throw new Error("PnP resolver output is malformed.");let o=a;if(typeof o.manifestPath!="string"||typeof o.entryPath!="string"||o.loaderSha256!==t.sha256)throw new Error("PnP resolver output is incomplete or has the wrong loader identity.");let d=await Ud(r,t.path);if(d.path!==t.path||d.relativePath!==t.relativePath||d.sha256!==t.sha256)throw new Error("PnP loader identity changed during resolution.");return{manifestPath:await Ke(o.manifestPath),entryPath:await Ke(o.entryPath)}}async function hR(r){let t=await W(r.root,r.paths.manifestPath,r.maxManifestBytes),e=await W(r.root,r.paths.entryPath,16*1024*1024);if(t.kind!=="read"||e.kind!=="read")throw new Error("Resolved package files are not authorized repository-local regular files.");let n=cR(t.bytes,r.packageName),i=Pt(r.paths.manifestPath);if(!dr(i,r.paths.entryPath))throw new Error("Package CLI entry escapes its package root.");let s=[],a=[];if(r.loader!==void 0){let o=await Ud(r.root,r.loader.path);if(o.path!==r.loader.path||o.relativePath!==r.loader.relativePath||o.sha256!==r.loader.sha256)throw new Error("PnP loader identity changed before tool authorization completed.");a.push("--require",r.loader.path),s.push({kind:"pnp-loader",path:zd(r.workspace,r.loader.path),sha256:r.loader.sha256,detail:"Repository-local Yarn Plug'n'Play loader."})}return a.push(r.paths.entryPath),{packageName:r.packageName,packageVersion:n.version,packageRoot:i,packageManifest:r.paths.manifestPath,packageManifestSha256:t.sha256,entryPath:r.paths.entryPath,entrySha256:e.sha256,executable:process.execPath,nodeArguments:a,packageManagerLayout:r.layout,resolutionEvidence:[{kind:"package-root",path:i,detail:`Canonical repository-local ${r.packageName} package root.`},{kind:"package-manifest",path:zd(r.workspace,r.paths.manifestPath),sha256:t.sha256,detail:`${n.name}@${n.version}`},{kind:"package-entry",path:zd(r.workspace,r.paths.entryPath),sha256:e.sha256,detail:"JavaScript CLI entry executed directly through the current Node runtime."},...s]}}async function Zn(r){try{let t=await Ke(r.workspaceRoot),e=r.repositoryRoot===void 0?t:await Ke(r.repositoryRoot);if(!dr(e,t))return{kind:"unavailable",reasons:[Qn("entry-outside-workspace","The workspace is outside its containing repository.")]};let n=await lR(e,qd(t,r.ownerPath));if(n===void 0)return{kind:"unavailable",reasons:[Qn("ambiguous-package-root","No owning repository package was found.")]};let i=r.maxManifestBytes??Hh;if(!Number.isInteger(i)||i<=0)return{kind:"unavailable",reasons:[Qn("budget-exceeded","Package manifest byte limit is invalid.")]};let s,a="node-modules",o;try{s=await pR(n,r.packageName)}catch{let c=await uR(e,n);if(c===void 0)throw new Error("No repository-local dependency resolution succeeded.");o=await Ud(e,c),a="pnp",s=await fR(e,o,n,r.packageName)}return!dr(e,s.manifestPath)||!dr(e,s.entryPath)?{kind:"unavailable",reasons:[Qn("entry-outside-workspace","Resolved package files are outside the repository.")]}:{kind:"resolved",tool:await hR({root:e,workspace:t,packageName:r.packageName,paths:s,maxManifestBytes:i,layout:a,...o===void 0?{}:{loader:o}})}}catch{return{kind:"unavailable",reasons:[Qn("missing-dependency",`Repository-local ${r.packageName} could not be resolved safely. No installation or global fallback was attempted.`)]}}}function ei(r){if(r.tool.executable!==process.execPath||r.args.some(i=>i.includes("\0"))||r.workingDirectory.includes("\0")||!Number.isInteger(r.timeoutMs)||r.timeoutMs<=0)throw new Error("Resolved validation command is invalid.");let t=[...r.tool.nodeArguments,...r.args],e=[...r.tool.resolutionEvidence,...r.extraEvidence??[]],n=N({packageManifestSha256:r.tool.packageManifestSha256,entrySha256:r.tool.entrySha256,resolutionEvidence:e,kind:r.kind,timing:r.timing,executable:r.tool.executable,args:t,workingDirectory:r.workingDirectory,environmentDelta:r.environmentDelta,timeoutMs:r.timeoutMs,purpose:r.purpose,logicalTestIds:r.logicalTestIds,projectIds:r.projectIds,artifactPolicy:r.artifactPolicy});if(!dR.test(n))throw new Error("Command identity could not be constructed.");return{commandId:`cmd_${n.slice(0,24)}`,kind:r.kind,timing:r.timing,required:!0,executable:r.tool.executable,args:t,workingDirectory:r.workingDirectory,environmentDelta:r.environmentDelta,timeoutMs:r.timeoutMs,purpose:r.purpose,logicalTestIds:r.logicalTestIds,projectIds:r.projectIds,artifactPolicy:r.artifactPolicy,resolutionEvidence:e}}function Gd(r,t){return N({purpose:"kwikqa-validation-repository-fingerprint",evidence:r,targetHashes:t})}var yR=/^[a-f0-9]{64}$/,Wd=3,gR=/^rps_[a-f0-9]{24}$/,Kd=mR(new URL("./parse-check.mjs",import.meta.url));function wR(r,t){switch(r.tool){case"biome":return t.biome;case"prettier":return t.prettier;case"typescript":return t.typescript;case"eslint":return t.eslint;case"kwikqa-babel":return}}function bR(r,t){return t==="unavailable"?void 0:`${r}-${t}`}var qh={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"};function xR(r,t){let e=["test"];if(t==="focused"?e.push(`${r.originalTest.path}:${r.originalTest.line}`,`--repeat-each=${Wd}`):t==="affected"&&e.push(...r.discovery.testPaths),t!=="suite")for(let n of r.discovery.projectIds)n!==""&&e.push(`--project=${n}`);return r.originalTest.configPath!==void 0&&e.push(`--config=${r.originalTest.configPath}`),e.push("--reporter=json",`--output=${r.artifactRoot}`,"--trace=retain-on-failure","--retries=0"),e}function vR(r,t){let e=t.targets.map(n=>n.path);switch(r.tool){case"biome":return r.kind==="format"?["format",...e]:["lint",...e];case"prettier":return["--check",...e];case"typescript":return["--noEmit","--pretty","false",...r.configPath?["--project",r.configPath]:[]];case"eslint":return e;case"kwikqa-babel":return[]}}function Vs(r){return{code:"resolution-failed",message:r}}function Jd(r){if(!Number.isInteger(r.timeoutMs)||r.timeoutMs<=0||r.originalTest.line<=0||r.originalTest.logicalTestId.trim().length===0||r.originalTest.projectId.trim().length===0)throw new Error("Validation preparation input is invalid.");let t=N(r.advisoryPlan),e=[...new Set(r.affectedLogicalTestIds??[])].sort(),n=[...r.discovery.reasons.map(y=>({code:y.code==="budget-exceeded"?"budget-exceeded":"resolution-failed",message:y.message,...y.path===void 0?{}:{path:y.path}}))],i=[],s=[],a=r.framework??"playwright",o=r.tools[a],d=bR(a,r.discovery.scope),c=a==="playwright"?void 0:r.frameworkRun,l=()=>c?.args??xR(r,r.discovery.scope),u=c?.evidence??[],p=c?.workingDirectory??r.workspaceRoot;if(r.discovery.status!=="resolved"||d===void 0||o===void 0||a!=="playwright"&&c===void 0)n.push(Vs(`Repository-local ${qh[a]} validation could not be resolved.`));else{let y=[r.originalTest.logicalTestId,...(r.companionLogicalTestIds??[]).filter(x=>x!==r.originalTest.logicalTestId)],w=a!=="playwright"&&r.discovery.scope==="focused"?Wd:1;for(let x=1;x<=w;x+=1)i.push(ei({tool:o,kind:d,timing:"post-patch",args:l(),workingDirectory:p,environmentDelta:{},timeoutMs:r.timeoutMs,purpose:`Run the approved risk-based ${qh[a]} validation scope${w>1?` (run ${x} of ${w})`:""}.`,logicalTestIds:r.discovery.scope==="focused"?[...new Set(y)].sort():e,projectIds:r.discovery.projectIds,artifactPolicy:{outputDirectory:r.artifactRoot,...a==="playwright"?{reportFile:"report.json"}:{},maxArtifacts:100,maxArtifactBytes:32*1024*1024},extraEvidence:u}));if(r.discovery.scope!=="focused"){(e.length===0||!e.includes(r.originalTest.logicalTestId))&&n.push(Vs("Shared validation scope lacks complete canonical affected-test identities."));let x=ei({tool:o,kind:d,timing:"baseline",args:l(),workingDirectory:p,environmentDelta:{},timeoutMs:r.timeoutMs,purpose:"Capture required affected-test outcomes before shared-source mutation.",logicalTestIds:e,projectIds:r.discovery.projectIds,artifactPolicy:{outputDirectory:`${r.artifactRoot}-baseline`,...a==="playwright"?{reportFile:"report.json"}:{},maxArtifacts:100,maxArtifactBytes:32*1024*1024},extraEvidence:u});i.push(x);let v=`baseline_${N({commandId:x.commandId}).slice(0,24)}`;s.push({baselineId:v,commandId:x.commandId,logicalTestIds:e,reason:"Shared test support requires a pre-patch affected-test baseline."})}else r.originalTest.environmentEquivalent||n.push(Vs("Original failure evidence is not environment-equivalent to validation."))}for(let y of r.discovery.staticChecks){if(y.tool==="kwikqa-babel"){let x=N({purpose:"kwikqa-parse-check-command",executable:process.execPath,shim:Kd,paths:r.proposal.targets.map(v=>v.path),workingDirectory:r.workspaceRoot});i.push({commandId:`cmd_${x.slice(0,24)}`,kind:"parse",timing:"post-patch",required:!0,executable:process.execPath,args:[Kd,...r.proposal.targets.map(v=>v.path)],workingDirectory:r.workspaceRoot,environmentDelta:{},timeoutMs:r.timeoutMs,purpose:"Parse every changed JavaScript or TypeScript source file.",logicalTestIds:[],projectIds:r.discovery.projectIds,artifactPolicy:{outputDirectory:r.artifactRoot,maxArtifacts:1,maxArtifactBytes:1e6},resolutionEvidence:[{kind:"configuration",path:Kd,detail:"KwikQA-owned Babel parse-only validation shim."}]});continue}let w=wR(y,r.tools);if(w===void 0){n.push(Vs(`Required ${y.tool} check could not be resolved locally.`));continue}i.push(ei({tool:w,kind:y.kind,timing:"post-patch",args:vR(y,r.proposal),workingDirectory:r.workspaceRoot,environmentDelta:{},timeoutMs:r.timeoutMs,purpose:`Run required ${y.kind} validation.`,logicalTestIds:[],projectIds:r.discovery.projectIds,artifactPolicy:{outputDirectory:r.artifactRoot,maxArtifacts:10,maxArtifactBytes:8*1024*1024}}))}let f=i.flatMap(y=>y.resolutionEvidence),h=r.proposal.targets.map(y=>({path:y.path,sourceSha256:y.sourceSha256,resultSha256:y.resultSha256})),g={schemaVersion:gs,policyVersion:bs,status:n.length===0?"resolved":"unavailable",proposalHash:r.proposal.proposalHash,targetLogicalTestIds:[r.originalTest.logicalTestId],targetHashes:h,advisoryPlanHash:t,repositoryFingerprint:Gd(f,h),commands:[...i].sort((y,w)=>y.commandId.localeCompare(w.commandId)),baselineRequirements:[...s].sort((y,w)=>y.baselineId.localeCompare(w.baselineId)),unresolvedReasons:n},m={...g,planHash:vs(g)};return{plan:m,requiredBaselineCommands:m.commands.filter(y=>y.timing==="baseline")}}function Xd(r){if(r.plan.status!=="resolved"||!yR.test(r.plan.planHash)||!gR.test(r.repairSessionId)||r.attemptOrdinal!==1&&r.attemptOrdinal!==2)throw new Error("Only a resolved plan can become application execution authority.");let t=r.plan.baselineRequirements.map(i=>i.baselineId),e;if(t.length>0){if(r.baseline===void 0)throw new Error("Required pre-application baseline is missing.");e=Gn(r.baseline);let i=new Map(r.plan.baselineRequirements.map(s=>[s.commandId,s]));if(e.planHash!==r.plan.planHash||e.repositoryFingerprint!==r.plan.repositoryFingerprint||N(e.targetHashes)!==N(r.plan.targetHashes)||e.commandRecords.length!==i.size||e.commandRecords.some(s=>{let a=i.get(s.commandId);return a===void 0||s.planHash!==r.plan.planHash||s.timing!=="baseline"||s.status!=="passed"||s.termination.kind!=="exit"||s.termination.exitCode!==0||s.stdout.truncated||s.stderr.truncated||a.logicalTestIds.some(o=>e?.logicalTestOutcomes[o]===void 0)}))throw new Error("Required pre-application baseline does not match the resolved plan.")}let n=r.plan.commands.filter(i=>i.timing==="post-patch"&&i.required).sort((i,s)=>i.commandId.localeCompare(s.commandId));return{schemaVersion:"1.0",policyVersion:"1.0",planHash:r.plan.planHash,repositoryFingerprint:r.plan.repositoryFingerprint,targetHashes:r.plan.targetHashes,advisoryPlanHash:N(r.advisoryPlan),...e===void 0?{}:{baselineManifestHash:e.baselineHash},requiredBaselineIds:t,requiredCommandIds:n.map(i=>i.commandId),requiredCommands:n.map(i=>({commandId:i.commandId,commandHash:N(i)})),repairSessionId:r.repairSessionId,attemptOrdinal:r.attemptOrdinal}}import{randomUUID as VR}from"node:crypto";import{lstat as ii,mkdir as ac,readFile as zR,realpath as HR,rm as qR}from"node:fs/promises";import{isAbsolute as UR,join as Gr,relative as GR,resolve as KR,sep as WR}from"node:path";import{realpath as qr}from"node:fs/promises";import{realpath as Hr}from"node:fs/promises";var We=/^[a-f0-9]{64}$/,kR=/^rps_[a-f0-9]{24}$/;function Uh(r){let t=r.map(e=>e.trim());return t.every(e=>e.length>0)&&new Set(t).size===r.length}function IR(r){return{kind:"rejected",reasons:r}}function Wh(r){return r.length>0&&Number.isFinite(Date.parse(r))}function zs(r){return Number.isFinite(r)&&r>0}function PR(r){let{proposalHash:t,...e}=r;return We.test(t)&&N(e)===t}function RR(r){let t=[];(!PR(r)||N(r.diff)!==r.diffHash)&&t.push({code:"invalid-proposal",message:"Proposal and diff integrity hashes must match their canonical contents."}),(r.targets.length===0||r.changedFiles!==r.targets.length||r.targets.some(i=>!We.test(i.sourceSha256)||!We.test(i.resultSha256)||i.sourceSha256===i.resultSha256))&&t.push({code:"invalid-proposal",message:"Proposal targets and their source/result hashes must be complete and consistent."});let e=new Set,n=new Map;for(let i of r.targets){let s=i.path.toLocaleLowerCase("en-US"),a=n.get(s);(e.has(i.path)||a!==void 0&&a!==i.path)&&t.push({code:"invalid-proposal",message:"Proposal targets may not duplicate or case-collide.",path:i.path}),e.add(i.path),n.set(s,i.path)}return(r.replacements.length===0||r.replacements.some(i=>!e.has(i.path)))&&t.push({code:"invalid-proposal",message:"Every approved replacement must resolve to an approved proposal target."}),t}function TR(r){let t=RR(r.proposal);(r.context.workspace.workspaceRoot.length===0||r.context.workspace.gitRoot.length===0||r.context.snapshot.workspaceRoot!==r.context.workspace.workspaceRoot||r.context.snapshot.gitRoot!==r.context.workspace.gitRoot)&&t.push({code:"invalid-workspace",message:"Confirmed workspace and git roots must match the repository snapshot identity."}),(!Number.isInteger(r.context.maxTargetBytes)||r.context.maxTargetBytes<=0||r.context.config.schemaVersion.length===0)&&t.push({code:"invalid-configuration",message:"Application configuration and target byte limit must be explicit and bounded."}),(r.interactiveSession.sessionId.trim().length===0||!Wh(r.previewedAt))&&t.push({code:"invalid-preview",message:"An interactive session identity and valid preview timestamp are required."});let e=r.costBounds;(!Number.isInteger(e.maxRequestTokens)||!Number.isInteger(e.maxRunTokens)||!zs(e.maxRequestTokens)||!zs(e.maxRunTokens)||!zs(e.maxRequestDollars)||!zs(e.maxRunDollars)||e.maxRequestTokens>e.maxRunTokens||e.maxRequestDollars>e.maxRunDollars)&&t.push({code:"invalid-preview",message:"Approved request and run token/dollar bounds must be positive and internally consistent."});let n=new Set;for(let s of r.payloadManifests){if(!We.test(s.manifestHash)||!We.test(s.payloadHash)||!We.test(s.packetHash)||s.model.trim().length===0||s.provider.trim().length===0||s.promptVersion.trim().length===0||s.outputSchemaVersion.trim().length===0||n.has(s.manifestHash)){t.push({code:"invalid-preview",message:"Model payload manifest references must be sanitized, complete, and unique."});break}n.add(s.manifestHash)}(r.scopes.baseline.some(s=>s.trim().length===0)||r.scopes.validation.some(s=>s.trim().length===0))&&t.push({code:"invalid-preview",message:"Baseline and validation scopes may not contain empty entries."});let i=r.authoritativeValidation;return(i.schemaVersion!=="1.0"||i.policyVersion!=="1.0"||!We.test(i.planHash)||!We.test(i.repositoryFingerprint)||!We.test(i.advisoryPlanHash)||i.targetHashes.length!==r.proposal.targets.length||i.targetHashes.some((s,a)=>{let o=r.proposal.targets[a];return o===void 0||s.path!==o.path||s.sourceSha256!==o.sourceSha256||s.resultSha256!==o.resultSha256})||i.baselineManifestHash!==void 0&&!We.test(i.baselineManifestHash)||!kR.test(i.repairSessionId)||i.attemptOrdinal!==1&&i.attemptOrdinal!==2||!Uh(i.requiredBaselineIds)||!Uh(i.requiredCommandIds)||i.requiredCommandIds.length===0||i.requiredCommands.length!==i.requiredCommandIds.length||i.requiredCommands.some((s,a)=>s.commandId!==i.requiredCommandIds[a]||!We.test(s.commandHash))||i.requiredBaselineIds.length>0&&i.baselineManifestHash===void 0)&&t.push({code:"invalid-preview",message:"Authoritative validation approval metadata is incomplete or inconsistent."}),t}function Yd(r){return N({purpose:"kwikqa-approved-application",...r})}function Qd(r){let t=TR(r);if(t.length>0)return IR(t);let e={schemaVersion:"2.0",bindingVersion:"2.0",proposal:r.proposal,workspace:r.context.workspace,checkoutPristine:r.context.snapshot.dirtyPaths.length===0,validationPlan:r.proposal.validationPlan,scopes:r.scopes,authoritativeValidation:r.authoritativeValidation,payloadManifests:r.payloadManifests,costBounds:r.costBounds,previewedAt:r.previewedAt,interactiveSession:r.interactiveSession};return{kind:"preview-ready",preview:{...e,bindingHash:Yd(e)}}}function Hs(r,t,e,n){return N({purpose:"kwikqa-interactive-application-authorization",previewBindingHash:r.bindingHash,authorizationId:t,authorizedAt:e,interactiveSession:n})}function Zd(r,t){let{bindingHash:e,...n}=r;return We.test(e)&&Yd(n)===e&&t.authorizationId.trim().length>0&&Wh(t.authorizedAt)&&t.bindingHash===Hs(r,t.authorizationId,t.authorizedAt,t.interactiveSession)&&t.interactiveSession.sessionId===r.interactiveSession.sessionId}import{realpath as qs}from"node:fs/promises";import{isAbsolute as OR,relative as DR,sep as LR}from"node:path";import{createHash as AR}from"node:crypto";function SR(r){return AR("sha256").update(r,"utf8").digest("hex")}function ec(r,t,e){let n=[],i=[];for(let o of e){if(o.oldText.length===0||o.newText===o.oldText||o.rationale.trim().length===0||o.expectedEffect.trim().length===0||o.evidenceIds.length===0){n.push({code:"invalid-replacement",message:"Replacement fields must be meaningful, cited, and non-no-op.",path:r});continue}if(o.oldText===t){n.push({code:"invalid-replacement",message:"A replacement may not rewrite the complete file.",path:r});continue}let d=t.indexOf(o.oldText);if(d<0||t.indexOf(o.oldText,d+1)>=0){n.push({code:"non-unique-match",message:"Replacement preimage must occur exactly once.",path:r});continue}i.push({start:d,end:d+o.oldText.length,newText:o.newText})}let s=[...i].sort((o,d)=>o.start-d.start);for(let o=1;o<s.length;o+=1){let d=s[o-1],c=s[o];d!==void 0&&c!==void 0&&c.start<d.end&&n.push({code:"overlapping-replacement",message:"Exact replacements overlap in the original source.",path:r})}if(n.length>0)return{kind:"rejected",reasons:n};let a=t;for(let o of[...s].sort((d,c)=>c.start-d.start))a=`${a.slice(0,o.start)}${o.newText}${a.slice(o.end)}`;return{kind:"applied",result:a,resultSha256:SR(a)}}function Jh(r){let t=[],e=[];for(let n of r){let i=ec(n.path,n.source,n.replacements);if(i.kind==="rejected"){t.push(...i.reasons);continue}e.push({...n,result:i.result,resultSha256:i.resultSha256})}return t.length>0?{kind:"rejected",reasons:t}:{kind:"applied",targets:e}}import{isAbsolute as ER}from"node:path";function CR(r){return r.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function Xh(r,t){let e=CR(r).replaceAll("**/","\0").replaceAll("**","").replaceAll("*","[^/]*").replaceAll("\0","(?:.*/)?").replaceAll("",".*");return new RegExp(`^${e}$`).test(t)}function ti(r){return r.length===0||r.includes("\0")||r.includes("\\")||ER(r)||/^[A-Za-z]:/.test(r)?!0:r.split("/").some(t=>t===""||t==="."||t==="..")}function ri(r,t){let e=r.toLowerCase(),n=e.split("/").at(-1)??e;return e.includes("/node_modules/")||e.startsWith("node_modules/")||e.includes("/src/")||e.startsWith("src/")||new Set(["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"]).has(n)?!0:t.generatedPaths.some(i=>Xh(i,r))}function ni(r,t){return t.find(e=>Xh(e.pattern,r))}function NR(r){try{return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}async function Yh(r,t,e,n){let i=[],s=new Map;for(let l of e){if(ti(l.path)){i.push({code:"unauthorized-target",message:"Target path is not a safe repository-relative path.",path:l.path});continue}let u=s.get(l.path)??[];u.push(l),s.set(l.path,u)}if(i.length>0)return{kind:"rejected",reasons:i};let a=new Set(t.dirtyPaths.map(l=>l.replaceAll("\\","/").toLocaleLowerCase("en-US"))),o=new Set,d=new Map,c=[];for(let[l,u]of[...s].sort(([p],[f])=>p.localeCompare(f))){let p=ni(l,r.editablePaths);if(p===void 0||ri(l,r)){i.push({code:"unauthorized-target",message:"Target is outside the configured test-support repair boundary.",path:l});continue}if(a.has(l.toLocaleLowerCase("en-US"))){i.push({code:"dirty-target-file",message:"Already-dirty target files are read-only.",path:l});continue}let f=await W(t.workspaceRoot,l,n);if(f.kind!=="read"){i.push({code:f.kind==="unauthorized"?"unauthorized-target":"unreadable-target",message:f.message,...f.relativePath===void 0?{path:l}:{path:f.relativePath}});continue}if(f.relativePath!==l){i.push({code:"unauthorized-target",message:"Target path does not match its canonical repository-relative path.",path:l});continue}let h=f.relativePath.toLocaleLowerCase("en-US"),g=d.get(h);if(o.has(f.relativePath)||g!==void 0&&g!==f.relativePath){i.push({code:"unauthorized-target",message:"Target aliases or case-collides with another target.",path:l});continue}o.add(f.relativePath),d.set(h,f.relativePath);let m=NR(f.bytes);if(m===void 0){i.push({code:"unreadable-target",message:"Target is not valid UTF-8.",path:l});continue}if(u.some(y=>y.sourceSha256!==void 0&&y.sourceSha256!==f.sha256)){i.push({code:"source-hash-mismatch",message:"Target source hash differs from the proposed preimage.",path:l});continue}c.push({path:f.relativePath,class:p.class,source:m,sourceSha256:f.sha256,replacements:u})}return i.length>0?{kind:"rejected",reasons:i}:{kind:"authorized",targets:c}}function MR(r,t){let e=DR(r,t);return e===""||!OR(e)&&e!==".."&&!e.startsWith(`..${LR}`)}function $R(r){try{return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}async function Qh(r){if(!Number.isInteger(r.maxTargetBytes)||r.maxTargetBytes<=0||r.maxTargetBytes>1e6)return{kind:"rejected",code:"invalid-limit",message:"Target limit is invalid."};let t,e,n,i;try{[t,e,n,i]=await Promise.all([qs(r.workspaceRoot),qs(r.gitRoot),qs(r.approvedWorkspaceRoot),qs(r.approvedGitRoot)])}catch{return{kind:"rejected",code:"workspace-mismatch",message:"Workspace roots are unreadable."}}if(t!==n||e!==i||!MR(e,t))return{kind:"rejected",code:"workspace-mismatch",message:"Current and approved canonical workspace identities differ."};let s=new Set(r.dirtyPaths.map(c=>c.replaceAll("\\","/").toLocaleLowerCase("en-US"))),a=new Map;for(let c of r.proposal.replacements){let l=a.get(c.path)??[];l.push(c),a.set(c.path,l)}let o=new Set,d=[];for(let c of r.proposal.targets){let l=c.path.toLocaleLowerCase("en-US");if(o.has(l)||ti(c.path))return{kind:"rejected",code:"unsafe-target",message:"Target aliases, case-collides, or has an unsafe path.",path:c.path};o.add(l);let u=ni(c.path,r.config.editablePaths);if(u===void 0||u.class!==c.class||ri(c.path,r.config))return{kind:"rejected",code:"unauthorized-target",message:"Target is outside the approved repair boundary.",path:c.path};if(s.has(l))return{kind:"rejected",code:"dirty-target-file",message:"An approved target is currently dirty.",path:c.path};let p=await W(t,c.path,r.maxTargetBytes);if(p.kind!=="read"||p.relativePath!==c.path)return{kind:"rejected",code:"unreadable-target",message:"Target could not be read through its canonical authorized path.",path:c.path};if(p.sha256!==c.sourceSha256)return{kind:"rejected",code:"source-hash-mismatch",message:"Target no longer matches the approved preimage.",path:c.path};let f=$R(p.bytes);if(f===void 0)return{kind:"rejected",code:"unreadable-target",message:"Target is not valid UTF-8.",path:c.path};let h=a.get(c.path)??[],g=ec(c.path,f,h);if(g.kind!=="applied"||g.resultSha256!==c.resultSha256)return{kind:"rejected",code:"result-hash-mismatch",message:"Approved replacements no longer derive the approved result.",path:c.path};d.push({path:c.path,source:f,sourceBytes:p.bytes,sourceSha256:p.sha256,result:g.result,resultBytes:new TextEncoder().encode(g.result),resultSha256:g.resultSha256,replacements:h})}return{kind:"verified",workspaceRoot:t,gitRoot:e,targets:d,nonPristine:r.dirtyPaths.length>0}}var _R=new Set(["completed","rolled-back","conflicted"]);function cr(r,t,e){return{code:r,message:t,...e===void 0?{}:{path:e}}}function Pe(r){return{schemaVersion:"2.0",transactionId:r.manifest.transactionId,authorizationId:r.manifest.authorization.authorizationId,approvalBindingHash:r.manifest.preview.bindingHash,proposalHash:r.manifest.preview.proposal.proposalHash,diffHash:r.manifest.preview.proposal.diffHash,workspace:r.manifest.preview.workspace,phase:r.state.phase,revision:r.state.revision,targets:r.manifest.targets.map(t=>({path:t.path,sourceSha256:t.sourceSha256,resultSha256:t.resultSha256,preimageBytes:t.preimageBytes,resultBytes:t.resultBytes})),validationPlan:r.manifest.preview.validationPlan,authoritativeValidation:r.manifest.preview.authoritativeValidation,createdAt:r.manifest.createdAt,updatedAt:r.state.updatedAt}}async function FR(r){return(await Promise.all((await Yn(r)).map(e=>xe(r,e)))).filter(e=>!_R.has(e.state.phase))}async function Zh(r,t,e,n){let i=await W(r,t,e);return i.kind==="read"&&i.relativePath===t&&i.sha256===n}async function tc(r){return jR(r,{})}async function jR(r,t){if(!Zd(r.preview,r.authorization))return{kind:"rejected",reasons:[cr("authorization-mismatch","Authorization does not match this exact preview.")]};let e=r.now??new Date().toISOString(),n;try{let[i,s,a,o,d,c]=await Promise.all([Hr(r.context.workspace.workspaceRoot),Hr(r.context.snapshot.workspaceRoot),Hr(r.preview.workspace.workspaceRoot),Hr(r.context.workspace.gitRoot),Hr(r.context.snapshot.gitRoot),Hr(r.preview.workspace.gitRoot)]);if(i!==s||i!==a||o!==d||o!==c)return{kind:"rejected",reasons:[cr("invalid-workspace","Application workspace identity changed.")]};let l=a;n=await Ue(l,{operation:"apply",authorizationId:r.authorization.authorizationId,at:e});let u=await FR(l);if(u.length>0)return{kind:"recovery-required",reasons:[cr("transaction-blocked","A nonterminal transaction must be recovered before another application.")],transaction:Pe(u[0])};if((await Promise.all((await Yn(l)).map(m=>xe(l,m)))).some(m=>m.manifest.authorization.authorizationId===r.authorization.authorizationId))return{kind:"rejected",reasons:[cr("authorization-replayed","Authorization has already been consumed.")]};let f=await Qh({workspaceRoot:r.context.snapshot.workspaceRoot,gitRoot:r.context.snapshot.gitRoot,approvedWorkspaceRoot:r.preview.workspace.workspaceRoot,approvedGitRoot:r.preview.workspace.gitRoot,config:r.context.config,dirtyPaths:r.context.snapshot.dirtyPaths,proposal:r.preview.proposal,maxTargetBytes:r.context.maxTargetBytes});if(f.kind!=="verified")return{kind:"rejected",reasons:[cr(f.code==="dirty-target-file"?"dirty-target-file":f.code==="source-hash-mismatch"?"source-hash-mismatch":f.code==="result-hash-mismatch"?"result-hash-mismatch":"unsafe-target",f.message,f.path)]};let h=bh(),g=await Ah({workspaceRoot:f.workspaceRoot,transactionId:h,preview:r.preview,authorization:r.authorization,config:r.context.config,maxTargetBytes:r.context.maxTargetBytes,targets:f.targets,now:e});await t.failpoint?.("journal-prepared"),g=await Be({transaction:g,phase:"applying",type:"application-started",now:e}),await t.failpoint?.("phase-applying");for(let m of g.manifest.targets){if(!await Zh(f.workspaceRoot,m.path,r.context.maxTargetBytes,m.sourceSha256))return{kind:"recovery-required",reasons:[cr("source-hash-mismatch","Target changed immediately before mutation.",m.path)],transaction:Pe(g)};g=await Be({transaction:g,phase:"applying",type:"target-write-intent",path:m.path,now:e}),await t.failpoint?.(`before-target:${m.path}`);let w=g.results.get(m.path);if(w===void 0)throw new Error("Journal result bytes are unavailable.");if(await As(f.workspaceRoot,m.path,m.sourceSha256,w),await t.failpoint?.(`after-target:${m.path}`),!await Zh(f.workspaceRoot,m.path,r.context.maxTargetBytes,m.resultSha256))throw new Error("Applied target hash could not be verified.");g=await Be({transaction:g,phase:"applying",type:"target-write-complete",path:m.path,now:e})}return g=await Be({transaction:g,phase:"applied",type:"application-complete",now:e}),await t.failpoint?.("phase-applied"),{kind:"applied",transaction:Pe(g)}}catch{return{kind:"failed",reasons:[cr("application-failed","Application stopped safely; inspect transaction discovery before continuing.")]}}finally{await n?.release().catch(()=>{})}}var tm=new Set(["completed","rolled-back","conflicted"]);function $t(r,t){return{code:"transaction-conflict",message:r,...t===void 0?{}:{path:t}}}async function nc(r,t){let e=r.manifest.targets.find(i=>i.path===t);if(e===void 0)return"conflict";let n=await W(r.manifest.preview.workspace.workspaceRoot,t,r.manifest.maxTargetBytes);return n.kind!=="read"||n.relativePath!==t?"conflict":n.sha256===e.sourceSha256?"preimage":n.sha256===e.resultSha256?"applied":"conflict"}async function Us(r,t){let e=await xe(r,t),n=await Promise.all(e.manifest.targets.map(async i=>({path:i.path,classification:await nc(e,i.path)})));return{transactionId:t,phase:e.state.phase,targets:n}}async function ic(r){try{let t=await Promise.all((await Yn(r)).map(n=>Us(r,n))),e=t.filter(n=>!tm.has(n.phase));return e.some(n=>n.targets.some(i=>i.classification==="conflict"))?{kind:"conflicted",transactions:e}:e.length===0?{kind:"clear",transactions:t}:{kind:"recovery-required",transactions:e}}catch{return{kind:"failed",reasons:[$t("Transaction discovery failed closed because a journal is unreadable.")]}}}async function rc(r,t,e){return r.state.phase==="conflicted"?r:Be({transaction:r,phase:"conflicted",type:"conflict-detected",message:e,now:t})}async function em(r){let t=await Promise.all(r.manifest.targets.map(async e=>[e.path,await nc(r,e.path)]));return new Map(t)}async function BR(r,t,e,n,i){let s;try{let[a,o,d,c]=await Promise.all([qr(r.workspace.workspaceRoot),qr(r.snapshot.workspaceRoot),qr(r.workspace.gitRoot),qr(r.snapshot.gitRoot)]);if(a!==o||d!==c)return{kind:"rejected",reasons:[$t("Recovery workspace identity differs.")]};s=await Ue(a,{operation:e,transactionId:t,at:n});let l=await xe(a,t);if(await qr(l.manifest.preview.workspace.workspaceRoot)!==a||await qr(l.manifest.preview.workspace.gitRoot)!==d)return{kind:"rejected",reasons:[$t("Recovery workspace identity differs.")]};if(tm.has(l.state.phase))return e==="rollback"&&l.state.phase==="rolled-back"?{kind:"rolled-back",transaction:Pe(l)}:{kind:"rejected",reasons:[$t("Terminal transaction cannot perform this recovery operation.")],transaction:Pe(l)};let u=await em(l),p=[...u].find(([,g])=>g==="conflict");if(p!==void 0)return l=await rc(l,n,"Current target bytes match neither recorded preimage nor applied image."),{kind:"conflicted",reasons:[$t("Developer or unknown target bytes prohibit automatic recovery.",p[0])],transaction:Pe(l)};e==="rollback"&&(l=await Be({transaction:l,phase:"rolling-back",type:"rollback-started",now:n}),await i?.("phase-rolling-back"));for(let g of l.manifest.targets){let m=u.get(g.path);if(!(e==="resume"&&m==="preimage"||e==="rollback"&&m==="applied"))continue;let w=e==="resume"?"resume":"rollback";if(await i?.(`before-${w}-target:${g.path}`),await nc(l,g.path)!==m)return l=await rc(l,n,"Target changed after recovery classification."),{kind:"conflicted",reasons:[$t("Target changed immediately before recovery mutation.",g.path)],transaction:Pe(l)};let v=e==="resume"?l.results.get(g.path):l.preimages.get(g.path);if(v===void 0)throw new Error("Recovery bytes are unavailable.");await As(a,g.path,e==="resume"?g.sourceSha256:g.resultSha256,v),await i?.(`after-${w}-target:${g.path}`),l=await Be({transaction:l,phase:e==="resume"?"applying":"rolling-back",type:`${e}-target-complete`,path:g.path,now:n})}let f=await em(l),h=e==="resume"?"applied":"preimage";return[...f.values()].some(g=>g!==h)?(l=await rc(l,n,"Recovery result hashes did not verify."),{kind:"conflicted",reasons:[$t("Recovery completed with an unknown target state.")],transaction:Pe(l)}):(l=await Be({transaction:l,phase:e==="resume"?"applied":"rolled-back",type:e==="resume"?"resume-complete":"rollback-complete",now:n}),{kind:e==="resume"?"resumed":"rolled-back",transaction:Pe(l)})}catch{return{kind:"failed",reasons:[$t("Recovery stopped safely; rediscover transaction state.")]}}finally{await s?.release().catch(()=>{})}}async function sc(r,t,e=new Date().toISOString()){return BR(r,t,"rollback",e)}var rm=/^rps_[a-f0-9]{24}$/,Gs=/^[a-f0-9]{64}$/,JR=new Set(["rolling-back","rolled-back","conflicted"]);function XR(r,t){let e=GR(r,t);return e===""||!UR(e)&&e!==".."&&!e.startsWith(`..${WR}`)}function Ur(r){return r.length>0&&Number.isFinite(Date.parse(r))}function nm(r){if(r.ordinal!==1&&r.ordinal!==2||!Gs.test(r.proposalHash)||!/^txn_[a-f0-9]{24}$/.test(r.transactionId)||r.validationManifestHash!==void 0&&!Gs.test(r.validationManifestHash)||!Ur(r.recordedAt))throw new Error("Repair attempt record is malformed.")}function YR(r){let{sessionHash:t,...e}=r;if(r.schemaVersion!=="1.0"||!rm.test(r.repairSessionId)||r.originalRunId.trim().length===0||!Gs.test(r.originalPacketHash)||r.maxAttempts!==2||!Ur(r.createdAt)||!Ur(r.updatedAt)||!Number.isInteger(r.revision)||r.revision<1||r.attempts.length>2||N(e)!==t)throw new Error("Repair session integrity check failed.");r.attempts.forEach(nm);for(let[n,i]of r.attempts.entries())if(i.ordinal!==n+1)throw new Error("Repair attempt order is malformed.");return r}async function Ks(r){let t=await HR(r),e=KR(t,".kwikqa");if(!XR(t,e))throw new Error("Repair session directory escapes workspace.");await ac(e,{mode:448}).catch(a=>{if(a.code!=="EEXIST")throw a});let n=await ii(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Repair session path is unsafe.");let i=Gr(e,"repair-sessions");await ac(i,{mode:448}).catch(a=>{if(a.code!=="EEXIST")throw a});let s=await ii(i);if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Repair session path is unsafe.");return i}function Ws(r){return{...r,sessionHash:N(r)}}function oc(r){return{schemaVersion:r.schemaVersion,repairSessionId:r.repairSessionId,originalRunId:r.originalRunId,originalPacketHash:r.originalPacketHash,maxAttempts:r.maxAttempts,attempts:r.attempts,state:r.state,createdAt:r.createdAt,updatedAt:r.updatedAt,revision:r.revision}}async function dc(r){if(r.originalRunId.trim().length===0||!Gs.test(r.originalPacketHash))throw new Error("Original repair evidence identity is invalid.");let t=r.now??new Date().toISOString();if(!Ur(t))throw new Error("Repair session timestamp is invalid.");let e=`rps_${VR().replaceAll("-","").slice(0,24)}`,n=Ws({schemaVersion:"1.0",repairSessionId:e,originalRunId:r.originalRunId,originalPacketHash:r.originalPacketHash,maxAttempts:2,attempts:[],state:"first-attempt",createdAt:t,updatedAt:t,revision:1}),i=await Ks(r.workspaceRoot);return await me(Gr(i,`${e}.json`),`${le(n)}
53
+ `,{mode:384,replace:!1}),n}async function _t(r,t){if(!rm.test(t))throw new Error("Repair session id is invalid.");let e=await Ks(r),n=Gr(e,`${t}.json`),i=await ii(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("Repair session record is unsafe.");let s=JSON.parse(await zR(n,"utf8"));if(s===null||typeof s!="object"||Array.isArray(s))throw new Error("Repair session record is malformed.");return YR(s)}async function cc(r,t){let e=await Ks(r),n=Gr(e,`${t}.lock`);await ac(n,{mode:448});let i=await ii(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Repair session lock is unsafe.");return{release:async()=>{let s=await ii(n);if(s.dev!==i.dev||s.ino!==i.ino||s.isSymbolicLink())throw new Error("Repair session lock ownership changed.");await qR(n,{recursive:!0,force:!1})}}}async function lc(r,t,e){let n=await _t(r,t.repairSessionId);if(n.revision!==t.revision||n.sessionHash!==t.sessionHash)throw new Error("Repair session changed concurrently.");let i=await Ks(r);return await me(Gr(i,`${t.repairSessionId}.json`),`${le(e)}
54
+ `,{mode:384,replace:!0}),_t(r,t.repairSessionId)}async function uc(r,t,e){nm(e);let n=await cc(r,t);try{let i=await _t(r,t);if(i.state==="repaired"||i.state==="stopped")throw new Error("Terminal repair session cannot accept another attempt.");if(e.ordinal!==i.attempts.length+1||e.ordinal>i.maxAttempts)throw new Error("Repair session attempt limit or ordering was violated.");if(e.ordinal===1&&i.state!=="first-attempt"||e.ordinal===2&&i.state!=="retry-approval-required")throw new Error("Repair session is not ready for this attempt.");let s=e.recordedAt,a=Ws({...oc(i),attempts:[...i.attempts,e],state:e.ordinal===1?"first-attempt":"second-attempt",updatedAt:s,revision:i.revision+1});return await lc(r,i,a)}finally{await n.release()}}function QR(r,t){let e=r.status;if(e==="blocked")throw new Error("A blocked validation run has no attempt outcome.");let n=t.state.history,i=n.findLastIndex(d=>d.type==="validation-started"),s=n[i];if(s===void 0||s.validationRunId!==r.validationRunId||s.planHash!==r.planHash)throw new Error("Validation run was not started for this transaction approval.");let a=n.slice(i+1).find(d=>d.type==="validation-passed"),o=t.state.phase;if(a!==void 0){if(o!=="completed"||e!=="passed"||a.validationRunId!==r.validationRunId||a.planHash!==r.planHash||a.validationManifestHash!==r.manifestHash)throw new Error("Validation outcome does not match the durable transaction state.");return"passed"}if(o==="validating"){if(e==="passed")throw new Error("A passing validation run must be completed by M6, or rolled back, before it is recorded.");return e}if(JR.has(o))return e==="passed"?"incomplete":e;throw new Error("Validation outcome does not match the durable transaction state.")}async function Js(r){if(!/^vld_[a-f0-9]{24}$/.test(r.validationRunId))throw new Error("Validation run id is invalid.");let t=r.now??new Date().toISOString();if(!Ur(t))throw new Error("Repair session timestamp is invalid.");let e=await cc(r.workspaceRoot,r.repairSessionId),n;try{n=await Ue(r.workspaceRoot,{operation:"record-repair-validation",repairSessionId:r.repairSessionId,validationRunId:r.validationRunId});let i=await _t(r.workspaceRoot,r.repairSessionId),s=i.attempts.at(-1);if(s===void 0||s.ordinal!==r.ordinal)throw new Error("Repair attempt cannot be finalized from its current state.");let a=await xe(r.workspaceRoot,s.transactionId),o=a.manifest.preview.authoritativeValidation,d=Gr(a.directory,"validation",r.validationRunId),c=Lt(await or(d,"manifest.json",$s)),l=new Map(o.requiredCommands.map(g=>[g.commandId,g.commandHash]));if(c.transactionId!==s.transactionId||c.validationRunId!==r.validationRunId||c.planHash!==o.planHash||c.repositoryFingerprint!==o.repositoryFingerprint||N(c.targetHashes)!==N(o.targetHashes)||c.requiredCommandIds.length!==l.size||c.requiredCommandIds.some(g=>!l.has(g))||c.commandRecords.some(g=>l.get(g.commandId)!==g.commandHash)||o.repairSessionId!==i.repairSessionId||o.attemptOrdinal!==s.ordinal||a.manifest.preview.proposal.proposalHash!==s.proposalHash)throw new Error("Validation manifest does not match the repair attempt authority.");for(let g of c.commandRecords)if(!await Oh(d,g,jr))throw new Error("Validation manifest command evidence failed verification.");let u=QR(c,a);if(s.outcome!=="applied"){if(s.validationManifestHash===c.manifestHash&&s.outcome===u)return{session:i};throw new Error("Repair attempt was already finalized with different evidence.")}let p={...s,validationManifestHash:c.manifestHash,outcome:u,recordedAt:t},f=u==="passed"?"repaired":"rollback-required",h=Ws({...oc(i),attempts:[...i.attempts.slice(0,-1),p],state:f,updatedAt:t,revision:i.revision+1});return{session:await lc(r.workspaceRoot,i,h)}}finally{await n?.release(),await e.release()}}async function pc(r){if(!/^txn_[a-f0-9]{24}$/.test(r.proof.transactionId)||r.proof.phase!=="rolled-back"||!Number.isInteger(r.proof.transactionRevision)||r.proof.transactionRevision<1)throw new Error("Repair rollback proof is invalid.");let t=r.now??new Date().toISOString();if(!Ur(t))throw new Error("Repair session timestamp is invalid.");let e=await cc(r.workspaceRoot,r.repairSessionId),n;try{n=await Ue(r.workspaceRoot,{operation:"confirm-repair-rollback",repairSessionId:r.repairSessionId,transactionId:r.proof.transactionId});let i=await _t(r.workspaceRoot,r.repairSessionId),s=i.attempts.at(-1);if(i.state!=="rollback-required"||s===void 0||s.ordinal!==r.ordinal||s.transactionId!==r.proof.transactionId||s.validationManifestHash===void 0||s.outcome==="passed"||s.outcome==="applied")throw new Error("Repair session does not match the rolled-back attempt.");let a=await xe(r.workspaceRoot,s.transactionId),o=a.manifest.preview.authoritativeValidation;if(a.state.phase!=="rolled-back"||a.state.revision!==r.proof.transactionRevision||o.repairSessionId!==i.repairSessionId||o.attemptOrdinal!==s.ordinal||a.manifest.preview.proposal.proposalHash!==s.proposalHash)throw new Error("Repair rollback proof does not match the durable transaction.");let d=await Us(r.workspaceRoot,s.transactionId);if(d.phase!=="rolled-back"||d.targets.some(f=>f.classification!=="preimage"))throw new Error("Durable rollback could not be verified from recorded preimages.");let c=r.ordinal===1?"retry-approval-required":"stopped",l=Ws({...oc(i),state:c,updatedAt:t,revision:i.revision+1}),u=await lc(r.workspaceRoot,i,l);if(c!=="retry-approval-required")return{session:u};let p={repairSessionId:u.repairSessionId,failedTransactionId:s.transactionId,failedValidationManifestHash:s.validationManifestHash,nextAttemptOrdinal:2};return{session:u,retry:{...p,handoffHash:N(p)}}}finally{await n?.release(),await e.release()}}import{basename as lT,dirname as om,join as Kr,relative as wc,resolve as Rt,sep as uT}from"node:path";import{createHash as ZR}from"node:crypto";import{lstat as eT,mkdir as tT,readFile as im,realpath as fc,rename as rT,writeFile as nT}from"node:fs/promises";import{isAbsolute as iT,join as sm,relative as hc,sep as am}from"node:path";import{fileURLToPath as sT}from"node:url";var aT=".kwikqa/runtime",oT=["cypress-reporter.cjs","cypress-capture.js","wdio-reporter.mjs","wdio-capture.mjs"];async function dT(r){return im(sT(new URL(`./${r}`,import.meta.url)),"utf8")}function cT(r,t){let e=hc(r,t);return e===""||!iT(e)&&e!==".."&&!e.startsWith(`..${am}`)}async function Xs(r,t){let e=await fc(r),n=e;for(let i of t.split("/").filter(s=>s!=="")){if(i==="."||i==="..")throw new Error("Unsafe KwikQA directory.");n=sm(n,i);let s=await eT(n).catch(()=>{});if(s===void 0)await tT(n);else if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`${hc(e,n)} must be a real directory inside the workspace.`)}if(!cT(e,await fc(n)))throw new Error("KwikQA directory escapes workspace.");return n}async function mc(r,t){let e=`${r}.${process.pid}.tmp`;await nT(e,t,{mode:420}),await rT(e,r)}function yc(r){return ZR("sha256").update(r,"utf8").digest("hex")}async function Ys(r){let t=await fc(r),e=await Xs(t,aT),n={};for(let i of oT){let s=await dT(i),a=sm(e,i);await im(a,"utf8").catch(()=>{})!==s&&await mc(a,s),n[i]={path:a,relativePath:hc(t,a).split(am).join("/"),sha256:yc(s)}}return n}function bc(r){return r.split(uT).join("/")}function si(r,t){let e=bc(wc(r,t));return e.startsWith(".")?e:`./${e}`}async function gc(r,t,e){return await mc(t,e),{path:t,relativePath:bc(wc(r,t)),sha256:yc(e)}}async function Qs(r){let t=r.workspaceRoot,e=r.configFile===void 0?t:om(Rt(t,r.configFile)),n=["video=false","screenshotOnRunFailure=true",`screenshotsFolder=${Rt(t,r.screenshotsDirectory)}`,...r.noRetries?["retries=0"]:[]],i=[];if(r.capture!==void 0){let a=await Xs(t,r.capture.directory),o=await gc(t,Kr(a,"kwikqa-settings.js"),`// Generated by KwikQA for one run.
55
+ globalThis.__kwikqaCapture = ${JSON.stringify({directory:bc(wc(e,Kr(a,"pages"))),...r.capture.only===void 0?{}:{only:[...r.capture.only].sort()}})};
56
+ `),d=[`import ${JSON.stringify(si(a,o.path))};`,`import ${JSON.stringify(si(a,r.runtime["cypress-capture.js"].path))};`,...r.capture.supportFile===null||r.capture.supportFile===void 0?[]:[`import ${JSON.stringify(si(a,Rt(t,r.capture.supportFile)))};`]],c=await gc(t,Kr(a,"kwikqa-support.js"),`// Generated by KwikQA: its failure capture, then the project's support file.
57
57
  ${d.join(`
58
58
  `)}
59
- `);i.push(o,c),n.push(`supportFile=${c.path}`)}return{args:["run","--project",e,...r.configFile===void 0?[]:["--config-file",sT(r.configFile)],...r.specs.length===0?[]:["--spec",r.specs.map(a=>Rt(t,a)).join(",")],"--reporter",r.runtime["cypress-reporter.cjs"].path,"--reporter-options",[`screenshotsFolder=${Rt(t,r.screenshotsDirectory)}`,...r.capture===void 0?[]:[`captureDir=${Gr(Rt(t,r.capture.directory),"pages")}`]].join(","),"--config",n.join(",")],generated:i}}function em(r){return r.filter(t=>t!=="").slice(-2).join(" ")}async function Xs(r){let t=r.workspaceRoot,e=await Ks(t,r.directory),n=Rt(t,r.configFile),i=/\.([cm]?ts)$/.exec(r.configFile)?.[1]??"mjs",s={rootDir:Zh(n),noRetries:r.noRetries,...r.grep===void 0?{}:{grep:r.grep},...r.reportDirectory===void 0?{}:{reportDir:Rt(t,r.reportDirectory)},...r.capture?{captureDir:Gr(e,"pages")}:{}},a=["// Generated by KwikQA: the project's WebdriverIO config, with KwikQA's reporter added.",`import { config as base } from ${JSON.stringify(ni(e,n))};`,`import { withKwikqa } from ${JSON.stringify(ni(e,r.runtime["wdio-capture.mjs"].path))};`,"",`export const config = withKwikqa(base, ${JSON.stringify(s,null,2)});`,""].join(`
60
- `),o=await lc(t,Gr(e,`wdio.kwikqa.conf.${i}`),a);return{args:["run",o.path,...r.specs.flatMap(c=>["--spec",Rt(t,c)])],generated:[o]}}var nm=".kwikqa/capture",lT=10*6e4,uT={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};function fc(r){let t=dT(r.workspaceRoot,r.tool.entryPath).replaceAll("\\","/"),e=r.workspaceRoot,n=r.args.map(i=>{let s=i===e?".":i.split(`${e}/`).join("").split(`${e}\\`).join("").replaceAll("\\","/");return/[\s"']/.test(s)?JSON.stringify(s):s});return`node ${t} ${n.join(" ")}`}async function im(r){let t=r.targets[0];if(t===void 0)return{kind:"unavailable",message:"No failing tests to capture."};let e=r.run.framework,n=uT[e],i=await Yn({workspaceRoot:r.workspaceRoot,ownerPath:Kr(r.workspaceRoot,t.file),packageName:n});if(i.kind!=="resolved")return{kind:"unavailable",message:i.reasons[0]?.message??`The project's ${n} could not be resolved; nothing was installed.`};let s=`${nm}/${r.captureId}`,a={framework:e,tool:i.tool,workspaceRoot:r.workspaceRoot,directory:s,targets:r.targets};if(e==="playwright"){let f=[...new Set(r.targets.map(y=>`${y.file}:${y.line}`))],h=[...new Set(r.targets.map(y=>y.project).filter(y=>y!==void 0))],g=Kr(r.workspaceRoot,s,"report.json"),m=["test",...f,...h.map(y=>`--project=${y}`),...r.run.configFile===void 0?[]:[`--config=${r.run.configFile}`],"--trace=retain-on-failure","--retries=0","--reporter=json",`--output=${s}/results`];return{kind:"ready",plan:{...a,args:m,workingDirectory:r.workspaceRoot,environment:{PLAYWRIGHT_JSON_OUTPUT_NAME:g,PLAYWRIGHT_HTML_OPEN:"never"},reportPath:g,...r.run.configFile===void 0?{}:{configPath:r.run.configFile}}}}let o=[...new Set(r.targets.map(f=>f.file))],d=r.run.configFile??await Ri(r.workspaceRoot,e,t.file),c=Kr(r.workspaceRoot,s,"reports"),l=await Ws(r.workspaceRoot);await rm(Kr(r.workspaceRoot,s),{recursive:!0});let u=d===void 0?r.workspaceRoot:oT(cT(r.workspaceRoot,d));if(e==="cypress"){let f=await Js({workspaceRoot:r.workspaceRoot,runtime:l,...d===void 0?{}:{configFile:d},specs:o,screenshotsDirectory:`${s}/screenshots`,noRetries:!0,capture:{directory:s,supportFile:await Ti(r.workspaceRoot,d)}});return{kind:"ready",plan:{...a,args:f.args,workingDirectory:u,environment:{KWIKQA_REPORT_DIR:c},reportPath:c,...d===void 0?{}:{configPath:d}}}}if(d===void 0)return{kind:"unavailable",message:`No wdio.conf was found for ${t.file}; nothing was run.`};let p=await Xs({workspaceRoot:r.workspaceRoot,runtime:l,configFile:d,specs:o,directory:s,noRetries:!0,reportDirectory:`${s}/reports`,capture:!0});return{kind:"ready",plan:{...a,args:p.args,workingDirectory:u,environment:{KWIKQA_REPORT_DIR:c},reportPath:c,configPath:d}}}async function sm(r,t){let e=Kr(r.workspaceRoot,r.directory);if(r.framework==="playwright")await tm(e,{recursive:!0,force:!0}),await rm(e,{recursive:!0});else for(let u of["reports","pages","screenshots"])await tm(Kr(e,u),{recursive:!0,force:!0});let n=await us(r.tool.executable,[...r.tool.nodeArguments,...r.args],{cwd:r.workingDirectory,env:ls(t.env,r.environment),timeoutMs:t.timeoutMs??lT}),i=await et(r.reportPath,{workspaceRoot:r.workspaceRoot}),s=Pi[r.framework];if(i.kind!=="parsed"){let u=n.output.trim().split(`
59
+ `);i.push(o,c),n.push(`supportFile=${c.path}`)}return{args:["run","--project",e,...r.configFile===void 0?[]:["--config-file",lT(r.configFile)],...r.specs.length===0?[]:["--spec",r.specs.map(a=>Rt(t,a)).join(",")],"--reporter",r.runtime["cypress-reporter.cjs"].path,"--reporter-options",[`screenshotsFolder=${Rt(t,r.screenshotsDirectory)}`,...r.capture===void 0?[]:[`captureDir=${Kr(Rt(t,r.capture.directory),"pages")}`]].join(","),"--config",n.join(",")],generated:i}}function dm(r){return r.filter(t=>t!=="").slice(-2).join(" ")}async function Zs(r){let t=r.workspaceRoot,e=await Xs(t,r.directory),n=Rt(t,r.configFile),i=/\.([cm]?ts)$/.exec(r.configFile)?.[1]??"mjs",s={rootDir:om(n),noRetries:r.noRetries,...r.grep===void 0?{}:{grep:r.grep},...r.reportDirectory===void 0?{}:{reportDir:Rt(t,r.reportDirectory)},...r.capture?{captureDir:Kr(e,"pages")}:{}},a=["// Generated by KwikQA: the project's WebdriverIO config, with KwikQA's reporter added.",`import { config as base } from ${JSON.stringify(si(e,n))};`,`import { withKwikqa } from ${JSON.stringify(si(e,r.runtime["wdio-capture.mjs"].path))};`,"",`export const config = withKwikqa(base, ${JSON.stringify(s,null,2)});`,""].join(`
60
+ `),o=await gc(t,Kr(e,`wdio.kwikqa.conf.${i}`),a);return{args:["run",o.path,...r.specs.flatMap(c=>["--spec",Rt(t,c)])],generated:[o]}}var um=".kwikqa/capture",mT=10*6e4,yT={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};function xc(r){let t=fT(r.workspaceRoot,r.tool.entryPath).replaceAll("\\","/"),e=r.workspaceRoot,n=r.args.map(i=>{let s=i===e?".":i.split(`${e}/`).join("").split(`${e}\\`).join("").replaceAll("\\","/");return/[\s"']/.test(s)?JSON.stringify(s):s});return`node ${t} ${n.join(" ")}`}async function pm(r){let t=r.targets[0];if(t===void 0)return{kind:"unavailable",message:"No failing tests to capture."};let e=r.run.framework,n=yT[e],i=await Zn({workspaceRoot:r.workspaceRoot,...r.repositoryRoot===void 0?{}:{repositoryRoot:r.repositoryRoot},ownerPath:Wr(r.workspaceRoot,t.file),packageName:n});if(i.kind!=="resolved")return{kind:"unavailable",message:i.reasons[0]?.message??`The project's ${n} could not be resolved; nothing was installed.`};let s=`${um}/${r.captureId}`,a={framework:e,tool:i.tool,workspaceRoot:r.workspaceRoot,directory:s,targets:r.targets};if(e==="playwright"){let f=[...new Set(r.targets.map(y=>`${y.file}:${y.line}`))],h=[...new Set(r.targets.map(y=>y.project).filter(y=>y!==void 0))],g=Wr(r.workspaceRoot,s,"report.json"),m=["test",...f,...h.map(y=>`--project=${y}`),...r.run.configFile===void 0?[]:[`--config=${r.run.configFile}`],"--trace=retain-on-failure","--retries=0","--reporter=json",`--output=${s}/results`];return{kind:"ready",plan:{...a,args:m,workingDirectory:r.workspaceRoot,environment:{PLAYWRIGHT_JSON_OUTPUT_NAME:g,PLAYWRIGHT_HTML_OPEN:"never"},reportPath:g,...r.run.configFile===void 0?{}:{configPath:r.run.configFile}}}}let o=[...new Set(r.targets.map(f=>f.file))],d=r.run.configFile??await Ei(r.workspaceRoot,e,t.file),c=Wr(r.workspaceRoot,s,"reports"),l=await Ys(r.workspaceRoot);await lm(Wr(r.workspaceRoot,s),{recursive:!0});let u=d===void 0?r.workspaceRoot:pT(hT(r.workspaceRoot,d));if(e==="cypress"){let f=await Qs({workspaceRoot:r.workspaceRoot,runtime:l,...d===void 0?{}:{configFile:d},specs:o,screenshotsDirectory:`${s}/screenshots`,noRetries:!0,capture:{directory:s,supportFile:await Ci(r.workspaceRoot,d)}});return{kind:"ready",plan:{...a,args:f.args,workingDirectory:u,environment:{KWIKQA_REPORT_DIR:c},reportPath:c,...d===void 0?{}:{configPath:d}}}}if(d===void 0)return{kind:"unavailable",message:`No wdio.conf was found for ${t.file}; nothing was run.`};let p=await Zs({workspaceRoot:r.workspaceRoot,runtime:l,configFile:d,specs:o,directory:s,noRetries:!0,reportDirectory:`${s}/reports`,capture:!0});return{kind:"ready",plan:{...a,args:p.args,workingDirectory:u,environment:{KWIKQA_REPORT_DIR:c},reportPath:c,configPath:d}}}async function fm(r,t){let e=Wr(r.workspaceRoot,r.directory);if(r.framework==="playwright")await cm(e,{recursive:!0,force:!0}),await lm(e,{recursive:!0});else for(let u of["reports","pages","screenshots"])await cm(Wr(e,u),{recursive:!0,force:!0});let n=await ms(r.tool.executable,[...r.tool.nodeArguments,...r.args],{cwd:r.workingDirectory,env:hs(t.env,r.environment),timeoutMs:t.timeoutMs??mT}),i=await tt(r.reportPath,{workspaceRoot:r.workspaceRoot}),s=Si[r.framework];if(i.kind!=="parsed"){let u=n.output.trim().split(`
61
61
  `).slice(-5).join(`
62
62
  `);return{kind:"failed",message:n.timedOut?`The capture run timed out before ${s} wrote its report.`:`${s} wrote no report.${u===""?"":`
63
- ${u}`}`,reproduced:0,passed:0}}let a=new Set(r.targets.map(u=>u.logicalTestId)),o=i.run.logicalTests.filter(u=>a.has(u.logicalTestId)),d=o.filter(u=>u.status==="unexpected"||u.status==="flaky").map(u=>u.logicalTestId),c=d.length,l=o.filter(u=>u.status==="expected").length;return{kind:"captured",reportPath:r.reportPath,reproduced:c,passed:l,failedAgain:d,message:c===0?`None of the ${r.targets.length} failing tests failed again, so the failure may be flaky or depend on state the re-run did not have.`:`Captured full evidence for ${c} failing test${c===1?"":"s"}${l>0?`; ${l} passed this time, which suggests flakiness`:""}.`}}var pT=/\b(?:getBy\w+|locator|frameLocator)\((?:[^()]|\([^()]*\))*\)/;function fT(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hT(r,t){if(r===void 0)return;let n=new RegExp(`${fT(t)}:(\\d+):\\d+`).exec(r.replaceAll("\\","/"));return n?.[1]===void 0?void 0:Number(n[1])}function am(r,t){if(r===void 0)return!1;let e=r.replaceAll("\\","/");return e===t||e.endsWith(`/${t}`)}function Ys(r){let t=new Map(r.projects.map(n=>[n.projectId,n.name])),e=[];for(let n of r.logicalTests){let i=$r(n),s=i.at(-1);if(s===void 0)continue;let a=n.location.file,o=s.errors.map(u=>`${u.message??""}
64
- ${u.stack??""}`),d=(am(s.errorLocation?.file,a)?s.errorLocation?.line:void 0)??s.errors.map(u=>am(u.location?.file,a)?u.location?.line:hT(u.stack,a)).find(u=>u!==void 0),c=o.map(u=>pT.exec(u)?.[0]).find(u=>u!==void 0),l=t.get(n.projectId);e.push({logicalTestId:n.logicalTestId,title:n.title,file:a,line:n.location.line??1,...l===void 0||l===""?{}:{project:l},...d===void 0?{}:{failingLine:d},...c===void 0?{}:{locator:c},hasTrace:i.some(u=>u.attachments.some(p=>p.name==="trace")),hasPageSnapshot:i.some(u=>u.attachments.some(p=>p.name==="error-context"))})}return e}var dm=3;async function hc(r){let t=Ys(r.run),e=await im({run:r.run,workspaceRoot:r.workspaceRoot,targets:t,captureId:r.captureId});if(e.kind!=="ready")return e;let{plan:n}=e,i,s,a=r.run.framework;r.probe&&a==="playwright"&&(fd(n.tool.packageVersion)?(i=await Bf(r.workspaceRoot,r.env),i===void 0&&(s="Live probing needs Playwright CLI: `npm i -D @playwright/cli` (nothing was installed).")):s=`Live probing needs Playwright 1.59 or later; this project has ${n.tool.packageVersion}.`);let o=Pi[a],d=`${t.length} failing test${t.length===1?"":"s"}`,c=new Set(t.map(u=>u.file)).size,l=a==="playwright"?[`Re-run ${d} with full tracing, using this project's Playwright ${n.tool.packageVersion}:`,` ${fc(n)}`,...i===void 0?[]:[`Then pause up to ${dm} locator failures at their failing line and ask Playwright for locators, using Playwright CLI ${i.version} (${i.source==="project"?"project dependency":i.entryPath}).`],`Everything is written under ${n.directory}/. Your tests run on this machine, as they do in \`npx playwright test\`.`]:[`Re-run the ${c} spec file${c===1?"":"s"} with ${d}, using this project's ${o} ${n.tool.packageVersion} and its own config:`,` ${fc(n)}`,a==="cypress"?"KwikQA adds its reporter and a support file that loads its failure capture and then yours, and records each failed attempt's page: DOM, Cypress command log, console errors, and network.":"KwikQA adds its reporter and hooks after yours that record each failed attempt's page: DOM, screenshot, WebdriverIO commands, console, and network.",`Everything is written under ${n.directory}/. Your tests run on this machine, as they do in \`npx ${a==="cypress"?"cypress run":"wdio run"}\`.`];return{kind:"ready",prepared:{plan:n,...i===void 0?{}:{cli:i},...s===void 0?{}:{probeUnavailable:s},description:l}}}async function mc(r,t){let e=await sm(r.plan,{env:t});if(r.cli===void 0||e.reportPath===void 0||e.reproduced===0)return{outcome:e};let n=await et(e.reportPath,{workspaceRoot:r.plan.workspaceRoot}),s=(n.kind==="parsed"?Ys(n.run):[]).filter(l=>l.locator!==void 0).slice(0,dm);if(s.length===0)return{outcome:e};let a=om(r.plan.workspaceRoot,r.plan.directory,"probe");await mT(a,{recursive:!0});let o=[];for(let l of s)o.push(await Uf({workspaceRoot:r.plan.workspaceRoot,playwright:r.plan.tool,cli:r.cli,target:l,...r.plan.configPath===void 0?{}:{configPath:r.plan.configPath},scratchDirectory:a,env:t}));let d={schemaVersion:jf,tool:{name:"@playwright/cli",version:r.cli.version,source:r.cli.source},playwrightVersion:r.plan.tool.packageVersion,results:o},c=om(r.plan.workspaceRoot,r.plan.directory,"probe.json");return await yT(c,`${JSON.stringify(d,null,2)}
65
- `),{outcome:e,probePath:c,probe:d}}var dr=class{#e=new Set;consume(t,e){return this.#e.has(t)?!1:(this.#e.add(t),!0)}};function Qs(r){return C({runId:r.manifest.runId,packetHash:r.manifest.packetHash,payloadHash:r.manifest.payloadHash,manifestHash:r.manifestHash,model:r.manifest.model,promptVersion:r.manifest.promptVersion,outputSchemaVersion:r.manifest.outputSchemaVersion,endpoint:r.endpoint,estimate:r.estimate,caps:r.caps})}function yc(r,t){return{runId:r.manifest.runId,packetHash:r.manifest.packetHash,payloadManifestHash:r.manifestHash,authorizationBindingHash:t,model:r.manifest.model,estimate:r.estimate,caps:r.caps,evidence:r.manifest.evidence,artifactIds:r.manifest.artifactIds,channels:r.manifest.channels,omissionIds:r.manifest.omissionIds,redactionIds:r.manifest.redactionIds}}function gc(r,t){return r.bindingHash===t&&r.authorizationId.trim().length>0&&r.authorizedAt.trim().length>0}var gT={purpose:"diagnosis",promptVersion:"1.1",outputSchemaVersion:"1.0"};function wc(r){return{...r.extra,schemaVersion:"1.1",runId:r.runId,createdAt:r.createdAt,workspace:r.workspace,sourceHashes:r.sourceHashes,packetHash:r.packetHash,...r.request??gT,model:r.model,caps:r.caps,outcome:r.outcome,recordedAt:r.recordedAt}}function Ve(r,t,e){return{kind:r,...t===void 0?{}:{reasonCode:t},...e===void 0?{}:{message:e}}}function bc(r){if(r===void 0||r.trim().length===0)return;let t=Number(r);return Number.isFinite(t)&&t>=0?t:void 0}function wT(r){let t=[r.prompt,...r.overrides.map(i=>i.prompt)].map(bc).filter(i=>i!==void 0),e=[r.completion,...r.overrides.map(i=>i.completion)].map(bc).filter(i=>i!==void 0),n=[r.request??"0",...r.overrides.map(i=>i.request)].map(bc).filter(i=>i!==void 0);if(!(t.length!==r.overrides.filter(i=>i.prompt!==void 0).length+1||e.length!==r.overrides.filter(i=>i.completion!==void 0).length+1||n.length!==r.overrides.filter(i=>i.request!==void 0).length+1))return{prompt:Math.max(...t),completion:Math.max(...e),request:Math.max(...n)}}function Zs(r,t,e){if(!Number.isInteger(t)||t<=0)return;let n=wT(e);if(n===void 0)return;let i=Buffer.byteLength(r,"utf8"),s=i+64,a=s*n.prompt+t*n.completion+n.request;if(Number.isFinite(a))return{method:"utf8-byte-upper-bound-v1",requestBytes:i,estimatedInputTokens:s,estimatedOutputTokens:t,estimatedDollars:a,promptDollarsPerToken:n.prompt,completionDollarsPerToken:n.completion,fixedRequestDollars:n.request}}function xc(r){for(let[t,e]of[["request",r.request],["run",r.run]]){if(!Number.isInteger(e.maxInputTokens)||e.maxInputTokens<=0)return`${t} maxInputTokens must be a positive integer.`;if(!Number.isInteger(e.maxOutputTokens)||e.maxOutputTokens<=0)return`${t} maxOutputTokens must be a positive integer.`;if(!Number.isFinite(e.maxDollars)||e.maxDollars<=0)return`${t} maxDollars must be a positive finite number.`}}function vc(r,t){return r.estimatedInputTokens>t.request.maxInputTokens||r.estimatedOutputTokens>t.request.maxOutputTokens?{kind:"blocked",reasonCode:"request-token-budget-exceeded",message:"The conservative request token estimate exceeds the request cap."}:r.estimatedDollars>t.request.maxDollars?{kind:"blocked",reasonCode:"request-dollar-budget-exceeded",message:"The conservative request cost estimate exceeds the request cap."}:r.estimatedInputTokens>t.run.maxInputTokens||r.estimatedOutputTokens>t.run.maxOutputTokens?{kind:"blocked",reasonCode:"run-token-budget-exceeded",message:"The conservative request token estimate exceeds the remaining run cap."}:r.estimatedDollars>t.run.maxDollars?{kind:"blocked",reasonCode:"run-dollar-budget-exceeded",message:"The conservative request cost estimate exceeds the remaining run cap."}:{kind:"within-budget"}}function ii(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0}function ta(r){return typeof r=="string"&&r.trim().length>0?r:void 0}function ra(r){return typeof r=="number"&&Number.isInteger(r)&&r>=0?r:void 0}function lm(r){return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:void 0}function um(r){if(r!=null)return ra(r)??null}function Wr(r){if(typeof r!="string"||r.trim().length===0)return;let t=Number(r);return Number.isFinite(t)&&t>=0?r:void 0}function bT(r){let t=ii(r);if(t===void 0)return;let e=t.prompt===void 0?void 0:Wr(t.prompt),n=t.completion===void 0?void 0:Wr(t.completion),i=t.request===void 0?void 0:Wr(t.request),s=t.min_prompt_tokens===void 0?void 0:ra(t.min_prompt_tokens),a=t.utc_start===void 0?void 0:lm(t.utc_start),o=t.utc_end===void 0?void 0:lm(t.utc_end),d=t.utc_days===void 0?void 0:Array.isArray(t.utc_days)?t.utc_days.map(ra):void 0;if(!(t.prompt!==void 0&&e===void 0||t.completion!==void 0&&n===void 0||t.request!==void 0&&i===void 0||t.min_prompt_tokens!==void 0&&s===void 0||t.utc_start!==void 0&&a===void 0||t.utc_end!==void 0&&o===void 0||t.utc_days!==void 0&&(d===void 0||d.includes(void 0))))return{...e===void 0?{}:{prompt:e},...n===void 0?{}:{completion:n},...i===void 0?{}:{request:i},...s===void 0?{}:{minPromptTokens:s},...a===void 0?{}:{utcStart:a},...o===void 0?{}:{utcEnd:o},...d===void 0?{}:{utcDays:d}}}function xT(r){let t=ii(r);if(t===void 0)return;let e=Wr(t.prompt),n=Wr(t.completion),i=t.request===void 0?void 0:Wr(t.request);if(e===void 0||n===void 0||t.request!==void 0&&i===void 0)return;let s=t.overrides;if(s!==void 0&&!Array.isArray(s))return;let a=(s??[]).map(bT);if(!a.includes(void 0))return{prompt:e,completion:n,...i===void 0?{}:{request:i},overrides:a}}function pm(r){return r.trim().toLocaleLowerCase("en-US")}function fm(r){return ta(r.tag)}function ea(r,t){return{kind:"unsupported",code:r,message:t}}function kc(r,t){let e=ii(r),i=ii(e?.data)?.endpoints;if(!Array.isArray(i))return{kind:"failed",code:"invalid-metadata",message:"Endpoint metadata was malformed."};let s=pm(t.providerSlug),a=i.map(ii).filter(m=>m!==void 0).filter(m=>{let y=fm(m);return y!==void 0&&pm(y)===s});if(a.length===0)return ea("provider-unavailable",`The exact provider ${t.providerSlug} does not serve ${t.modelId}.`);if(a.length!==1)return ea("provider-ambiguous",`The provider route ${t.providerSlug} did not identify one endpoint.`);let o=a[0];if(o===void 0)return{kind:"failed",code:"invalid-metadata",message:"Endpoint metadata was malformed."};let d=ta(o.model_id);if(d!==t.modelId)return ea("model-mismatch","OpenRouter metadata did not preserve the configured exact model identifier.");let c=Array.isArray(o.supported_parameters)?o.supported_parameters.map(ta):[];if(c.includes(void 0))return{kind:"failed",code:"invalid-metadata",message:"Supported parameters were malformed."};if(!c.includes("structured_outputs"))return ea("structured-output-unsupported","The exact endpoint does not advertise structured output support.");let l=ra(o.context_length),u=um(o.max_prompt_tokens),p=um(o.max_completion_tokens),f=xT(o.pricing),h=typeof o.status=="number"?o.status:void 0;return l===void 0||u===null||p===null||f===void 0||h===void 0||!Number.isFinite(h)?{kind:"failed",code:"invalid-metadata",message:"Endpoint limits or pricing were malformed."}:h!==0?{kind:"unavailable",code:"endpoint-unavailable",message:"The exact endpoint is not currently marked available."}:{kind:"available",endpoint:{providerName:ta(o.provider_name)??t.providerSlug,providerSlug:fm(o)??t.providerSlug,modelId:d,contextLength:l,...u===void 0?{}:{maxPromptTokens:u},...p===void 0?{}:{maxCompletionTokens:p},supportedParameters:c,pricing:f,status:h}}}function vT(r){return{...r.prompt===void 0?{}:{prompt:r.prompt},...r.completion===void 0?{}:{completion:r.completion},...r.request===void 0?{}:{request:r.request},...r.minPromptTokens===void 0?{}:{minPromptTokens:r.minPromptTokens},...r.utcStart===void 0?{}:{utcStart:String(r.utcStart)},...r.utcEnd===void 0?{}:{utcEnd:String(r.utcEnd)},...r.utcDays===void 0?{}:{utcDays:r.utcDays}}}function Ic(r){let t={prompt:r.pricing.prompt,completion:r.pricing.completion,...r.pricing.request===void 0?{}:{request:r.pricing.request},overrides:r.pricing.overrides.map(vT)};return{modelId:r.modelId,providerId:r.providerSlug,providerName:r.providerName,contextLength:r.contextLength,...r.maxPromptTokens===void 0?{}:{maxPromptTokens:r.maxPromptTokens},...r.maxCompletionTokens===void 0?{}:{maxCompletionTokens:r.maxCompletionTokens},supportedParameters:r.supportedParameters,status:r.status,pricing:t}}var kT="https://openrouter.ai",IT=`${kT}/api/v1`,PT=3e4,RT=4*1024*1024;function Tt(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Rc(r){if(r instanceof DOMException&&(r.name==="AbortError"||r.name==="TimeoutError"))return"timed out";let t=r?.cause;return typeof t?.code=="string"?t.code:typeof t?.message=="string"?t.message:r instanceof Error?r.message:"unknown error"}function Pc(r,t){return r!==void 0&&Number.isInteger(r)&&r>0?r:t}function TT(r){let t=r.split("/");if(!(t.length!==2||t.some(e=>e.length===0)))return t.map(encodeURIComponent).join("/")}function hm(r){let t=r();return t===void 0||t.trim().length===0?void 0:t.trim()}async function mm(r,t){let e=r.headers.get("content-length");if(e!==null){let d=Number(e);if(Number.isFinite(d)&&d>t)return{kind:"too-large"}}if(r.body===null)return{kind:"invalid-json"};let n=r.body.getReader(),i=[],s=0;try{for(;;){let d=await n.read();if(d.done)break;if(s+=d.value.byteLength,s>t)return await n.cancel(),{kind:"too-large"};i.push(d.value)}}finally{n.releaseLock()}let a=new Uint8Array(s),o=0;for(let d of i)a.set(d,o),o+=d.byteLength;try{return{kind:"parsed",value:JSON.parse(new TextDecoder().decode(a))}}catch{return{kind:"invalid-json"}}}function na(r){if(!Tt(r)||!Tt(r.error))return;let t=r.error.code;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Tc(r,t){let e=Tt(t)&&Tt(t.error)?t.error:void 0,n=Tt(e?.metadata)?e.metadata:void 0,i=[e?.message,n?.raw].filter(a=>typeof a=="string"&&a.trim()!=="").map(a=>a.replace(/\s+/g," ").trim()).join(": "),s=i.length>300?`${i.slice(0,299)}\u2026`:i;return`OpenRouter completion request failed (HTTP ${r})${s===""?".":`: ${s}`}`}function Ac(r){return Tt(r)&&Tt(r.error)&&r.choices===void 0}function ym(r){return{Accept:"application/json",Authorization:`Bearer ${r}`}}function Sc(r){if(r.body.model!==r.route.modelId)return"The completion body does not preserve the configured exact model.";if("models"in r.body)return"Model fallback arrays are forbidden.";if("tools"in r.body||"tool_choice"in r.body)return"Model tools are forbidden for bounded diagnosis.";if(r.body.stream===!0)return"Streaming is not supported by bounded diagnosis.";let t=Tt(r.body.provider)?r.body.provider:void 0,e=Array.isArray(t?.only)?t.only:void 0;if(e?.length!==1||e[0]!==r.route.providerSlug||t?.allow_fallbacks!==!1||t.require_parameters!==!0)return"The completion body does not preserve the exact no-fallback provider route.";if((Tt(r.body.response_format)?r.body.response_format:void 0)?.type!=="json_schema")return"The completion body does not require JSON Schema output."}var ur=class{#e;#r;#t;#n;#i;#s;#a;#o;constructor(t={}){this.#e=t.fetch??fetch,this.#r=Pc(t.timeoutMs,PT),this.#t=Pc(t.maxResponseBytes,RT),this.#n=t.apiRoot??IT,this.#i=t.readApiKey??(()=>process.env.OPENROUTER_API_KEY),this.#s=t.credentialName??"OPENROUTER_API_KEY",this.#a=t.extraHeaders??(()=>({})),this.#o=t.onCompletionBody??(()=>{})}async preflight(t){let e=await this.#d(t);return e.kind==="failed"&&(e.code==="network-error"||e.code==="timeout")?this.#d(t):e}async#d(t){let e=TT(t.modelId);if(e===void 0||t.providerSlug.trim().length===0)return{kind:"failed",code:"invalid-request",message:"An exact model and provider route are required."};let n=hm(this.#i);if(n===void 0)return{kind:"failed",code:"credential-unavailable",message:`${this.#s} is not configured.`};let i=new AbortController,s=setTimeout(()=>i.abort(),this.#r);try{let a=await this.#e(`${this.#n}/models/${e}/endpoints`,{method:"GET",headers:{...this.#a(),...ym(n)},redirect:"error",signal:i.signal}),o=await mm(a,this.#t);return o.kind!=="parsed"?{kind:"failed",code:o.kind==="too-large"?"response-too-large":"invalid-json",message:"OpenRouter endpoint metadata could not be read safely.",httpStatus:a.status}:a.ok?kc(o.value,t):{kind:"failed",code:"http-error",message:"OpenRouter endpoint metadata request failed.",httpStatus:a.status}}catch(a){return{kind:"failed",code:a instanceof DOMException&&a.name==="AbortError"?"timeout":"network-error",message:`OpenRouter endpoint metadata request did not complete (${Rc(a)}).`}}finally{clearTimeout(s)}}async complete(t){let e=performance.now(),n=Sc(t);if(n!==void 0)return{kind:"failed",code:"invalid-request",message:n,elapsedMs:0};let i=hm(this.#i);if(i===void 0)return{kind:"failed",code:"credential-unavailable",message:`${this.#s} is not configured.`,elapsedMs:performance.now()-e};let s=Pc(t.timeoutMs,this.#r),a=new AbortController,o=setTimeout(()=>a.abort(),s);try{let d=await this.#e(`${this.#n}/chat/completions`,{method:"POST",headers:{...this.#a(t.body),...ym(i),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(t.body),redirect:"error",signal:a.signal}),c=await mm(d,this.#t),l=performance.now()-e;if(c.kind!=="parsed")return{kind:"failed",code:c.kind==="too-large"?"response-too-large":"invalid-json",message:"OpenRouter completion response could not be read safely.",httpStatus:d.status,elapsedMs:l};if(!d.ok||Ac(c.value)){let u=na(c.value),p=d.ok?u??502:d.status;return{kind:"failed",code:"http-error",message:Tc(p,c.value),httpStatus:p,...u===void 0?{}:{providerCode:u},elapsedMs:l}}return this.#o(c.value),{kind:"response",httpStatus:d.status,body:c.value,elapsedMs:l}}catch(d){return{kind:"failed",code:d instanceof DOMException&&d.name==="AbortError"?"timeout":"network-error",message:"OpenRouter completion request did not complete.",elapsedMs:performance.now()-e}}finally{clearTimeout(o)}}};var pr={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},AT={type:"object",additionalProperties:!1,required:["hypothesisId","rank","causalCategory","probableOwner","evidenceGrade","supportingEvidenceIds","contradictingEvidenceIds","missingEvidence","unresolvedAssumptions","nextAction","statement"],properties:{hypothesisId:{type:"string",minLength:1},rank:{type:"integer",minimum:1,maximum:3},causalCategory:{type:"string",minLength:1},probableOwner:{type:"string",enum:["test-support","application","environment","undetermined"]},evidenceGrade:{type:"string",enum:["strong","moderate","weak","insufficient"]},supportingEvidenceIds:pr,contradictingEvidenceIds:pr,missingEvidence:pr,unresolvedAssumptions:pr,nextAction:{type:"string",minLength:1},statement:{type:"string",minLength:1}}},Ec={type:"object",additionalProperties:!1,required:["status","hypotheses","symptomIds","missingEvidence","recommendedNextAction","repairEligibility","ownershipEvidenceIds","packetHash"],properties:{status:{type:"string",enum:["conclusive","probable","inconclusive"]},hypotheses:{type:"array",items:AT,maxItems:3},symptomIds:pr,missingEvidence:pr,recommendedNextAction:{type:"string",minLength:1},repairEligibility:{type:"string",enum:["eligible","ineligible","undetermined"]},ownershipEvidenceIds:pr,packetHash:{type:"string",minLength:1}}},ST=["status","hypotheses","symptomIds","missingEvidence","recommendedNextAction","repairEligibility","ownershipEvidenceIds","packetHash"],ET=["hypothesisId","rank","causalCategory","probableOwner","evidenceGrade","supportingEvidenceIds","contradictingEvidenceIds","missingEvidence","unresolvedAssumptions","nextAction","statement"],CT=new Set(["conclusive","probable","inconclusive"]),NT=new Set(["strong","moderate","weak","insufficient"]),OT=new Set(["test-support","application","environment","undetermined"]),DT=new Set(["eligible","ineligible","undetermined"]);function Xr(r){if(r===null||typeof r!="object"||Array.isArray(r))return!1;let t=Object.getPrototypeOf(r);return t===Object.prototype||t===null}function ie(r,t,e,n){r.push({path:t,code:e,message:n})}function Yr(r,t,e,n){let i=new Set(t);for(let s of t)Object.hasOwn(r,s)||ie(n,`${e}.${s}`,"missing-field","field is required");for(let s of Object.keys(r))i.has(s)||ie(n,`${e}.${s}`,"unknown-field","field is not allowed")}function Me(r,t,e){if(typeof r!="string"){ie(e,t,"expected-string","expected a string");return}if(r.trim()===""){ie(e,t,"empty-string","string must not be empty");return}return r}function Jr(r,t,e,n){let i=Me(r,e,n);if(i!==void 0){if(!t.has(i)){ie(n,e,"invalid-enum",`unsupported value ${JSON.stringify(i)}`);return}return i}}function We(r,t,e){if(!Array.isArray(r)){ie(e,t,"expected-array","expected an array");return}let n=[],i=new Set;return r.forEach((s,a)=>{let o=Me(s,`${t}[${a}]`,e);if(o!==void 0){if(i.has(o)){ie(e,`${t}[${a}]`,"duplicate-item",`duplicate value ${JSON.stringify(o)}`);return}i.add(o),n.push(o)}}),n}function LT(r,t,e){let n=`$.hypotheses[${t}]`;if(!Xr(r)){ie(e,n,"expected-object","expected an object");return}Yr(r,ET,n,e);let i=Me(r.hypothesisId,`${n}.hypothesisId`,e),s=r.rank;!Number.isInteger(s)||typeof s!="number"?ie(e,`${n}.rank`,"expected-integer","rank must be an integer"):(s<1||s>3)&&ie(e,`${n}.rank`,"invalid-rank","rank must be between 1 and 3");let a=Me(r.causalCategory,`${n}.causalCategory`,e),o=Jr(r.probableOwner,OT,`${n}.probableOwner`,e),d=Jr(r.evidenceGrade,NT,`${n}.evidenceGrade`,e),c=We(r.supportingEvidenceIds,`${n}.supportingEvidenceIds`,e),l=We(r.contradictingEvidenceIds,`${n}.contradictingEvidenceIds`,e),u=We(r.missingEvidence,`${n}.missingEvidence`,e),p=We(r.unresolvedAssumptions,`${n}.unresolvedAssumptions`,e),f=Me(r.nextAction,`${n}.nextAction`,e),h=Me(r.statement,`${n}.statement`,e);if(c!==void 0&&l!==void 0){let g=new Set(l);for(let m of c)g.has(m)&&ie(e,`${n}.contradictingEvidenceIds`,"citation-overlap",`${m} cannot both support and contradict a hypothesis`)}if(d!==void 0&&d!=="insufficient"&&c?.length===0&&ie(e,`${n}.supportingEvidenceIds`,"support-required",`${d} evidence requires at least one supporting citation`),!(i===void 0||typeof s!="number"||!Number.isInteger(s)||s<1||s>3||a===void 0||o===void 0||d===void 0||c===void 0||l===void 0||u===void 0||p===void 0||f===void 0||h===void 0))return{hypothesisId:i,rank:s,causalCategory:a,probableOwner:o,evidenceGrade:d,supportingEvidenceIds:c,contradictingEvidenceIds:l,missingEvidence:u,unresolvedAssumptions:p,nextAction:f,statement:h}}function ia(r){let t=[];if(!Xr(r))return{kind:"invalid",issues:[{path:"$",code:"expected-object",message:"diagnosis must be an object"}]};Yr(r,ST,"$",t);let e=Jr(r.status,CT,"$.status",t),n=[];Array.isArray(r.hypotheses)?(r.hypotheses.length>3&&ie(t,"$.hypotheses","too-many-items","at most three hypotheses are allowed"),r.hypotheses.forEach((p,f)=>{let h=LT(p,f,t);h!==void 0&&n.push(h)})):ie(t,"$.hypotheses","expected-array","expected an array");let i=new Set;for(let p of n)i.has(p.hypothesisId)&&ie(t,"$.hypotheses","duplicate-id",`duplicate hypothesis id ${JSON.stringify(p.hypothesisId)}`),i.add(p.hypothesisId);[...n].map(p=>p.rank).sort((p,f)=>p-f).forEach((p,f)=>{p!==f+1&&ie(t,"$.hypotheses","invalid-rank","hypothesis ranks must be contiguous from 1")});let a=We(r.symptomIds,"$.symptomIds",t),o=We(r.missingEvidence,"$.missingEvidence",t),d=Me(r.recommendedNextAction,"$.recommendedNextAction",t),c=Jr(r.repairEligibility,DT,"$.repairEligibility",t),l=We(r.ownershipEvidenceIds,"$.ownershipEvidenceIds",t),u=Me(r.packetHash,"$.packetHash",t);return t.length>0||e===void 0||a===void 0||o===void 0||d===void 0||c===void 0||l===void 0||u===void 0?{kind:"invalid",issues:t}:{kind:"valid",diagnosis:{status:e,hypotheses:n,symptomIds:a,missingEvidence:o,recommendedNextAction:d,repairEligibility:c,ownershipEvidenceIds:l,packetHash:u}}}function pt(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0}function sa(r){return typeof r=="string"&&r.trim().length>0?r:void 0}function fr(r){return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:void 0}function MT(r){if(r===void 0)return{valid:!0};let t=pt(r);if(t===void 0)return{valid:!1};let e=fr(t.prompt_tokens),n=fr(t.completion_tokens),i=fr(t.total_tokens);if(e===void 0||n===void 0||i===void 0)return{valid:!1};let s=pt(t.completion_tokens_details),a=pt(t.prompt_tokens_details),o=pt(t.cost_details),d=fr(s?.reasoning_tokens),c=fr(a?.cached_tokens),l=fr(t.cost),u=fr(o?.upstream_inference_cost);return i!==e+n||d!==void 0&&d>n||c!==void 0&&c>e||t.completion_tokens_details!==void 0&&s===void 0||t.prompt_tokens_details!==void 0&&a===void 0||t.cost_details!==void 0&&o===void 0||s?.reasoning_tokens!==void 0&&d===void 0||a?.cached_tokens!==void 0&&c===void 0||t.cost!==void 0&&l===void 0||o?.upstream_inference_cost!==void 0&&u===void 0?{valid:!1}:{valid:!0,usage:{promptTokens:e,completionTokens:n,totalTokens:i,...d===void 0?{}:{reasoningTokens:d},...c===void 0?{}:{cachedTokens:c},...l===void 0?{}:{cost:l},...u===void 0?{}:{upstreamInferenceCost:u}}}}function $T(r){let e=pt(r?.endpoints)?.available;if(!Array.isArray(e))return;let n=e.map(pt).filter(i=>i!==void 0&&i.selected===!0);return n.length!==1?null:sa(n[0]?.provider)??null}function gm(r,t,e){let n=pt(r),i=sa(n?.model),s=n?.choices;if(n===void 0||i===void 0||!Array.isArray(s))return{kind:"malformed-response",message:"Completion response fields were malformed."};if(s.length!==1)return{kind:"malformed-response",message:"Completion response must contain exactly one choice."};let a=pt(s[0]),o=pt(a?.message),d=sa(a?.finish_reason);if(o===void 0||d===void 0)return{kind:"malformed-response",message:"Completion choice was malformed."};if("tool_calls"in o||"function_call"in o)return{kind:"malformed-response",message:`Tool calls are forbidden in ${t} output.`};if(o.refusal!==void 0&&o.refusal!==null)return{kind:"provider-refusal",message:`The provider refused the ${t} request.`};if(d!=="stop")return{kind:"provider-refusal",message:`The provider did not complete the structured response (${d}).`};let c=sa(o.content);if(c===void 0)return{kind:"malformed-response",message:`Structured ${t} content was missing.`};let l;try{l=JSON.parse(c)}catch{return{kind:"malformed-response",message:`Structured ${t} was not valid JSON.`}}let u=e(l);if(u.kind!=="valid")return{kind:"schema-invalid",message:u.message};let p=pt(n.openrouter_metadata),f=$T(p);if(f===null)return{kind:"malformed-response",message:"Router metadata did not identify exactly one selected provider."};let h=MT(n.usage);return h.valid?{kind:"parsed",value:{output:u.output,reportedModel:i,...f===void 0?{}:{reportedProvider:f},...h.usage===void 0?{}:{usage:h.usage},finishReason:d}}:{kind:"malformed-response",message:"Completion usage metadata was malformed."}}var _T=new Set(["$defs","$ref","additionalProperties","anyOf","const","definitions","description","enum","exclusiveMaximum","exclusiveMinimum","format","items","maxItems","maximum","minItems","minimum","multipleOf","pattern","properties","required","title","type"]),FT=new Set(["$defs","definitions","properties"]);function wm(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function aa(r){return Array.isArray(r)?r.map(aa):wm(r)?Object.fromEntries(Object.entries(r).filter(([t])=>_T.has(t)).map(([t,e])=>[t,FT.has(t)&&wm(e)?Object.fromEntries(Object.entries(e).map(([n,i])=>[n,aa(i)])):t==="enum"||t==="const"||t==="required"?e:aa(e)])):r}function bm(r,t){return t.startsWith("openai/")?aa(r):r}var jT=`You diagnose end-to-end test failures from one bounded, redacted evidence packet. The packet's framework field says whether the tests run in Playwright, Cypress, or WebdriverIO; read errors, commands, and locators in that framework's terms.
63
+ ${u}`}`,reproduced:0,passed:0}}let a=new Set(r.targets.map(u=>u.logicalTestId)),o=i.run.logicalTests.filter(u=>a.has(u.logicalTestId)),d=o.filter(u=>u.status==="unexpected"||u.status==="flaky").map(u=>u.logicalTestId),c=d.length,l=o.filter(u=>u.status==="expected").length;return{kind:"captured",reportPath:r.reportPath,reproduced:c,passed:l,failedAgain:d,message:c===0?`None of the ${r.targets.length} failing tests failed again, so the failure may be flaky or depend on state the re-run did not have.`:`Captured full evidence for ${c} failing test${c===1?"":"s"}${l>0?`; ${l} passed this time, which suggests flakiness`:""}.`}}var gT=/\b(?:getBy\w+|locator|frameLocator)\((?:[^()]|\([^()]*\))*\)/;function wT(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bT(r,t){if(r===void 0)return;let n=new RegExp(`${wT(t)}:(\\d+):\\d+`).exec(r.replaceAll("\\","/"));return n?.[1]===void 0?void 0:Number(n[1])}function hm(r,t){if(r===void 0)return!1;let e=r.replaceAll("\\","/");return e===t||e.endsWith(`/${t}`)}function ea(r){let t=new Map(r.projects.map(n=>[n.projectId,n.name])),e=[];for(let n of r.logicalTests){let i=Fr(n),s=i.at(-1);if(s===void 0)continue;let a=n.location.file,o=s.errors.map(u=>`${u.message??""}
64
+ ${u.stack??""}`),d=(hm(s.errorLocation?.file,a)?s.errorLocation?.line:void 0)??s.errors.map(u=>hm(u.location?.file,a)?u.location?.line:bT(u.stack,a)).find(u=>u!==void 0),c=o.map(u=>gT.exec(u)?.[0]).find(u=>u!==void 0),l=t.get(n.projectId);e.push({logicalTestId:n.logicalTestId,title:n.title,file:a,line:n.location.line??1,...l===void 0||l===""?{}:{project:l},...d===void 0?{}:{failingLine:d},...c===void 0?{}:{locator:c},hasTrace:i.some(u=>u.attachments.some(p=>p.name==="trace")),hasPageSnapshot:i.some(u=>u.attachments.some(p=>p.name==="error-context"))})}return e}var ym=3;async function vc(r){let t=ea(r.run),e=await pm({run:r.run,workspaceRoot:r.workspaceRoot,...r.repositoryRoot===void 0?{}:{repositoryRoot:r.repositoryRoot},targets:t,captureId:r.captureId});if(e.kind!=="ready")return e;let{plan:n}=e,i,s,a=r.run.framework;r.probe&&a==="playwright"&&(wd(n.tool.packageVersion)?(i=await Gf(r.workspaceRoot,r.env),i===void 0&&(s="Live probing needs Playwright CLI: add `@playwright/cli` to the project's dev dependencies (nothing was installed).")):s=`Live probing needs Playwright 1.59 or later; this project has ${n.tool.packageVersion}.`);let o=Si[a],d=`${t.length} failing test${t.length===1?"":"s"}`,c=new Set(t.map(u=>u.file)).size,l=a==="playwright"?[`Re-run ${d} with full tracing, using this project's Playwright ${n.tool.packageVersion}:`,` ${xc(n)}`,...i===void 0?[]:[`Then pause up to ${ym} locator failures at their failing line and ask Playwright for locators, using Playwright CLI ${i.version} (${i.source==="project"?"project dependency":i.entryPath}).`],`Everything is written under ${n.directory}/. Your tests run on this machine, as they do in \`npx playwright test\`.`]:[`Re-run the ${c} spec file${c===1?"":"s"} with ${d}, using this project's ${o} ${n.tool.packageVersion} and its own config:`,` ${xc(n)}`,a==="cypress"?"KwikQA adds its reporter and a support file that loads its failure capture and then yours, and records each failed attempt's page: DOM, Cypress command log, console errors, and network.":"KwikQA adds its reporter and hooks after yours that record each failed attempt's page: DOM, screenshot, WebdriverIO commands, console, and network.",`Everything is written under ${n.directory}/. Your tests run on this machine, as they do in \`npx ${a==="cypress"?"cypress run":"wdio run"}\`.`];return{kind:"ready",prepared:{plan:n,...i===void 0?{}:{cli:i},...s===void 0?{}:{probeUnavailable:s},description:l}}}async function kc(r,t){let e=await fm(r.plan,{env:t});if(r.cli===void 0||e.reportPath===void 0||e.reproduced===0)return{outcome:e};let n=await tt(e.reportPath,{workspaceRoot:r.plan.workspaceRoot}),s=(n.kind==="parsed"?ea(n.run):[]).filter(l=>l.locator!==void 0).slice(0,ym);if(s.length===0)return{outcome:e};let a=mm(r.plan.workspaceRoot,r.plan.directory,"probe");await xT(a,{recursive:!0});let o=[];for(let l of s)o.push(await Yf({workspaceRoot:r.plan.workspaceRoot,playwright:r.plan.tool,cli:r.cli,target:l,...r.plan.configPath===void 0?{}:{configPath:r.plan.configPath},scratchDirectory:a,env:t}));let d={schemaVersion:Uf,tool:{name:"@playwright/cli",version:r.cli.version,source:r.cli.source},playwrightVersion:r.plan.tool.packageVersion,results:o},c=mm(r.plan.workspaceRoot,r.plan.directory,"probe.json");return await vT(c,`${JSON.stringify(d,null,2)}
65
+ `),{outcome:e,probePath:c,probe:d}}var lr=class{#e=new Set;consume(t,e){return this.#e.has(t)?!1:(this.#e.add(t),!0)}};function ta(r){return N({runId:r.manifest.runId,packetHash:r.manifest.packetHash,payloadHash:r.manifest.payloadHash,manifestHash:r.manifestHash,model:r.manifest.model,promptVersion:r.manifest.promptVersion,outputSchemaVersion:r.manifest.outputSchemaVersion,endpoint:r.endpoint,estimate:r.estimate,caps:r.caps})}function Ic(r,t){return{runId:r.manifest.runId,packetHash:r.manifest.packetHash,payloadManifestHash:r.manifestHash,authorizationBindingHash:t,model:r.manifest.model,estimate:r.estimate,caps:r.caps,evidence:r.manifest.evidence,artifactIds:r.manifest.artifactIds,channels:r.manifest.channels,omissionIds:r.manifest.omissionIds,redactionIds:r.manifest.redactionIds}}function Pc(r,t){return r.bindingHash===t&&r.authorizationId.trim().length>0&&r.authorizedAt.trim().length>0}var kT={purpose:"diagnosis",promptVersion:"1.1",outputSchemaVersion:"1.0"};function Rc(r){return{...r.extra,schemaVersion:"1.1",runId:r.runId,createdAt:r.createdAt,workspace:r.workspace,sourceHashes:r.sourceHashes,packetHash:r.packetHash,...r.request??kT,model:r.model,caps:r.caps,outcome:r.outcome,recordedAt:r.recordedAt}}function Ve(r,t,e){return{kind:r,...t===void 0?{}:{reasonCode:t},...e===void 0?{}:{message:e}}}function Tc(r){if(r===void 0||r.trim().length===0)return;let t=Number(r);return Number.isFinite(t)&&t>=0?t:void 0}function IT(r){let t=[r.prompt,...r.overrides.map(i=>i.prompt)].map(Tc).filter(i=>i!==void 0),e=[r.completion,...r.overrides.map(i=>i.completion)].map(Tc).filter(i=>i!==void 0),n=[r.request??"0",...r.overrides.map(i=>i.request)].map(Tc).filter(i=>i!==void 0);if(!(t.length!==r.overrides.filter(i=>i.prompt!==void 0).length+1||e.length!==r.overrides.filter(i=>i.completion!==void 0).length+1||n.length!==r.overrides.filter(i=>i.request!==void 0).length+1))return{prompt:Math.max(...t),completion:Math.max(...e),request:Math.max(...n)}}function ra(r,t,e){if(!Number.isInteger(t)||t<=0)return;let n=IT(e);if(n===void 0)return;let i=Buffer.byteLength(r,"utf8"),s=i+64,a=s*n.prompt+t*n.completion+n.request;if(Number.isFinite(a))return{method:"utf8-byte-upper-bound-v1",requestBytes:i,estimatedInputTokens:s,estimatedOutputTokens:t,estimatedDollars:a,promptDollarsPerToken:n.prompt,completionDollarsPerToken:n.completion,fixedRequestDollars:n.request}}function Ac(r){for(let[t,e]of[["request",r.request],["run",r.run]]){if(!Number.isInteger(e.maxInputTokens)||e.maxInputTokens<=0)return`${t} maxInputTokens must be a positive integer.`;if(!Number.isInteger(e.maxOutputTokens)||e.maxOutputTokens<=0)return`${t} maxOutputTokens must be a positive integer.`;if(!Number.isFinite(e.maxDollars)||e.maxDollars<=0)return`${t} maxDollars must be a positive finite number.`}}function Sc(r,t){return r.estimatedInputTokens>t.request.maxInputTokens||r.estimatedOutputTokens>t.request.maxOutputTokens?{kind:"blocked",reasonCode:"request-token-budget-exceeded",message:"The conservative request token estimate exceeds the request cap."}:r.estimatedDollars>t.request.maxDollars?{kind:"blocked",reasonCode:"request-dollar-budget-exceeded",message:"The conservative request cost estimate exceeds the request cap."}:r.estimatedInputTokens>t.run.maxInputTokens||r.estimatedOutputTokens>t.run.maxOutputTokens?{kind:"blocked",reasonCode:"run-token-budget-exceeded",message:"The conservative request token estimate exceeds the remaining run cap."}:r.estimatedDollars>t.run.maxDollars?{kind:"blocked",reasonCode:"run-dollar-budget-exceeded",message:"The conservative request cost estimate exceeds the remaining run cap."}:{kind:"within-budget"}}function ai(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0}function ia(r){return typeof r=="string"&&r.trim().length>0?r:void 0}function sa(r){return typeof r=="number"&&Number.isInteger(r)&&r>=0?r:void 0}function wm(r){return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:void 0}function bm(r){if(r!=null)return sa(r)??null}function Jr(r){if(typeof r!="string"||r.trim().length===0)return;let t=Number(r);return Number.isFinite(t)&&t>=0?r:void 0}function PT(r){let t=ai(r);if(t===void 0)return;let e=t.prompt===void 0?void 0:Jr(t.prompt),n=t.completion===void 0?void 0:Jr(t.completion),i=t.request===void 0?void 0:Jr(t.request),s=t.min_prompt_tokens===void 0?void 0:sa(t.min_prompt_tokens),a=t.utc_start===void 0?void 0:wm(t.utc_start),o=t.utc_end===void 0?void 0:wm(t.utc_end),d=t.utc_days===void 0?void 0:Array.isArray(t.utc_days)?t.utc_days.map(sa):void 0;if(!(t.prompt!==void 0&&e===void 0||t.completion!==void 0&&n===void 0||t.request!==void 0&&i===void 0||t.min_prompt_tokens!==void 0&&s===void 0||t.utc_start!==void 0&&a===void 0||t.utc_end!==void 0&&o===void 0||t.utc_days!==void 0&&(d===void 0||d.includes(void 0))))return{...e===void 0?{}:{prompt:e},...n===void 0?{}:{completion:n},...i===void 0?{}:{request:i},...s===void 0?{}:{minPromptTokens:s},...a===void 0?{}:{utcStart:a},...o===void 0?{}:{utcEnd:o},...d===void 0?{}:{utcDays:d}}}function RT(r){let t=ai(r);if(t===void 0)return;let e=Jr(t.prompt),n=Jr(t.completion),i=t.request===void 0?void 0:Jr(t.request);if(e===void 0||n===void 0||t.request!==void 0&&i===void 0)return;let s=t.overrides;if(s!==void 0&&!Array.isArray(s))return;let a=(s??[]).map(PT);if(!a.includes(void 0))return{prompt:e,completion:n,...i===void 0?{}:{request:i},overrides:a}}function xm(r){return r.trim().toLocaleLowerCase("en-US")}function vm(r){return ia(r.tag)}function na(r,t){return{kind:"unsupported",code:r,message:t}}function Ec(r,t){let e=ai(r),i=ai(e?.data)?.endpoints;if(!Array.isArray(i))return{kind:"failed",code:"invalid-metadata",message:"Endpoint metadata was malformed."};let s=xm(t.providerSlug),a=i.map(ai).filter(m=>m!==void 0).filter(m=>{let y=vm(m);return y!==void 0&&xm(y)===s});if(a.length===0)return na("provider-unavailable",`The exact provider ${t.providerSlug} does not serve ${t.modelId}.`);if(a.length!==1)return na("provider-ambiguous",`The provider route ${t.providerSlug} did not identify one endpoint.`);let o=a[0];if(o===void 0)return{kind:"failed",code:"invalid-metadata",message:"Endpoint metadata was malformed."};let d=ia(o.model_id);if(d!==t.modelId)return na("model-mismatch","OpenRouter metadata did not preserve the configured exact model identifier.");let c=Array.isArray(o.supported_parameters)?o.supported_parameters.map(ia):[];if(c.includes(void 0))return{kind:"failed",code:"invalid-metadata",message:"Supported parameters were malformed."};if(!c.includes("structured_outputs"))return na("structured-output-unsupported","The exact endpoint does not advertise structured output support.");let l=sa(o.context_length),u=bm(o.max_prompt_tokens),p=bm(o.max_completion_tokens),f=RT(o.pricing),h=typeof o.status=="number"?o.status:void 0;return l===void 0||u===null||p===null||f===void 0||h===void 0||!Number.isFinite(h)?{kind:"failed",code:"invalid-metadata",message:"Endpoint limits or pricing were malformed."}:h!==0?{kind:"unavailable",code:"endpoint-unavailable",message:"The exact endpoint is not currently marked available."}:{kind:"available",endpoint:{providerName:ia(o.provider_name)??t.providerSlug,providerSlug:vm(o)??t.providerSlug,modelId:d,contextLength:l,...u===void 0?{}:{maxPromptTokens:u},...p===void 0?{}:{maxCompletionTokens:p},supportedParameters:c,pricing:f,status:h}}}function TT(r){return{...r.prompt===void 0?{}:{prompt:r.prompt},...r.completion===void 0?{}:{completion:r.completion},...r.request===void 0?{}:{request:r.request},...r.minPromptTokens===void 0?{}:{minPromptTokens:r.minPromptTokens},...r.utcStart===void 0?{}:{utcStart:String(r.utcStart)},...r.utcEnd===void 0?{}:{utcEnd:String(r.utcEnd)},...r.utcDays===void 0?{}:{utcDays:r.utcDays}}}function Cc(r){let t={prompt:r.pricing.prompt,completion:r.pricing.completion,...r.pricing.request===void 0?{}:{request:r.pricing.request},overrides:r.pricing.overrides.map(TT)};return{modelId:r.modelId,providerId:r.providerSlug,providerName:r.providerName,contextLength:r.contextLength,...r.maxPromptTokens===void 0?{}:{maxPromptTokens:r.maxPromptTokens},...r.maxCompletionTokens===void 0?{}:{maxCompletionTokens:r.maxCompletionTokens},supportedParameters:r.supportedParameters,status:r.status,pricing:t}}var AT="https://openrouter.ai",ST=`${AT}/api/v1`,ET=3e4,CT=4*1024*1024;function Tt(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function oi(r){if(r instanceof DOMException&&(r.name==="AbortError"||r.name==="TimeoutError"))return"timed out";let t=r?.cause;return typeof t?.code=="string"?t.code:typeof t?.message=="string"?t.message:r instanceof Error?r.message:"unknown error"}function Nc(r,t){return r!==void 0&&Number.isInteger(r)&&r>0?r:t}function NT(r){let t=r.split("/");if(!(t.length!==2||t.some(e=>e.length===0)))return t.map(encodeURIComponent).join("/")}function km(r){let t=r();return t===void 0||t.trim().length===0?void 0:t.trim()}async function Im(r,t){let e=r.headers.get("content-length");if(e!==null){let d=Number(e);if(Number.isFinite(d)&&d>t)return{kind:"too-large"}}if(r.body===null)return{kind:"invalid-json"};let n=r.body.getReader(),i=[],s=0;try{for(;;){let d=await n.read();if(d.done)break;if(s+=d.value.byteLength,s>t)return await n.cancel(),{kind:"too-large"};i.push(d.value)}}finally{n.releaseLock()}let a=new Uint8Array(s),o=0;for(let d of i)a.set(d,o),o+=d.byteLength;try{return{kind:"parsed",value:JSON.parse(new TextDecoder().decode(a))}}catch{return{kind:"invalid-json"}}}function aa(r){if(!Tt(r)||!Tt(r.error))return;let t=r.error.code;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Oc(r,t){let e=Tt(t)&&Tt(t.error)?t.error:void 0,n=Tt(e?.metadata)?e.metadata:void 0,i=[e?.message,n?.raw].filter(a=>typeof a=="string"&&a.trim()!=="").map(a=>a.replace(/\s+/g," ").trim()).join(": "),s=i.length>300?`${i.slice(0,299)}\u2026`:i;return`OpenRouter completion request failed (HTTP ${r})${s===""?".":`: ${s}`}`}function Dc(r){return Tt(r)&&Tt(r.error)&&r.choices===void 0}function Pm(r){return{Accept:"application/json",Authorization:`Bearer ${r}`}}function Lc(r){if(r.body.model!==r.route.modelId)return"The completion body does not preserve the configured exact model.";if("models"in r.body)return"Model fallback arrays are forbidden.";if("tools"in r.body||"tool_choice"in r.body)return"Model tools are forbidden for bounded diagnosis.";if(r.body.stream===!0)return"Streaming is not supported by bounded diagnosis.";let t=Tt(r.body.provider)?r.body.provider:void 0,e=Array.isArray(t?.only)?t.only:void 0;if(e?.length!==1||e[0]!==r.route.providerSlug||t?.allow_fallbacks!==!1||t.require_parameters!==!0)return"The completion body does not preserve the exact no-fallback provider route.";if((Tt(r.body.response_format)?r.body.response_format:void 0)?.type!=="json_schema")return"The completion body does not require JSON Schema output."}var fr=class{#e;#r;#t;#n;#i;#s;#a;#o;constructor(t={}){this.#e=t.fetch??fetch,this.#r=Nc(t.timeoutMs,ET),this.#t=Nc(t.maxResponseBytes,CT),this.#n=t.apiRoot??ST,this.#i=t.readApiKey??(()=>process.env.OPENROUTER_API_KEY),this.#s=t.credentialName??"OPENROUTER_API_KEY",this.#a=t.extraHeaders??(()=>({})),this.#o=t.onCompletionBody??(()=>{})}async preflight(t){let e=await this.#d(t);return e.kind==="failed"&&(e.code==="network-error"||e.code==="timeout")?this.#d(t):e}async#d(t){let e=NT(t.modelId);if(e===void 0||t.providerSlug.trim().length===0)return{kind:"failed",code:"invalid-request",message:"An exact model and provider route are required."};let n=km(this.#i);if(n===void 0)return{kind:"failed",code:"credential-unavailable",message:`${this.#s} is not configured.`};let i=new AbortController,s=setTimeout(()=>i.abort(),this.#r);try{let a=await this.#e(`${this.#n}/models/${e}/endpoints`,{method:"GET",headers:{...this.#a(),...Pm(n)},redirect:"error",signal:i.signal}),o=await Im(a,this.#t);return o.kind!=="parsed"?{kind:"failed",code:o.kind==="too-large"?"response-too-large":"invalid-json",message:"OpenRouter endpoint metadata could not be read safely.",httpStatus:a.status}:a.ok?Ec(o.value,t):{kind:"failed",code:"http-error",message:"OpenRouter endpoint metadata request failed.",httpStatus:a.status}}catch(a){return{kind:"failed",code:a instanceof DOMException&&a.name==="AbortError"?"timeout":"network-error",message:`OpenRouter endpoint metadata request did not complete (${oi(a)}).`}}finally{clearTimeout(s)}}async complete(t){let e=performance.now(),n=Lc(t);if(n!==void 0)return{kind:"failed",code:"invalid-request",message:n,elapsedMs:0};let i=km(this.#i);if(i===void 0)return{kind:"failed",code:"credential-unavailable",message:`${this.#s} is not configured.`,elapsedMs:performance.now()-e};let s=Nc(t.timeoutMs,this.#r),a=new AbortController,o=setTimeout(()=>a.abort(),s);try{let d=await this.#e(`${this.#n}/chat/completions`,{method:"POST",headers:{...this.#a(t.body),...Pm(i),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(t.body),redirect:"error",signal:a.signal}),c=await Im(d,this.#t),l=performance.now()-e;if(c.kind!=="parsed")return{kind:"failed",code:c.kind==="too-large"?"response-too-large":"invalid-json",message:"OpenRouter completion response could not be read safely.",httpStatus:d.status,elapsedMs:l};if(!d.ok||Dc(c.value)){let u=aa(c.value),p=d.ok?u??502:d.status;return{kind:"failed",code:"http-error",message:Oc(p,c.value),httpStatus:p,...u===void 0?{}:{providerCode:u},elapsedMs:l}}return this.#o(c.value),{kind:"response",httpStatus:d.status,body:c.value,elapsedMs:l}}catch(d){return{kind:"failed",code:d instanceof DOMException&&d.name==="AbortError"?"timeout":"network-error",message:"OpenRouter completion request did not complete.",elapsedMs:performance.now()-e}}finally{clearTimeout(o)}}};var hr={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},OT={type:"object",additionalProperties:!1,required:["hypothesisId","rank","causalCategory","probableOwner","evidenceGrade","supportingEvidenceIds","contradictingEvidenceIds","missingEvidence","unresolvedAssumptions","nextAction","statement"],properties:{hypothesisId:{type:"string",minLength:1},rank:{type:"integer",minimum:1,maximum:3},causalCategory:{type:"string",minLength:1},probableOwner:{type:"string",enum:["test-support","application","environment","undetermined"]},evidenceGrade:{type:"string",enum:["strong","moderate","weak","insufficient"]},supportingEvidenceIds:hr,contradictingEvidenceIds:hr,missingEvidence:hr,unresolvedAssumptions:hr,nextAction:{type:"string",minLength:1},statement:{type:"string",minLength:1}}},Mc={type:"object",additionalProperties:!1,required:["status","hypotheses","symptomIds","missingEvidence","recommendedNextAction","repairEligibility","ownershipEvidenceIds","packetHash"],properties:{status:{type:"string",enum:["conclusive","probable","inconclusive"]},hypotheses:{type:"array",items:OT,maxItems:3},symptomIds:hr,missingEvidence:hr,recommendedNextAction:{type:"string",minLength:1},repairEligibility:{type:"string",enum:["eligible","ineligible","undetermined"]},ownershipEvidenceIds:hr,packetHash:{type:"string",minLength:1}}},DT=["status","hypotheses","symptomIds","missingEvidence","recommendedNextAction","repairEligibility","ownershipEvidenceIds","packetHash"],LT=["hypothesisId","rank","causalCategory","probableOwner","evidenceGrade","supportingEvidenceIds","contradictingEvidenceIds","missingEvidence","unresolvedAssumptions","nextAction","statement"],MT=new Set(["conclusive","probable","inconclusive"]),$T=new Set(["strong","moderate","weak","insufficient"]),_T=new Set(["test-support","application","environment","undetermined"]),FT=new Set(["eligible","ineligible","undetermined"]);function Yr(r){if(r===null||typeof r!="object"||Array.isArray(r))return!1;let t=Object.getPrototypeOf(r);return t===Object.prototype||t===null}function ae(r,t,e,n){r.push({path:t,code:e,message:n})}function Qr(r,t,e,n){let i=new Set(t);for(let s of t)Object.hasOwn(r,s)||ae(n,`${e}.${s}`,"missing-field","field is required");for(let s of Object.keys(r))i.has(s)||ae(n,`${e}.${s}`,"unknown-field","field is not allowed")}function Me(r,t,e){if(typeof r!="string"){ae(e,t,"expected-string","expected a string");return}if(r.trim()===""){ae(e,t,"empty-string","string must not be empty");return}return r}function Xr(r,t,e,n){let i=Me(r,e,n);if(i!==void 0){if(!t.has(i)){ae(n,e,"invalid-enum",`unsupported value ${JSON.stringify(i)}`);return}return i}}function Je(r,t,e){if(!Array.isArray(r)){ae(e,t,"expected-array","expected an array");return}let n=[],i=new Set;return r.forEach((s,a)=>{let o=Me(s,`${t}[${a}]`,e);if(o!==void 0){if(i.has(o)){ae(e,`${t}[${a}]`,"duplicate-item",`duplicate value ${JSON.stringify(o)}`);return}i.add(o),n.push(o)}}),n}function jT(r,t,e){let n=`$.hypotheses[${t}]`;if(!Yr(r)){ae(e,n,"expected-object","expected an object");return}Qr(r,LT,n,e);let i=Me(r.hypothesisId,`${n}.hypothesisId`,e),s=r.rank;!Number.isInteger(s)||typeof s!="number"?ae(e,`${n}.rank`,"expected-integer","rank must be an integer"):(s<1||s>3)&&ae(e,`${n}.rank`,"invalid-rank","rank must be between 1 and 3");let a=Me(r.causalCategory,`${n}.causalCategory`,e),o=Xr(r.probableOwner,_T,`${n}.probableOwner`,e),d=Xr(r.evidenceGrade,$T,`${n}.evidenceGrade`,e),c=Je(r.supportingEvidenceIds,`${n}.supportingEvidenceIds`,e),l=Je(r.contradictingEvidenceIds,`${n}.contradictingEvidenceIds`,e),u=Je(r.missingEvidence,`${n}.missingEvidence`,e),p=Je(r.unresolvedAssumptions,`${n}.unresolvedAssumptions`,e),f=Me(r.nextAction,`${n}.nextAction`,e),h=Me(r.statement,`${n}.statement`,e);if(c!==void 0&&l!==void 0){let g=new Set(l);for(let m of c)g.has(m)&&ae(e,`${n}.contradictingEvidenceIds`,"citation-overlap",`${m} cannot both support and contradict a hypothesis`)}if(d!==void 0&&d!=="insufficient"&&c?.length===0&&ae(e,`${n}.supportingEvidenceIds`,"support-required",`${d} evidence requires at least one supporting citation`),!(i===void 0||typeof s!="number"||!Number.isInteger(s)||s<1||s>3||a===void 0||o===void 0||d===void 0||c===void 0||l===void 0||u===void 0||p===void 0||f===void 0||h===void 0))return{hypothesisId:i,rank:s,causalCategory:a,probableOwner:o,evidenceGrade:d,supportingEvidenceIds:c,contradictingEvidenceIds:l,missingEvidence:u,unresolvedAssumptions:p,nextAction:f,statement:h}}function oa(r){let t=[];if(!Yr(r))return{kind:"invalid",issues:[{path:"$",code:"expected-object",message:"diagnosis must be an object"}]};Qr(r,DT,"$",t);let e=Xr(r.status,MT,"$.status",t),n=[];Array.isArray(r.hypotheses)?(r.hypotheses.length>3&&ae(t,"$.hypotheses","too-many-items","at most three hypotheses are allowed"),r.hypotheses.forEach((p,f)=>{let h=jT(p,f,t);h!==void 0&&n.push(h)})):ae(t,"$.hypotheses","expected-array","expected an array");let i=new Set;for(let p of n)i.has(p.hypothesisId)&&ae(t,"$.hypotheses","duplicate-id",`duplicate hypothesis id ${JSON.stringify(p.hypothesisId)}`),i.add(p.hypothesisId);[...n].map(p=>p.rank).sort((p,f)=>p-f).forEach((p,f)=>{p!==f+1&&ae(t,"$.hypotheses","invalid-rank","hypothesis ranks must be contiguous from 1")});let a=Je(r.symptomIds,"$.symptomIds",t),o=Je(r.missingEvidence,"$.missingEvidence",t),d=Me(r.recommendedNextAction,"$.recommendedNextAction",t),c=Xr(r.repairEligibility,FT,"$.repairEligibility",t),l=Je(r.ownershipEvidenceIds,"$.ownershipEvidenceIds",t),u=Me(r.packetHash,"$.packetHash",t);return t.length>0||e===void 0||a===void 0||o===void 0||d===void 0||c===void 0||l===void 0||u===void 0?{kind:"invalid",issues:t}:{kind:"valid",diagnosis:{status:e,hypotheses:n,symptomIds:a,missingEvidence:o,recommendedNextAction:d,repairEligibility:c,ownershipEvidenceIds:l,packetHash:u}}}function pt(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0}function da(r){return typeof r=="string"&&r.trim().length>0?r:void 0}function mr(r){return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:void 0}function BT(r){if(r===void 0)return{valid:!0};let t=pt(r);if(t===void 0)return{valid:!1};let e=mr(t.prompt_tokens),n=mr(t.completion_tokens),i=mr(t.total_tokens);if(e===void 0||n===void 0||i===void 0)return{valid:!1};let s=pt(t.completion_tokens_details),a=pt(t.prompt_tokens_details),o=pt(t.cost_details),d=mr(s?.reasoning_tokens),c=mr(a?.cached_tokens),l=mr(t.cost),u=mr(o?.upstream_inference_cost);return i!==e+n||d!==void 0&&d>n||c!==void 0&&c>e||t.completion_tokens_details!==void 0&&s===void 0||t.prompt_tokens_details!==void 0&&a===void 0||t.cost_details!==void 0&&o===void 0||s?.reasoning_tokens!==void 0&&d===void 0||a?.cached_tokens!==void 0&&c===void 0||t.cost!==void 0&&l===void 0||o?.upstream_inference_cost!==void 0&&u===void 0?{valid:!1}:{valid:!0,usage:{promptTokens:e,completionTokens:n,totalTokens:i,...d===void 0?{}:{reasoningTokens:d},...c===void 0?{}:{cachedTokens:c},...l===void 0?{}:{cost:l},...u===void 0?{}:{upstreamInferenceCost:u}}}}function VT(r){let e=pt(r?.endpoints)?.available;if(!Array.isArray(e))return;let n=e.map(pt).filter(i=>i!==void 0&&i.selected===!0);return n.length!==1?null:da(n[0]?.provider)??null}function Rm(r,t,e){let n=pt(r),i=da(n?.model),s=n?.choices;if(n===void 0||i===void 0||!Array.isArray(s))return{kind:"malformed-response",message:"Completion response fields were malformed."};if(s.length!==1)return{kind:"malformed-response",message:"Completion response must contain exactly one choice."};let a=pt(s[0]),o=pt(a?.message),d=da(a?.finish_reason);if(o===void 0||d===void 0)return{kind:"malformed-response",message:"Completion choice was malformed."};if("tool_calls"in o||"function_call"in o)return{kind:"malformed-response",message:`Tool calls are forbidden in ${t} output.`};if(o.refusal!==void 0&&o.refusal!==null)return{kind:"provider-refusal",message:`The provider refused the ${t} request.`};if(d!=="stop")return{kind:"provider-refusal",message:`The provider did not complete the structured response (${d}).`};let c=da(o.content);if(c===void 0)return{kind:"malformed-response",message:`Structured ${t} content was missing.`};let l;try{l=JSON.parse(c)}catch{return{kind:"malformed-response",message:`Structured ${t} was not valid JSON.`}}let u=e(l);if(u.kind!=="valid")return{kind:"schema-invalid",message:u.message};let p=pt(n.openrouter_metadata),f=VT(p);if(f===null)return{kind:"malformed-response",message:"Router metadata did not identify exactly one selected provider."};let h=BT(n.usage);return h.valid?{kind:"parsed",value:{output:u.output,reportedModel:i,...f===void 0?{}:{reportedProvider:f},...h.usage===void 0?{}:{usage:h.usage},finishReason:d}}:{kind:"malformed-response",message:"Completion usage metadata was malformed."}}var zT=new Set(["$defs","$ref","additionalProperties","anyOf","const","definitions","description","enum","exclusiveMaximum","exclusiveMinimum","format","items","maxItems","maximum","minItems","minimum","multipleOf","pattern","properties","required","title","type"]),HT=new Set(["$defs","definitions","properties"]);function Tm(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function ca(r){return Array.isArray(r)?r.map(ca):Tm(r)?Object.fromEntries(Object.entries(r).filter(([t])=>zT.has(t)).map(([t,e])=>[t,HT.has(t)&&Tm(e)?Object.fromEntries(Object.entries(e).map(([n,i])=>[n,ca(i)])):t==="enum"||t==="const"||t==="required"?e:ca(e)])):r}function Am(r,t){return t.startsWith("openai/")?ca(r):r}var qT=`You diagnose end-to-end test failures from one bounded, redacted evidence packet. The packet's framework field says whether the tests run in Playwright, Cypress, or WebdriverIO; read errors, commands, and locators in that framework's terms.
66
66
  Deterministic observations are authoritative; your output contains causal hypotheses, not new facts.
67
67
  Cite only supplied evidence, artifact, and symptom IDs. State contradictions, missing evidence, and assumptions.
68
68
  Return no more than three ranked hypotheses and abstain with an inconclusive diagnosis when evidence cannot rank a cause.
69
69
  Owner and repair eligibility require positive cited evidence; absence of application evidence proves nothing.
70
70
  Diff evidence holds recent commits and uncommitted changes whose changed lines mention this failure, each with its commit subject, and a change-search item says what was searched and lists the searched commits' subjects. A deliberate application change that produces the new behaviour (a renamed, moved, or removed element, or new copy or data, in a commit that describes that change) is positive evidence that the test is out of date. A change that breaks what the test checks without describing an intended change points to the application. Recency alone, or finding no related change, is never ownership proof.
71
- You have no tools, filesystem, shell, repository access, commands, or external lookup. Return only the required JSON object.`;function hr(r,t){return[...r].sort((e,n)=>t(e).localeCompare(t(n)))}function BT(r){return{gitRootAvailable:r.workspace.gitRoot!==void 0,sourceHashes:r.sourceHashes}}function Cc(r){return r.replaceAll("\\","/").split("/").filter(Boolean).at(-1)??"<path>"}function vm(r){return r.type==="source-range"||r.type==="diff-hunk"?{...r,path:Cc(r.path)}:r.type==="report-field"?{...r,path:r.path.startsWith("/")?Cc(r.path):r.path}:r}function Nc(r){return hr(r,t=>t.artifactId).map(t=>({artifactId:t.artifactId,channel:t.channel,availability:t.availability,...t.sha256===void 0?{}:{sha256:t.sha256},...t.format===void 0?{}:{format:t.format},...t.producerVersion===void 0?{}:{producerVersion:t.producerVersion},...t.attemptId===void 0?{}:{attemptId:t.attemptId},warnings:t.warnings}))}function Oc(r){return hr(r,t=>t.evidenceId).map(t=>({...t,locator:vm(t.locator)}))}function VT(r){return hr(r.omissions,t=>t.omissionId).map(t=>({omissionId:t.omissionId,channel:t.channel,reason:t.reason,message:t.message,...t.locator===void 0?{}:{locator:Cc(t.locator)},...t.cap===void 0?{}:{cap:t.cap}}))}function zT(r,t,e){return{requestSchemaVersion:"1.0",promptVersion:"1.1",outputSchemaVersion:"1.0",runId:r.runId,packetHash:r.packetHash,framework:r.framework??"playwright",workspace:BT(r),artifacts:Nc(r.artifacts),evidence:Oc(r.evidence),omissions:VT(r),accounting:hr(r.accounting,n=>n.channel),symptoms:hr(t.symptoms,n=>n.symptomId),unclassifiedAttemptIds:[...t.unclassifiedAttemptIds].sort(),clusters:hr(e.clusters,n=>n.clusterId)}}function HT(r,t,e,n,i){let s=new Map(r.artifacts.map(o=>[o.artifactId,o.channel])),a=new Set(t.artifactIds);return{schemaVersion:"1.1",runId:r.runId,packetHash:r.packetHash,payloadHash:n,purpose:t.purpose,model:e,promptVersion:t.promptVersion,outputSchemaVersion:t.outputSchemaVersion,evidence:hr(t.evidence,o=>o.evidenceId).map(o=>({evidenceId:o.evidenceId,artifactId:o.artifactId,channel:s.get(o.artifactId)??"report",locator:vm(o.locator),...o.logicalTestId===void 0?{}:{logicalTestId:o.logicalTestId},...o.attemptId===void 0?{}:{attemptId:o.attemptId},redactionIds:[...o.redactionIds].sort()})),artifactIds:[...t.artifactIds].sort(),symptomIds:[...t.symptomIds].sort(),clusterIds:[...t.clusterIds].sort(),omissionIds:[...t.omissionIds].sort(),redactionIds:[...t.redactionIds].sort(),channels:[...new Set(r.artifacts.filter(o=>a.has(o.artifactId)).map(o=>o.channel))].sort(),serializedBytes:i}}function Dc(r,t,e,n){let i={model:e.modelId,messages:[{role:"system",content:t.systemPrompt},{role:"user",content:de(t.userContent)}],max_completion_tokens:n,...e.reasoningEffort===void 0?{}:{reasoning:{effort:e.reasoningEffort,exclude:!0}},response_format:{type:"json_schema",json_schema:{name:t.schemaName,strict:!0,schema:bm(t.schema,e.modelId)}},provider:{only:[e.providerId],allow_fallbacks:!1,require_parameters:!0,...e.zeroDataRetention===!0?{zdr:!0}:{},max_price:{prompt:0,completion:0,request:0}}},s=de(i),a=C(i);return{body:i,canonicalBody:s,payloadHash:a,manifest:HT(r,t,e,a,Buffer.byteLength(s,"utf8")),manifestHash:""}}function Lc(r,t,e,n,i){return Dc(r,{purpose:"diagnosis",schemaName:"kwikqa_diagnosis",schema:Ec,systemPrompt:jT,promptVersion:"1.1",outputSchemaVersion:"1.0",userContent:zT(r,t,e),evidence:r.evidence,artifactIds:r.artifacts.map(s=>s.artifactId),symptomIds:t.symptoms.map(s=>s.symptomId),clusterIds:e.clusters.map(s=>s.clusterId),omissionIds:r.omissions.map(s=>s.omissionId),redactionIds:r.redactions.map(s=>s.redactionId)},n,i)}function Mc(r,t){let e={...r.body,provider:{...r.body.provider,max_price:{prompt:t.promptDollarsPerToken*1e6,completion:t.completionDollarsPerToken*1e6,request:t.fixedRequestDollars}}},n=de(e),i=C(e),s={...r.manifest,payloadHash:i,serializedBytes:Buffer.byteLength(n,"utf8")};return{body:e,canonicalBody:n,payloadHash:i,manifest:s,manifestHash:C(s)}}var qT=[[/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,"<uuid>"],[/\b0x[0-9a-f]+\b/gi,"<hex>"],[/\b[0-9a-f]{16,}\b/gi,"<hex>"],[/\d+(?:\.\d+)?\s*(?:ms|milliseconds?)\b/gi,"<duration>"],[/\d+(?:\.\d+)?\s*(?:s|seconds?)\b/gi,"<duration>"],[/:\d+:\d+\b/g,":<line>:<col>"],[/\b(?:localhost|127\.0\.0\.1|\[::1\])(:\d+)?/gi,"<localhost>"],[/:\d{2,5}\b/g,":<port>"],[/\b\d+\b/g,"<n>"]];function si(r){return r.replace(/\\/g,"/").replace(/^[A-Za-z]:/,"").split("/").filter(n=>n.length>0).slice(-2).join("/")}function oa(r,t=200){let e=r.replace(/\r\n/g,`
72
- `).replace(/(?:file:\/\/)?(?:[A-Za-z]:)?(?:\/[\w.@+-]+){2,}/g,n=>si(n));for(let[n,i]of qT)e=e.replace(n,i);return e=e.replace(/\s+/g," ").trim().toLowerCase(),e.length<=t?e:e.slice(0,t)}function km(r){return r.replace(/['`]/g,'"').replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/\{\s*/g,"{ ").replace(/\s*\}/g," }").trim()}function ai(r,t){return`${si(r)}:${t}`}var Qr=["error-field","stack-frame","step"],Im=["error-field","stack-frame"],$c=["trace-event","console-event"];function _t(r,t,e){return r.evidence.filter(n=>{if(!t.includes(n.kind))return!1;let i=r.normalized.get(n.evidenceId)??"";return e.some(s=>s.test(i))})}function UT(r,t,e){return r.evidence.filter(n=>t.includes(n.kind)&&e.some(i=>i.test(n.observation)))}var GT=[/timeouterror/,/timeout of <duration> exceeded/,/timeout <duration> exceeded/,/exceeded.{0,40}timeout/,/timed out/,/still not (?:existing|displayed|clickable|enabled|visible|selected) after/,/because element wasn't found/],KT=[/\bexpect\(/,/\bassertion\b/,/\bexpect \$\$?\(/,/\bexpected .{0,200} to (?:have|be|equal|eq|contain|include|exist|match|deep)\b/],WT=[/expected:.{0,80}received:/s,/received:.{0,80}expected:/s],JT=[/uncaught \w*error/,/\bpageerror\b/,/unhandled (?:promise )?rejection/,/uncaught page error/,/originated from your application code/],XT=[/net::err_/,/navigation timeout/,/failed to navigate/,/navigation failed/,/err_(?:aborted|connection|name_not_resolved|empty_response|ssl)/,/cy\.visit\(\) failed/,/failed trying to load/],YT=[/target (?:page, context or browser )?(?:has been )?closed/,/browser has been closed/,/page crashed/,/target closed/,/browser closed unexpectedly/,/invalid session id/,/session deleted because of page crash/,/chrome not reachable/,/renderer process (?:just )?crashed/,/browser process (?:just )?crashed/],QT=[/cy\.request\(\) failed/,/response we received from your web server was/,/request failed with status code/],ZT=[/"(?:before|after) (?:each|all)" hook/,/\bglobal (?:setup|teardown)\b/,/\bteardown\b/,/\bin (?:before|after)(?:each|all)? hook\b/,/\bbefore hooks\b/,/\bafter hooks\b/,/\bbeforeall\b/,/\bbeforeeach\b/,/\bafterall\b/,/\baftereach\b/,/\bfixture\b/],_c=[{ruleId:"action-timeout/timeout-text",category:"action-timeout",description:"Failure text reports an expired action, element wait, or test timeout.",match:r=>_t(r,Qr,GT)},{ruleId:"action-timeout/timed-out-status",category:"action-timeout",description:"The attempt status is timedOut and failure text is present to cite.",match:r=>r.attempt?.status==="timedOut"?r.evidence.filter(t=>t.kind==="error-field"):[]},{ruleId:"assertion-mismatch/expect-failure",category:"assertion-mismatch",description:"Failure text reports an expectation that did not hold.",match:r=>{let t=_t(r,Qr,KT);return t.length>0?t:_t(r,Qr,WT)}},{ruleId:"page-exception/uncaught-error",category:"page-exception",description:"An uncaught page error or unhandled rejection was observed.",match:r=>_t(r,[...Qr,...$c],JT)},{ruleId:"navigation-failure/net-error",category:"navigation-failure",description:"Navigation reported a network-level or navigation timeout error.",match:r=>_t(r,[...Qr,...$c],XT)},{ruleId:"http-failure/error-status",category:"http-failure",description:"A recorded request returned a 4xx or 5xx status, or reported a failure.",match:r=>UT(r,["network-event"],[/-> [45]\d\d\b/,/\bfailure=/])},{ruleId:"http-failure/request-error",category:"http-failure",description:"Failure text reports a request the test made that returned an error status.",match:r=>_t(r,Im,QT)},{ruleId:"browser-crash/target-closed",category:"browser-crash",description:"The page, context, or browser was closed or crashed during the attempt.",match:r=>_t(r,[...Qr,...$c],YT)},{ruleId:"setup-failure/hook-or-fixture",category:"setup-failure",description:"The failure is attributed to a hook or fixture rather than the test body.",match:r=>_t(r,Im,ZT)}];var Am={"action-timeout":"Action timeout","assertion-mismatch":"Assertion mismatch","page-exception":"Page exception","navigation-failure":"Navigation failure","http-failure":"HTTP failure","browser-crash":"Browser crash","setup-failure":"Setup failure","artifact-failure":"Artifact failure",unclassified:"Unclassified failure"},eA=new Set(["failed","timedOut","interrupted"]),Pm=160;function Sm(r){let t=r.replace(/\s+/g," ").trim();return t.length<=Pm?t:`${t.slice(0,Pm)}\u2026`}function tA(r){for(let t of r){if(t.kind!=="trace-event")continue;let n=/^action(?: started| finished)?: ([\w.]+)/.exec(t.observation)?.[1];if(n!==void 0&&n!=="unknown")return n}}function rA(r){for(let t of r){if(t.kind!=="network-event")continue;let e=/^(\w+) (\S+) -> (\d{3})/.exec(t.observation);if(e===null)continue;let[,n,i,s]=e;if(n===void 0||i===void 0||s===void 0)continue;let a=i;try{a=new URL(i).host}catch{}return`${n} ${a} -> ${s}`}}function nA(r,t){if(r?.errorLocation!==void 0)return ai(r.errorLocation.file,r.errorLocation.line??1);for(let e of t)if(e.locator.type==="source-range")return ai(e.locator.path,e.locator.startLine);for(let e of t){if(e.kind!=="stack-frame")continue;let n=/([^\s():]+):(\d+):\d+/.exec(e.observation),i=n?.[1],s=n?.[2];if(i!==void 0&&s!==void 0)return ai(i,Number.parseInt(s,10))}}function Em(r){let t=e=>r.find(n=>n.kind==="error-field"&&n.locator.type==="report-field"&&n.locator.path.endsWith(e));return t(".message")??t(".value")??r.find(e=>e.kind==="error-field")??r[0]}function iA(r,t,e){let n=Em(t),i=n===void 0?void 0:oa(n.observation),s=nA(r,t),a=tA(t),o=rA(t),[d]=r===void 0?[]:Vn(r),c=d===void 0?void 0:km(d),l=s!==void 0&&e!==void 0&&!s.startsWith(`${si(e)}:`)?s:void 0;return{...i===void 0||i===""?{}:{errorFingerprint:i},...s===void 0?{}:{sourceLocation:s},...a===void 0?{}:{actionApi:a},...o===void 0?{}:{networkEndpoint:o},...c===void 0||c===""?{}:{targetLocator:c},...l===void 0?{}:{supportLocation:l}}}function da(r,t,e,n,i){let s=[...new Set(n.map(c=>c.evidenceId))].sort(),a=iA(i.attempt,n,i.specFile),o=Em(n),d=i.attempt?.attemptId??"run";return{symptomId:$("sym",[r,d,t,a.errorFingerprint??""]),category:t,ruleId:e,...i.logicalTestId===void 0?{}:{logicalTestId:i.logicalTestId},...i.attempt===void 0?{}:{attemptId:i.attempt.attemptId},evidenceIds:s,artifactIds:[],summary:`${Am[t]}: ${Sm(o?.observation??"")}`,signals:a}}function Rm(r){let t=new Map;for(let e of _c){let n=e.match(r);if(n.length===0)continue;let i=t.get(e.category);i===void 0?t.set(e.category,{ruleId:e.ruleId,cited:[...n]}):i.cited.push(...n)}return t}function Tm(r){return new Map(r.map(t=>[t.evidenceId,oa(t.observation,400)]))}function la(r,t){let e=new Map;for(let s of t.evidence){if(s.attemptId===void 0)continue;let a=e.get(s.attemptId);a===void 0?e.set(s.attemptId,[s]):a.push(s)}let n=[],i=[];for(let s of r.logicalTests)for(let a of s.attempts){if(!eA.has(a.status))continue;let o=e.get(a.attemptId)??[],d={attempt:a,evidence:o,normalized:Tm(o)},c=Rm(d);if(c.size===0){if(o.length===0){i.push(a.attemptId);continue}n.push(da(r.runId,"unclassified","unclassified/no-rule-matched",o.filter(l=>l.kind==="error-field").slice(0,3),{logicalTestId:s.logicalTestId,attempt:a,specFile:s.location.file}));continue}for(let[l,{ruleId:u,cited:p}]of c)n.push(da(r.runId,l,u,p,{logicalTestId:s.logicalTestId,attempt:a,specFile:s.location.file}))}if(r.reportErrors.length>0){let s=t.evidence.filter(a=>a.attemptId===void 0&&a.logicalTestId===void 0);if(s.length>0){let a=Rm({evidence:s,normalized:Tm(s)});a.size===0&&n.push(da(r.runId,"unclassified","unclassified/no-rule-matched",s.filter(o=>o.kind==="error-field").slice(0,3),{}));for(let[o,{ruleId:d,cited:c}]of a)n.push(da(r.runId,o,d,c,{}))}}for(let s of t.artifacts)s.availability==="unreadable"&&n.push({symptomId:$("sym",[r.runId,s.artifactId,"artifact-failure"]),category:"artifact-failure",ruleId:"artifact-failure/unreadable-artifact",...s.attemptId===void 0?{}:{attemptId:s.attemptId},evidenceIds:[],artifactIds:[s.artifactId],summary:`${Am["artifact-failure"]}: ${s.channel} artifact could not be read${s.warnings[0]===void 0?"":` (${Sm(s.warnings[0])})`}`,signals:{}});return{schemaVersion:"1.0",runId:r.runId,packetHash:t.packetHash,symptoms:[...n].sort((s,a)=>s.symptomId.localeCompare(a.symptomId)),unclassifiedAttemptIds:[...i].sort()}}var sA=new Set(["error-fingerprint","network-endpoint","failing-source-location","target-locator","support-location"]);var Ft="<absent>";function Fc(r,t){switch(t){case"symptom-category":return r.category;case"action-api":return r.signals.actionApi??Ft;case"error-fingerprint":return r.signals.errorFingerprint??Ft;case"network-endpoint":return r.signals.networkEndpoint??Ft;case"failing-source-location":return r.signals.sourceLocation??Ft;case"target-locator":return r.signals.targetLocator??Ft;case"support-location":return r.signals.supportLocation??Ft}}function aA(r,t){if(t.length<2)return{supported:!1,rationale:"A single logical test provides no shared behavior for a common cause."};let e=r.filter(n=>sA.has(n.kind)&&n.value!==Ft);return e.length===0?{supported:!1,rationale:"Members share only broad signals, which group failures by shape rather than by origin."}:{supported:!0,rationale:`Members share ${e.map(n=>`${n.kind}=${n.value}`).join(" and ")}, which is specific enough to be consistent with one cause. This is a statement about evidence specificity, not proof that one cause produced every member.`}}var Cm=["target-locator","support-location","network-endpoint"],Nm=["symptom-category","error-fingerprint"];function jc(r){let t=new Map;for(let i of r.symptoms){if(i.logicalTestId===void 0)continue;let s=t.get(i.logicalTestId);s===void 0?t.set(i.logicalTestId,[i]):s.push(i)}let e=new Map;for(let i of t.values()){let s=[...i].sort((l,u)=>l.symptomId.localeCompare(u.symptomId)),a;for(let l of Cm){let u=s.find(p=>Fc(p,l)!==Ft);if(u!==void 0){a=[{kind:l,value:Fc(u,l)}];break}}let o=s[0];if(a===void 0&&o!==void 0&&(a=Nm.map(l=>({kind:l,value:Fc(o,l)}))),a===void 0)continue;let d=a.map(l=>`${l.kind}=${l.value}`).join("|"),c=e.get(d);c===void 0?e.set(d,{signals:a,members:[...i]}):c.members.push(...i)}let n=[...e.values()].map(({signals:i,members:s})=>{let a=[...new Set(s.map(d=>d.logicalTestId).filter(d=>d!==void 0))].sort(),o=aA(i,a);return{clusterId:$("clu",[r.runId,...i.map(d=>`${d.kind}=${d.value}`)]),logicalTestIds:a,symptomIds:s.map(d=>d.symptomId).sort(),signals:i,commonCauseSupported:o.supported,commonCauseRationale:o.rationale}});return{schemaVersion:"1.0",runId:r.runId,clusters:n.sort((i,s)=>i.clusterId.localeCompare(s.clusterId)),signalKinds:[...Cm,...Nm]}}function le(r,t,e,n,i={}){return{graderId:r,code:t,severity:e,message:n,...i.hypothesisId===void 0?{}:{hypothesisId:i.hypothesisId},...i.reference===void 0?{}:{reference:i.reference}}}function jt(r,t,e){return{graderId:r,passed:!e.some(n=>n.severity==="violation"),checked:t,findings:e}}var oi={insufficient:0,weak:1,moderate:2,strong:3},Bc={graderId:"abstention",description:"Diagnosis status matches evidence strength, and insufficient evidence abstains.",grade:r=>{let t=[],{diagnosis:e}=r,i=[...e.hypotheses].sort((o,d)=>o.rank-d.rank)[0],s=i===void 0?-1:oi[i.evidenceGrade],a=1;return i===void 0||s===oi.insufficient?e.status!=="inconclusive"&&t.push(le("abstention","failed-to-abstain","violation",`Evidence cannot rank a cause, but the diagnosis claims ${e.status}.`)):e.status==="conclusive"&&s<oi.strong?t.push(le("abstention","conclusive-without-strong-evidence","violation",`Diagnosis claims conclusive on ${i.evidenceGrade} evidence.`,{hypothesisId:i.hypothesisId})):e.status==="probable"&&s<oi.moderate&&t.push(le("abstention","probable-without-moderate-evidence","violation",`Diagnosis claims probable on ${i.evidenceGrade} evidence.`,{hypothesisId:i.hypothesisId})),a+=1,e.status==="inconclusive"&&e.repairEligibility==="eligible"&&t.push(le("abstention","repair-eligible-while-inconclusive","violation","Repair was marked eligible while the diagnosis is inconclusive.")),a+=1,e.status==="inconclusive"&&s>=oi.strong&&t.push(le("abstention","abstained-with-strong-evidence","warning","Diagnosis abstained although the leading hypothesis carries strong evidence.",{...i===void 0?{}:{hypothesisId:i.hypothesisId}})),a+=1,e.status==="inconclusive"&&e.missingEvidence.length===0&&t.push(le("abstention","abstained-without-naming-gaps","warning","Diagnosis abstained without naming the evidence that was missing.")),jt("abstention",a,t)}};var Vc={graderId:"citation-validity",description:"Every cited evidence, artifact, and symptom id exists in the graded packet.",grade:r=>{let t=[],e=0;r.diagnosis.packetHash!==r.packetHash&&t.push(le("citation-validity","packet-hash-mismatch","violation","The diagnosis was produced from a different evidence packet than the one being graded.",{reference:r.diagnosis.packetHash}));let n=s=>r.evidenceIds.has(s)||r.artifactIds.has(s),i=[["ownershipEvidenceIds",r.diagnosis.ownershipEvidenceIds,void 0],...r.diagnosis.hypotheses.flatMap(s=>[["supportingEvidenceIds",s.supportingEvidenceIds,s.hypothesisId],["contradictingEvidenceIds",s.contradictingEvidenceIds,s.hypothesisId]])];for(let[s,a,o]of i)for(let d of a)e+=1,!n(d)&&t.push(le("citation-validity","unknown-evidence-id","violation",`${s} cites ${d}, which the evidence packet does not contain.`,{...o===void 0?{}:{hypothesisId:o},reference:d}));for(let s of r.diagnosis.symptomIds)e+=1,!r.symptomIds.has(s)&&t.push(le("citation-validity","unknown-symptom-id","violation",`The diagnosis cites symptom ${s}, which this run did not produce.`,{reference:s}));return jt("citation-validity",e,t)}};var oA=new Set(["strong","moderate"]),zc={graderId:"ownership",description:"A named owner rests on cited positive evidence, and eligibility proves it.",grade:r=>{let t=[],{diagnosis:e}=r,n=0;for(let i of e.hypotheses)n+=1,i.probableOwner!=="undetermined"&&i.supportingEvidenceIds.length===0&&t.push(le("ownership","ownership-from-absence","violation",`Hypothesis assigns the ${i.probableOwner} owner without citing any supporting evidence.`,{hypothesisId:i.hypothesisId}));if(e.repairEligibility==="eligible"){n+=1,e.ownershipEvidenceIds.length===0&&t.push(le("ownership","eligible-without-ownership-evidence","violation","Repair was marked eligible without identifying the evidence that proves test-side ownership."));let i=[...e.hypotheses].sort((s,a)=>s.rank-a.rank)[0];i===void 0?t.push(le("ownership","eligible-without-hypothesis","violation","Repair was marked eligible without an accepted hypothesis.")):(i.probableOwner!=="test-support"&&t.push(le("ownership","eligible-without-test-ownership","violation",`Repair was marked eligible while the accepted hypothesis assigns the ${i.probableOwner} owner.`,{hypothesisId:i.hypothesisId})),oA.has(i.evidenceGrade)||t.push(le("ownership","eligible-on-insufficient-grade","violation",`Repair was marked eligible on ${i.evidenceGrade} evidence.`,{hypothesisId:i.hypothesisId})))}return jt("ownership",n,t)}};var dA=/\b(?:evd|art|sym|clu|omi|red)_[a-f0-9]{8,}\b/g,Hc={graderId:"unsupported-claims",description:"Claims are backed by citations, and grades match the evidence offered.",grade:r=>{let t=[],e=0;for(let i of r.diagnosis.hypotheses){e+=1;let{hypothesisId:s,supportingEvidenceIds:a,contradictingEvidenceIds:o}=i;i.evidenceGrade!=="insufficient"&&a.length===0&&t.push(le("unsupported-claims","claim-without-evidence","violation",`Hypothesis is graded ${i.evidenceGrade} but cites no supporting evidence.`,{hypothesisId:s})),i.evidenceGrade==="strong"&&(a.length<2&&t.push(le("unsupported-claims","strong-grade-underspecified","violation","A strong grade requires multiple specific observations, but only one was cited.",{hypothesisId:s})),o.length>0&&t.push(le("unsupported-claims","strong-grade-with-contradiction","violation","A strong grade requires no material unresolved contradiction, but contradicting evidence was cited.",{hypothesisId:s})),i.unresolvedAssumptions.length>0&&t.push(le("unsupported-claims","strong-grade-with-unresolved-assumptions","warning","A strong grade carries unresolved assumptions.",{hypothesisId:s})));let d=a.filter(l=>o.includes(l));for(let l of d)t.push(le("unsupported-claims","contradictory-citation","violation",`Evidence ${l} is cited as both supporting and contradicting the same hypothesis.`,{hypothesisId:s,reference:l}));let c=new Set([...a,...o]);for(let l of[i.statement,i.nextAction])for(let u of l.matchAll(dA)){let p=u[0];e+=1,!c.has(p)&&t.push(le("unsupported-claims","uncited-identifier-in-prose","violation",`Prose references ${p}, which this hypothesis does not cite.`,{hypothesisId:s,reference:p}))}}e+=1;let n=r.diagnosis.hypotheses.map(i=>i.rank);return new Set(n).size!==n.length&&t.push(le("unsupported-claims","duplicate-hypothesis-rank","violation","Hypotheses do not carry a distinct rank, so the accepted hypothesis is ambiguous.")),r.diagnosis.hypotheses.length>3&&t.push(le("unsupported-claims","too-many-hypotheses","violation",`A diagnosis returns at most three ranked hypotheses; ${r.diagnosis.hypotheses.length} were supplied.`)),jt("unsupported-claims",e,t)}};var Dm=[Vc,zc,Bc,Hc];function cA(r){return[...r].sort((t,e)=>{if(t.severity!==e.severity)return t.severity==="violation"?-1:1;let n=t.graderId.localeCompare(e.graderId);if(n!==0)return n;let i=t.code.localeCompare(e.code);return i!==0?i:(t.reference??"").localeCompare(e.reference??"")})}function di(r,t,e){let n={diagnosis:r,evidenceIds:new Set(t.evidence.map(s=>s.evidenceId)),artifactIds:new Set(t.artifacts.map(s=>s.artifactId)),symptomIds:new Set(e.symptoms.map(s=>s.symptomId)),packetHash:t.packetHash},i=Dm.map(s=>s.grade(n));return{schemaVersion:"1.0",packetHash:t.packetHash,passed:i.every(s=>s.passed),outcomes:i,findings:cA(i.flatMap(s=>s.findings))}}function lA(r){let{packetHash:t,...e}=r;return Sr(e)===t}function uA(r){if(!/^[^/\s]+\/[^/\s]+$/.test(r.modelId))return"An exact non-empty author/model identifier is required.";if(r.providerId.trim().length===0)return"An exact provider route is required."}function st(r,t,e,n={}){return wc({runId:r.packet.runId,createdAt:r.packet.createdAt,workspace:r.packet.workspace,sourceHashes:r.packet.sourceHashes,packetHash:r.packet.packetHash,model:r.model,caps:r.caps,recordedAt:t,outcome:e,request:r.request,extra:n})}function it(r,t,e,n,i,s={}){return{kind:e,reasonCode:n,message:i,audit:st(r,t,Ve(e,n,i),s)}}function pA(r,t){if(r.kind==="available")return{kind:"supported",endpoint:Ic(r.endpoint),checkedAt:t};let e=r.code==="structured-output-unsupported"?"schema-capability-unsupported":r.code==="provider-unavailable"||r.code==="model-mismatch"?"model-or-provider-mismatch":r.code==="credential-unavailable"?"credential-unavailable":"preflight-failed";return{kind:r.kind==="failed"?"failed":r.kind,reasonCode:e,message:r.message,checkedAt:t}}async function ua(r){let{identity:t,recordedAt:e}=r,n=uA(t.model)??xc(t.caps);if(n!==void 0)return it(t,e,"blocked","invalid-configuration",n);if(!lA(t.packet))return it(t,e,"blocked","invalid-provenance","The evidence packet contents do not match its packet hash.");if(r.provenanceError!==void 0)return it(t,e,"blocked","invalid-provenance",r.provenanceError);let i=await r.transport.preflight({modelId:t.model.modelId,providerSlug:t.model.providerId}),s=pA(i,e);if(s.kind!=="supported")return it(t,e,s.kind==="failed"?"failed":"blocked",s.reasonCode,s.message,{preflight:s});if(s.endpoint.maxCompletionTokens!==void 0&&t.caps.request.maxOutputTokens>s.endpoint.maxCompletionTokens)return it(t,e,"blocked","context-limit-exceeded","Requested output cap exceeds the exact endpoint limit.",{preflight:s});if(t.model.reasoningEffort!==void 0&&t.model.reasoningEffort!=="none"&&!s.endpoint.supportedParameters.includes("reasoning"))return it(t,e,"blocked","schema-capability-unsupported","The exact endpoint does not support the requested reasoning effort.",{preflight:s});let a=r.buildPayload(t.caps.request.maxOutputTokens),o=Zs(a.canonicalBody,t.caps.request.maxOutputTokens,s.endpoint.pricing);if(o===void 0)return it(t,e,"blocked","pricing-unavailable","A conservative dollar estimate could not be derived from endpoint pricing.",{preflight:s});let d=Mc(a,o),c=Zs(d.canonicalBody,t.caps.request.maxOutputTokens,s.endpoint.pricing);if(c===void 0)return it(t,e,"blocked","estimate-unavailable","A conservative final request estimate could not be computed.",{preflight:s});if(c.estimatedInputTokens+c.estimatedOutputTokens>s.endpoint.contextLength||s.endpoint.maxPromptTokens!==void 0&&c.estimatedInputTokens>s.endpoint.maxPromptTokens)return it(t,e,"blocked","context-limit-exceeded","The conservative request estimate exceeds the exact endpoint context limit.",{preflight:s,estimate:c});let l=vc(c,t.caps);if(l.kind==="blocked")return it(t,e,"blocked",l.reasonCode,l.message,{preflight:s,estimate:c});let u={manifest:d.manifest,manifestHash:d.manifestHash,endpoint:s.endpoint,estimate:c,caps:t.caps},p=Qs(u);return{kind:"ready",prepared:{preflight:s,preparedAt:e,payload:d,estimate:c,preview:yc(u,p),authorizationBindingHash:p}}}function fA(r){return r.code==="credential-unavailable"?"credential-unavailable":"transport-failed"}async function pa(r){let{identity:t,prepared:e,recordedAt:n}=r,i={payloadHash:e.payload.payloadHash,payloadManifestHash:e.payload.manifestHash,authorizationBindingHash:e.authorizationBindingHash,preflight:e.preflight,estimate:e.estimate},s=(f,h,g,m={})=>it(t,n,f,h,g,{...i,...m}),a=Qs({manifest:e.payload.manifest,manifestHash:e.payload.manifestHash,endpoint:e.preflight.endpoint,estimate:e.estimate,caps:t.caps});if(de(e.payload.body)!==e.payload.canonicalBody||C(e.payload.body)!==e.payload.payloadHash||e.payload.manifest.payloadHash!==e.payload.payloadHash||C(e.payload.manifest)!==e.payload.manifestHash||!r.inputsIntact||a!==e.authorizationBindingHash||!gc(r.authorization,a))return s("blocked","authorization-mismatch","Authorization does not match the exact prepared request.");if(!r.authorizationStore.consume(r.authorization.authorizationId,e.authorizationBindingHash))return s("blocked","authorization-replayed","Authorization has already been consumed for this prepared request.");let d=await r.transport.complete({route:{modelId:t.model.modelId,providerSlug:t.model.providerId},body:e.payload.body}),c={mode:r.authorization.mode,authorizationId:r.authorization.authorizationId,authorizedAt:r.authorization.authorizedAt};if(d.kind==="failed")return s("failed",fA(d),d.message,{authorization:c,latencyMs:d.elapsedMs});let l=gm(d.body,r.label,r.validate);if(l.kind!=="parsed")return s("rejected",l.kind,l.message,{authorization:c,latencyMs:d.elapsedMs});let u=l.value.usage===void 0?{}:{usage:l.value.usage};if(l.value.reportedModel!==t.model.modelId)return s("rejected","routed-model-mismatch","Reported model differs from the authorized model.",{authorization:c,reportedModel:l.value.reportedModel,...l.value.reportedProvider===void 0?{}:{reportedProvider:l.value.reportedProvider},latencyMs:d.elapsedMs,...u});if(l.value.reportedProvider===void 0)return s("rejected","routed-provider-mismatch","The completion response did not report the selected provider route.",{authorization:c,reportedModel:l.value.reportedModel,providerProvenance:"unavailable",latencyMs:d.elapsedMs,...u});let p=l.value.reportedProvider.toLocaleLowerCase("en-US");return p!==t.model.providerId.toLocaleLowerCase("en-US")&&p!==e.preflight.endpoint.providerName?.toLocaleLowerCase("en-US")?s("rejected","routed-provider-mismatch","Reported provider differs from the authorized provider.",{authorization:c,reportedModel:l.value.reportedModel,reportedProvider:l.value.reportedProvider,providerProvenance:"reported",latencyMs:d.elapsedMs,...u}):{kind:"parsed",output:l.value.output,audit:{...i,reportedModel:l.value.reportedModel,reportedProvider:l.value.reportedProvider,providerProvenance:"reported",...u,latencyMs:d.elapsedMs,authorization:c}}}var hA={purpose:"diagnosis",promptVersion:"1.1",outputSchemaVersion:"1.0"};function Lm(r){return r??new Date().toISOString()}function Mm(r,t){return C({packet:r,symptoms:t})}function $m(r){return{packet:r.packet,model:r.model,caps:r.caps,request:hA}}async function fa(r){let t=Lm(r.now),e=r.symptoms.runId===r.packet.runId&&r.clusters.runId===r.packet.runId&&r.symptoms.packetHash===r.packet.packetHash,n=await ua({identity:$m(r),transport:r.transport,recordedAt:t,...e?{}:{provenanceError:"M2 and M3 inputs do not identify the same run and packet."},buildPayload:i=>Lc(r.packet,r.symptoms,r.clusters,r.model,i)});return n.kind!=="ready"?{...n,kind:n.kind==="failed"?"failed":"blocked"}:{kind:"preview-ready",prepared:{packet:r.packet,symptoms:r.symptoms,clusters:r.clusters,model:r.model,caps:r.caps,...n.prepared,gradingInputHash:Mm(r.packet,r.symptoms)}}}async function qc(r){let t=Lm(r.now),e=r.prepared,n=$m(e),i=await pa({identity:n,prepared:e,inputsIntact:Mm(e.packet,e.symptoms)===e.gradingInputHash,authorization:r.authorization,authorizationStore:r.authorizationStore,transport:r.transport,recordedAt:t,label:"diagnosis",validate:d=>{let c=ia(d);return c.kind==="valid"?{kind:"valid",output:c.diagnosis}:{kind:"invalid",message:`Diagnosis failed strict schema validation: ${c.issues.map(l=>`${l.path}:${l.code}`).join(", ")}`}}});if(i.kind!=="parsed")return i;let s=i.output,a=di(s,e.packet,e.symptoms),o={...i.audit,grading:a};if(!a.passed){let d="Diagnosis failed deterministic local grading.";return{kind:"rejected",reasonCode:"citation-or-grading-invalid",message:d,audit:st(n,t,Ve("rejected","citation-or-grading-invalid",d),o)}}return s.status==="inconclusive"?{kind:"abstained",reasonCode:"insufficient-evidence",diagnosis:s,grading:a,audit:st(n,t,Ve("abstained","insufficient-evidence"),o)}:{kind:"diagnosed",diagnosis:s,grading:a,audit:st(n,t,Ve("diagnosed"),o)}}var Uc=20,ha={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},_m=["targetEvidenceId","oldText","newText","rationale","evidenceIds","expectedEffect","latencyContractEvidenceIds","brittleLocatorEvidenceIds"],Fm=["statement","preservedBehavior","evidenceIds"],jm=["status","acceptedHypothesisId","declineReason","intent","replacements","packetHash"],Gc={type:"object",additionalProperties:!1,required:jm,properties:{status:{type:"string",enum:["proposed","declined"]},acceptedHypothesisId:{type:"string",minLength:1},declineReason:{type:"string"},intent:{type:"object",additionalProperties:!1,required:Fm,properties:{statement:{type:"string"},preservedBehavior:{type:"string"},evidenceIds:ha}},replacements:{type:"array",maxItems:Uc,items:{type:"object",additionalProperties:!1,required:_m,properties:{targetEvidenceId:{type:"string",minLength:1},oldText:{type:"string",minLength:1},newText:{type:"string"},rationale:{type:"string",minLength:1},evidenceIds:ha,expectedEffect:{type:"string",minLength:1},latencyContractEvidenceIds:ha,brittleLocatorEvidenceIds:ha}}},packetHash:{type:"string",minLength:1}}},mA=new Set(["proposed","declined"]);function ma(r,t,e){if(typeof r=="string")return r;ie(e,t,"expected-string","expected a string")}function yA(r,t,e){let n=`$.replacements[${t}]`;if(!Xr(r)){ie(e,n,"expected-object","replacement must be an object");return}Yr(r,_m,n,e);let i=Me(r.targetEvidenceId,`${n}.targetEvidenceId`,e),s=Me(r.oldText,`${n}.oldText`,e),a=ma(r.newText,`${n}.newText`,e),o=Me(r.rationale,`${n}.rationale`,e),d=We(r.evidenceIds,`${n}.evidenceIds`,e),c=Me(r.expectedEffect,`${n}.expectedEffect`,e),l=We(r.latencyContractEvidenceIds,`${n}.latencyContractEvidenceIds`,e),u=We(r.brittleLocatorEvidenceIds,`${n}.brittleLocatorEvidenceIds`,e);if(d!==void 0&&d.length===0&&ie(e,`${n}.evidenceIds`,"support-required","a replacement must cite evidence"),!(i===void 0||s===void 0||a===void 0||o===void 0||d===void 0||c===void 0||l===void 0||u===void 0))return{targetEvidenceId:i,oldText:s,newText:a,rationale:o,evidenceIds:d,expectedEffect:c,latencyContractEvidenceIds:l,brittleLocatorEvidenceIds:u}}function Kc(r){let t=[];if(!Xr(r))return{kind:"invalid",issues:[{path:"$",code:"expected-object",message:"proposal must be an object"}]};Yr(r,jm,"$",t);let e=Jr(r.status,mA,"$.status",t),n=Me(r.acceptedHypothesisId,"$.acceptedHypothesisId",t),i=ma(r.declineReason,"$.declineReason",t),s=Me(r.packetHash,"$.packetHash",t),a;if(!Xr(r.intent))ie(t,"$.intent","expected-object","intent must be an object");else{Yr(r.intent,Fm,"$.intent",t);let d=ma(r.intent.statement,"$.intent.statement",t),c=ma(r.intent.preservedBehavior,"$.intent.preservedBehavior",t),l=We(r.intent.evidenceIds,"$.intent.evidenceIds",t);d!==void 0&&c!==void 0&&l!==void 0&&(a={statement:d,preservedBehavior:c,evidenceIds:l})}let o=[];return Array.isArray(r.replacements)?(r.replacements.length>Uc&&ie(t,"$.replacements","too-many-items","too many replacements"),r.replacements.forEach((d,c)=>{let l=yA(d,c,t);l!==void 0&&o.push(l)})):ie(t,"$.replacements","expected-array","expected an array"),e==="proposed"&&a!==void 0&&(o.length===0&&Array.isArray(r.replacements)&&ie(t,"$.replacements","support-required","a proposal needs a replacement"),a.statement.trim()===""&&ie(t,"$.intent.statement","empty-string","a proposal must state its intent"),a.preservedBehavior.trim()===""&&ie(t,"$.intent.preservedBehavior","empty-string","a proposal must state the preserved behavior"),a.evidenceIds.length===0&&ie(t,"$.intent.evidenceIds","support-required","intent must cite evidence")),e==="declined"&&(i!==void 0&&i.trim()===""&&ie(t,"$.declineReason","empty-string","a decline must give its reason"),Array.isArray(r.replacements)&&r.replacements.length>0&&ie(t,"$.replacements","too-many-items","a decline must not propose edits")),t.length>0||e===void 0||n===void 0||i===void 0||a===void 0||s===void 0?{kind:"invalid",issues:t}:{kind:"valid",proposal:{status:e,acceptedHypothesisId:n,declineReason:i,intent:a,replacements:o,packetHash:s}}}var Bm="1.0",ya="1.1",ga="1.0",gA={purpose:"repair-proposal",promptVersion:ya,outputSchemaVersion:ga},wA=`You propose a minimal repair to end-to-end test-support code for one accepted, test-side diagnosis. The framework field says whether the code is Playwright, Cypress, or WebdriverIO; write idiomatic code for that framework and its existing style.
71
+ You have no tools, filesystem, shell, repository access, commands, or external lookup. Return only the required JSON object.`;function yr(r,t){return[...r].sort((e,n)=>t(e).localeCompare(t(n)))}function UT(r){return{gitRootAvailable:r.workspace.gitRoot!==void 0,sourceHashes:r.sourceHashes}}function $c(r){return r.replaceAll("\\","/").split("/").filter(Boolean).at(-1)??"<path>"}function Em(r){return r.type==="source-range"||r.type==="diff-hunk"?{...r,path:$c(r.path)}:r.type==="report-field"?{...r,path:r.path.startsWith("/")?$c(r.path):r.path}:r}function _c(r){return yr(r,t=>t.artifactId).map(t=>({artifactId:t.artifactId,channel:t.channel,availability:t.availability,...t.sha256===void 0?{}:{sha256:t.sha256},...t.format===void 0?{}:{format:t.format},...t.producerVersion===void 0?{}:{producerVersion:t.producerVersion},...t.attemptId===void 0?{}:{attemptId:t.attemptId},warnings:t.warnings}))}function Fc(r){return yr(r,t=>t.evidenceId).map(t=>({...t,locator:Em(t.locator)}))}function GT(r){return yr(r.omissions,t=>t.omissionId).map(t=>({omissionId:t.omissionId,channel:t.channel,reason:t.reason,message:t.message,...t.locator===void 0?{}:{locator:$c(t.locator)},...t.cap===void 0?{}:{cap:t.cap}}))}function KT(r,t,e){return{requestSchemaVersion:"1.0",promptVersion:"1.1",outputSchemaVersion:"1.0",runId:r.runId,packetHash:r.packetHash,framework:r.framework??"playwright",workspace:UT(r),artifacts:_c(r.artifacts),evidence:Fc(r.evidence),omissions:GT(r),accounting:yr(r.accounting,n=>n.channel),symptoms:yr(t.symptoms,n=>n.symptomId),unclassifiedAttemptIds:[...t.unclassifiedAttemptIds].sort(),clusters:yr(e.clusters,n=>n.clusterId)}}function WT(r,t,e,n,i){let s=new Map(r.artifacts.map(o=>[o.artifactId,o.channel])),a=new Set(t.artifactIds);return{schemaVersion:"1.1",runId:r.runId,packetHash:r.packetHash,payloadHash:n,purpose:t.purpose,model:e,promptVersion:t.promptVersion,outputSchemaVersion:t.outputSchemaVersion,evidence:yr(t.evidence,o=>o.evidenceId).map(o=>({evidenceId:o.evidenceId,artifactId:o.artifactId,channel:s.get(o.artifactId)??"report",locator:Em(o.locator),...o.logicalTestId===void 0?{}:{logicalTestId:o.logicalTestId},...o.attemptId===void 0?{}:{attemptId:o.attemptId},redactionIds:[...o.redactionIds].sort()})),artifactIds:[...t.artifactIds].sort(),symptomIds:[...t.symptomIds].sort(),clusterIds:[...t.clusterIds].sort(),omissionIds:[...t.omissionIds].sort(),redactionIds:[...t.redactionIds].sort(),channels:[...new Set(r.artifacts.filter(o=>a.has(o.artifactId)).map(o=>o.channel))].sort(),serializedBytes:i}}function jc(r,t,e,n){let i={model:e.modelId,messages:[{role:"system",content:t.systemPrompt},{role:"user",content:le(t.userContent)}],max_completion_tokens:n,...e.reasoningEffort===void 0?{}:{reasoning:{effort:e.reasoningEffort,exclude:!0}},response_format:{type:"json_schema",json_schema:{name:t.schemaName,strict:!0,schema:Am(t.schema,e.modelId)}},provider:{only:[e.providerId],allow_fallbacks:!1,require_parameters:!0,...e.zeroDataRetention===!0?{zdr:!0}:{},max_price:{prompt:0,completion:0,request:0}}},s=le(i),a=N(i);return{body:i,canonicalBody:s,payloadHash:a,manifest:WT(r,t,e,a,Buffer.byteLength(s,"utf8")),manifestHash:""}}function Bc(r,t,e,n,i){return jc(r,{purpose:"diagnosis",schemaName:"kwikqa_diagnosis",schema:Mc,systemPrompt:qT,promptVersion:"1.1",outputSchemaVersion:"1.0",userContent:KT(r,t,e),evidence:r.evidence,artifactIds:r.artifacts.map(s=>s.artifactId),symptomIds:t.symptoms.map(s=>s.symptomId),clusterIds:e.clusters.map(s=>s.clusterId),omissionIds:r.omissions.map(s=>s.omissionId),redactionIds:r.redactions.map(s=>s.redactionId)},n,i)}function Vc(r,t){let e={...r.body,provider:{...r.body.provider,max_price:{prompt:t.promptDollarsPerToken*1e6,completion:t.completionDollarsPerToken*1e6,request:t.fixedRequestDollars}}},n=le(e),i=N(e),s={...r.manifest,payloadHash:i,serializedBytes:Buffer.byteLength(n,"utf8")};return{body:e,canonicalBody:n,payloadHash:i,manifest:s,manifestHash:N(s)}}var JT=[[/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,"<uuid>"],[/\b0x[0-9a-f]+\b/gi,"<hex>"],[/\b[0-9a-f]{16,}\b/gi,"<hex>"],[/\d+(?:\.\d+)?\s*(?:ms|milliseconds?)\b/gi,"<duration>"],[/\d+(?:\.\d+)?\s*(?:s|seconds?)\b/gi,"<duration>"],[/:\d+:\d+\b/g,":<line>:<col>"],[/\b(?:localhost|127\.0\.0\.1|\[::1\])(:\d+)?/gi,"<localhost>"],[/:\d{2,5}\b/g,":<port>"],[/\b\d+\b/g,"<n>"]];function di(r){return r.replace(/\\/g,"/").replace(/^[A-Za-z]:/,"").split("/").filter(n=>n.length>0).slice(-2).join("/")}function la(r,t=200){let e=r.replace(/\r\n/g,`
72
+ `).replace(/(?:file:\/\/)?(?:[A-Za-z]:)?(?:\/[\w.@+-]+){2,}/g,n=>di(n));for(let[n,i]of JT)e=e.replace(n,i);return e=e.replace(/\s+/g," ").trim().toLowerCase(),e.length<=t?e:e.slice(0,t)}function Cm(r){return r.replace(/['`]/g,'"').replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/\{\s*/g,"{ ").replace(/\s*\}/g," }").trim()}function ci(r,t){return`${di(r)}:${t}`}var Zr=["error-field","stack-frame","step"],Nm=["error-field","stack-frame"],zc=["trace-event","console-event"];function Ft(r,t,e){return r.evidence.filter(n=>{if(!t.includes(n.kind))return!1;let i=r.normalized.get(n.evidenceId)??"";return e.some(s=>s.test(i))})}function XT(r,t,e){return r.evidence.filter(n=>t.includes(n.kind)&&e.some(i=>i.test(n.observation)))}var YT=[/timeouterror/,/timeout of <duration> exceeded/,/timeout <duration> exceeded/,/exceeded.{0,40}timeout/,/timed out/,/still not (?:existing|displayed|clickable|enabled|visible|selected) after/,/because element wasn't found/],QT=[/\bexpect\(/,/\bassertion\b/,/\bexpect \$\$?\(/,/\bexpected .{0,200} to (?:have|be|equal|eq|contain|include|exist|match|deep)\b/],ZT=[/expected:.{0,80}received:/s,/received:.{0,80}expected:/s],eA=[/uncaught \w*error/,/\bpageerror\b/,/unhandled (?:promise )?rejection/,/uncaught page error/,/originated from your application code/],tA=[/net::err_/,/navigation timeout/,/failed to navigate/,/navigation failed/,/err_(?:aborted|connection|name_not_resolved|empty_response|ssl)/,/cy\.visit\(\) failed/,/failed trying to load/],rA=[/target (?:page, context or browser )?(?:has been )?closed/,/browser has been closed/,/page crashed/,/target closed/,/browser closed unexpectedly/,/invalid session id/,/session deleted because of page crash/,/chrome not reachable/,/renderer process (?:just )?crashed/,/browser process (?:just )?crashed/],nA=[/cy\.request\(\) failed/,/response we received from your web server was/,/request failed with status code/],iA=[/"(?:before|after) (?:each|all)" hook/,/\bglobal (?:setup|teardown)\b/,/\bteardown\b/,/\bin (?:before|after)(?:each|all)? hook\b/,/\bbefore hooks\b/,/\bafter hooks\b/,/\bbeforeall\b/,/\bbeforeeach\b/,/\bafterall\b/,/\baftereach\b/,/\bfixture\b/],Hc=[{ruleId:"action-timeout/timeout-text",category:"action-timeout",description:"Failure text reports an expired action, element wait, or test timeout.",match:r=>Ft(r,Zr,YT)},{ruleId:"action-timeout/timed-out-status",category:"action-timeout",description:"The attempt status is timedOut and failure text is present to cite.",match:r=>r.attempt?.status==="timedOut"?r.evidence.filter(t=>t.kind==="error-field"):[]},{ruleId:"assertion-mismatch/expect-failure",category:"assertion-mismatch",description:"Failure text reports an expectation that did not hold.",match:r=>{let t=Ft(r,Zr,QT);return t.length>0?t:Ft(r,Zr,ZT)}},{ruleId:"page-exception/uncaught-error",category:"page-exception",description:"An uncaught page error or unhandled rejection was observed.",match:r=>Ft(r,[...Zr,...zc],eA)},{ruleId:"navigation-failure/net-error",category:"navigation-failure",description:"Navigation reported a network-level or navigation timeout error.",match:r=>Ft(r,[...Zr,...zc],tA)},{ruleId:"http-failure/error-status",category:"http-failure",description:"A recorded request returned a 4xx or 5xx status, or reported a failure.",match:r=>XT(r,["network-event"],[/-> [45]\d\d\b/,/\bfailure=/])},{ruleId:"http-failure/request-error",category:"http-failure",description:"Failure text reports a request the test made that returned an error status.",match:r=>Ft(r,Nm,nA)},{ruleId:"browser-crash/target-closed",category:"browser-crash",description:"The page, context, or browser was closed or crashed during the attempt.",match:r=>Ft(r,[...Zr,...zc],rA)},{ruleId:"setup-failure/hook-or-fixture",category:"setup-failure",description:"The failure is attributed to a hook or fixture rather than the test body.",match:r=>Ft(r,Nm,iA)}];var Mm={"action-timeout":"Action timeout","assertion-mismatch":"Assertion mismatch","page-exception":"Page exception","navigation-failure":"Navigation failure","http-failure":"HTTP failure","browser-crash":"Browser crash","setup-failure":"Setup failure","artifact-failure":"Artifact failure",unclassified:"Unclassified failure"},sA=new Set(["failed","timedOut","interrupted"]),Om=160;function $m(r){let t=r.replace(/\s+/g," ").trim();return t.length<=Om?t:`${t.slice(0,Om)}\u2026`}function aA(r){for(let t of r){if(t.kind!=="trace-event")continue;let n=/^action(?: started| finished)?: ([\w.]+)/.exec(t.observation)?.[1];if(n!==void 0&&n!=="unknown")return n}}function oA(r){for(let t of r){if(t.kind!=="network-event")continue;let e=/^(\w+) (\S+) -> (\d{3})/.exec(t.observation);if(e===null)continue;let[,n,i,s]=e;if(n===void 0||i===void 0||s===void 0)continue;let a=i;try{a=new URL(i).host}catch{}return`${n} ${a} -> ${s}`}}function dA(r,t){if(r?.errorLocation!==void 0)return ci(r.errorLocation.file,r.errorLocation.line??1);for(let e of t)if(e.locator.type==="source-range")return ci(e.locator.path,e.locator.startLine);for(let e of t){if(e.kind!=="stack-frame")continue;let n=/([^\s():]+):(\d+):\d+/.exec(e.observation),i=n?.[1],s=n?.[2];if(i!==void 0&&s!==void 0)return ci(i,Number.parseInt(s,10))}}function _m(r){let t=e=>r.find(n=>n.kind==="error-field"&&n.locator.type==="report-field"&&n.locator.path.endsWith(e));return t(".message")??t(".value")??r.find(e=>e.kind==="error-field")??r[0]}function cA(r,t,e){let n=_m(t),i=n===void 0?void 0:la(n.observation),s=dA(r,t),a=aA(t),o=oA(t),[d]=r===void 0?[]:zn(r),c=d===void 0?void 0:Cm(d),l=s!==void 0&&e!==void 0&&!s.startsWith(`${di(e)}:`)?s:void 0;return{...i===void 0||i===""?{}:{errorFingerprint:i},...s===void 0?{}:{sourceLocation:s},...a===void 0?{}:{actionApi:a},...o===void 0?{}:{networkEndpoint:o},...c===void 0||c===""?{}:{targetLocator:c},...l===void 0?{}:{supportLocation:l}}}function ua(r,t,e,n,i){let s=[...new Set(n.map(c=>c.evidenceId))].sort(),a=cA(i.attempt,n,i.specFile),o=_m(n),d=i.attempt?.attemptId??"run";return{symptomId:$("sym",[r,d,t,a.errorFingerprint??""]),category:t,ruleId:e,...i.logicalTestId===void 0?{}:{logicalTestId:i.logicalTestId},...i.attempt===void 0?{}:{attemptId:i.attempt.attemptId},evidenceIds:s,artifactIds:[],summary:`${Mm[t]}: ${$m(o?.observation??"")}`,signals:a}}function Dm(r){let t=new Map;for(let e of Hc){let n=e.match(r);if(n.length===0)continue;let i=t.get(e.category);i===void 0?t.set(e.category,{ruleId:e.ruleId,cited:[...n]}):i.cited.push(...n)}return t}function Lm(r){return new Map(r.map(t=>[t.evidenceId,la(t.observation,400)]))}function fa(r,t){let e=new Map;for(let s of t.evidence){if(s.attemptId===void 0)continue;let a=e.get(s.attemptId);a===void 0?e.set(s.attemptId,[s]):a.push(s)}let n=[],i=[];for(let s of r.logicalTests)for(let a of s.attempts){if(!sA.has(a.status))continue;let o=e.get(a.attemptId)??[],d={attempt:a,evidence:o,normalized:Lm(o)},c=Dm(d);if(c.size===0){if(o.length===0){i.push(a.attemptId);continue}n.push(ua(r.runId,"unclassified","unclassified/no-rule-matched",o.filter(l=>l.kind==="error-field").slice(0,3),{logicalTestId:s.logicalTestId,attempt:a,specFile:s.location.file}));continue}for(let[l,{ruleId:u,cited:p}]of c)n.push(ua(r.runId,l,u,p,{logicalTestId:s.logicalTestId,attempt:a,specFile:s.location.file}))}if(r.reportErrors.length>0){let s=t.evidence.filter(a=>a.attemptId===void 0&&a.logicalTestId===void 0);if(s.length>0){let a=Dm({evidence:s,normalized:Lm(s)});a.size===0&&n.push(ua(r.runId,"unclassified","unclassified/no-rule-matched",s.filter(o=>o.kind==="error-field").slice(0,3),{}));for(let[o,{ruleId:d,cited:c}]of a)n.push(ua(r.runId,o,d,c,{}))}}for(let s of t.artifacts)s.availability==="unreadable"&&n.push({symptomId:$("sym",[r.runId,s.artifactId,"artifact-failure"]),category:"artifact-failure",ruleId:"artifact-failure/unreadable-artifact",...s.attemptId===void 0?{}:{attemptId:s.attemptId},evidenceIds:[],artifactIds:[s.artifactId],summary:`${Mm["artifact-failure"]}: ${s.channel} artifact could not be read${s.warnings[0]===void 0?"":` (${$m(s.warnings[0])})`}`,signals:{}});return{schemaVersion:"1.0",runId:r.runId,packetHash:t.packetHash,symptoms:[...n].sort((s,a)=>s.symptomId.localeCompare(a.symptomId)),unclassifiedAttemptIds:[...i].sort()}}var lA=new Set(["error-fingerprint","network-endpoint","failing-source-location","target-locator","support-location"]);var jt="<absent>";function qc(r,t){switch(t){case"symptom-category":return r.category;case"action-api":return r.signals.actionApi??jt;case"error-fingerprint":return r.signals.errorFingerprint??jt;case"network-endpoint":return r.signals.networkEndpoint??jt;case"failing-source-location":return r.signals.sourceLocation??jt;case"target-locator":return r.signals.targetLocator??jt;case"support-location":return r.signals.supportLocation??jt}}function uA(r,t){if(t.length<2)return{supported:!1,rationale:"A single logical test provides no shared behavior for a common cause."};let e=r.filter(n=>lA.has(n.kind)&&n.value!==jt);return e.length===0?{supported:!1,rationale:"Members share only broad signals, which group failures by shape rather than by origin."}:{supported:!0,rationale:`Members share ${e.map(n=>`${n.kind}=${n.value}`).join(" and ")}, which is specific enough to be consistent with one cause. This is a statement about evidence specificity, not proof that one cause produced every member.`}}var Fm=["target-locator","support-location","network-endpoint"],jm=["symptom-category","error-fingerprint"];function Uc(r){let t=new Map;for(let i of r.symptoms){if(i.logicalTestId===void 0)continue;let s=t.get(i.logicalTestId);s===void 0?t.set(i.logicalTestId,[i]):s.push(i)}let e=new Map;for(let i of t.values()){let s=[...i].sort((l,u)=>l.symptomId.localeCompare(u.symptomId)),a;for(let l of Fm){let u=s.find(p=>qc(p,l)!==jt);if(u!==void 0){a=[{kind:l,value:qc(u,l)}];break}}let o=s[0];if(a===void 0&&o!==void 0&&(a=jm.map(l=>({kind:l,value:qc(o,l)}))),a===void 0)continue;let d=a.map(l=>`${l.kind}=${l.value}`).join("|"),c=e.get(d);c===void 0?e.set(d,{signals:a,members:[...i]}):c.members.push(...i)}let n=[...e.values()].map(({signals:i,members:s})=>{let a=[...new Set(s.map(d=>d.logicalTestId).filter(d=>d!==void 0))].sort(),o=uA(i,a);return{clusterId:$("clu",[r.runId,...i.map(d=>`${d.kind}=${d.value}`)]),logicalTestIds:a,symptomIds:s.map(d=>d.symptomId).sort(),signals:i,commonCauseSupported:o.supported,commonCauseRationale:o.rationale}});return{schemaVersion:"1.0",runId:r.runId,clusters:n.sort((i,s)=>i.clusterId.localeCompare(s.clusterId)),signalKinds:[...Fm,...jm]}}function pe(r,t,e,n,i={}){return{graderId:r,code:t,severity:e,message:n,...i.hypothesisId===void 0?{}:{hypothesisId:i.hypothesisId},...i.reference===void 0?{}:{reference:i.reference}}}function Bt(r,t,e){return{graderId:r,passed:!e.some(n=>n.severity==="violation"),checked:t,findings:e}}var li={insufficient:0,weak:1,moderate:2,strong:3},Gc={graderId:"abstention",description:"Diagnosis status matches evidence strength, and insufficient evidence abstains.",grade:r=>{let t=[],{diagnosis:e}=r,i=[...e.hypotheses].sort((o,d)=>o.rank-d.rank)[0],s=i===void 0?-1:li[i.evidenceGrade],a=1;return i===void 0||s===li.insufficient?e.status!=="inconclusive"&&t.push(pe("abstention","failed-to-abstain","violation",`Evidence cannot rank a cause, but the diagnosis claims ${e.status}.`)):e.status==="conclusive"&&s<li.strong?t.push(pe("abstention","conclusive-without-strong-evidence","violation",`Diagnosis claims conclusive on ${i.evidenceGrade} evidence.`,{hypothesisId:i.hypothesisId})):e.status==="probable"&&s<li.moderate&&t.push(pe("abstention","probable-without-moderate-evidence","violation",`Diagnosis claims probable on ${i.evidenceGrade} evidence.`,{hypothesisId:i.hypothesisId})),a+=1,e.status==="inconclusive"&&e.repairEligibility==="eligible"&&t.push(pe("abstention","repair-eligible-while-inconclusive","violation","Repair was marked eligible while the diagnosis is inconclusive.")),a+=1,e.status==="inconclusive"&&s>=li.strong&&t.push(pe("abstention","abstained-with-strong-evidence","warning","Diagnosis abstained although the leading hypothesis carries strong evidence.",{...i===void 0?{}:{hypothesisId:i.hypothesisId}})),a+=1,e.status==="inconclusive"&&e.missingEvidence.length===0&&t.push(pe("abstention","abstained-without-naming-gaps","warning","Diagnosis abstained without naming the evidence that was missing.")),Bt("abstention",a,t)}};var Kc={graderId:"citation-validity",description:"Every cited evidence, artifact, and symptom id exists in the graded packet.",grade:r=>{let t=[],e=0;r.diagnosis.packetHash!==r.packetHash&&t.push(pe("citation-validity","packet-hash-mismatch","violation","The diagnosis was produced from a different evidence packet than the one being graded.",{reference:r.diagnosis.packetHash}));let n=s=>r.evidenceIds.has(s)||r.artifactIds.has(s),i=[["ownershipEvidenceIds",r.diagnosis.ownershipEvidenceIds,void 0],...r.diagnosis.hypotheses.flatMap(s=>[["supportingEvidenceIds",s.supportingEvidenceIds,s.hypothesisId],["contradictingEvidenceIds",s.contradictingEvidenceIds,s.hypothesisId]])];for(let[s,a,o]of i)for(let d of a)e+=1,!n(d)&&t.push(pe("citation-validity","unknown-evidence-id","violation",`${s} cites ${d}, which the evidence packet does not contain.`,{...o===void 0?{}:{hypothesisId:o},reference:d}));for(let s of r.diagnosis.symptomIds)e+=1,!r.symptomIds.has(s)&&t.push(pe("citation-validity","unknown-symptom-id","violation",`The diagnosis cites symptom ${s}, which this run did not produce.`,{reference:s}));return Bt("citation-validity",e,t)}};var pA=new Set(["strong","moderate"]),Wc={graderId:"ownership",description:"A named owner rests on cited positive evidence, and eligibility proves it.",grade:r=>{let t=[],{diagnosis:e}=r,n=0;for(let i of e.hypotheses)n+=1,i.probableOwner!=="undetermined"&&i.supportingEvidenceIds.length===0&&t.push(pe("ownership","ownership-from-absence","violation",`Hypothesis assigns the ${i.probableOwner} owner without citing any supporting evidence.`,{hypothesisId:i.hypothesisId}));if(e.repairEligibility==="eligible"){n+=1,e.ownershipEvidenceIds.length===0&&t.push(pe("ownership","eligible-without-ownership-evidence","violation","Repair was marked eligible without identifying the evidence that proves test-side ownership."));let i=[...e.hypotheses].sort((s,a)=>s.rank-a.rank)[0];i===void 0?t.push(pe("ownership","eligible-without-hypothesis","violation","Repair was marked eligible without an accepted hypothesis.")):(i.probableOwner!=="test-support"&&t.push(pe("ownership","eligible-without-test-ownership","violation",`Repair was marked eligible while the accepted hypothesis assigns the ${i.probableOwner} owner.`,{hypothesisId:i.hypothesisId})),pA.has(i.evidenceGrade)||t.push(pe("ownership","eligible-on-insufficient-grade","violation",`Repair was marked eligible on ${i.evidenceGrade} evidence.`,{hypothesisId:i.hypothesisId})))}return Bt("ownership",n,t)}};var fA=/\b(?:evd|art|sym|clu|omi|red)_[a-f0-9]{8,}\b/g,Jc={graderId:"unsupported-claims",description:"Claims are backed by citations, and grades match the evidence offered.",grade:r=>{let t=[],e=0;for(let i of r.diagnosis.hypotheses){e+=1;let{hypothesisId:s,supportingEvidenceIds:a,contradictingEvidenceIds:o}=i;i.evidenceGrade!=="insufficient"&&a.length===0&&t.push(pe("unsupported-claims","claim-without-evidence","violation",`Hypothesis is graded ${i.evidenceGrade} but cites no supporting evidence.`,{hypothesisId:s})),i.evidenceGrade==="strong"&&(a.length<2&&t.push(pe("unsupported-claims","strong-grade-underspecified","violation","A strong grade requires multiple specific observations, but only one was cited.",{hypothesisId:s})),o.length>0&&t.push(pe("unsupported-claims","strong-grade-with-contradiction","violation","A strong grade requires no material unresolved contradiction, but contradicting evidence was cited.",{hypothesisId:s})),i.unresolvedAssumptions.length>0&&t.push(pe("unsupported-claims","strong-grade-with-unresolved-assumptions","warning","A strong grade carries unresolved assumptions.",{hypothesisId:s})));let d=a.filter(l=>o.includes(l));for(let l of d)t.push(pe("unsupported-claims","contradictory-citation","violation",`Evidence ${l} is cited as both supporting and contradicting the same hypothesis.`,{hypothesisId:s,reference:l}));let c=new Set([...a,...o]);for(let l of[i.statement,i.nextAction])for(let u of l.matchAll(fA)){let p=u[0];e+=1,!c.has(p)&&t.push(pe("unsupported-claims","uncited-identifier-in-prose","violation",`Prose references ${p}, which this hypothesis does not cite.`,{hypothesisId:s,reference:p}))}}e+=1;let n=r.diagnosis.hypotheses.map(i=>i.rank);return new Set(n).size!==n.length&&t.push(pe("unsupported-claims","duplicate-hypothesis-rank","violation","Hypotheses do not carry a distinct rank, so the accepted hypothesis is ambiguous.")),r.diagnosis.hypotheses.length>3&&t.push(pe("unsupported-claims","too-many-hypotheses","violation",`A diagnosis returns at most three ranked hypotheses; ${r.diagnosis.hypotheses.length} were supplied.`)),Bt("unsupported-claims",e,t)}};var Vm=[Kc,Wc,Gc,Jc];function hA(r){return[...r].sort((t,e)=>{if(t.severity!==e.severity)return t.severity==="violation"?-1:1;let n=t.graderId.localeCompare(e.graderId);if(n!==0)return n;let i=t.code.localeCompare(e.code);return i!==0?i:(t.reference??"").localeCompare(e.reference??"")})}function ui(r,t,e){let n={diagnosis:r,evidenceIds:new Set(t.evidence.map(s=>s.evidenceId)),artifactIds:new Set(t.artifacts.map(s=>s.artifactId)),symptomIds:new Set(e.symptoms.map(s=>s.symptomId)),packetHash:t.packetHash},i=Vm.map(s=>s.grade(n));return{schemaVersion:"1.0",packetHash:t.packetHash,passed:i.every(s=>s.passed),outcomes:i,findings:hA(i.flatMap(s=>s.findings))}}function mA(r){let{packetHash:t,...e}=r;return Cr(e)===t}function yA(r){if(!/^[^/\s]+\/[^/\s]+$/.test(r.modelId))return"An exact non-empty author/model identifier is required.";if(r.providerId.trim().length===0)return"An exact provider route is required."}function st(r,t,e,n={}){return Rc({runId:r.packet.runId,createdAt:r.packet.createdAt,workspace:r.packet.workspace,sourceHashes:r.packet.sourceHashes,packetHash:r.packet.packetHash,model:r.model,caps:r.caps,recordedAt:t,outcome:e,request:r.request,extra:n})}function it(r,t,e,n,i,s={}){return{kind:e,reasonCode:n,message:i,audit:st(r,t,Ve(e,n,i),s)}}function gA(r,t){if(r.kind==="available")return{kind:"supported",endpoint:Cc(r.endpoint),checkedAt:t};let e=r.code==="structured-output-unsupported"?"schema-capability-unsupported":r.code==="provider-unavailable"||r.code==="model-mismatch"?"model-or-provider-mismatch":r.code==="credential-unavailable"?"credential-unavailable":"preflight-failed";return{kind:r.kind==="failed"?"failed":r.kind,reasonCode:e,message:r.message,checkedAt:t}}async function ha(r){let{identity:t,recordedAt:e}=r,n=yA(t.model)??Ac(t.caps);if(n!==void 0)return it(t,e,"blocked","invalid-configuration",n);if(!mA(t.packet))return it(t,e,"blocked","invalid-provenance","The evidence packet contents do not match its packet hash.");if(r.provenanceError!==void 0)return it(t,e,"blocked","invalid-provenance",r.provenanceError);let i=await r.transport.preflight({modelId:t.model.modelId,providerSlug:t.model.providerId}),s=gA(i,e);if(s.kind!=="supported")return it(t,e,s.kind==="failed"?"failed":"blocked",s.reasonCode,s.message,{preflight:s});if(s.endpoint.maxCompletionTokens!==void 0&&t.caps.request.maxOutputTokens>s.endpoint.maxCompletionTokens)return it(t,e,"blocked","context-limit-exceeded","Requested output cap exceeds the exact endpoint limit.",{preflight:s});if(t.model.reasoningEffort!==void 0&&t.model.reasoningEffort!=="none"&&!s.endpoint.supportedParameters.includes("reasoning"))return it(t,e,"blocked","schema-capability-unsupported","The exact endpoint does not support the requested reasoning effort.",{preflight:s});let a=r.buildPayload(t.caps.request.maxOutputTokens),o=ra(a.canonicalBody,t.caps.request.maxOutputTokens,s.endpoint.pricing);if(o===void 0)return it(t,e,"blocked","pricing-unavailable","A conservative dollar estimate could not be derived from endpoint pricing.",{preflight:s});let d=Vc(a,o),c=ra(d.canonicalBody,t.caps.request.maxOutputTokens,s.endpoint.pricing);if(c===void 0)return it(t,e,"blocked","estimate-unavailable","A conservative final request estimate could not be computed.",{preflight:s});if(c.estimatedInputTokens+c.estimatedOutputTokens>s.endpoint.contextLength||s.endpoint.maxPromptTokens!==void 0&&c.estimatedInputTokens>s.endpoint.maxPromptTokens)return it(t,e,"blocked","context-limit-exceeded","The conservative request estimate exceeds the exact endpoint context limit.",{preflight:s,estimate:c});let l=Sc(c,t.caps);if(l.kind==="blocked")return it(t,e,"blocked",l.reasonCode,l.message,{preflight:s,estimate:c});let u={manifest:d.manifest,manifestHash:d.manifestHash,endpoint:s.endpoint,estimate:c,caps:t.caps},p=ta(u);return{kind:"ready",prepared:{preflight:s,preparedAt:e,payload:d,estimate:c,preview:Ic(u,p),authorizationBindingHash:p}}}function wA(r){return r.code==="credential-unavailable"?"credential-unavailable":"transport-failed"}async function ma(r){let{identity:t,prepared:e,recordedAt:n}=r,i={payloadHash:e.payload.payloadHash,payloadManifestHash:e.payload.manifestHash,authorizationBindingHash:e.authorizationBindingHash,preflight:e.preflight,estimate:e.estimate},s=(f,h,g,m={})=>it(t,n,f,h,g,{...i,...m}),a=ta({manifest:e.payload.manifest,manifestHash:e.payload.manifestHash,endpoint:e.preflight.endpoint,estimate:e.estimate,caps:t.caps});if(le(e.payload.body)!==e.payload.canonicalBody||N(e.payload.body)!==e.payload.payloadHash||e.payload.manifest.payloadHash!==e.payload.payloadHash||N(e.payload.manifest)!==e.payload.manifestHash||!r.inputsIntact||a!==e.authorizationBindingHash||!Pc(r.authorization,a))return s("blocked","authorization-mismatch","Authorization does not match the exact prepared request.");if(!r.authorizationStore.consume(r.authorization.authorizationId,e.authorizationBindingHash))return s("blocked","authorization-replayed","Authorization has already been consumed for this prepared request.");let d=await r.transport.complete({route:{modelId:t.model.modelId,providerSlug:t.model.providerId},body:e.payload.body}),c={mode:r.authorization.mode,authorizationId:r.authorization.authorizationId,authorizedAt:r.authorization.authorizedAt};if(d.kind==="failed")return s("failed",wA(d),d.message,{authorization:c,latencyMs:d.elapsedMs});let l=Rm(d.body,r.label,r.validate);if(l.kind!=="parsed")return s("rejected",l.kind,l.message,{authorization:c,latencyMs:d.elapsedMs});let u=l.value.usage===void 0?{}:{usage:l.value.usage};if(l.value.reportedModel!==t.model.modelId)return s("rejected","routed-model-mismatch","Reported model differs from the authorized model.",{authorization:c,reportedModel:l.value.reportedModel,...l.value.reportedProvider===void 0?{}:{reportedProvider:l.value.reportedProvider},latencyMs:d.elapsedMs,...u});if(l.value.reportedProvider===void 0)return s("rejected","routed-provider-mismatch","The completion response did not report the selected provider route.",{authorization:c,reportedModel:l.value.reportedModel,providerProvenance:"unavailable",latencyMs:d.elapsedMs,...u});let p=l.value.reportedProvider.toLocaleLowerCase("en-US");return p!==t.model.providerId.toLocaleLowerCase("en-US")&&p!==e.preflight.endpoint.providerName?.toLocaleLowerCase("en-US")?s("rejected","routed-provider-mismatch","Reported provider differs from the authorized provider.",{authorization:c,reportedModel:l.value.reportedModel,reportedProvider:l.value.reportedProvider,providerProvenance:"reported",latencyMs:d.elapsedMs,...u}):{kind:"parsed",output:l.value.output,audit:{...i,reportedModel:l.value.reportedModel,reportedProvider:l.value.reportedProvider,providerProvenance:"reported",...u,latencyMs:d.elapsedMs,authorization:c}}}var bA={purpose:"diagnosis",promptVersion:"1.1",outputSchemaVersion:"1.0"};function zm(r){return r??new Date().toISOString()}function Hm(r,t){return N({packet:r,symptoms:t})}function qm(r){return{packet:r.packet,model:r.model,caps:r.caps,request:bA}}async function ya(r){let t=zm(r.now),e=r.symptoms.runId===r.packet.runId&&r.clusters.runId===r.packet.runId&&r.symptoms.packetHash===r.packet.packetHash,n=await ha({identity:qm(r),transport:r.transport,recordedAt:t,...e?{}:{provenanceError:"M2 and M3 inputs do not identify the same run and packet."},buildPayload:i=>Bc(r.packet,r.symptoms,r.clusters,r.model,i)});return n.kind!=="ready"?{...n,kind:n.kind==="failed"?"failed":"blocked"}:{kind:"preview-ready",prepared:{packet:r.packet,symptoms:r.symptoms,clusters:r.clusters,model:r.model,caps:r.caps,...n.prepared,gradingInputHash:Hm(r.packet,r.symptoms)}}}async function Xc(r){let t=zm(r.now),e=r.prepared,n=qm(e),i=await ma({identity:n,prepared:e,inputsIntact:Hm(e.packet,e.symptoms)===e.gradingInputHash,authorization:r.authorization,authorizationStore:r.authorizationStore,transport:r.transport,recordedAt:t,label:"diagnosis",validate:d=>{let c=oa(d);return c.kind==="valid"?{kind:"valid",output:c.diagnosis}:{kind:"invalid",message:`Diagnosis failed strict schema validation: ${c.issues.map(l=>`${l.path}:${l.code}`).join(", ")}`}}});if(i.kind!=="parsed")return i;let s=i.output,a=ui(s,e.packet,e.symptoms),o={...i.audit,grading:a};if(!a.passed){let d="Diagnosis failed deterministic local grading.";return{kind:"rejected",reasonCode:"citation-or-grading-invalid",message:d,audit:st(n,t,Ve("rejected","citation-or-grading-invalid",d),o)}}return s.status==="inconclusive"?{kind:"abstained",reasonCode:"insufficient-evidence",diagnosis:s,grading:a,audit:st(n,t,Ve("abstained","insufficient-evidence"),o)}:{kind:"diagnosed",diagnosis:s,grading:a,audit:st(n,t,Ve("diagnosed"),o)}}var Yc=20,ga={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Um=["targetEvidenceId","oldText","newText","rationale","evidenceIds","expectedEffect","latencyContractEvidenceIds","brittleLocatorEvidenceIds"],Gm=["statement","preservedBehavior","evidenceIds"],Km=["status","acceptedHypothesisId","declineReason","intent","replacements","packetHash"],Qc={type:"object",additionalProperties:!1,required:Km,properties:{status:{type:"string",enum:["proposed","declined"]},acceptedHypothesisId:{type:"string",minLength:1},declineReason:{type:"string"},intent:{type:"object",additionalProperties:!1,required:Gm,properties:{statement:{type:"string"},preservedBehavior:{type:"string"},evidenceIds:ga}},replacements:{type:"array",maxItems:Yc,items:{type:"object",additionalProperties:!1,required:Um,properties:{targetEvidenceId:{type:"string",minLength:1},oldText:{type:"string",minLength:1},newText:{type:"string"},rationale:{type:"string",minLength:1},evidenceIds:ga,expectedEffect:{type:"string",minLength:1},latencyContractEvidenceIds:ga,brittleLocatorEvidenceIds:ga}}},packetHash:{type:"string",minLength:1}}},xA=new Set(["proposed","declined"]);function wa(r,t,e){if(typeof r=="string")return r;ae(e,t,"expected-string","expected a string")}function vA(r,t,e){let n=`$.replacements[${t}]`;if(!Yr(r)){ae(e,n,"expected-object","replacement must be an object");return}Qr(r,Um,n,e);let i=Me(r.targetEvidenceId,`${n}.targetEvidenceId`,e),s=Me(r.oldText,`${n}.oldText`,e),a=wa(r.newText,`${n}.newText`,e),o=Me(r.rationale,`${n}.rationale`,e),d=Je(r.evidenceIds,`${n}.evidenceIds`,e),c=Me(r.expectedEffect,`${n}.expectedEffect`,e),l=Je(r.latencyContractEvidenceIds,`${n}.latencyContractEvidenceIds`,e),u=Je(r.brittleLocatorEvidenceIds,`${n}.brittleLocatorEvidenceIds`,e);if(d!==void 0&&d.length===0&&ae(e,`${n}.evidenceIds`,"support-required","a replacement must cite evidence"),!(i===void 0||s===void 0||a===void 0||o===void 0||d===void 0||c===void 0||l===void 0||u===void 0))return{targetEvidenceId:i,oldText:s,newText:a,rationale:o,evidenceIds:d,expectedEffect:c,latencyContractEvidenceIds:l,brittleLocatorEvidenceIds:u}}function Zc(r){let t=[];if(!Yr(r))return{kind:"invalid",issues:[{path:"$",code:"expected-object",message:"proposal must be an object"}]};Qr(r,Km,"$",t);let e=Xr(r.status,xA,"$.status",t),n=Me(r.acceptedHypothesisId,"$.acceptedHypothesisId",t),i=wa(r.declineReason,"$.declineReason",t),s=Me(r.packetHash,"$.packetHash",t),a;if(!Yr(r.intent))ae(t,"$.intent","expected-object","intent must be an object");else{Qr(r.intent,Gm,"$.intent",t);let d=wa(r.intent.statement,"$.intent.statement",t),c=wa(r.intent.preservedBehavior,"$.intent.preservedBehavior",t),l=Je(r.intent.evidenceIds,"$.intent.evidenceIds",t);d!==void 0&&c!==void 0&&l!==void 0&&(a={statement:d,preservedBehavior:c,evidenceIds:l})}let o=[];return Array.isArray(r.replacements)?(r.replacements.length>Yc&&ae(t,"$.replacements","too-many-items","too many replacements"),r.replacements.forEach((d,c)=>{let l=vA(d,c,t);l!==void 0&&o.push(l)})):ae(t,"$.replacements","expected-array","expected an array"),e==="proposed"&&a!==void 0&&(o.length===0&&Array.isArray(r.replacements)&&ae(t,"$.replacements","support-required","a proposal needs a replacement"),a.statement.trim()===""&&ae(t,"$.intent.statement","empty-string","a proposal must state its intent"),a.preservedBehavior.trim()===""&&ae(t,"$.intent.preservedBehavior","empty-string","a proposal must state the preserved behavior"),a.evidenceIds.length===0&&ae(t,"$.intent.evidenceIds","support-required","intent must cite evidence")),e==="declined"&&(i!==void 0&&i.trim()===""&&ae(t,"$.declineReason","empty-string","a decline must give its reason"),Array.isArray(r.replacements)&&r.replacements.length>0&&ae(t,"$.replacements","too-many-items","a decline must not propose edits")),t.length>0||e===void 0||n===void 0||i===void 0||a===void 0||s===void 0?{kind:"invalid",issues:t}:{kind:"valid",proposal:{status:e,acceptedHypothesisId:n,declineReason:i,intent:a,replacements:o,packetHash:s}}}var Wm="1.0",ba="1.1",xa="1.0",kA={purpose:"repair-proposal",promptVersion:ba,outputSchemaVersion:xa},IA=`You propose a minimal repair to end-to-end test-support code for one accepted, test-side diagnosis. The framework field says whether the code is Playwright, Cypress, or WebdriverIO; write idiomatic code for that framework and its existing style.
73
73
  Edit only source excerpts listed in targetEvidenceIds. Each oldText must be copied exactly from that excerpt's text and identify one place to change.
74
74
  Cite only supplied evidence IDs. State the test's intent and the behavior every edit preserves, citing evidence for it; the intent may cite only the accepted hypothesis's supportingEvidenceIds, and a proposal whose intent cites anything else is rejected.
75
75
  Never skip, focus, or mark tests as expected to fail (test.skip, it.only, xit, describe.skip, fixme); never add fixed sleeps (waitForTimeout, cy.wait with a number, browser.pause), retries, or error swallowing, including a Cypress uncaught:exception handler that returns false; never pass force: true to bypass Cypress actionability checks; never remove or weaken an assertion (expect, should, and, assert); never regenerate snapshots to accept current output.
76
76
  Increase a timeout only with cited evidence of a legitimate latency contract, and replace a semantic locator with a brittle selector only with cited evidence that requires it.
77
77
  Stay within the file and line budget. If no edit can repair the accepted cause while preserving intent, decline and explain why.
78
- You have no tools, filesystem, shell, repository access, commands, or external lookup. Return only the required JSON object.`;function Vm(r){return r??new Date().toISOString()}function zm(r){return{packet:r.packet,model:r.model,caps:r.caps,request:gA}}function bA(r){return r.locator.type==="source-range"?r.locator.path:void 0}function xA(r){let{packet:t,diagnosis:e,grading:n}=r;if(!n.passed||n.packetHash!==t.packetHash||e.packetHash!==t.packetHash)return{message:"The diagnosis did not pass local grading for this evidence packet."};if(e.status==="inconclusive"||e.repairEligibility!=="eligible")return{message:"The diagnosis does not declare a repair-eligible cause."};let i=e.hypotheses.find(s=>s.hypothesisId===r.hypothesisId);return i===void 0||i.rank!==1?{message:"Only the rank-1 hypothesis of a graded diagnosis can be repaired."}:i.probableOwner!=="test-support"?{message:"The accepted hypothesis is not owned by test support."}:i.evidenceGrade!=="strong"&&i.evidenceGrade!=="moderate"||e.ownershipEvidenceIds.length===0?{message:"Test-side ownership is not supported by cited positive evidence."}:{hypothesis:i}}function Hm(r){return C({packet:r.packet,diagnosis:r.diagnosis,hypothesisId:r.hypothesisId,targetEvidenceIds:r.targetEvidenceIds,budgets:r.budgets})}async function Wc(r){let t=Vm(r.now),e=zm(r),n=xA(r);if("message"in n)return{kind:"blocked",reasonCode:"repair-not-eligible",message:n.message,audit:st(e,t,Ve("blocked","repair-not-eligible",n.message))};let{packet:i,diagnosis:s}=r,a=new Set(r.editablePaths),o=new Set([...n.hypothesis.supportingEvidenceIds,...n.hypothesis.contradictingEvidenceIds,...s.ownershipEvidenceIds]),d=i.evidence.filter(m=>o.has(m.evidenceId)||m.kind==="source-range"),l=d.filter(m=>{let y=bA(m);return y!==void 0&&a.has(y)}).map(m=>m.evidenceId).sort();if(l.length===0){let m="No source excerpt in the evidence packet is an authorized repair target.";return{kind:"blocked",reasonCode:"repair-not-eligible",message:m,audit:st(e,t,Ve("blocked","repair-not-eligible",m))}}let u=new Set(d.map(m=>m.artifactId)),p=i.artifacts.filter(m=>u.has(m.artifactId)),f=[...new Set(d.flatMap(m=>m.redactionIds))],h=await ua({identity:e,transport:r.transport,recordedAt:t,buildPayload:m=>Dc(i,{purpose:"repair-proposal",schemaName:"kwikqa_repair_proposal",schema:Gc,systemPrompt:wA,promptVersion:ya,outputSchemaVersion:ga,userContent:{requestSchemaVersion:Bm,promptVersion:ya,outputSchemaVersion:ga,runId:i.runId,packetHash:i.packetHash,framework:i.framework??"playwright",acceptedHypothesis:n.hypothesis,diagnosis:{status:s.status,symptomIds:s.symptomIds,ownershipEvidenceIds:s.ownershipEvidenceIds,recommendedNextAction:s.recommendedNextAction},budgets:r.budgets,targetEvidenceIds:l,artifacts:Nc(p),evidence:Oc(d)},evidence:d,artifactIds:[...u],symptomIds:s.symptomIds,clusterIds:[],omissionIds:[],redactionIds:f},r.model,m)});if(h.kind!=="ready")return{...h,kind:h.kind==="failed"?"failed":"blocked"};let g={packet:i,diagnosis:s,hypothesisId:r.hypothesisId,targetEvidenceIds:l,budgets:r.budgets};return{kind:"preview-ready",prepared:{...h.prepared,...g,includedEvidenceIds:d.map(m=>m.evidenceId).sort(),model:r.model,caps:r.caps,inputHash:Hm(g)}}}function vA(r){let t=r.observation.indexOf(`
79
- `);return t===-1?"":r.observation.slice(t+1)}function kA(r,t){let e=[],n=new Set(r.includedEvidenceIds),i=new Set(r.targetEvidenceIds),s=new Map(r.packet.evidence.map(d=>[d.evidenceId,d])),a=(d,c)=>{for(let l of d)n.has(l)||e.push(`${c} cites evidence that was not supplied: ${l}`)};t.packetHash!==r.packet.packetHash&&e.push("The proposal names a different evidence packet."),t.acceptedHypothesisId!==r.hypothesisId&&e.push("The proposal names a different hypothesis than the accepted one."),a(t.intent.evidenceIds,"intent");let o=[];return t.replacements.forEach((d,c)=>{let l=`replacement ${c+1}`;a(d.evidenceIds,l),a(d.latencyContractEvidenceIds,l),a(d.brittleLocatorEvidenceIds,l);let u=s.get(d.targetEvidenceId);if(u===void 0||!i.has(d.targetEvidenceId)||u.locator.type!=="source-range"){e.push(`${l} targets an excerpt that is not an authorized repair target.`);return}if(!vA(u).includes(d.oldText)){e.push(`${l} replaces text that does not appear in its cited excerpt.`);return}o.push({path:u.locator.path,sourceSha256:u.locator.sha256,oldText:d.oldText,newText:d.newText,rationale:d.rationale,evidenceIds:d.evidenceIds,expectedEffect:d.expectedEffect,...d.latencyContractEvidenceIds.length===0?{}:{latencyContractEvidenceIds:d.latencyContractEvidenceIds},...d.brittleLocatorEvidenceIds.length===0?{}:{brittleLocatorEvidenceIds:d.brittleLocatorEvidenceIds}})}),e.length>0?{problems:e}:{draft:{acceptedHypothesisId:t.acceptedHypothesisId,intent:t.intent,replacements:o}}}async function Jc(r){let t=Vm(r.now),e=r.prepared,n=zm(e),i=await pa({identity:n,prepared:e,inputsIntact:Hm(e)===e.inputHash,authorization:r.authorization,authorizationStore:r.authorizationStore,transport:r.transport,recordedAt:t,label:"repair proposal",validate:a=>{let o=Kc(a);return o.kind==="valid"?{kind:"valid",output:o.proposal}:{kind:"invalid",message:`Repair proposal failed strict schema validation: ${o.issues.map(d=>`${d.path}:${d.code}`).join(", ")}`}}});if(i.kind!=="parsed")return i;let s=kA(e,i.output);if("problems"in s){let a=`Repair proposal failed local checks: ${s.problems.join(" ")}`;return{kind:"rejected",reasonCode:"citation-or-grading-invalid",message:a,audit:st(n,t,Ve("rejected","citation-or-grading-invalid",a),i.audit)}}return i.output.status==="declined"?{kind:"declined",reasonCode:"model-declined-repair",message:i.output.declineReason,audit:st(n,t,Ve("declined","model-declined-repair",i.output.declineReason),i.audit)}:{kind:"proposed",draft:s.draft,audit:st(n,t,Ve("proposed"),i.audit)}}var qm=new Set(["spec","page-object","fixture","test-data","test-helper","playwright-config","framework-config"]),IA=new Set(["schemaVersion","editablePaths","generatedPaths","budgets"]),PA=new Set(["pattern","class"]),RA=new Set(["maxFiles","maxChangedLines"]);function Xc(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0}function wa(r,t=!1){return r.length===0||r.includes("\0")||r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/.test(r)||r.split("/").some(n=>n===""||n==="."||n==="..")?!1:r!=="*"&&r!=="**"&&(t||!r.startsWith("**/"))}function TA(r){if(!(!Array.isArray(r)||r.some(t=>typeof t!="string")))return r}function Um(r,t){return Number.isInteger(r)&&typeof r=="number"&&r>0&&r<=t}function mr(r){let t=Xc(r);if(t===void 0)return{kind:"invalid",issues:["Configuration must be an object."]};let e=[];for(let o of Object.keys(t))IA.has(o)||e.push(`Unknown configuration field: ${o}.`);t.schemaVersion!=="1.0"&&e.push(`schemaVersion must be ${"1.0"}.`);let n=t.editablePaths,i=[];if(!Array.isArray(n)||n.length===0)e.push("editablePaths must contain at least one explicit rule.");else for(let[o,d]of n.entries()){let c=Xc(d);if(c===void 0){e.push(`editablePaths[${o}] must be an object.`);continue}for(let l of Object.keys(c))PA.has(l)||e.push(`Unknown editablePaths[${o}] field: ${l}.`);(typeof c.pattern!="string"||!wa(c.pattern))&&e.push(`editablePaths[${o}].pattern is unsafe or overly broad.`),(typeof c.class!="string"||!qm.has(c.class))&&e.push(`editablePaths[${o}].class is invalid.`),typeof c.pattern=="string"&&wa(c.pattern)&&typeof c.class=="string"&&qm.has(c.class)&&i.push({pattern:c.pattern,class:c.class})}let s=TA(t.generatedPaths);(s===void 0||s.some(o=>!wa(o,!0)))&&e.push("generatedPaths must contain only safe repository-relative patterns.");let a=Xc(t.budgets);if(a===void 0)e.push("budgets must be an object.");else{for(let o of Object.keys(a))RA.has(o)||e.push(`Unknown budgets field: ${o}.`);Um(a.maxFiles,3)||e.push(`budgets.maxFiles must be an integer from 1 to ${3}.`),Um(a.maxChangedLines,100)||e.push(`budgets.maxChangedLines must be an integer from 1 to ${100}.`)}return e.length>0||a===void 0||s===void 0?{kind:"invalid",issues:e}:{kind:"valid",config:{schemaVersion:"1.0",editablePaths:i,generatedPaths:s,budgets:{maxFiles:a.maxFiles,maxChangedLines:a.maxChangedLines}}}}var Gm={schemaVersion:"1.0",editablePaths:[{pattern:"tests/**/*.ts",class:"spec"},{pattern:"tests/**/*.tsx",class:"spec"}],generatedPaths:["**/*.generated.ts","**/__snapshots__/**"],budgets:{maxFiles:3,maxChangedLines:100}};var AA=[{prefix:"tests/",rules:[{pattern:"tests/**/*.ts",class:"spec"}]},{prefix:"e2e/",rules:[{pattern:"e2e/**/*.ts",class:"spec"}]},{prefix:"cypress/e2e/",rules:[{pattern:"cypress/e2e/**/*.cy.ts",class:"spec"},{pattern:"cypress/e2e/**/*.cy.js",class:"spec"}]},{prefix:"test/specs/",rules:[{pattern:"test/specs/**/*.ts",class:"spec"},{pattern:"test/specs/**/*.js",class:"spec"}]}],SA=[{prefix:"cypress/support/",rule:{pattern:"cypress/support/**/*.ts",class:"test-helper"}},{prefix:"cypress/pages/",rule:{pattern:"cypress/pages/**/*.ts",class:"page-object"}},{prefix:"test/pageobjects/",rule:{pattern:"test/pageobjects/**/*.ts",class:"page-object"}}];function Yc(r){let t=r.repositoryPaths.map(a=>a.replaceAll("\\","/")).filter(a=>wa(a)),e=a=>t.some(o=>o.startsWith(a)),n=[];(e("tests/")||e("test/")&&!e("test/specs/"))&&n.push({pattern:"tests/**/*.ts",class:"spec"});for(let a of AA.slice(1))e(a.prefix)&&n.push(...a.rules);let i=[];n.length===0&&i.push("No standard test directory was found."),i.push("Shared support modules require explicit review before authorization.");for(let a of SA)e(a.prefix)&&i.push(`${a.prefix} looks like shared ${a.rule.class==="page-object"?"page objects":"support code"}; add {"pattern": "${a.rule.pattern}", "class": "${a.rule.class}"} to let KwikQA propose fixes there.`);let s={...Gm,editablePaths:n.length===0?Gm.editablePaths:n};return{destination:"kwikqa.config.json",config:s,canonicalContents:`${de(s)}
80
- `,reasons:n.map(a=>`Observed repository paths matching ${a.pattern}.`),ambiguities:i}}function Km(r){let e=r.replaceAll(`\r
78
+ You have no tools, filesystem, shell, repository access, commands, or external lookup. Return only the required JSON object.`;function Jm(r){return r??new Date().toISOString()}function Xm(r){return{packet:r.packet,model:r.model,caps:r.caps,request:kA}}function PA(r){return r.locator.type==="source-range"?r.locator.path:void 0}function RA(r){let{packet:t,diagnosis:e,grading:n}=r;if(!n.passed||n.packetHash!==t.packetHash||e.packetHash!==t.packetHash)return{message:"The diagnosis did not pass local grading for this evidence packet."};if(e.status==="inconclusive"||e.repairEligibility!=="eligible")return{message:"The diagnosis does not declare a repair-eligible cause."};let i=e.hypotheses.find(s=>s.hypothesisId===r.hypothesisId);return i===void 0||i.rank!==1?{message:"Only the rank-1 hypothesis of a graded diagnosis can be repaired."}:i.probableOwner!=="test-support"?{message:"The accepted hypothesis is not owned by test support."}:i.evidenceGrade!=="strong"&&i.evidenceGrade!=="moderate"||e.ownershipEvidenceIds.length===0?{message:"Test-side ownership is not supported by cited positive evidence."}:{hypothesis:i}}function Ym(r){return N({packet:r.packet,diagnosis:r.diagnosis,hypothesisId:r.hypothesisId,targetEvidenceIds:r.targetEvidenceIds,budgets:r.budgets})}async function el(r){let t=Jm(r.now),e=Xm(r),n=RA(r);if("message"in n)return{kind:"blocked",reasonCode:"repair-not-eligible",message:n.message,audit:st(e,t,Ve("blocked","repair-not-eligible",n.message))};let{packet:i,diagnosis:s}=r,a=new Set(r.editablePaths),o=new Set([...n.hypothesis.supportingEvidenceIds,...n.hypothesis.contradictingEvidenceIds,...s.ownershipEvidenceIds]),d=i.evidence.filter(m=>o.has(m.evidenceId)||m.kind==="source-range"),l=d.filter(m=>{let y=PA(m);return y!==void 0&&a.has(y)}).map(m=>m.evidenceId).sort();if(l.length===0){let m="No source excerpt in the evidence packet is an authorized repair target.";return{kind:"blocked",reasonCode:"repair-not-eligible",message:m,audit:st(e,t,Ve("blocked","repair-not-eligible",m))}}let u=new Set(d.map(m=>m.artifactId)),p=i.artifacts.filter(m=>u.has(m.artifactId)),f=[...new Set(d.flatMap(m=>m.redactionIds))],h=await ha({identity:e,transport:r.transport,recordedAt:t,buildPayload:m=>jc(i,{purpose:"repair-proposal",schemaName:"kwikqa_repair_proposal",schema:Qc,systemPrompt:IA,promptVersion:ba,outputSchemaVersion:xa,userContent:{requestSchemaVersion:Wm,promptVersion:ba,outputSchemaVersion:xa,runId:i.runId,packetHash:i.packetHash,framework:i.framework??"playwright",acceptedHypothesis:n.hypothesis,diagnosis:{status:s.status,symptomIds:s.symptomIds,ownershipEvidenceIds:s.ownershipEvidenceIds,recommendedNextAction:s.recommendedNextAction},budgets:r.budgets,targetEvidenceIds:l,artifacts:_c(p),evidence:Fc(d)},evidence:d,artifactIds:[...u],symptomIds:s.symptomIds,clusterIds:[],omissionIds:[],redactionIds:f},r.model,m)});if(h.kind!=="ready")return{...h,kind:h.kind==="failed"?"failed":"blocked"};let g={packet:i,diagnosis:s,hypothesisId:r.hypothesisId,targetEvidenceIds:l,budgets:r.budgets};return{kind:"preview-ready",prepared:{...h.prepared,...g,includedEvidenceIds:d.map(m=>m.evidenceId).sort(),model:r.model,caps:r.caps,inputHash:Ym(g)}}}function TA(r){let t=r.observation.indexOf(`
79
+ `);return t===-1?"":r.observation.slice(t+1)}function AA(r,t){let e=[],n=new Set(r.includedEvidenceIds),i=new Set(r.targetEvidenceIds),s=new Map(r.packet.evidence.map(d=>[d.evidenceId,d])),a=(d,c)=>{for(let l of d)n.has(l)||e.push(`${c} cites evidence that was not supplied: ${l}`)};t.packetHash!==r.packet.packetHash&&e.push("The proposal names a different evidence packet."),t.acceptedHypothesisId!==r.hypothesisId&&e.push("The proposal names a different hypothesis than the accepted one."),a(t.intent.evidenceIds,"intent");let o=[];return t.replacements.forEach((d,c)=>{let l=`replacement ${c+1}`;a(d.evidenceIds,l),a(d.latencyContractEvidenceIds,l),a(d.brittleLocatorEvidenceIds,l);let u=s.get(d.targetEvidenceId);if(u===void 0||!i.has(d.targetEvidenceId)||u.locator.type!=="source-range"){e.push(`${l} targets an excerpt that is not an authorized repair target.`);return}if(!TA(u).includes(d.oldText)){e.push(`${l} replaces text that does not appear in its cited excerpt.`);return}o.push({path:u.locator.path,sourceSha256:u.locator.sha256,oldText:d.oldText,newText:d.newText,rationale:d.rationale,evidenceIds:d.evidenceIds,expectedEffect:d.expectedEffect,...d.latencyContractEvidenceIds.length===0?{}:{latencyContractEvidenceIds:d.latencyContractEvidenceIds},...d.brittleLocatorEvidenceIds.length===0?{}:{brittleLocatorEvidenceIds:d.brittleLocatorEvidenceIds}})}),e.length>0?{problems:e}:{draft:{acceptedHypothesisId:t.acceptedHypothesisId,intent:t.intent,replacements:o}}}async function tl(r){let t=Jm(r.now),e=r.prepared,n=Xm(e),i=await ma({identity:n,prepared:e,inputsIntact:Ym(e)===e.inputHash,authorization:r.authorization,authorizationStore:r.authorizationStore,transport:r.transport,recordedAt:t,label:"repair proposal",validate:a=>{let o=Zc(a);return o.kind==="valid"?{kind:"valid",output:o.proposal}:{kind:"invalid",message:`Repair proposal failed strict schema validation: ${o.issues.map(d=>`${d.path}:${d.code}`).join(", ")}`}}});if(i.kind!=="parsed")return i;let s=AA(e,i.output);if("problems"in s){let a=`Repair proposal failed local checks: ${s.problems.join(" ")}`;return{kind:"rejected",reasonCode:"citation-or-grading-invalid",message:a,audit:st(n,t,Ve("rejected","citation-or-grading-invalid",a),i.audit)}}return i.output.status==="declined"?{kind:"declined",reasonCode:"model-declined-repair",message:i.output.declineReason,audit:st(n,t,Ve("declined","model-declined-repair",i.output.declineReason),i.audit)}:{kind:"proposed",draft:s.draft,audit:st(n,t,Ve("proposed"),i.audit)}}var Qm=new Set(["spec","page-object","fixture","test-data","test-helper","playwright-config","framework-config"]),SA=new Set(["schemaVersion","editablePaths","generatedPaths","budgets"]),EA=new Set(["pattern","class"]),CA=new Set(["maxFiles","maxChangedLines"]);function rl(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0}function va(r,t=!1){return r.length===0||r.includes("\0")||r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/.test(r)||r.split("/").some(n=>n===""||n==="."||n==="..")?!1:r!=="*"&&r!=="**"&&(t||!r.startsWith("**/"))}function NA(r){if(!(!Array.isArray(r)||r.some(t=>typeof t!="string")))return r}function Zm(r,t){return Number.isInteger(r)&&typeof r=="number"&&r>0&&r<=t}function gr(r){let t=rl(r);if(t===void 0)return{kind:"invalid",issues:["Configuration must be an object."]};let e=[];for(let o of Object.keys(t))SA.has(o)||e.push(`Unknown configuration field: ${o}.`);t.schemaVersion!=="1.0"&&e.push(`schemaVersion must be ${"1.0"}.`);let n=t.editablePaths,i=[];if(!Array.isArray(n)||n.length===0)e.push("editablePaths must contain at least one explicit rule.");else for(let[o,d]of n.entries()){let c=rl(d);if(c===void 0){e.push(`editablePaths[${o}] must be an object.`);continue}for(let l of Object.keys(c))EA.has(l)||e.push(`Unknown editablePaths[${o}] field: ${l}.`);(typeof c.pattern!="string"||!va(c.pattern))&&e.push(`editablePaths[${o}].pattern is unsafe or overly broad.`),(typeof c.class!="string"||!Qm.has(c.class))&&e.push(`editablePaths[${o}].class is invalid.`),typeof c.pattern=="string"&&va(c.pattern)&&typeof c.class=="string"&&Qm.has(c.class)&&i.push({pattern:c.pattern,class:c.class})}let s=NA(t.generatedPaths);(s===void 0||s.some(o=>!va(o,!0)))&&e.push("generatedPaths must contain only safe repository-relative patterns.");let a=rl(t.budgets);if(a===void 0)e.push("budgets must be an object.");else{for(let o of Object.keys(a))CA.has(o)||e.push(`Unknown budgets field: ${o}.`);Zm(a.maxFiles,3)||e.push(`budgets.maxFiles must be an integer from 1 to ${3}.`),Zm(a.maxChangedLines,100)||e.push(`budgets.maxChangedLines must be an integer from 1 to ${100}.`)}return e.length>0||a===void 0||s===void 0?{kind:"invalid",issues:e}:{kind:"valid",config:{schemaVersion:"1.0",editablePaths:i,generatedPaths:s,budgets:{maxFiles:a.maxFiles,maxChangedLines:a.maxChangedLines}}}}var ey={schemaVersion:"1.0",editablePaths:[{pattern:"tests/**/*.ts",class:"spec"},{pattern:"tests/**/*.tsx",class:"spec"}],generatedPaths:["**/*.generated.ts","**/__snapshots__/**"],budgets:{maxFiles:3,maxChangedLines:100}};var OA=[{prefix:"tests/",rules:[{pattern:"tests/**/*.ts",class:"spec"}]},{prefix:"e2e/",rules:[{pattern:"e2e/**/*.ts",class:"spec"}]},{prefix:"cypress/e2e/",rules:[{pattern:"cypress/e2e/**/*.cy.ts",class:"spec"},{pattern:"cypress/e2e/**/*.cy.js",class:"spec"}]},{prefix:"test/specs/",rules:[{pattern:"test/specs/**/*.ts",class:"spec"},{pattern:"test/specs/**/*.js",class:"spec"}]}],DA=[{prefix:"cypress/support/",rule:{pattern:"cypress/support/**/*.ts",class:"test-helper"}},{prefix:"cypress/pages/",rule:{pattern:"cypress/pages/**/*.ts",class:"page-object"}},{prefix:"test/pageobjects/",rule:{pattern:"test/pageobjects/**/*.ts",class:"page-object"}}];function nl(r){let t=r.repositoryPaths.map(a=>a.replaceAll("\\","/")).filter(a=>va(a)),e=a=>t.some(o=>o.startsWith(a)),n=[];(e("tests/")||e("test/")&&!e("test/specs/"))&&n.push({pattern:"tests/**/*.ts",class:"spec"});for(let a of OA.slice(1))e(a.prefix)&&n.push(...a.rules);let i=[];n.length===0&&i.push("No standard test directory was found."),i.push("Shared support modules require explicit review before authorization.");for(let a of DA)e(a.prefix)&&i.push(`${a.prefix} looks like shared ${a.rule.class==="page-object"?"page objects":"support code"}; add {"pattern": "${a.rule.pattern}", "class": "${a.rule.class}"} to let KwikQA propose fixes there.`);let s={...ey,editablePaths:n.length===0?ey.editablePaths:n};return{destination:"kwikqa.config.json",config:s,canonicalContents:`${le(s)}
80
+ `,reasons:n.map(a=>`Observed repository paths matching ${a.pattern}.`),ambiguities:i}}function ty(r){let e=r.replaceAll(`\r
81
81
  `,`
82
82
  `).split(`
83
- `);return e.at(-1)===""?e.slice(0,-1):e}function EA(r,t){let e=Array.from({length:r.length+1},()=>Array(t.length+1).fill(0));for(let a=r.length-1;a>=0;a-=1)for(let o=t.length-1;o>=0;o-=1){let d=e[a],c=e[a+1];d===void 0||c===void 0||(d[o]=r[a]===t[o]?(c[o+1]??0)+1:Math.max(c[o]??0,d[o+1]??0))}let n=[],i=0,s=0;for(;i<r.length||s<t.length;)i<r.length&&s<t.length&&r[i]===t[s]?(n.push({kind:"context",text:r[i]??""}),i+=1,s+=1):s<t.length&&(i>=r.length||(e[i]?.[s+1]??0)>=(e[i+1]?.[s]??0))?(n.push({kind:"add",text:t[s]??""}),s+=1):(n.push({kind:"delete",text:r[i]??""}),i+=1);return n}function CA(r){let t=Km(r.source),e=Km(r.result),n=EA(t,e),i=n.filter(a=>a.kind!=="context").length;return{text:`${[`diff --git a/${r.path} b/${r.path}`,`--- a/${r.path}`,`+++ b/${r.path}`,`@@ -1,${t.length} +1,${e.length} @@`,...n.map(a=>`${a.kind==="add"?"+":a.kind==="delete"?"-":" "}${a.text}`)].join(`
83
+ `);return e.at(-1)===""?e.slice(0,-1):e}function LA(r,t){let e=Array.from({length:r.length+1},()=>Array(t.length+1).fill(0));for(let a=r.length-1;a>=0;a-=1)for(let o=t.length-1;o>=0;o-=1){let d=e[a],c=e[a+1];d===void 0||c===void 0||(d[o]=r[a]===t[o]?(c[o+1]??0)+1:Math.max(c[o]??0,d[o+1]??0))}let n=[],i=0,s=0;for(;i<r.length||s<t.length;)i<r.length&&s<t.length&&r[i]===t[s]?(n.push({kind:"context",text:r[i]??""}),i+=1,s+=1):s<t.length&&(i>=r.length||(e[i]?.[s+1]??0)>=(e[i+1]?.[s]??0))?(n.push({kind:"add",text:t[s]??""}),s+=1):(n.push({kind:"delete",text:r[i]??""}),i+=1);return n}function MA(r){let t=ty(r.source),e=ty(r.result),n=LA(t,e),i=n.filter(a=>a.kind!=="context").length;return{text:`${[`diff --git a/${r.path} b/${r.path}`,`--- a/${r.path}`,`+++ b/${r.path}`,`@@ -1,${t.length} +1,${e.length} @@`,...n.map(a=>`${a.kind==="add"?"+":a.kind==="delete"?"-":" "}${a.text}`)].join(`
84
84
  `)}
85
- `,changed:i}}function Qc(r){let t=[],e={},n=0;for(let i of[...r].sort((s,a)=>s.path.localeCompare(a.path))){let s=CA(i);t.push(s.text),e[i.path]=s.changed,n+=s.changed}return{text:t.join(""),changedFiles:r.length,changedLines:n,perFileChangedLines:e}}function Wm(r,t){return r.changedFiles<=t.maxFiles&&r.changedLines<=t.maxChangedLines?[]:[{code:"budget-exceeded",message:`Proposal changes ${r.changedFiles} files and ${r.changedLines} lines; configured limits are ${t.maxFiles} files and ${t.maxChangedLines} lines.`,manualRepairRecommended:!0}]}function Jm(r,t,e,n){let i=[];(t.packetHash!==r.packetHash||e.packetHash!==r.packetHash||!e.passed)&&i.push({code:"invalid-provenance",message:"Diagnosis and passing deterministic grading must match the evidence packet."});let s=[...t.hypotheses].sort((d,c)=>d.rank-c.rank)[0],a=new Set(r.evidence.map(d=>d.evidenceId)),o=new Set(t.ownershipEvidenceIds);return(t.repairEligibility!=="eligible"||s===void 0||s.probableOwner!=="test-support"||!new Set(["strong","moderate"]).has(s.evidenceGrade)||o.size===0||[...o].some(d=>!a.has(d)||!s.supportingEvidenceIds.includes(d)))&&i.push({code:"insufficient-ownership-evidence",message:"Repair requires a sufficiently graded test-support hypothesis with positive evidence."}),(n.statement.trim().length===0||n.preservedBehavior.trim().length===0||n.evidenceIds.length===0||n.evidenceIds.some(d=>!a.has(d)||!s?.supportingEvidenceIds.includes(d)))&&i.push({code:"intent-ambiguous",message:"Test intent and preserved behavior require valid positive evidence citations."}),i.length>0||s===void 0?{kind:"rejected",reasons:i}:{kind:"eligible",hypothesis:s}}var Xm=bi(Pn(),1),NA=/\.([cm]?[jt]sx?)$/i;function Zc(r,t){let e=r.match(NA)?.[1]?.toLowerCase();if(e===void 0)return!1;let n=[];e.includes("t")&&n.push("typescript"),e.endsWith("x")&&n.push("jsx");try{return(0,Xm.parse)(t,{sourceType:"unambiguous",errorRecovery:!1,plugins:n}),!0}catch{return!1}}var OA=[{pattern:/\b(?:test|describe|it|context|specify)\.(?:skip|only|fixme)\s*\(|\bx(?:it|test|describe|context|specify)\s*\(|\bf(?:it|describe)\s*\(/g,message:"skip, focus, and expected-failure controls are forbidden",exception:"never"},{pattern:/\bwaitForTimeout\s*\(|\bcy\.wait\(\s*\d|\.pause\s*\(/g,message:"arbitrary fixed waits are forbidden",exception:"never"},{pattern:/\bforce\s*:\s*true\b/g,message:"forcing actions past actionability checks is forbidden",exception:"never"},{pattern:/uncaught:exception/g,message:"suppressing application errors is forbidden",exception:"never"},{pattern:/\bthis\.retries\s*\(|\bretries\s*\(\s*\d/g,message:"retry additions are forbidden",exception:"never"},{pattern:/\bsetTimeout\s*\(/g,message:"timeout increases require a demonstrated latency contract",exception:"latency"},{pattern:/\bretries\s*:/g,message:"retry additions are forbidden",exception:"never"},{pattern:/\btoMatchSnapshot\s*\(/g,message:"broad snapshot acceptance is forbidden",exception:"never"},{pattern:/catch\s*\([^)]*\)\s*\{\s*\}/g,message:"empty catches swallow errors",exception:"never"},{pattern:/\.locator\(\s*["'`](?:#|\.|\/\/|css=)/g,message:"brittle locator regressions require positive evidence",exception:"locator"},{pattern:/(?:\bcy\.get|\.find|(?<![\w$])\$\$?)\(\s*["'`](?:#|\.[A-Za-z_-]|\/\/|\.\/\/)/g,message:"brittle locator regressions require positive evidence",exception:"locator"}];function li(r,t){return[...r.matchAll(t)].length}function Ym(r){return li(r,/\bexpect\s*\(/g)+li(r,/\bassert(?:\.|\s*\()/g)+li(r,/\.(?:should|and)\s*\(/g)}function Qm(r){let t=new Map;for(let e of r.matchAll(/\.((?:(?:not|resolves|rejects)\.)*)(to[A-Z]\w*)\s*\(/g)){let n=`${e[1]??""}${e[2]??""}`;t.set(n,(t.get(n)??0)+1)}for(let e of r.matchAll(/\.(?:should|and)\s*\(\s*["'`]([\w.]+)["'`]/g)){let n=`should:${e[1]??""}`;t.set(n,(t.get(n)??0)+1)}return t}function DA(r,t){let e=Qm(t);return[...Qm(r)].filter(([n,i])=>(e.get(n)??0)<i).map(([n])=>n).sort()}function Zm(r){let t=[];for(let e of r){if(!Zc(e.path,e.source)||!Zc(e.path,e.result)){t.push({code:"parse-failed",message:"Original and resulting source must parse as supported JavaScript or TypeScript.",path:e.path});continue}let n=DA(e.source,e.result);n.length>0&&t.push({code:"forbidden-edit",message:`The proposal removes, negates, or swaps assertion matchers: ${n.join(", ")}.`,path:e.path});for(let i of e.replacements){Ym(i.newText)<Ym(i.oldText)&&t.push({code:"forbidden-edit",message:"The proposal removes or weakens assertion coverage.",path:e.path});for(let s of OA){if(li(i.newText,s.pattern)<=li(i.oldText,s.pattern))continue;let a=s.exception==="latency"?i.latencyContractEvidenceIds??[]:s.exception==="locator"?i.brittleLocatorEvidenceIds??[]:[];s.exception!=="never"&&a.length>0||t.push({code:"forbidden-edit",message:s.message,path:e.path})}}}return t}var LA=/^(?:\.\/)?[A-Za-z0-9_./-]+$/,MA=/^[A-Z][A-Z0-9_]*$/,$A=/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTH)/i,_A=new Set(["focused","affected","static"]);function ey(r){return r.length>0&&!r.includes("\0")&&!r.includes("\\")&&!r.startsWith("/")&&!/^[A-Za-z]:/.test(r)&&!r.split("/").some(t=>t===".."||t==="")}var FA=new Set(["page-object","fixture","test-data","test-helper","playwright-config","framework-config"]);function jA(r){let t=Object.entries(r.environment);return r.id.trim().length>0&&LA.test(r.executable)&&ey(r.executable.replace(/^\.\//,""))&&!r.args.some(e=>e.includes("\0"))&&(r.workingDirectory==="."||ey(r.workingDirectory))&&_A.has(r.scope)&&t.every(([e,n])=>MA.test(e)&&!$A.test(e)&&!n.includes("\0"))&&Number.isInteger(r.timeoutMs)&&r.timeoutMs>0&&r.reason.trim().length>0}function ty(r,t){let e=t.some(s=>FA.has(s)),n=[...r.validation].sort((s,a)=>s.id.localeCompare(a.id));if(n.some(s=>!jA(s)))return{plan:{status:"unresolved",steps:[],unresolvedReasons:["Validation discovery supplied an unsafe or malformed structured step."]},reasons:[{code:"invalid-provenance",message:"Validation plan inputs must be safe structured executable/argument records."}]};let i=[];return n.length===0&&i.push("No deterministic validation steps were discovered."),e&&!n.some(s=>s.scope==="affected")&&i.push("Shared test-support edits require affected-test validation."),{plan:{status:i.length===0?"planned":"unresolved",steps:n,unresolvedReasons:i},reasons:[]}}var el=1e6,tl=1e3;function Je(r){return{kind:"rejected",reasons:r}}function BA(r){let{packetHash:t,...e}=r;return Sr(e)===t}function VA(r,t){let e=[];for(let n of r)[...n.evidenceIds,...n.latencyContractEvidenceIds??[],...n.brittleLocatorEvidenceIds??[]].some(s=>!t.has(s))&&e.push({code:"invalid-replacement",message:"Every replacement and policy exception must cite accepted supporting evidence.",path:n.path});return e}async function rl(r){let t=mr(r.config);if(t.kind!=="valid")return Je(t.issues.map(p=>({code:"invalid-config",message:p})));if(!BA(r.packet)||r.snapshot.workspaceRoot!==r.packet.workspace.root||r.packet.workspace.gitRoot!==void 0&&r.snapshot.gitRoot!==r.packet.workspace.gitRoot)return Je([{code:"invalid-provenance",message:"Packet integrity and repository snapshot identity must match."}]);let e=Jm(r.packet,r.diagnosis,r.grading,r.intent);if(e.kind!=="eligible")return Je(e.reasons);let n=r.maxSourceBytes??el;if(!Number.isInteger(n)||n<=0||n>el)return Je([{code:"invalid-provenance",message:`maxSourceBytes must be an integer from 1 to ${el}.`}]);if(r.replacements.length===0)return Je([{code:"invalid-replacement",message:"Proposal has no replacements."}]);let i=VA(r.replacements,new Set(e.hypothesis.supportingEvidenceIds));if(i.length>0)return Je(i);let s=await Hh(t.config,r.snapshot,r.replacements,n);if(s.kind!=="authorized")return Je(s.reasons);if(s.targets.some(p=>p.source.split(/\r?\n/u).length>tl||p.replacements.some(f=>f.newText.split(/\r?\n/u).length>tl)))return Je([{code:"budget-exceeded",message:`M5 safely derives diffs only for targets and replacement text up to ${tl} lines.`,manualRepairRecommended:!0}]);let a=Vh(s.targets);if(a.kind!=="applied")return Je(a.reasons);let o=Zm(a.targets);if(o.length>0)return Je(o);let d=Qc(a.targets),c=Wm(d,t.config.budgets);if(c.length>0)return Je(c);let l=ty(r.snapshot,a.targets.map(p=>p.class));if(l.reasons.length>0)return Je(l.reasons);let u={schemaVersion:"1.0",policyVersion:"1.0",runId:r.packet.runId,packetHash:r.packet.packetHash,acceptedHypothesisId:e.hypothesis.hypothesisId,intent:r.intent,budgets:t.config.budgets,changedFiles:d.changedFiles,changedLines:d.changedLines,replacements:r.replacements,targets:a.targets.map(p=>({path:p.path,class:p.class,sourceSha256:p.sourceSha256,resultSha256:p.resultSha256,changedLines:d.perFileChangedLines[p.path]??0})),diff:d.text,diffHash:C(d.text),validationPlan:l.plan};return{kind:"proposal-ready",proposal:{...u,proposalHash:C(u)}}}import{readFile as YA,realpath as QA}from"node:fs/promises";import{join as ZA}from"node:path";var zA=new Set(["failed","timedOut","interrupted"]);function HA(r){return r.status==="unexpected"||r.status==="flaky"}function iy(r){return[...r.clusters].sort((t,e)=>e.logicalTestIds.length-t.logicalTestIds.length||t.clusterId.localeCompare(e.clusterId)).slice(0,6)}function qA(r){return r.attachments.reduce((t,e)=>t+(e.name==="trace"||e.contentType==="application/zip"?10:e.path===void 0?0:1),0)}function sy(r,t){let e=new Set(t.logicalTestIds);return r.logicalTests.filter(i=>e.has(i.logicalTestId)).map(i=>{let s=i.attempts.filter(a=>zA.has(a.status));return{test:i,score:Math.max(0,...s.map(qA)),startedAt:s.map(a=>a.startTime).sort()[0]??""}}).sort((i,s)=>s.score-i.score||i.startedAt.localeCompare(s.startedAt)||i.test.logicalTestId.localeCompare(s.test.logicalTestId))[0]?.test}function ay(r,t,e){let n=new Set(t.logicalTestIds);return{...r,logicalTests:r.logicalTests.map(i=>n.has(i.logicalTestId)?i.logicalTestId===e?i:{...i,attempts:i.attempts.map(s=>({...s,attachments:[]}))}:HA(i)?{...i,attempts:[]}:i)}}function oy(r,t,e){return{...e,runId:t.runId,clusters:[{...r,symptomIds:t.symptoms.filter(n=>n.logicalTestId!==void 0&&r.logicalTestIds.includes(n.logicalTestId)).map(n=>n.symptomId).sort()}]}}async function dy(r,t,e){let n=new Array(r.length),i=0,s=Array.from({length:Math.min(t,r.length)},async()=>{for(;i<r.length;){let a=i;i+=1,n[a]=await e(r[a])}});return await Promise.all(s),n}import{randomUUID as ly}from"node:crypto";import{realpath as UA}from"node:fs/promises";import{join as cy,relative as GA,sep as KA}from"node:path";var WA=/^run_[a-f0-9]{24}$/,JA=/^rec_[a-f0-9]{24}$/;function va(){return`rec_${ly().replaceAll("-","").slice(0,24)}`}function Zr(){return`auth_${ly().replaceAll("-","").slice(0,24)}`}async function ui(r,t){if(!WA.test(t.runId)||!JA.test(t.recordId))throw new Error("Run record identity is not path-safe.");let e=await Fe(r,[".kwikqa","runs",t.runId]),n=await Fe(r,[".kwikqa","runs",t.runId,"records"]),i=`${de(t)}
86
- `,s=cy(n,`${t.recordId}.json`);return await me(s,i,{mode:384,replace:!1}),await me(cy(e,"result.json"),i,{mode:384,replace:!0}),GA(await UA(r),s).split(KA).join("/")}var Ia=new Set(["context-limit-exceeded","request-token-budget-exceeded","request-dollar-budget-exceeded","run-token-budget-exceeded","run-dollar-budget-exceeded"]),eS={"test-support":"test-support-owned",application:"application-owned",environment:"environment-owned",undetermined:"owner-undetermined"};function tS(r){return r.logicalTests.filter(t=>t.status==="unexpected"||t.status==="flaky").map(t=>t.logicalTestId).sort()}function rS(r,t){switch(r.usability){case"zero-tests":return{reasonCode:"zero-tests",message:"The report contains no tests to diagnose."};case"interrupted":return{reasonCode:"interrupted-run",message:"The run was interrupted, so its failures cannot support a diagnosis."};case"report-errors":return{reasonCode:"report-errors",message:"The report has run-level errors, so its failures cannot support a diagnosis."};case"analysis-ready":return t.length===0?{reasonCode:"no-failures",message:"The run has no failing or flaky tests."}:void 0}}function Pa(r){let t=[...r.hypotheses].sort((e,n)=>e.rank-n.rank)[0];return eS[t?.probableOwner??"undetermined"]??"owner-undetermined"}function nS(r,t){return r==="operation-failed"?"failed":t?"insufficient-evidence":"completed"}async function Ra(r,t){let e=await et(r.reportPath,{workspaceRoot:r.workspaceRoot,...r.gitRoot===void 0?{}:{gitRoot:r.gitRoot},...r.framework===void 0?{}:{framework:r.framework}});if(e.kind==="unreadable")return{kind:"unreadable",outcome:"inconclusive",reasonCode:e.artifact.availability==="unavailable"?"report-unavailable":"report-unreadable",message:e.diagnostic.message};let n=e.run,i=tS(n),s=(w,x={})=>({kind:"analyzed",stage:{run:n,failing:i,...x,result:w}}),a=await cs(n,{artifactRoot:r.artifactRoot??n.workspace.root,includeCurrentDiff:r.includeCurrentDiff===!0,includeChangeHistory:r.includeChangeHistory===!0,...r.probePath===void 0?{}:{probePath:r.probePath}},{...r.evidencePolicy,workspaceRoot:n.workspace.root});if(a.kind!=="built")return s(a.kind==="invalid-policy"?{outcome:"operation-failed",reasonCode:"invalid-evidence-policy",message:a.message}:{outcome:"inconclusive",reasonCode:"evidence-budget-exceeded",message:a.message,insufficient:!0});let o=a.packet,d=la(n,o),c=jc(d),l={packet:o,symptoms:d,clusters:c},u=rS(n,i);if(u!==void 0)return s({outcome:"inconclusive",...u,insufficient:!0},l);if(r.remote===void 0)return s({outcome:"inconclusive",reasonCode:"remote-diagnosis-not-configured",message:"Local evidence analysis completed; no remote diagnosis was configured."},l);let p=await dS(r,n,c,t),f=aS(p);if(f===void 0)return s({outcome:"inconclusive",reasonCode:"no-failures",message:"No failing test produced a symptom to diagnose.",insufficient:!0},l);let h=p.filter(w=>w.result.reasonCode!=="cluster-not-requested"),g=h.filter(w=>w.result.outcome==="diagnosed").length,m=c.clusters.length-h.length,y=c.clusters.length>1?`${g} of ${c.clusters.length} failure groups diagnosed.${m>0?` ${m} not sent: ${iS(p)}`:""}`:f.result.message;return s({...f.result,message:y},{...f.packet===void 0?l:{packet:f.packet},...f.symptoms===void 0?{}:{symptoms:f.symptoms},...f.clusters===void 0?{}:{clusters:f.clusters},clusterStages:[f,...p.filter(w=>w!==f)],representativeId:f.representativeId})}function iS(r){return r.find(e=>e.result.reasonCode==="cluster-not-requested")?.result.message??"at most 6 groups are sent per analysis."}var sS={strong:3,moderate:2,weak:1,insufficient:0};function uy(r){let[t]=[...r.result.diagnosis?.hypotheses??[]].sort((e,n)=>e.rank-n.rank);return sS[t?.evidenceGrade??""]??0}function Ta(r){return r.map((t,e)=>({item:t,index:e})).filter(({item:t})=>t.result.outcome==="diagnosed"&&t.result.reasonCode==="test-support-owned").sort((t,e)=>uy(e.item)-uy(t.item)||e.item.cluster.logicalTestIds.length-t.item.cluster.logicalTestIds.length||t.index-e.index).map(({item:t})=>t)}function aS(r){let t=r.filter(e=>e.result.outcome==="diagnosed");return Ta(r)[0]??t[0]??r[0]}var oS=new Set(["provider-refusal","malformed-response","schema-invalid","citation-or-grading-invalid"]);async function dS(r,t,e,n){let i=r.remote;if(i===void 0)return[];let s=iy(e),a=[],o=[];for(let m of s){let y=sy(t,m);if(y===void 0)continue;let w=ay(t,m,y.logicalTestId),x=await cs(w,{artifactRoot:r.artifactRoot??t.workspace.root,includeCurrentDiff:r.includeCurrentDiff===!0,includeChangeHistory:r.includeChangeHistory===!0,...r.probePath===void 0?{}:{probePath:r.probePath}},{...r.evidencePolicy,workspaceRoot:t.workspace.root});if(x.kind!=="built"){a.push({cluster:m,representativeId:y.logicalTestId,result:{outcome:"inconclusive",reasonCode:"evidence-budget-exceeded",message:x.message,insufficient:!0}});continue}let v=la(w,x.packet);o.push({cluster:m,representativeId:y.logicalTestId,packet:x.packet,symptoms:v,clusters:oy(m,v,e)})}let d=[];for(let m of o){let y=r.reuseDiagnosis===!0?await lS(t.workspace.root,t.runId,m.packet,m.symptoms):void 0;y===void 0?d.push(m):a.push(Bt(m,y))}let c=a.some(m=>m.result.reasonCode==="test-support-owned"),l=(m,y)=>{for(let w of m)a.push(Bt(w,{outcome:"inconclusive",reasonCode:"cluster-not-requested",message:y}))};if(r.reuseDiagnosis===!0&&c)return l(d,"A recorded diagnosis of another group already supports a repair."),pi(a,s);let u=i.session===void 0?d.slice(0,1):d;l(d.slice(u.length),"the service counts each request separately, so only the largest group was sent.");let f=(await Promise.all(u.map(async m=>({item:m,prepared:await fa({packet:m.packet,symptoms:m.symptoms,clusters:m.clusters,model:i.model,caps:i.caps,transport:i.transport,now:n()})})))).flatMap(({item:m,prepared:y})=>y.kind==="preview-ready"?[{item:m,prepared:y.prepared}]:(a.push(Bt(m,{outcome:Ia.has(y.reasonCode)?"inconclusive":"operation-failed",reasonCode:y.reasonCode,message:y.message,audit:y.audit})),[]));if(f.length===0)return pi(a,s);let h=f.map(m=>m.prepared.preview),g;if(r.interaction.approveDiagnoses!==void 0)g=await r.interaction.approveDiagnoses(h);else{g=!0;for(let m of h)await r.interaction.approveDiagnosis(m)||(g=!1)}if(!g){for(let m of f)a.push(Bt(m.item,{outcome:"inconclusive",reasonCode:"remote-consent-declined",message:"The developer declined the diagnosis request; no evidence was sent."}));return pi(a,s)}if(i.session!==void 0)try{await i.session.open(f.length)}catch(m){let y=m instanceof Error?m.message:"The analysis session could not be opened.";for(let w of f)a.push(Bt(w.item,{outcome:"operation-failed",reasonCode:"session-unavailable",message:y}));return pi(a,s)}try{let m=await dy(f,3,async y=>{let w=await py(r,y.prepared,i.transport,n),x=i.escalation;if(x===void 0||!oS.has(w.reasonCode))return Bt(y.item,w);let v=await cS(r,y.item,x,i.transport,n);return v===void 0?Bt(y.item,w):{...Bt(y.item,v),escalated:!0}});a.push(...m)}finally{await i.session?.close().catch(()=>{})}return pi(a,s)}function pi(r,t){let e=new Map(t.map((n,i)=>[n.clusterId,i]));return[...r].sort((n,i)=>(e.get(n.cluster.clusterId)??0)-(e.get(i.cluster.clusterId)??0))}function Bt(r,t){return{cluster:r.cluster,representativeId:r.representativeId,packet:r.packet,symptoms:r.symptoms,clusters:r.clusters,result:t}}async function py(r,t,e,n){let i=await qc({prepared:t,authorization:{bindingHash:t.authorizationBindingHash,mode:"interactive",authorizedAt:n(),authorizationId:Zr()},authorizationStore:r.authorizationStore??new dr,transport:e,now:n()});switch(i.kind){case"diagnosed":return{outcome:"diagnosed",reasonCode:Pa(i.diagnosis),message:"The diagnosis passed schema validation and local grading.",diagnosis:i.diagnosis,grading:i.grading,audit:i.audit};case"abstained":return{outcome:"inconclusive",reasonCode:i.reasonCode,message:"The evidence was insufficient for a supported diagnosis.",diagnosis:i.diagnosis,grading:i.grading,audit:i.audit};default:return{outcome:Ia.has(i.reasonCode)?"inconclusive":"operation-failed",reasonCode:i.reasonCode,message:i.message,audit:i.audit}}}async function cS(r,t,e,n,i){let s=await fa({packet:t.packet,symptoms:t.symptoms,clusters:t.clusters,model:e.model,caps:e.caps,transport:n,now:i()});if(s.kind==="preview-ready"&&await r.interaction.approveDiagnosis(s.prepared.preview))return py(r,s.prepared,n,i)}async function lS(r,t,e,n){if(/^run_[a-f0-9]{24}$/.test(t))try{let i=await QA(r),s=JSON.parse(await YA(ZA(i,".kwikqa","runs",t,"result.json"),"utf8")),a=u=>u==="diagnosed"||u==="inconclusive",o=[...(s.clusters??[]).filter(u=>a(u.outcome)),...a(s.outcome)?[s]:[]].find(u=>u.diagnosis?.packetHash===e.packetHash&&u.diagnosisAudit!==void 0),d=o?.diagnosis;if(o===void 0||d===void 0||o.diagnosisAudit===void 0)return;let c=di(d,e,n);if(!c.passed)return;let l=o.outcome==="inconclusive";return{outcome:l?"inconclusive":"diagnosed",reasonCode:l?o.reasonCode??"insufficient-evidence":Pa(d),message:"Reused the graded diagnosis recorded for this exact evidence packet.",diagnosis:d,grading:c,audit:o.diagnosisAudit}}catch{return}}function uS(r){return{clusterId:r.cluster.clusterId,logicalTestIds:r.cluster.logicalTestIds,representativeId:r.representativeId,signals:r.cluster.signals,...r.packet===void 0?{}:{packetHash:r.packet.packetHash},outcome:r.result.outcome,reasonCode:r.result.reasonCode,message:r.result.message,...r.result.diagnosis===void 0?{}:{diagnosis:r.result.diagnosis},...r.result.grading===void 0?{}:{grading:r.result.grading},...r.result.audit===void 0?{}:{diagnosisAudit:r.result.audit},...r.escalated===!0?{escalated:!0}:{}}}function Aa(r,t,e,n,i={}){let{run:s,packet:a,symptoms:o,clusters:d}=r,c=r.result;return{schemaVersion:"1.0",recordId:va(),command:t,runId:s.runId,createdAt:s.createdAt,recordedAt:n(),workspace:s.workspace,sourceHashes:a?.sourceHashes??s.sourceHashes,usability:s.usability,failingLogicalTestIds:r.failing,analysis:{status:nS(c.outcome,c.insufficient===!0)},proposal:{status:"not-requested"},application:{status:"not-requested"},validation:{status:"not-requested"},...a===void 0?{}:{evidence:{packetHash:a.packetHash,evidence:a.totals.evidence,artifacts:a.totals.artifacts,omissions:a.totals.omissions,redactions:a.totals.redactions,serializedBytes:a.totals.serializedBytes}},...o===void 0||d===void 0?{}:{symptoms:{symptoms:o.symptoms.length,unclassifiedAttempts:o.unclassifiedAttemptIds.length,clusters:d.clusters.length}},...r.clusterStages===void 0||r.clusterStages.length===0?{}:{clusters:r.clusterStages.map(uS)},...c.diagnosis===void 0?{}:{diagnosis:c.diagnosis},...c.grading===void 0?{}:{grading:c.grading},...c.audit===void 0?{}:{diagnosisAudit:c.audit},...i,outcome:e.outcome,reasonCode:e.reasonCode,message:e.message}}async function Sa(r,t,e){let n={run:r.run,...r.packet===void 0?{}:{packet:r.packet},...r.symptoms===void 0?{}:{symptoms:r.symptoms},...r.clusters===void 0?{}:{clusters:r.clusters}},i=(s,a)=>({outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s,...a===void 0?{}:{recordPath:a},...n});if(!e)return i(t);try{return i(t,await ui(r.run.workspace.root,t))}catch{return i({...t,outcome:"operation-failed",reasonCode:"record-write-failed",message:"The run record could not be written safely under .kwikqa/runs/."})}}async function nl(r){let t=r.now??(()=>new Date().toISOString()),e=await Ra(r,t);if(e.kind==="unreadable")return{outcome:e.outcome,reasonCode:e.reasonCode,message:e.message};let{stage:n}=e;return Sa(n,Aa(n,"analyze",n.result,t),r.persist!==!1)}import{randomUUID as CS}from"node:crypto";import{relative as NS,resolve as OS,sep as DS}from"node:path";import{createHash as fy}from"node:crypto";import{lstat as pS,readFile as fS,realpath as Ea}from"node:fs/promises";import{isAbsolute as hS,join as mS,relative as yS,resolve as gS,sep as wS}from"node:path";var Vt=/^[a-f0-9]{64}$/,my=/^vld_[a-f0-9]{24}$/,bS=Ot,xS=4*1024*1024,vS=2*1024*1024;function yr(r){return{code:"transaction-unavailable",message:r}}function fi(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function sl(r,t){let e=Object.keys(r).sort(),n=[...t].sort();return e.length===n.length&&e.every((i,s)=>i===n[s])}function il(r){return Array.isArray(r)&&r.every(t=>typeof t=="string"&&t.length>0&&!t.includes("\0"))}function kS(r,t){let e=yS(r,t);return e===""||!hS(e)&&e!==".."&&!e.startsWith(`..${wS}`)}function IS(r){return typeof r=="string"&&r.length>0&&Number.isFinite(Date.parse(r))}function hy(r){return fi(r)?sl(r,["path","observedBytes","storedBytes","sha256","storedSha256","truncated","redacted"])&&typeof r.path=="string"&&r.path.length>0&&typeof r.sha256=="string"&&Vt.test(r.sha256)&&typeof r.storedSha256=="string"&&Vt.test(r.storedSha256)&&Number.isInteger(r.observedBytes)&&r.observedBytes>=0&&Number.isInteger(r.storedBytes)&&r.storedBytes>=0&&typeof r.truncated=="boolean"&&typeof r.redacted=="boolean":!1}function yy(r){if(!fi(r))throw new Error("Validation command record is not an object.");let t=r,{recordHash:e,...n}=t;if(!sl(r,["schemaVersion","validationRunId","commandId","commandHash","planHash","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","startedAt","durationMs","termination","stdout","stderr","artifacts","status","recordHash"])||t.schemaVersion!=="1.0"||!my.test(t.validationRunId)||!bS.test(t.commandId)||!Vt.test(t.commandHash)||!Vt.test(t.planHash)||t.timing!=="post-patch"||t.required!==!0||t.executable!==process.execPath||!il(t.args)||typeof t.kind!="string"||t.kind.length===0||typeof t.workingDirectory!="string"||t.workingDirectory.length===0||!fi(t.environmentDelta)||!Object.entries(t.environmentDelta).every(([i,s])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)&&typeof s=="string"&&!s.includes("\0"))||!Number.isInteger(t.timeoutMs)||t.timeoutMs<=0||typeof t.purpose!="string"||t.purpose.length===0||!il(t.logicalTestIds)||!il(t.projectIds)||!IS(t.startedAt)||!Number.isInteger(t.durationMs)||t.durationMs<0||!fi(t.termination)||t.termination.kind!=="exit"||t.termination.exitCode!==0||!hy(t.stdout)||!hy(t.stderr)||t.stdout.truncated||t.stderr.truncated||!Array.isArray(t.artifacts)||!t.artifacts.every(i=>fi(i)&&sl(i,["path","sha256","bytes"])&&typeof i.path=="string"&&i.path.length>0&&typeof i.sha256=="string"&&Vt.test(i.sha256)&&Number.isInteger(i.bytes)&&i.bytes>=0)||t.status!=="passed"||!Vt.test(e)||C(n)!==e)throw new Error("Validation command record is malformed or non-passing.");return t}function PS(r){let t=Dt(JSON.parse(r));if(t.status!=="passed")throw new Error("Validation manifest is not passing.");for(let e of t.commandRecords)yy(e);return t}async function gy(r){let[t,e,n,i]=await Promise.all([Ea(r.workspace.workspaceRoot),Ea(r.snapshot.workspaceRoot),Ea(r.workspace.gitRoot),Ea(r.snapshot.gitRoot)]);if(t!==e||n!==i)throw new Error("Validation workspace identity changed.");return t}async function wy(r,t,e){for(let n of e.manifest.targets){let i=await K(r,n.path,t.maxTargetBytes);if(i.kind!=="read"||i.relativePath!==n.path||i.sha256!==n.resultSha256)return!1}return!0}function by(r){return Vt.test(r.planHash)&&my.test(r.validationRunId)}async function Ca(r,t,e){let n=gS(r,t);if(!kS(r,n))throw new Error("Validation record path escapes its run.");let i=await pS(n);if(!i.isFile()||i.isSymbolicLink()||i.size>e)throw new Error("Validation record path is unsafe or unbounded.");return fS(n)}async function RS(r,t,e){let n=new Map(e.requiredCommands.map(i=>[i.commandId,i.commandHash]));for(let i of t.commandRecords){if(i.validationRunId!==t.validationRunId||i.planHash!==t.planHash||n.get(i.commandId)===void 0)return!1;let s=n.get(i.commandId);if(s===void 0||i.commandHash!==s)return!1;let a=await Ca(r,`commands/${i.commandId}/result.json`,vS),o=yy(JSON.parse(a.toString("utf8")));if(C(o)!==C(i))return!1;for(let d of[i.stdout,i.stderr]){let c=await Ca(r,d.path,rr);if(c.byteLength!==d.storedBytes||fy("sha256").update(c).digest("hex")!==d.storedSha256)return!1}for(let d of i.artifacts){let c=await Ca(r,d.path,_r);if(c.byteLength!==d.bytes||fy("sha256").update(c).digest("hex")!==d.sha256)return!1}}return!0}async function al(r){if(!by(r))return{kind:"rejected",reasons:[yr("Validation identity is invalid.")]};let t=r.now??new Date().toISOString(),e;try{let n=await gy(r.context);e=await Ue(n,{operation:"begin-validation",transactionId:r.transactionId,validationRunId:r.validationRunId,at:t});let i=await xe(n,r.transactionId),s=i.state.history.at(-1);return i.state.phase==="validating"&&s?.type==="validation-started"&&s.planHash===r.planHash&&s.validationRunId===r.validationRunId?{kind:"validating",transaction:Pe(i)}:i.state.phase!=="applied"||i.manifest.preview.authoritativeValidation.planHash!==r.planHash||!await wy(n,r.context,i)?{kind:"rejected",reasons:[yr("Applied transaction does not match the approved validation handoff.")],transaction:Pe(i)}:(i=await Be({transaction:i,phase:"validating",type:"validation-started",planHash:r.planHash,validationRunId:r.validationRunId,now:t}),{kind:"validating",transaction:Pe(i)})}catch{return{kind:"failed",reasons:[yr("Validation transition failed closed.")]}}finally{await e?.release().catch(()=>{})}}async function ol(r){if(!by(r)||!Vt.test(r.validationManifestHash))return{kind:"rejected",reasons:[yr("Validation completion identity is invalid.")]};let t=r.now??new Date().toISOString(),e;try{let n=await gy(r.context);e=await Ue(n,{operation:"complete-validation",transactionId:r.transactionId,validationRunId:r.validationRunId,at:t});let i=await xe(n,r.transactionId),s=i.manifest.preview.authoritativeValidation,a=i.state.history.at(-1);if(i.state.phase==="completed"&&a?.type==="validation-passed"&&a.planHash===r.planHash&&a.validationRunId===r.validationRunId&&a.validationManifestHash===r.validationManifestHash)return{kind:"completed",transaction:Pe(i)};if(i.state.phase!=="validating"||s.planHash!==r.planHash||a?.type!=="validation-started"||a.validationRunId!==r.validationRunId||a.planHash!==r.planHash||!await wy(n,r.context,i))return{kind:"rejected",reasons:[yr("Transaction is not validating this exact approved run.")],transaction:Pe(i)};let o=mS(i.directory,"validation",r.validationRunId),d=await Ca(o,"manifest.json",xS),c=PS(d.toString("utf8")),l=new Set(c.requiredCommandIds),u=new Set(c.commandRecords.map(f=>f.commandId)),p=s.targetHashes;return c.manifestHash!==r.validationManifestHash||c.transactionId!==r.transactionId||c.validationRunId!==r.validationRunId||c.planHash!==r.planHash||c.repositoryFingerprint!==s.repositoryFingerprint||C(c.targetHashes)!==C(p)||l.size!==c.requiredCommandIds.length||u.size!==c.commandRecords.length||s.requiredCommandIds.some(f=>!l.has(f)||!u.has(f))||l.size!==s.requiredCommandIds.length||u.size!==s.requiredCommandIds.length||!await RS(o,c,s)?{kind:"rejected",reasons:[yr("Validation manifest does not prove the exact approved command set.")],transaction:Pe(i)}:(i=await Be({transaction:i,phase:"completed",type:"validation-passed",planHash:r.planHash,validationRunId:r.validationRunId,validationManifestHash:c.manifestHash,now:t}),{kind:"completed",transaction:Pe(i)})}catch{return{kind:"failed",reasons:[yr("Validation completion failed closed.")]}}finally{await e?.release().catch(()=>{})}}import{join as TS}from"node:path";var xy="1.0",AS=/^rps_[a-f0-9]{24}$/,SS=8*1024*1024;function ES(r){if(typeof r!="object"||r===null)return;let t=r;if(!(typeof t.reportPath!="string"||!Array.isArray(t.logicalTestIds)||!t.logicalTestIds.every(e=>typeof e=="string")||t.framework!==void 0&&!wr.includes(t.framework)))return{reportPath:t.reportPath,...t.framework===void 0?{}:{framework:t.framework},logicalTestIds:t.logicalTestIds}}function vy(r){if(!AS.test(r))throw new Error("Repair session id is invalid.");return[".kwikqa","repairs",r]}async function ky(r,t){let e=await Fe(r,vy(t.repairSessionId));await me(TS(e,`attempt-${t.attempt}.json`),`${de(t)}
87
- `,{mode:384,replace:!1})}async function Iy(r,t,e){let n=await Fe(r,vy(t)),i=await ar(n,`attempt-${e}.json`,SS),s=mr(i.config);if(i.schemaVersion!==xy||i.repairSessionId!==t||i.attempt!==e||typeof i.transactionId!="string"||i.workspace===void 0||typeof i.maxTargetBytes!="number"||i.record===void 0||s.kind!=="valid")throw new Error("Repair attempt state is malformed.");let a=ES(i.group);return{schemaVersion:xy,repairSessionId:t,attempt:e,transactionId:i.transactionId,plan:nr(i.plan),workspace:i.workspace,config:s.config,maxTargetBytes:i.maxTargetBytes,record:i.record,...a===void 0?{}:{group:a}}}import{dirname as Py,resolve as Ry}from"node:path";function en(r,t){return{kind:"configuration",path:r.relativePath,sha256:r.sha256,detail:t}}async function Ty(r){let{run:t,test:e,discovery:n}=r,i=t.framework;if(i==="playwright")return{kind:"unavailable",message:"Playwright validation needs no prepared run."};let s=t.configFile??await Ri(r.workspaceRoot,i,e.location.file),a=n.scope==="focused"?[e.location.file]:n.scope==="affected"?n.testPaths:[],o=await Ws(r.workspaceRoot);if(i==="cypress"){let c=await Ti(r.workspaceRoot,s),l=n.scope==="focused"?t.logicalTests.filter(f=>f.location.file===e.location.file&&f.projectId===e.projectId&&f.status==="expected"):[],u=await Js({workspaceRoot:r.workspaceRoot,runtime:o,...s===void 0?{}:{configFile:s},specs:a,screenshotsDirectory:`${r.artifactRoot}/screenshots`,noRetries:!0,capture:{directory:`${r.artifactRoot}/capture`,supportFile:c,...n.scope==="focused"?{only:[e,...l].map(f=>f.titlePath.join(" "))}:{}}}),p=l.map(f=>f.logicalTestId);return{kind:"prepared",prepared:{args:u.args,workingDirectory:s===void 0?r.workspaceRoot:Py(Ry(r.workspaceRoot,s)),evidence:[en(o["cypress-reporter.cjs"],"KwikQA's Cypress reporter."),en(o["cypress-capture.js"],"KwikQA's Cypress failure capture."),...u.generated.map(f=>en(f,"Support file KwikQA generated for this validation."))],companionLogicalTestIds:p}}}if(s===void 0)return{kind:"unavailable",message:"No wdio.conf was found for the failing spec, so its validation run is unknown."};let d=await Xs({workspaceRoot:r.workspaceRoot,runtime:o,configFile:s,specs:a,directory:`${r.artifactRoot}/runner`,noRetries:!0,...n.scope==="focused"?{grep:em(e.titlePath)}:{},capture:!0});return{kind:"prepared",prepared:{args:d.args,workingDirectory:Py(Ry(r.workspaceRoot,s)),evidence:[en(o["wdio-reporter.mjs"],"KwikQA's WebdriverIO reporter."),en(o["wdio-capture.mjs"],"KwikQA's WebdriverIO run wrapper."),...d.generated.map(c=>en(c,"WebdriverIO config KwikQA generated for this validation."))],companionLogicalTestIds:[]}}}var LS=600*1e3,Ay=1e6,MS={maxFiles:5e3,maxFileBytes:1024*1024,maxTotalBytes:64*1024*1024,maxImportEdges:5e4,maxImportDepth:20},$S={biome:"@biomejs/biome",prettier:"prettier",typescript:"typescript",eslint:"eslint"};function Na(r,t,e,n){let i=r.logicalTests.filter(l=>l.status==="unexpected"||l.status==="flaky"),s=[...t.hypotheses].sort((l,u)=>l.rank-u.rank)[0],a=new Set([...s?.supportingEvidenceIds??[],...t.ownershipEvidenceIds]),o=new Set(e.evidence.filter(l=>a.has(l.evidenceId)&&l.logicalTestId!==void 0).map(l=>l.logicalTestId)),d=i.filter(l=>o.has(l.logicalTestId));if(d.length===1)return d[0];let c=i.find(l=>l.logicalTestId===n);return c!==void 0&&(d.length===0||d.includes(c))?c:i.length===1?i[0]:void 0}function _S(r){return Na(r.run,r.diagnosis,r.packet,r.representativeId)}function Sy(r){return r.payloadManifestHash===void 0||r.payloadHash===void 0?[]:[{manifestHash:r.payloadManifestHash,payloadHash:r.payloadHash,packetHash:r.packetHash,model:r.model.modelId,provider:r.model.providerId,promptVersion:r.promptVersion,outputSchemaVersion:r.outputSchemaVersion}]}function FS(r){return{maxRequestTokens:r.request.maxInputTokens+r.request.maxOutputTokens,maxRunTokens:r.run.maxInputTokens+r.run.maxOutputTokens,maxRequestDollars:r.request.maxDollars,maxRunDollars:r.run.maxDollars}}var jS={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};async function BS(r,t,e,n){let i=async o=>{let d=await Yn({workspaceRoot:r,ownerPath:t,packageName:o});return d.kind==="resolved"?d.tool:void 0},s={},a=await i(jS[e]);a!==void 0&&(s[e]=a);for(let o of new Set(n)){if(o==="kwikqa-babel")continue;let d=await i($S[o]);d!==void 0&&(s[o]=d)}return s}async function Ey(r){let{input:t,now:e,run:n,proposal:i,repository:s}=r,a={repairProposal:i,repairAudit:r.repairAudit},o=(P,O)=>r.finish({outcome:"validation-unavailable",reasonCode:P,message:O},{...a,proposal:{status:"ready"},application:{status:"not-run"},validation:{status:"unavailable"}}),d=_S(r);if(d===void 0)return o("original-test-ambiguous","The repair cannot be validated because the original failing test is ambiguous.");let c=n.projects.find(P=>P.projectId===d.projectId),l=await Rd({workspaceRoot:s.workspaceRoot,targets:i.targets.map(P=>({path:P.path,class:P.class})),originalTestPath:d.location.file,projects:n.projects.map(P=>({id:P.name,testDirectory:P.testDir??"",...n.configFile===void 0?{}:{configPath:n.configFile}})),limits:MS}),u=l.scope==="focused"&&l.projectIds.length===0&&c!==void 0&&c.name!==""?{...l,projectIds:[c.name]}:l,p=await BS(s.workspaceRoot,d.location.file,n.framework,u.staticChecks.map(P=>P.tool)),f=`.kwikqa/validation-artifacts/${i.proposalHash.slice(0,24)}`,h;if(n.framework!=="playwright"&&u.status==="resolved"){let P=await Ty({workspaceRoot:s.workspaceRoot,run:n,test:d,discovery:u,artifactRoot:f});if(P.kind==="unavailable")return o("validation-scope-unavailable",P.message);h=P.prepared}let g=zd({proposal:i,advisoryPlan:i.validationPlan,discovery:u,tools:p,workspaceRoot:s.workspaceRoot,originalTest:{path:d.location.file,line:d.location.line??1,logicalTestId:d.logicalTestId,projectId:c===void 0||c.name===""?d.projectId:c.name,...n.configFile===void 0?{}:{configPath:n.configFile},environmentEquivalent:t.environmentEquivalent!==!1},artifactRoot:f,timeoutMs:t.validationTimeoutMs??LS,framework:n.framework,...h===void 0?{}:{frameworkRun:{args:h.args,workingDirectory:h.workingDirectory,evidence:h.evidence},companionLogicalTestIds:h.companionLogicalTestIds}}),m=g.plan;if(m.status!=="resolved")return o("validation-scope-unavailable",m.unresolvedReasons.map(P=>P.message).join(" "));if(g.requiredBaselineCommands.length>0)return o("baseline-capture-unavailable","This repair changes shared test support, which needs a pre-patch baseline that cannot be captured yet.");let y=r.retry===void 0?1:2,w=r.retry?.repairSessionId??(await tc({workspaceRoot:s.workspaceRoot,originalRunId:n.runId,originalPacketHash:r.packet.packetHash,now:e()})).repairSessionId,x={config:r.config,snapshot:{workspaceRoot:s.workspaceRoot,gitRoot:s.gitRoot,dirtyPaths:s.dirtyPaths,validation:[]},workspace:{workspaceRoot:s.workspaceRoot,gitRoot:s.gitRoot},maxTargetBytes:Ay},v={sessionId:`kwikqa-${CS()}`},I=Ud({proposal:i,context:x,payloadManifests:[...r.diagnosisAudit===void 0?[]:Sy(r.diagnosisAudit),...Sy(r.repairAudit)],costBounds:FS(r.caps),scopes:{baseline:[],validation:[u.scope]},authoritativeValidation:Hd({plan:m,advisoryPlan:i.validationPlan,repairSessionId:w,attemptOrdinal:y}),previewedAt:e(),interactiveSession:v}),R={repairSessionId:w,attempt:y,planHash:m.planHash};if(I.kind!=="preview-ready")return r.finish({outcome:"operation-failed",reasonCode:"application-rejected",message:I.reasons.map(P=>P.message).join(" ")},{...a,proposal:{status:"ready"},application:{status:"blocked"}});if(!await t.interaction.approveApplication(I.preview,m))return r.finish({outcome:"repair-declined",reasonCode:"application-declined",message:"The developer declined the patch and validation plan; nothing was changed."},{...a,proposal:{status:"declined"},application:{status:"not-run"},repair:R});let E=Zr(),A=e(),N=await Wd({preview:I.preview,authorization:{authorizationId:E,bindingHash:Bs(I.preview,E,A,v),authorizedAt:A,interactiveSession:v},context:x,now:A});if(N.kind!=="applied")return r.finish({outcome:"operation-failed",reasonCode:N.kind==="recovery-required"?"application-recovery-required":"application-rejected",message:N.reasons.map(P=>P.message).join(" ")},{...a,proposal:{status:"approved"},application:{status:N.kind==="recovery-required"?"recovery-required":"failed"},repair:R});let B=N.transaction.transactionId;await ic(s.workspaceRoot,w,{ordinal:y,proposalHash:i.proposalHash,transactionId:B,outcome:"applied",recordedAt:e()});let V=(r.memberIds??[]).filter(P=>P!==d.logicalTestId);return await ky(s.workspaceRoot,{schemaVersion:"1.0",repairSessionId:w,attempt:y,transactionId:B,plan:m,workspace:x.workspace,config:r.config,maxTargetBytes:Ay,...V.length===0?{}:{group:{reportPath:NS(s.workspaceRoot,OS(s.workspaceRoot,t.reportPath)).split(DS).join("/"),...t.framework===void 0?{}:{framework:t.framework},logicalTestIds:V}},record:{runId:n.runId,createdAt:n.createdAt,workspace:n.workspace,sourceHashes:r.packet.sourceHashes,usability:n.usability,failingLogicalTestIds:n.logicalTests.filter(P=>P.status==="unexpected"||P.status==="flaky").map(P=>P.logicalTestId).sort()}}),r.finish({outcome:"awaiting-validation",reasonCode:"patch-applied",message:"The approved patch was applied. Run `kwikqa validate` to verify it."},{...a,proposal:{status:"approved"},application:{status:"applied"},repair:{...R,transactionId:B}})}import{execFile as VS}from"node:child_process";import{realpath as dl}from"node:fs/promises";import{isAbsolute as zS,relative as HS,resolve as Ny,sep as Cy}from"node:path";import{promisify as qS}from"node:util";var US=qS(VS),GS=3e4,KS=16*1024*1024;async function cl(r,t){return(await US("git",["-C",r,"--no-optional-locks",...t],{timeout:GS,maxBuffer:KS,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}function Oy(r){let t=r.split("\0"),e=[];for(let n=0;n<t.length;n+=1){let i=t[n]??"";if(i.length<4)continue;let s=i.slice(0,2);if(e.push(i.slice(3)),s.includes("R")||s.includes("C")){let a=t[n+1];a!==void 0&&a.length>0&&e.push(a),n+=1}}return e}function WS(r,t,e){let n=HS(r,Ny(t,e));if(!(n===""||zS(n)||n===".."||n.startsWith(`..${Cy}`)))return n.split(Cy).join("/")}async function ll(r){let t=await dl(r);return(await cl(t,["-c","core.quotePath=false","ls-files","-z"])).split("\0").filter(n=>n.length>0).sort()}async function hi(r){let t,e,n;try{t=await dl(r),e=await dl(Ny((await cl(t,["rev-parse","--show-toplevel"])).trim())),n=await cl(e,["-c","core.quotePath=false","status","--porcelain=v1","-z","--untracked-files=all","--ignored=no"])}catch(a){let o=a,d=o.code==="ENOENT"?"git executable was not found.":(o.stderr??o.message??"").trim().split(`
88
- `)[0]??"";return{kind:"unavailable",message:`Repository status could not be read: ${d===""?"git failed.":d}`}}let i=Oy(n),s=[...new Set(i.map(a=>WS(t,e,a)).filter(a=>a!==void 0))].sort();return{kind:"read",status:{workspaceRoot:t,gitRoot:e,dirtyPaths:s,pristine:i.length===0}}}var JS="kwikqa.config.json",XS=256*1024;async function YS(r,t){let e=await K(r,t,XS);if(e.kind==="unavailable")return{kind:"repair-config-missing",message:`Repair requires a reviewed ${t}; none was found in the workspace.`};if(e.kind!=="read")return{kind:"repair-config-invalid",message:`${t} could not be read: ${e.message}`};let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.bytes))}catch{return{kind:"repair-config-invalid",message:`${t} is not valid UTF-8 JSON.`}}let i=mr(n);return i.kind!=="valid"?{kind:"repair-config-invalid",message:i.issues.join(" ")}:i}function QS(r,t,e){let n=new Set(e.map(s=>s.toLocaleLowerCase("en-US"))),i=new Set;for(let s of r.evidence){if(s.locator.type!=="source-range")continue;let a=s.locator.path;ti(a,t.editablePaths)!==void 0&&!ei(a,t)&&!Zn(a)&&!n.has(a.toLocaleLowerCase("en-US"))&&i.add(a)}return[...i].sort()}async function ul(r){let t=r.now??(()=>new Date().toISOString()),e=await hi(r.workspaceRoot);if(e.kind==="unavailable")return{outcome:"operation-failed",reasonCode:"repository-status-unavailable",message:e.message};let{workspaceRoot:n,gitRoot:i,dirtyPaths:s,pristine:a}=e.status,o=await YS(n,r.configPath??JS);if(o.kind!=="valid")return{outcome:"operation-failed",reasonCode:o.kind,message:o.message};let d=o.config;if(r.retryRepairSessionId!==void 0&&(await $t(n,r.retryRepairSessionId).catch(()=>{}))?.state!=="retry-approval-required")return{outcome:"operation-failed",reasonCode:"no-retry-available",message:"That repair session has no retry available; only one retry follows a failed validation."};let c=await Ra({...r,workspaceRoot:n,gitRoot:i},t);if(c.kind==="unreadable")return{outcome:c.outcome,reasonCode:c.reasonCode,message:c.message};let{stage:l}=c,u={workspaceRoot:n,gitRoot:i,dirtyPaths:s},p=(g,m=[])=>(y,w={})=>Sa(g,Aa(g,"fix",m.length===0?y:{...y,message:`${m.join(" ")} ${y.message}`},t,{repository:{pristine:a,dirtyPaths:s},...w}),r.persist!==!1),f=i0(l,r);if("refusal"in f)return p(l)(f.refusal);if(f.groups.length===0){let{packet:g}=l,{diagnosis:m,grading:y}=l.result;return l.result.outcome!=="diagnosed"||g===void 0||m===void 0||y===void 0?p(l)(l.result):Dy(r,l,{packet:g,diagnosis:m,grading:y},d,t,p(l),u)}let h=[];f.groups.length>0&&await r.repairSession?.open(f.groups.length);try{let g;for(let m of f.groups){let y=n0(l,m),{packet:w}=y,{diagnosis:x,grading:v}=m.result;if(!(w===void 0||x===void 0||v===void 0)){if(g=await Dy(r,y,{packet:w,diagnosis:x,grading:v},d,t,p(y,h),u),!t0(g))return g;h.push(`Failure group ${r0(l,m)}: ${g.message}`)}}return g??p(l)(l.result)}finally{await r.repairSession?.close()}}var ZS=3,e0=new Set(["model-declined-repair","repair-not-eligible","failure-not-reproduced","insufficient-ownership-evidence","intent-ambiguous","invalid-replacement","unauthorized-target","dirty-target-file","source-hash-mismatch","non-unique-match","overlapping-replacement","forbidden-edit","parse-failed","budget-exceeded","unreadable-target"]);function t0(r){return r.outcome==="abstained-from-repair"?e0.has(r.reasonCode):r.outcome==="validation-unavailable"&&r.record?.application.status==="not-run"}function r0(r,t){return(r.clusterStages??[]).indexOf(t)+1}function n0(r,t){return{...r,...t.packet===void 0?{}:{packet:t.packet},...t.symptoms===void 0?{}:{symptoms:t.symptoms},...t.clusters===void 0?{}:{clusters:t.clusters},result:t.result,clusterStages:[t,...(r.clusterStages??[]).filter(e=>e!==t)],representativeId:t.representativeId}}function i0(r,t){let e=r.clusterStages??[];if(t.group!==void 0){let s=e[t.group-1];return s===void 0?{refusal:{outcome:"operation-failed",reasonCode:"group-not-found",message:`There is no failure group ${t.group}; this run has ${e.length}.`}}:Ta([s]).includes(s)?{groups:[s]}:{refusal:{outcome:"abstained-from-repair",reasonCode:"group-not-repairable",message:`Failure group ${t.group} is not diagnosed as the test's fault (${s.result.reasonCode}); KwikQA repairs only test-side causes.`}}}let n=Ta(e),i=t.repairSession===void 0||t.retryRepairSessionId!==void 0?1:ZS;return{groups:n.slice(0,i)}}async function s0(r,t){let{interaction:e}=r;if(e.confirmFailure===void 0||r.retryRepairSessionId!==void 0)return;let n=t.clusterStages?.[0]?.cluster.logicalTestIds??t.failing,i=t.representativeId??n[0];if(i===void 0)return;let s=await e.confirmFailure(t.run,n);if(s.kind==="declined")return{status:"declined",logicalTestIds:n,message:"The developer chose not to re-run the failing tests first."};if(s.kind==="unavailable")return{status:"unavailable",logicalTestIds:n,message:s.message};let a=n.filter(d=>s.failedAgain.includes(d));if(a.includes(i))return{status:"reproduced",logicalTestIds:n,failedAgain:a};let o=t.run.logicalTests.find(d=>d.logicalTestId===i)?.title;return{status:"not-reproduced",logicalTestIds:n,failedAgain:a,message:`${o===void 0?"The failing test":`"${o}"`} passed when re-run, so the failure looks flaky or depends on state the re-run did not have. KwikQA does not patch a test that passes; no repair was requested.`}}async function Dy(r,t,e,n,i,s,a){let{packet:o,diagnosis:d,grading:c}=e,l=[...d.hypotheses].sort((y,w)=>y.rank-w.rank)[0],u=r.repairCaps??r.remote.caps,p=await Wc({packet:o,diagnosis:d,grading:c,hypothesisId:l?.hypothesisId??"",editablePaths:QS(o,n,a.dirtyPaths),budgets:n.budgets,model:r.repairModel??r.remote.model,caps:u,transport:r.remote.transport,now:i()});if(p.kind!=="preview-ready"){let y=p.reasonCode==="repair-not-eligible"&&l?.probableOwner!=="test-support"?Pa(d):p.reasonCode,w=p.reasonCode==="repair-not-eligible"||Ia.has(p.reasonCode);return s({outcome:w?"abstained-from-repair":"operation-failed",reasonCode:y,message:p.message},{proposal:{status:w?"not-eligible":"failed"},repairAudit:p.audit})}let f=await s0(r,t),h=(y,w={})=>s(y,{...f===void 0?{}:{confirmation:f},...w});if(f?.status==="not-reproduced")return h({outcome:"abstained-from-repair",reasonCode:"failure-not-reproduced",message:f.message??"The failing test passed when re-run."},{proposal:{status:"not-eligible"}});if(!await r.interaction.approveRepairRequest(p.prepared.preview))return h({outcome:"repair-declined",reasonCode:"remote-consent-declined",message:"The developer declined the repair-proposal request; no evidence was sent."},{proposal:{status:"declined"}});let g=await Jc({prepared:p.prepared,authorization:{bindingHash:p.prepared.authorizationBindingHash,mode:"interactive",authorizedAt:i(),authorizationId:Zr()},authorizationStore:r.authorizationStore??new dr,transport:r.remote.transport,now:i()});if(g.kind==="declined")return h({outcome:"abstained-from-repair",reasonCode:g.reasonCode,message:g.message},{proposal:{status:"not-eligible"},repairAudit:g.audit});if(g.kind!=="proposed")return h({outcome:"operation-failed",reasonCode:g.reasonCode,message:g.message},{proposal:{status:"failed"},repairAudit:g.audit});let m=await rl({packet:o,diagnosis:d,grading:c,config:n,snapshot:{workspaceRoot:a.workspaceRoot,gitRoot:a.gitRoot,dirtyPaths:a.dirtyPaths,validation:[]},intent:g.draft.intent,replacements:g.draft.replacements});if(m.kind==="rejected"){let[y]=m.reasons;return h({outcome:"abstained-from-repair",reasonCode:y?.code??"invalid-replacement",message:m.reasons.map(w=>w.message).join(" ")},{proposal:{status:"not-eligible"},repairAudit:g.audit,proposalRejections:m.reasons})}return r.proposeOnly===!0?h({outcome:"proposal-ready",reasonCode:"test-support-owned",message:"A policy-checked proposal is ready for review; nothing was applied."},{proposal:{status:"ready"},repairAudit:g.audit,repairProposal:m.proposal}):Ey({input:r,now:i,run:t.run,packet:o,diagnosis:d,...t.representativeId===void 0?{}:{representativeId:t.representativeId},...t.clusterStages?.[0]===void 0?{}:{memberIds:t.clusterStages[0].cluster.logicalTestIds},proposal:m.proposal,config:n,repository:a,diagnosisAudit:t.result.audit,repairAudit:g.audit,caps:u,...r.retryRepairSessionId===void 0?{}:{retry:{repairSessionId:r.retryRepairSessionId}},finish:h})}import{randomUUID as a0}from"node:crypto";import{realpath as o0}from"node:fs/promises";import{join as d0,relative as c0,sep as pl}from"node:path";var l0={maxStreamBytes:4*1024*1024,maxTotalStreamBytes:16*1024*1024,terminationGraceMs:5e3},u0=32*1024*1024,p0=new Set(["applied","validating"]);function f0(){return`vld_${a0().replaceAll("-","").slice(0,24)}`}function h0(r){return{config:r.config,snapshot:{workspaceRoot:r.workspace.workspaceRoot,gitRoot:r.workspace.gitRoot,dirtyPaths:[],validation:[]},workspace:r.workspace,maxTargetBytes:r.maxTargetBytes}}function m0(r,t,e){let n=i=>c0(r,`${t}${pl}${i.split("/").join(pl)}`).split(pl).join("/");for(let i of e.commandRecords){let s=i.artifacts.find(d=>d.path.endsWith("/report.json"));if(s!==void 0)return n(s.path);let o=i.artifacts.filter(d=>Ms.test(d.path.split("/").at(-1)??""))[0];if(o!==void 0)return n(o.path.split("/").slice(0,-1).join("/"))}}async function y0(r,t,e){let n=t.group;if(n===void 0||n.logicalTestIds.length===0||r.checkGroup===void 0)return;let{logicalTestIds:i}=n,s=`${i.length} other test${i.length===1?"":"s"}`,a=await et(d0(e,n.reportPath),{workspaceRoot:e,gitRoot:t.workspace.gitRoot,...n.framework===void 0?{}:{framework:n.framework}}),o=a.kind==="parsed"?new Set(a.run.logicalTests.map(u=>u.logicalTestId)):void 0;if(a.kind!=="parsed"||!i.every(u=>o?.has(u)))return{status:"unavailable",logicalTestIds:i,message:`The report fix read has changed, so the group's ${s} were not re-run.`};let d=await r.checkGroup(a.run,i);if(d.kind==="declined")return{status:"declined",logicalTestIds:i,message:`The group's ${s} were not re-run.`};if(d.kind==="unavailable")return{status:"unavailable",logicalTestIds:i,message:d.message};let c=i.filter(u=>d.failedAgain.includes(u)),l=c.map(u=>a.run.logicalTests.find(p=>p.logicalTestId===u)?.title??u).map(u=>`"${u}"`).join(", ");return{status:"rerun",logicalTestIds:i,stillFailing:c,message:c.length===0?`The group's ${s} pass now as well.`:`${c.length} of the group's ${s} still fail${c.length===1?"s":""}: ${l}. The patch stays; run \`kwikqa fix\` again for them.`}}async function hl(r){let t=r.now??(()=>new Date().toISOString()),e=()=>new Date().toISOString(),n=await o0(r.workspaceRoot),i=await Yd(n);if(i.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-recovery-required",message:i.reasons.map(R=>R.message).join(" ")};let s=i.transactions.filter(R=>p0.has(R.phase));if(s.length!==1||s[0]===void 0)return{outcome:"operation-failed",reasonCode:"no-pending-repair",message:s.length===0?"There is no applied repair waiting for validation. Run `kwikqa fix` first.":"More than one repair is waiting for validation; recover the workspace first."};let a=await xe(n,s[0].transactionId),o=a.manifest.preview.authoritativeValidation,d=await Iy(n,o.repairSessionId,o.attemptOrdinal);if(d.transactionId!==a.manifest.transactionId)throw new Error("Repair attempt state does not belong to the pending transaction.");if(d.plan.planHash!==o.planHash)throw new Error("Saved validation plan does not match the approved plan.");let c=h0(d),l=d.transactionId,u=d.plan,p;if(a.state.phase==="validating"){let R=a.state.history.findLast(E=>E.type==="validation-started");if(R?.validationRunId===void 0)throw new Error("Validating transaction has no started validation run.");p=R.validationRunId}else{p=f0();let R=await al({context:c,transactionId:l,planHash:u.planHash,validationRunId:p,now:e()});if(R.kind==="rejected"||R.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-rejected",message:R.reasons.map(E=>E.message).join(" ")};for(let E of u.commands)if(!(!E.required||E.timing!=="post-patch")){if(r.signal?.aborted===!0)break;await Nd({workspaceRoot:n,transactionId:l,validationRunId:p,plan:u,commandId:E.commandId,limits:l0,...r.signal===void 0?{}:{signal:r.signal}}).catch(()=>{})}}let f=await $d({workspaceRoot:n,gitRoot:d.workspace.gitRoot,transactionId:l,validationRunId:p,plan:u,reportMaxBytes:u0,completedAt:e()}),h=f.manifest,g={repairSessionId:d.repairSessionId,attempt:d.attempt,transactionId:l,planHash:u.planHash,validationRunId:p,validationManifestHash:h.manifestHash};if(h.status==="passed"&&(await ol({context:c,transactionId:l,planHash:u.planHash,validationRunId:p,validationManifestHash:h.manifestHash,now:e()})).kind==="completed"){await Gs({workspaceRoot:n,repairSessionId:d.repairSessionId,ordinal:d.attempt,validationRunId:p,now:t()});let E=await y0(r,d,n);return fl(r,d,t,{outcome:"repaired",reasonCode:"validation-passed",message:`Every required validation check passed; the repair is complete.${E?.message===void 0?"":` ${E.message}`}`,application:"applied",validation:"passed",repair:g,...E===void 0?{}:{groupCheck:E}})}await Gs({workspaceRoot:n,repairSessionId:d.repairSessionId,ordinal:d.attempt,validationRunId:p,now:t()});let m=await Qd(c,l,e()),y=h.status==="passed"?"incomplete":h.status,w=y==="failed"?"validation-failed":y==="unavailable"?"validation-unavailable":"validation-incomplete";if(m.kind!=="rolled-back")return fl(r,d,t,{outcome:"repair-failed",reasonCode:"rollback-conflicted",message:"Validation did not pass and the patch could not be rolled back automatically because the files changed; resolve them manually.",application:"recovery-required",validation:y==="blocked"?"incomplete":y,repair:g});let v=(await sc({workspaceRoot:n,repairSessionId:d.repairSessionId,ordinal:d.attempt,proof:{transactionId:l,phase:"rolled-back",transactionRevision:m.transaction.revision},now:t()})).retry!==void 0,I=v?m0(n,f.directory,h):void 0;return fl(r,d,t,{outcome:"repair-failed",reasonCode:w,message:v?"Validation did not pass, so the patch was rolled back. One retry is available.":"Validation did not pass, so the patch was rolled back. No retry remains.",application:"rolled-back",validation:y==="blocked"?"incomplete":y,repair:{...g,retryAvailable:v,...I===void 0?{}:{retryReportPath:I}}})}async function fl(r,t,e,n){let i={schemaVersion:"1.0",recordId:va(),command:"validate",...t.record,recordedAt:e(),analysis:{status:"completed"},proposal:{status:"approved"},application:{status:n.application},validation:{status:n.validation},repair:n.repair,...n.groupCheck===void 0?{}:{groupCheck:n.groupCheck},outcome:n.outcome,reasonCode:n.reasonCode,message:n.message};if(r.persist===!1)return{outcome:i.outcome,reasonCode:i.reasonCode,message:i.message,record:i};try{let s=await ui(t.workspace.workspaceRoot,i);return{outcome:i.outcome,reasonCode:i.reasonCode,message:i.message,record:i,recordPath:s}}catch{return{outcome:"operation-failed",reasonCode:"record-write-failed",message:`${i.message} The run record could not be written safely under .kwikqa/runs/.`,record:i}}}var g0=1200*1e3,w0=10,b0=1e3,x0=15e3,v0=3e3,k0=6e4,Ly=3e4,I0=2;function yl(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}async function My(r){try{let t=await r.json();return yl(t)?t:{}}catch{return{}}}function $y(r){return typeof r=="number"&&Number.isFinite(r)?Math.min(x0,Math.max(b0,r)):v0}function ml(r){let t=yl(r.error)?r.error:void 0;return typeof t?.message=="string"?t.message:void 0}var Oa=class{constructor(t){this.options=t}options;preflight(t){return this.options.preflight.preflight(t)}async complete(t){let e=performance.now(),n=()=>performance.now()-e;for(let i=0;;i+=1){let s=await this.#e(t,n);if(s!=="interrupted")return s;if(i===I0)return{kind:"failed",code:"http-error",message:"The model request was interrupted on our side; nothing was charged. Try again.",httpStatus:503,elapsedMs:n()};this.options.onRestart?.()}}async#e(t,e){let n=(u,p)=>({kind:"failed",code:u,message:p,elapsedMs:e()}),i=Sc(t);if(i!==void 0)return{kind:"failed",code:"invalid-request",message:i,elapsedMs:0};let s;try{s=await this.#t("POST","/v1/jobs",k0,{headers:{...this.options.headers(t.body),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(t.body)})}catch(u){return n("network-error",`The model request could not reach the KwikQA service (${Rc(u)}).`)}let a=await My(s);if(s.status!==202){let u=na(a);return{kind:"failed",code:"http-error",message:ml(a)??"The KwikQA service refused the model request.",httpStatus:s.status,...u===void 0?{}:{providerCode:u},elapsedMs:e()}}let o=a.jobId;if(typeof o!="string"||o==="")return n("invalid-json","The KwikQA service did not name the job it started.");let d=this.options.sleep??(u=>new Promise(p=>setTimeout(p,u))),c=$y(a.pollAfterMs),l=0;for(;;){if(e()>(this.options.maxWaitMs??g0))return await this.#r(o),n("timeout","The model did not answer in time; nothing was charged.");await d(c);let u;try{u=await this.#t("GET",`/v1/jobs/${o}`,Ly)}catch{u=new Response(null,{status:599})}if(u.status>=500){if(l+=1,l>w0)return n("network-error","Lost contact with the KwikQA service while the model was working. If it answered, it is given back unused.");continue}l=0;let p=await My(u);if(u.status===404)return"interrupted";if(!u.ok)return{kind:"failed",code:"http-error",message:ml(p)??"The KwikQA service refused to report the job.",httpStatus:u.status,elapsedMs:e()};if(p.status==="running"){this.options.onProgress?.(e()),c=$y(p.pollAfterMs);continue}if(p.status==="failed")return yl(p.error)&&p.error.code==="job-interrupted"?"interrupted":{kind:"failed",code:"http-error",message:ml(p)??"The model request was interrupted; nothing was charged.",httpStatus:503,elapsedMs:e()};if(p.status!=="answered")return n("invalid-json","The KwikQA service reported a job state the CLI does not know.");await this.#r(o);let f=typeof p.httpStatus=="number"?p.httpStatus:502,h=p.result,g=f>=200&&f<300;if(!g||Ac(h)){let m=na(h),y=g?m??502:f;return{kind:"failed",code:"http-error",message:Tc(y,h),httpStatus:y,...m===void 0?{}:{providerCode:m},elapsedMs:e()}}return this.options.onCompletionBody?.(h),{kind:"response",httpStatus:f,body:h,elapsedMs:e()}}}async#r(t){try{await this.#t("DELETE",`/v1/jobs/${t}`,Ly)}catch{}}#t(t,e,n,i={}){return this.options.fetch(`${this.options.baseUrl}${e}`,{method:t,headers:{Accept:"application/json",Authorization:`Bearer ${this.options.token}`,...i.headers},...i.body===void 0?{}:{body:i.body},redirect:"error",signal:AbortSignal.timeout(n)})}};var P0="https://api.kwikqa.com",mi="https://kwikqa.com/dashboard/";function _y(r){return r.hosted??!(r.plan==="byo"||r.plan==="byo-team")}function R0(r){return r?.response_format?.json_schema?.name==="kwikqa_diagnosis"}var ft=class extends Error{constructor(e,n,i){super(i);this.status=e;this.code=n}status;code};function zt(r,t){return(r.KWIKQA_API_URL??(t===void 0||t===""?P0:t)).replace(/\/+$/,"")}function Fy(r){let t=r?.messages;if(!Array.isArray(t))return;let e=t.find(n=>typeof n=="object"&&n!==null&&n.role==="user"&&typeof n.content=="string");if(e!==void 0)try{let n=JSON.parse(e.content).framework;return n==="playwright"||n==="cypress"||n==="webdriverio"?n:void 0}catch{return}}var ht=class{constructor(t,e,n=fetch){this.baseUrl=t;this.token=e;this.fetchImpl=n}baseUrl;token;fetchImpl;async#e(t,e,n,i,s){let a;try{a=await this.fetchImpl(`${this.baseUrl}${e}`,{method:t,headers:{Accept:"application/json",...n===void 0?{}:{"Content-Type":"application/json"},...this.token===void 0?{}:{Authorization:`Bearer ${this.token}`},...i===void 0?{}:{"X-KwikQA-Retry-Ticket":i},...s===void 0?{}:{"X-KwikQA-Session":s}},...n===void 0?{}:{body:JSON.stringify(n)},redirect:"error"})}catch{throw new ft(0,"network-error",`Could not reach the KwikQA service at ${this.baseUrl}.`)}let o;try{o=await a.json()}catch{o=void 0}if(!a.ok){let d=o?.error;throw new ft(a.status,d?.code??"http-error",d?.message??`The KwikQA service returned HTTP ${a.status}.`)}return o}startDeviceLogin(){return this.#e("POST","/v1/auth/device")}pollDeviceLogin(t){return this.#e("POST","/v1/auth/token",{deviceCode:t})}status(){return this.#e("GET","/v1/me")}hostedConfig(){return this.#e("GET","/v1/config")}plans(){return this.#e("GET","/v1/plans")}checkout(t,e){return this.#e("POST","/v1/billing/checkout",{plan:t,...e})}billingPortal(){return this.#e("POST","/v1/billing/portal")}reserveUsage(t,e,n){return this.#e("POST","/v1/usage/reserve",t,e,n)}openSession(t,e="diagnosis"){return this.#e("POST","/v1/usage/session",e==="diagnosis"?{requests:t}:{requests:t,kind:e})}async closeSession(t){let n=(await this.#e("DELETE","/v1/usage/session",void 0,void 0,t))?.retryTicket;return typeof n=="string"&&n!==""?{retryTicket:n}:{}}reportInsights(t){return this.#e("POST","/v1/insights",{events:t})}releaseUsage(t,e){return this.#e("POST","/v1/usage/release",{id:t,status:e})}logout(){return this.#e("POST","/v1/auth/logout")}transport(t){let e=s=>{let a=Fy(s),o=R0(s)?t.session?.():t.repairSession?.();return{...t.retryTicket===void 0?{}:{"X-KwikQA-Retry-Ticket":t.retryTicket},...o===void 0?{}:{"X-KwikQA-Session":o},...a===void 0?{}:{"X-KwikQA-Framework":a}}},n=s=>{let a=s?.kwikqa?.retryTicket;typeof a=="string"&&a!==""&&t.onRetryTicket?.(a)},i=new ur({apiRoot:`${this.baseUrl}/v1/openrouter`,credentialName:"A KwikQA login (run `npx kwikqa login`)",readApiKey:()=>this.token,fetch:this.fetchImpl,timeoutMs:6e5,extraHeaders:e,onCompletionBody:n});return t.jobs!==!0||this.token===void 0?i:new Oa({baseUrl:this.baseUrl,token:this.token,fetch:this.fetchImpl,preflight:i,headers:e,onCompletionBody:n,...t.onProgress===void 0?{}:{onProgress:t.onProgress},...t.onRestart===void 0?{}:{onRestart:t.onRestart},...t.sleep===void 0?{}:{sleep:t.sleep}})}},Da=class{constructor(t,e,n={}){this.inner=t;this.client=e;this.options=n}inner;client;options;preflight(t){return this.inner.preflight(t)}async complete(t){let n=t.body.response_format?.json_schema?.name==="kwikqa_repair_proposal"?"repair":"diagnosis",i;try{let a=Fy(t.body);i=await this.client.reserveUsage({kind:n,model:t.route.modelId,provider:t.route.providerSlug,...a===void 0?{}:{framework:a}},this.options.retryTicket,n==="diagnosis"?this.options.session?.():this.options.repairSession?.())}catch(a){if(!(a instanceof ft))throw a;return{kind:"failed",code:"http-error",message:a.message,elapsedMs:0,...a.status===0?{}:{httpStatus:a.status}}}i.retryTicket!==void 0&&this.options.onRetryTicket?.(i.retryTicket);let s=await this.inner.complete(t);return s.kind!=="response"&&await this.client.releaseUsage(i.id,s.httpStatus??599).catch(()=>{}),s}};import{mkdir as T0,readFile as A0,rm as S0,writeFile as E0}from"node:fs/promises";import{homedir as jy}from"node:os";import{join as yi}from"node:path";function By(r){return r.KWIKQA_CONFIG_DIR!==void 0&&r.KWIKQA_CONFIG_DIR!==""?r.KWIKQA_CONFIG_DIR:process.platform==="win32"?yi(r.APPDATA??yi(jy(),"AppData","Roaming"),"kwikqa"):yi(r.XDG_CONFIG_HOME??yi(jy(),".config"),"kwikqa")}function gl(r){return yi(By(r),"credentials.json")}async function gr(r){if(r.KWIKQA_TOKEN!==void 0&&r.KWIKQA_TOKEN.trim()!=="")return{token:r.KWIKQA_TOKEN.trim(),login:"(KWIKQA_TOKEN)",apiUrl:""};try{let t=JSON.parse(await A0(gl(r),"utf8"));return typeof t.token!="string"||t.token===""||typeof t.login!="string"||typeof t.apiUrl!="string"?void 0:{token:t.token,login:t.login,apiUrl:t.apiUrl}}catch{return}}async function Vy(r,t){await T0(By(r),{recursive:!0,mode:448}),await E0(gl(r),`${JSON.stringify(t)}
89
- `,{mode:384})}async function zy(r){await S0(gl(r),{force:!0})}import{createHash as C0}from"node:crypto";import{basename as N0}from"node:path";var O0=100;function Hy(r){return C0("sha256").update(r).digest("hex")}function qy(r,t){let e=r.projects.find(s=>s.projectId===t.projectId)?.name??"",n=t.location.file,i=t.titlePath.filter(s=>s!==""&&s!==n&&s!==N0(n));return{key:Hy([e,n,...t.titlePath].join("\0")).slice(0,32),title:(i.length===0?[t.title]:i).join(" \u203A ").slice(0,300),file:n.slice(0,300),project:e.slice(0,100)}}function Uy(r){return r===void 0?void 0:Hy(r).slice(0,32)}function Gy(r){if(r.run===void 0)return;let t=r.run,e=t.logicalTests.filter(n=>n.status==="unexpected"||n.status==="flaky").slice(0,O0).map(n=>({...qy(t,n),status:n.status==="flaky"?"flaky":"failed"}));return{kind:"analysis",outcome:r.outcome,reasonCode:r.reasonCode,framework:t.framework,tests:e}}function Ky(r){let t=r.record,e=r.run===void 0||r.packet===void 0||t?.diagnosis===void 0?void 0:Na(r.run,t.diagnosis,r.packet,t.clusters?.[0]?.representativeId),n=Uy(t?.repair?.repairSessionId);return{kind:"fix",outcome:r.outcome,reasonCode:r.reasonCode,...r.run===void 0?{}:{framework:r.run.framework},...n===void 0?{}:{session:n},...t?.repair?.attempt===void 0?{}:{attempt:t.repair.attempt},...e===void 0||r.run===void 0?{}:{test:qy(r.run,e)},...t?.repairProposal===void 0?{}:{changedFiles:t.repairProposal.changedFiles,changedLines:t.repairProposal.changedLines}}}function Wy(r){let t=r.record?.repair,e=Uy(t?.repairSessionId);if(!(e===void 0||t===void 0))return{kind:"validation",outcome:r.outcome,reasonCode:r.reasonCode,session:e,attempt:t.attempt}}async function La(r,t,e,n){if(n===void 0||e.team?.insights!==!0)return;try{await t.reportInsights([n])}catch{r.print("Team insights: couldn't share this result; nothing else changed.");return}let i=n.kind==="analysis"?`${n.tests.length} failing or flaky test name${n.tests.length===1?"":"s"} and the result`:n.kind==="fix"?"this fix's test and outcome":"the validation result";r.print(`Team insights: shared ${i} with ${e.team.owner}'s team.`)}import{basename as D0}from"node:path";function Ht(r,t){return`${r} ${t}${r===1?"":"s"}`}function Jy(r){return`$${r.toFixed(r<.1?4:2)}`}function L0(r){let t=r.evidence.flatMap(i=>i.locator.type==="diff-hunk"?[i.locator]:[]);if(t.length===0)return[];let e=new Set(t.flatMap(i=>i.commit===void 0?[]:[i.commit])),n=[...e.size===0?[]:[Ht(e.size,"commit")],...t.some(i=>i.commit===void 0)?["uncommitted changes"]:[]].join(" and ");return[` Changes: ${Ht(t.length,"changed hunk")} from ${n} that mention the failures (--no-changes leaves them out)`]}function gi(r,t,e){let n=t.model.reasoningEffort===void 0?"":`, effort ${t.model.reasoningEffort}`,i=t.model.zeroDataRetention===!0?", zero data retention":"";return[`${r==="diagnosis"?"Diagnosis":"Repair proposal"} request -> ${e}`,` Model: ${t.model.modelId} via ${t.model.providerId}${n}${i}`,` Evidence: ${Ht(t.evidence.length,"redacted item")} from ${t.channels.join(", ")||"the report"}`,` ${Ht(t.redactionIds.length,"redaction")} applied, ${Ht(t.omissionIds.length,"item")} withheld by policy`,...L0(t),` Estimate: at most ${t.estimate.estimatedInputTokens.toLocaleString("en-US")} input + ${t.estimate.estimatedOutputTokens.toLocaleString("en-US")} output tokens, at most ${Jy(t.estimate.estimatedDollars)}`,` Caps: ${Jy(t.caps.request.maxDollars)} per request`,` Payload: ${t.payloadManifestHash.slice(0,16)}... (exactly this redacted payload is sent)`]}function Xy(r,t){let e=r.proposal,n=["Proposed repair",` Intent: ${e.intent.statement}`,` Preserves: ${e.intent.preservedBehavior}`,` Changes: ${Ht(e.changedFiles,"file")}, ${Ht(e.changedLines,"line")}`,"",...e.diff.trimEnd().split(`
90
- `),"","Validation commands (run later by `kwikqa validate`):"],i=new Map;for(let s of t.commands.filter(a=>a.timing==="post-patch")){let a=s.args.map(d=>/\s/.test(d)?JSON.stringify(d):d),o=` ${D0(s.executable)} ${a.join(" ")}`;i.set(o,(i.get(o)??0)+1)}for(let[s,a]of i)n.push(a===1?s:`${s} (${a} runs)`);return r.checkoutPristine||n.push("","Note: this checkout has other uncommitted changes; they are not touched."),n}function Yy(r,t){let e=n=>t?.logicalTests.find(i=>i.logicalTestId===n)?.title;return r.flatMap((n,i)=>{let s=n.logicalTestIds.map(d=>e(d)??d),a=s.length<=3?s.join(", "):`${s.slice(0,3).join(", ")} and ${s.length-3} more`,o=`${s.length} test${s.length===1?"":"s"}`;return[`Failure group ${i+1} of ${r.length}: ${o} (${a})${n.escalated===!0?", answered by the stronger model":""}`,...n.diagnosis!==void 0&&n.diagnosis.hypotheses.length>0?wl(n.diagnosis):[` ${n.outcome} (${n.reasonCode}): ${n.message}`],""]})}function wl(r){if(r.hypotheses.length===0)return["No cause is supported by the evidence.",` Next: ${r.recommendedNextAction}`];let t=[];for(let e of[...r.hypotheses].sort((n,i)=>n.rank-i.rank))t.push(`#${e.rank} ${e.statement}`,` owner: ${e.probableOwner}, evidence: ${e.evidenceGrade}, cause: ${e.causalCategory}`);return t.push(` Next: ${r.recommendedNextAction}`),t}function Qy(r,t){switch(t){case"diagnosed":return r?.diagnosis?.repairEligibility==="eligible"?"Run `npx kwikqa fix` to propose a repair.":void 0;case"proposal-ready":return"Run `npx kwikqa fix` without --propose-only to review and apply it.";case"awaiting-validation":return"Run `npx kwikqa validate` to verify the patch.";case"repair-failed":return r?.repair?.retryAvailable===!0?"Run `npx kwikqa fix --retry` to re-diagnose from the validation evidence (one retry left).":void 0;default:return}}var M0={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"},$0={"playwright-json":"JSON report","kwikqa-json":"KwikQA reporter","mochawesome-json":"mochawesome report","wdio-json":"@wdio/json-reporter report","junit-xml":"JUnit report"};function Zy(r){if(r===void 0)return;let t=r.artifact.formatVersion===void 0?"":` ${r.artifact.formatVersion}`,e=$0[r.artifact.format??""],n=r.logicalTests.filter(s=>s.status==="unexpected").length,i=r.logicalTests.filter(s=>s.status==="flaky").length;return`Read a ${M0[r.framework]}${t} run${e===void 0?"":` (${e})`}: ${Ht(r.logicalTests.length,"test")}, ${n} failing${i===0?"":`, ${i} flaky`}.`}function eg(r){if(r===void 0)return;let t=r.framework==="playwright",e=t?"trace":"kwikqa-capture",n=0,i=0;for(let d of r.logicalTests)for(let c of $r(d))n+=1,c.attachments.some(l=>l.name===e)&&(i+=1);if(n===0||i===n)return;let s=n-i;return[`Note: ${s===n?n===1?`The failing attempt has no ${t?"Playwright trace":"KwikQA failure capture"}`:`None of the ${n} failing attempts has ${t?"a Playwright trace":"a KwikQA failure capture"}`:`${s} of ${n} failing attempts have no ${t?"Playwright trace":"KwikQA failure capture"}`}, so browser actions, network, console, and DOM were not available to the diagnosis.`,t?" Run `npx kwikqa analyze --capture` to re-run them with full tracing, or set":" Run `npx kwikqa analyze --capture` to re-run the failing specs and record each failure's page.",...t?[' `use: { trace: "retain-on-failure" }` in playwright.config to keep traces of failures.']:[]].join(`
91
- `)}var W={ok:0,failed:1,usage:2,account:3},bl=(()=>{let{workspaceRoot:r,...t}=Mo;return{...t,maxPacketBytes:6e5}})(),V0=.85;function dg(r){if(r===void 0)return bl;let t=Math.min(r.diagnosis.caps.request.maxInputTokens,r.repairCaps.request.maxInputTokens);return{...bl,maxPacketBytes:Math.min(bl.maxPacketBytes,Math.floor(t*V0))}}var sg=["test-results/kwikqa-report.json","test-results/kwikqa","playwright-report/results.json","test-results/results.json","mochawesome-report","cypress/reports","cypress/results","results.json","report.json"],cg=je(".kwikqa","cli-state.json"),vl="Not signed in. Run `npx kwikqa login` first.";async function tn(r){return _0(r).then(()=>!0,()=>!1)}async function kl(r){try{return JSON.parse(await Ma(je(r,cg),"utf8"))}catch{return{}}}async function Il(r,t){await j0(je(r,".kwikqa"),{recursive:!0,mode:448}),await og(je(r,cg),`${JSON.stringify(t)}
92
- `,{mode:384})}async function lg(r,t,e){if(e!==void 0)return ng(e)?e:ig(r.cwd,e);for(let n of[r.env.PLAYWRIGHT_JSON_OUTPUT_NAME,r.env.KWIKQA_REPORT_DIR])if(n!==void 0&&n!==""){let i=ng(n)?n:ig(t,n);if(await tn(i))return i}for(let n of sg)if(await tn(je(t,n)))return je(t,n);return je(t,sg[0]??"report.json")}async function ug(r){try{if((await rg(r)).isDirectory()){let t=tg("sha256");for(let e of(await B0(r)).sort()){let n=je(r,e);(await rg(n)).isFile()&&t.update(`${e}\0`).update(await Ma(n))}return t.digest("hex")}return tg("sha256").update(await Ma(r)).digest("hex")}catch{return}}async function z0(r,t,e){let n=t.capture;if(n===void 0)return;let i=je(r,n.reportPath);if(await ug(e)!==n.sourceSha256||!await tn(i))return;let s=n.probePath===void 0?void 0:je(r,n.probePath);return{reportPath:i,...s!==void 0&&await tn(s)?{probePath:s}:{}}}async function H0(r,t,e,n){let i=await et(e,{workspaceRoot:t,...n.framework===void 0?{}:{framework:n.framework}});if(i.kind!=="parsed"){r.io.error(`Capture skipped: ${i.diagnostic.message}`);return}let s=i.run.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest",a=await hc({run:i.run,workspaceRoot:t,captureId:s,env:r.env,probe:n.probe});if(a.kind!=="ready"){r.io.print(`Capture skipped: ${a.message}`);return}for(let c of a.prepared.description)r.io.print(c);if(a.prepared.probeUnavailable!==void 0&&r.io.print(`Note: ${a.prepared.probeUnavailable}`),n.yes)r.io.print("Run these tests? yes (--yes)");else if(!await r.io.confirm("Run these tests?")){r.io.print("Capture declined; analyzing the existing report.");return}let o=await mc(a.prepared,r.env);if(r.io.print(o.outcome.message),o.probe!==void 0){let c=o.probe.results.reduce((l,u)=>l+u.candidates.length,0);r.io.print(`Live probe: ${c} Playwright-generated locator${c===1?"":"s"} for ${o.probe.results.length} failing test${o.probe.results.length===1?"":"s"}.`)}if(o.outcome.reportPath===void 0||o.outcome.reproduced===0)return;let d=await ug(e);if(d!==void 0){let c=await kl(t);await Il(t,{...c,capture:{sourceSha256:d,reportPath:xl(t,o.outcome.reportPath),...o.probePath===void 0?{}:{probePath:xl(t,o.probePath)}}})}return{reportPath:o.outcome.reportPath,...o.probePath===void 0?{}:{probePath:o.probePath}}}function ag(r,t){if(r===void 0||r==="")return{...t,evaluationStatus:"unverified-model"};let[e,n]=r.split("@");if(e===void 0||n===void 0||n==="")throw new ft(0,"invalid-model",`Model routes look like author/model@provider, not ${r}.`);return{modelId:e,providerId:n,evaluationStatus:"unverified-model"}}async function pg(r,t,e){let n=await gr(r.env);if(n===void 0)return r.io.error(vl),{exit:W.account};let i=new ht(zt(r.env,n.apiUrl),n.token,r.fetch),s=await i.status(),a=await i.hostedConfig(),o=_y(s);if(!o&&(r.env.OPENROUTER_API_KEY??"").trim()==="")return r.io.error("The BYOK plans need OPENROUTER_API_KEY in the environment."),{exit:W.account};let d=t==="analysis"?s.usage.analyses:s.usage.repairs;if(e===void 0&&d.limit!==void 0&&d.used>=d.limit){let v=t==="analysis"?"analyses":"fixes";return r.io.error(`You have used all ${d.limit} ${v} on the ${s.plan} plan until ${s.periodEnd.slice(0,10)}.`),r.io.error(s.team?.role==="member"?`Ask ${s.team.owner}, who manages your team's plan, to add seats.`:"Run `npx kwikqa upgrade` to see plans with more."),{exit:W.account}}let c,l,u=a.sessions===!0&&e===void 0?{open:async v=>{l=(await i.openSession(v)).sessionTicket},close:async()=>{let v=l;l=void 0,v!==void 0&&await i.closeSession(v)}}:void 0,p,f=a.repairSessions===!0&&e===void 0?{open:async v=>{p=(await i.openSession(v,"repair")).sessionTicket},close:async()=>{let v=p;if(p=void 0,v===void 0)return;let I=await i.closeSession(v);I.retryTicket!==void 0&&(c=I.retryTicket)}}:void 0,h={...e===void 0?{}:{retryTicket:e},onRetryTicket:v=>{c=v},session:()=>l,repairSession:()=>p};if(!o){let v=new Da(new ur({readApiKey:()=>r.env.OPENROUTER_API_KEY,fetch:r.fetch}),i,h);return{diagnosis:{model:ag(r.env.KWIKQA_DIAGNOSIS_MODEL,a.models.diagnosis),caps:a.caps.diagnosis,transport:v,...u===void 0?{}:{session:u}},repairModel:ag(r.env.KWIKQA_REPAIR_MODEL,a.models.repair),repairCaps:a.caps.repair,...f===void 0?{}:{repairSession:f},destination:"OpenRouter, with your own API key (KwikQA counts the request)",ticket:()=>c,client:i,status:s}}let g=i.transport({...h,jobs:a.jobs===!0,onProgress:G0(r),onRestart:()=>r.io.print(" The KwikQA service restarted while the model was working; sending the request again (nothing was charged)."),...r.sleep===void 0?{}:{sleep:r.sleep}}),m=e!==void 0&&a.models.escalation!==void 0&&a.caps.escalation!==void 0,y=m?a.models.escalation:void 0,w=m?a.caps.escalation:void 0,x=!m&&u!==void 0&&a.models.escalation!==void 0&&a.caps.escalation!==void 0?{model:a.models.escalation,caps:a.caps.escalation}:void 0;return{diagnosis:{model:y??a.models.diagnosis,caps:w??a.caps.diagnosis,transport:g,...u===void 0?{}:{session:u},...x===void 0?{}:{escalation:x}},repairModel:y??a.models.repair,repairCaps:w??a.caps.repair,...f===void 0?{}:{repairSession:f},destination:"the KwikQA service, which forwards it to OpenRouter",ticket:()=>c,client:i,status:s}}var q0=3e4;function U0(r){let t=Math.floor(r/1e3),e=Math.floor(t/60);return e===0?`${t}s`:`${e}m ${String(t%60).padStart(2,"0")}s`}function G0(r){let t=0;return e=>{let n=Math.floor(e/q0);n<=t||(t=n,r.io.print(` The model is still working (${U0(e)})\u2026`))}}function fg(r,t,e){let n=async(i,s)=>{for(let a of i)r.io.print(a);return e?(r.io.print(`${s} yes (--yes)`),!0):r.io.confirm(s)};return{approveDiagnosis:i=>n(gi("diagnosis",i,t),"Send this request?"),approveDiagnoses:i=>{let[s]=i;return i.length===1&&s!==void 0?n(gi("diagnosis",s,t),"Send this request?"):n([`${i.length} diagnosis requests, one for each group of failures with a shared cause:`,...i.flatMap((a,o)=>["",`Request ${o+1} of ${i.length}`,...gi("diagnosis",a,t)])],`Send these ${i.length} requests?`)},approveRepairRequest:i=>n(gi("repair proposal",i,t),"Send this request?"),approveApplication:async(i,s)=>{for(let a of Xy(i,s))r.io.print(a);return r.io.confirm("Apply this patch?")}}}async function hg(r,t,e,n,i){let s=new Set(n),a=await hc({run:{...e,logicalTests:e.logicalTests.filter(d=>s.has(d.logicalTestId))},workspaceRoot:t,captureId:`${i.purpose}-${e.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest"}`,env:r.env,probe:!1});if(a.kind!=="ready")return{kind:"unavailable",message:a.message};r.io.print(""),r.io.print(i.intro);for(let d of a.prepared.description)r.io.print(d);if(!await r.io.confirm(i.question))return{kind:"declined"};let o=await mc(a.prepared,r.env);return r.io.print(o.outcome.message),o.outcome.kind==="failed"?{kind:"unavailable",message:o.outcome.message}:{kind:"rerun",failedAgain:o.outcome.failedAgain??[]}}function K0(r){return r==="repair-failed"||r==="validation-unavailable"||r==="operation-failed"?W.failed:W.ok}function Pl(r,t){r.io.print("");let e=Zy("run"in t?t.run:void 0);e!==void 0&&t.record?.command!=="validate"&&r.io.print(e);let n=t.record?.clusters??[];if(n.length>1&&t.record?.command!=="validate")for(let a of Yy(n,"run"in t?t.run:void 0))r.io.print(a);else if(t.record?.diagnosis!==void 0&&t.record.command!=="validate"){for(let a of wl(t.record.diagnosis))r.io.print(a);r.io.print("")}r.io.print(`Result: ${t.outcome} (${t.reasonCode})`),r.io.print(t.message);let i=eg("run"in t?t.run:void 0);i!==void 0&&r.io.print(i);let s=Qy(t.record,t.outcome);return s!==void 0&&r.io.print(s),t.recordPath!==void 0&&r.io.print(`Record: ${t.recordPath}`),K0(t.outcome)}async function rn(r,t){try{return await t()}catch(e){if(e instanceof ft)return r.io.error(e.message),[401,402,403,409].includes(e.status)?W.account:W.failed;throw e}}async function mg(r){return rn(r,async()=>{let t=new ht(zt(r.env),void 0,r.fetch),e=await t.startDeviceLogin();r.io.print(`Open ${e.verificationUri} and enter the code: ${e.userCode}`);let n=r.sleep??(a=>new Promise(o=>setTimeout(o,a))),i=Math.max(1,e.interval),s=Date.now()+e.expiresIn*1e3;for(;Date.now()<s;){await n(i*1e3);let a=await t.pollDeviceLogin(e.deviceCode);if(a.status==="complete")return await Vy(r.env,{token:a.token,login:a.login,apiUrl:t.baseUrl}),r.io.print(`Signed in as ${a.login}.`),W.ok;if(a.status==="slow_down"&&(i+=5),a.status==="expired"||a.status==="denied")return r.io.error(a.status==="denied"?"Sign-in was denied.":"The code expired."),W.account}return r.io.error("The code expired before sign-in finished."),W.account})}async function yg(r){let t=(r.env.KWIKQA_TOKEN??"").trim()!=="",e=t?void 0:await gr(r.env);if(e!==void 0)try{await new ht(zt(r.env,e.apiUrl),e.token,r.fetch).logout()}catch{r.io.error(`Could not reach the KwikQA service to revoke this token; revoke it at ${mi}account/.`)}return await zy(r.env),r.io.print("Signed out."),t&&r.io.print("KWIKQA_TOKEN is still set in this environment; unset it to stop using it."),W.ok}function W0(r){let t=[...r.seats!==void 0&&r.seats>1?[`${r.seats} seats`]:[],...r.interval===void 0?[]:[r.interval==="year"?"billed yearly":"billed monthly"]];return`on the ${r.plan} plan${t.length===0?"":` (${t.join(", ")})`}`}async function gg(r){return rn(r,async()=>{let t=await gr(r.env);if(t===void 0)return r.io.print(vl),W.account;let n=await new ht(zt(r.env,t.apiUrl),t.token,r.fetch).status(),i=(s,a)=>a===void 0?`${s} (unlimited)`:`${s} of ${a}`;return r.io.print(`Signed in as ${n.login} ${W0(n)}.`),n.team!==void 0&&(r.io.print(n.team.role==="member"?`Team: ${n.team.owner}'s team; usage below is the team's shared pool.`:`Team: yours, with ${n.team.members} member${n.team.members===1?"":"s"}; usage below is the shared pool.`),r.io.print(n.team.insights===!0?"Team insights: on. Test names and fix outcomes from your runs are shared with your team.":"Team insights: off.")),r.io.print(`Analyses this period: ${i(n.usage.analyses.used,n.usage.analyses.limit)}`),r.io.print(`Fixes this period: ${i(n.usage.repairs.used,n.usage.repairs.limit)}`),r.io.print(`Period ends: ${n.periodEnd.slice(0,10)}`),r.io.print(`Manage your account, team, and tokens: ${mi}`),W.ok})}async function wg(r){let t=await gr(r.env);if(t===void 0){r.io.error(vl);return}return new ht(zt(r.env,t.apiUrl),t.token,r.fetch)}function J0(r){let t=r.perSeat?"/seat":"",e=r.monthlyUsd===0?"$0":`$${r.monthlyUsd}${t}/mo or $${r.annualUsd}${t}/yr`,n=r.analyses===void 0?"unlimited analyses and fixes":`${r.analyses} analyses and ${r.repairs} fixes a month${r.perSeat?" per seat, shared":""}`,i=[...r.hosted?[]:["your OpenRouter key"],...r.perSeat?[`${r.minSeats}+ seats`]:[]];return{price:e,limits:i.length===0?n:`${n} (${i.join(", ")})`}}async function bg(r,t,e={annual:!1}){return rn(r,async()=>{let n=await gr(r.env),i=await new ht(zt(r.env,n?.apiUrl),void 0,r.fetch).plans(),s=i.paidPlansOpen!==!1,o=i.plans.filter(g=>g.id!=="free").find(g=>g.id===t);if(o===void 0||!s){t!==void 0&&o===void 0&&r.io.error(`Unknown plan: ${t}`),r.io.print(`Plans (monthly, or yearly with ${12-i.annualMonthsCharged} months free):`);let g=Math.max(...i.plans.map(m=>m.id.length));for(let m of i.plans){let{price:y,limits:w}=J0(m);r.io.print(` ${m.id.padEnd(g)} ${y}: ${w}`)}if(s)r.io.print("Run `npx kwikqa upgrade <plan> [--annual] [--seats <n>]` to get a checkout link.");else if(r.io.print("Paid plans are coming soon. Until they open, every account uses Free."),o!==void 0)return W.account;return t===void 0?W.ok:W.usage}let d;if(e.seats!==void 0&&(d=Number(e.seats),!(o.perSeat?Number.isInteger(d)&&d>=o.minSeats&&d<=i.maxSeats:d===1)))return r.io.error(o.perSeat?`${o.name} needs ${o.minSeats} to ${i.maxSeats} seats.`:`${o.name} is for one person; --seats applies to team plans.`),W.usage;let c=await wg(r);if(c===void 0)return W.account;let l=await c.status();if(l.team?.role==="member")return r.io.print(`You're on ${l.team.owner}'s team, so ${l.team.owner} manages billing.`),W.ok;if(l.plan!=="free")return r.io.print(`You're on the ${l.plan} plan. Change plans, seats, or billing period in Billing, where you see the charge before you confirm:`),r.io.print(`${mi}billing/`),W.ok;let u=e.annual?"year":"month",p=await c.checkout(o.id,{interval:u,...d===void 0?{}:{seats:d}}),f=o.perSeat?d??o.minSeats:1,h=(e.annual?o.annualUsd:o.monthlyUsd)*f;return r.io.print(`Open this link to subscribe to ${o.name}${o.perSeat?` with ${f} seats`:""} for $${h} a ${e.annual?"year":"month"}:`),r.io.print(p.url),W.ok})}async function xg(r){return rn(r,async()=>{let t=await wg(r);if(t===void 0)return W.account;try{let{url:e}=await t.billingPortal();return r.io.print("Open this link to update your payment method or download invoices:"),r.io.print(e),r.io.print(`To change or cancel your plan: ${mi}billing/`),W.ok}catch(e){if(e instanceof ft&&e.code==="no-billing-account")return r.io.print("You don't have a paid subscription yet."),r.io.print("Run `npx kwikqa upgrade <plan>` to choose one."),W.ok;if(e instanceof ft&&e.code==="team-member")return r.io.print(e.message),W.ok;throw e}})}async function vg(r){let t=await $a(r.cwd),e=je(t,"kwikqa.config.json");if(await tn(e))r.io.print("kwikqa.config.json already exists; review it to change what KwikQA may edit.");else{let o=Yc({repositoryPaths:await ll(t)});r.io.print("Proposed kwikqa.config.json (what KwikQA may edit when repairing tests):");for(let d of o.canonicalContents.trimEnd().split(`
93
- `))r.io.print(` ${d}`);for(let d of[...o.reasons,...o.ambiguities])r.io.print(` - ${d}`);await r.io.confirm("Write kwikqa.config.json?")&&(await og(e,o.canonicalContents,{flag:"wx"}),r.io.print("Wrote kwikqa.config.json. Commit it so the policy is reviewed like code."))}let n=je(t,".gitignore");!(await tn(n)&&/^\/?\.kwikqa\/?$/m.test(await Ma(n,"utf8")))&&await r.io.confirm("Add .kwikqa/ (local run records) to .gitignore?")&&await F0(n,`
85
+ `,changed:i}}function il(r){let t=[],e={},n=0;for(let i of[...r].sort((s,a)=>s.path.localeCompare(a.path))){let s=MA(i);t.push(s.text),e[i.path]=s.changed,n+=s.changed}return{text:t.join(""),changedFiles:r.length,changedLines:n,perFileChangedLines:e}}function ry(r,t){return r.changedFiles<=t.maxFiles&&r.changedLines<=t.maxChangedLines?[]:[{code:"budget-exceeded",message:`Proposal changes ${r.changedFiles} files and ${r.changedLines} lines; configured limits are ${t.maxFiles} files and ${t.maxChangedLines} lines.`,manualRepairRecommended:!0}]}function ny(r,t,e,n){let i=[];(t.packetHash!==r.packetHash||e.packetHash!==r.packetHash||!e.passed)&&i.push({code:"invalid-provenance",message:"Diagnosis and passing deterministic grading must match the evidence packet."});let s=[...t.hypotheses].sort((d,c)=>d.rank-c.rank)[0],a=new Set(r.evidence.map(d=>d.evidenceId)),o=new Set(t.ownershipEvidenceIds);return(t.repairEligibility!=="eligible"||s===void 0||s.probableOwner!=="test-support"||!new Set(["strong","moderate"]).has(s.evidenceGrade)||o.size===0||[...o].some(d=>!a.has(d)||!s.supportingEvidenceIds.includes(d)))&&i.push({code:"insufficient-ownership-evidence",message:"Repair requires a sufficiently graded test-support hypothesis with positive evidence."}),(n.statement.trim().length===0||n.preservedBehavior.trim().length===0||n.evidenceIds.length===0||n.evidenceIds.some(d=>!a.has(d)||!s?.supportingEvidenceIds.includes(d)))&&i.push({code:"intent-ambiguous",message:"Test intent and preserved behavior require valid positive evidence citations."}),i.length>0||s===void 0?{kind:"rejected",reasons:i}:{kind:"eligible",hypothesis:s}}var iy=Ii(Rn(),1),$A=/\.([cm]?[jt]sx?)$/i;function sl(r,t){let e=r.match($A)?.[1]?.toLowerCase();if(e===void 0)return!1;let n=[];e.includes("t")&&n.push("typescript"),e.endsWith("x")&&n.push("jsx");try{return(0,iy.parse)(t,{sourceType:"unambiguous",errorRecovery:!1,plugins:n}),!0}catch{return!1}}var _A=[{pattern:/\b(?:test|describe|it|context|specify)\.(?:skip|only|fixme)\s*\(|\bx(?:it|test|describe|context|specify)\s*\(|\bf(?:it|describe)\s*\(/g,message:"skip, focus, and expected-failure controls are forbidden",exception:"never"},{pattern:/\bwaitForTimeout\s*\(|\bcy\.wait\(\s*\d|\.pause\s*\(/g,message:"arbitrary fixed waits are forbidden",exception:"never"},{pattern:/\bforce\s*:\s*true\b/g,message:"forcing actions past actionability checks is forbidden",exception:"never"},{pattern:/uncaught:exception/g,message:"suppressing application errors is forbidden",exception:"never"},{pattern:/\bthis\.retries\s*\(|\bretries\s*\(\s*\d/g,message:"retry additions are forbidden",exception:"never"},{pattern:/\bsetTimeout\s*\(/g,message:"timeout increases require a demonstrated latency contract",exception:"latency"},{pattern:/\bretries\s*:/g,message:"retry additions are forbidden",exception:"never"},{pattern:/\btoMatchSnapshot\s*\(/g,message:"broad snapshot acceptance is forbidden",exception:"never"},{pattern:/catch\s*\([^)]*\)\s*\{\s*\}/g,message:"empty catches swallow errors",exception:"never"},{pattern:/\.locator\(\s*["'`](?:#|\.|\/\/|css=)/g,message:"brittle locator regressions require positive evidence",exception:"locator"},{pattern:/(?:\bcy\.get|\.find|(?<![\w$])\$\$?)\(\s*["'`](?:#|\.[A-Za-z_-]|\/\/|\.\/\/)/g,message:"brittle locator regressions require positive evidence",exception:"locator"}];function fi(r,t){return[...r.matchAll(t)].length}function sy(r){return fi(r,/\bexpect\s*\(/g)+fi(r,/\bassert(?:\.|\s*\()/g)+fi(r,/\.(?:should|and)\s*\(/g)}function ay(r){let t=new Map;for(let e of r.matchAll(/\.((?:(?:not|resolves|rejects)\.)*)(to[A-Z]\w*)\s*\(/g)){let n=`${e[1]??""}${e[2]??""}`;t.set(n,(t.get(n)??0)+1)}for(let e of r.matchAll(/\.(?:should|and)\s*\(\s*["'`]([\w.]+)["'`]/g)){let n=`should:${e[1]??""}`;t.set(n,(t.get(n)??0)+1)}return t}function FA(r,t){let e=ay(t);return[...ay(r)].filter(([n,i])=>(e.get(n)??0)<i).map(([n])=>n).sort()}function oy(r){let t=[];for(let e of r){if(!sl(e.path,e.source)||!sl(e.path,e.result)){t.push({code:"parse-failed",message:"Original and resulting source must parse as supported JavaScript or TypeScript.",path:e.path});continue}let n=FA(e.source,e.result);n.length>0&&t.push({code:"forbidden-edit",message:`The proposal removes, negates, or swaps assertion matchers: ${n.join(", ")}.`,path:e.path});for(let i of e.replacements){sy(i.newText)<sy(i.oldText)&&t.push({code:"forbidden-edit",message:"The proposal removes or weakens assertion coverage.",path:e.path});for(let s of _A){if(fi(i.newText,s.pattern)<=fi(i.oldText,s.pattern))continue;let a=s.exception==="latency"?i.latencyContractEvidenceIds??[]:s.exception==="locator"?i.brittleLocatorEvidenceIds??[]:[];s.exception!=="never"&&a.length>0||t.push({code:"forbidden-edit",message:s.message,path:e.path})}}}return t}var jA=/^(?:\.\/)?[A-Za-z0-9_./-]+$/,BA=/^[A-Z][A-Z0-9_]*$/,VA=/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTH)/i,zA=new Set(["focused","affected","static"]);function dy(r){return r.length>0&&!r.includes("\0")&&!r.includes("\\")&&!r.startsWith("/")&&!/^[A-Za-z]:/.test(r)&&!r.split("/").some(t=>t===".."||t==="")}var HA=new Set(["page-object","fixture","test-data","test-helper","playwright-config","framework-config"]);function qA(r){let t=Object.entries(r.environment);return r.id.trim().length>0&&jA.test(r.executable)&&dy(r.executable.replace(/^\.\//,""))&&!r.args.some(e=>e.includes("\0"))&&(r.workingDirectory==="."||dy(r.workingDirectory))&&zA.has(r.scope)&&t.every(([e,n])=>BA.test(e)&&!VA.test(e)&&!n.includes("\0"))&&Number.isInteger(r.timeoutMs)&&r.timeoutMs>0&&r.reason.trim().length>0}function cy(r,t){let e=t.some(s=>HA.has(s)),n=[...r.validation].sort((s,a)=>s.id.localeCompare(a.id));if(n.some(s=>!qA(s)))return{plan:{status:"unresolved",steps:[],unresolvedReasons:["Validation discovery supplied an unsafe or malformed structured step."]},reasons:[{code:"invalid-provenance",message:"Validation plan inputs must be safe structured executable/argument records."}]};let i=[];return n.length===0&&i.push("No deterministic validation steps were discovered."),e&&!n.some(s=>s.scope==="affected")&&i.push("Shared test-support edits require affected-test validation."),{plan:{status:i.length===0?"planned":"unresolved",steps:n,unresolvedReasons:i},reasons:[]}}var al=1e6,ol=1e3;function Xe(r){return{kind:"rejected",reasons:r}}function UA(r){let{packetHash:t,...e}=r;return Cr(e)===t}function GA(r,t){let e=[];for(let n of r)[...n.evidenceIds,...n.latencyContractEvidenceIds??[],...n.brittleLocatorEvidenceIds??[]].some(s=>!t.has(s))&&e.push({code:"invalid-replacement",message:"Every replacement and policy exception must cite accepted supporting evidence.",path:n.path});return e}async function dl(r){let t=gr(r.config);if(t.kind!=="valid")return Xe(t.issues.map(p=>({code:"invalid-config",message:p})));if(!UA(r.packet)||r.snapshot.workspaceRoot!==r.packet.workspace.root||r.packet.workspace.gitRoot!==void 0&&r.snapshot.gitRoot!==r.packet.workspace.gitRoot)return Xe([{code:"invalid-provenance",message:"Packet integrity and repository snapshot identity must match."}]);let e=ny(r.packet,r.diagnosis,r.grading,r.intent);if(e.kind!=="eligible")return Xe(e.reasons);let n=r.maxSourceBytes??al;if(!Number.isInteger(n)||n<=0||n>al)return Xe([{code:"invalid-provenance",message:`maxSourceBytes must be an integer from 1 to ${al}.`}]);if(r.replacements.length===0)return Xe([{code:"invalid-replacement",message:"Proposal has no replacements."}]);let i=GA(r.replacements,new Set(e.hypothesis.supportingEvidenceIds));if(i.length>0)return Xe(i);let s=await Yh(t.config,r.snapshot,r.replacements,n);if(s.kind!=="authorized")return Xe(s.reasons);if(s.targets.some(p=>p.source.split(/\r?\n/u).length>ol||p.replacements.some(f=>f.newText.split(/\r?\n/u).length>ol)))return Xe([{code:"budget-exceeded",message:`M5 safely derives diffs only for targets and replacement text up to ${ol} lines.`,manualRepairRecommended:!0}]);let a=Jh(s.targets);if(a.kind!=="applied")return Xe(a.reasons);let o=oy(a.targets);if(o.length>0)return Xe(o);let d=il(a.targets),c=ry(d,t.config.budgets);if(c.length>0)return Xe(c);let l=cy(r.snapshot,a.targets.map(p=>p.class));if(l.reasons.length>0)return Xe(l.reasons);let u={schemaVersion:"1.0",policyVersion:"1.0",runId:r.packet.runId,packetHash:r.packet.packetHash,acceptedHypothesisId:e.hypothesis.hypothesisId,intent:r.intent,budgets:t.config.budgets,changedFiles:d.changedFiles,changedLines:d.changedLines,replacements:r.replacements,targets:a.targets.map(p=>({path:p.path,class:p.class,sourceSha256:p.sourceSha256,resultSha256:p.resultSha256,changedLines:d.perFileChangedLines[p.path]??0})),diff:d.text,diffHash:N(d.text),validationPlan:l.plan};return{kind:"proposal-ready",proposal:{...u,proposalHash:N(u)}}}import{readFile as rS,realpath as nS}from"node:fs/promises";import{join as iS}from"node:path";var KA=new Set(["failed","timedOut","interrupted"]);function WA(r){return r.status==="unexpected"||r.status==="flaky"}function py(r){return[...r.clusters].sort((t,e)=>e.logicalTestIds.length-t.logicalTestIds.length||t.clusterId.localeCompare(e.clusterId)).slice(0,6)}function JA(r){return r.attachments.reduce((t,e)=>t+(e.name==="trace"||e.contentType==="application/zip"?10:e.path===void 0?0:1),0)}function fy(r,t){let e=new Set(t.logicalTestIds);return r.logicalTests.filter(i=>e.has(i.logicalTestId)).map(i=>{let s=i.attempts.filter(a=>KA.has(a.status));return{test:i,score:Math.max(0,...s.map(JA)),startedAt:s.map(a=>a.startTime).sort()[0]??""}}).sort((i,s)=>s.score-i.score||i.startedAt.localeCompare(s.startedAt)||i.test.logicalTestId.localeCompare(s.test.logicalTestId))[0]?.test}function hy(r,t,e){let n=new Set(t.logicalTestIds);return{...r,logicalTests:r.logicalTests.map(i=>n.has(i.logicalTestId)?i.logicalTestId===e?i:{...i,attempts:i.attempts.map(s=>({...s,attachments:[]}))}:WA(i)?{...i,attempts:[]}:i)}}function my(r,t,e){return{...e,runId:t.runId,clusters:[{...r,symptomIds:t.symptoms.filter(n=>n.logicalTestId!==void 0&&r.logicalTestIds.includes(n.logicalTestId)).map(n=>n.symptomId).sort()}]}}async function yy(r,t,e){let n=new Array(r.length),i=0,s=Array.from({length:Math.min(t,r.length)},async()=>{for(;i<r.length;){let a=i;i+=1,n[a]=await e(r[a])}});return await Promise.all(s),n}import{randomUUID as wy}from"node:crypto";import{realpath as XA}from"node:fs/promises";import{join as gy,relative as YA,sep as QA}from"node:path";var ZA=/^run_[a-f0-9]{24}$/,eS=/^rec_[a-f0-9]{24}$/;function Pa(){return`rec_${wy().replaceAll("-","").slice(0,24)}`}function en(){return`auth_${wy().replaceAll("-","").slice(0,24)}`}async function hi(r,t){if(!ZA.test(t.runId)||!eS.test(t.recordId))throw new Error("Run record identity is not path-safe.");let e=await Fe(r,[".kwikqa","runs",t.runId]),n=await Fe(r,[".kwikqa","runs",t.runId,"records"]),i=`${le(t)}
86
+ `,s=gy(n,`${t.recordId}.json`);return await me(s,i,{mode:384,replace:!1}),await me(gy(e,"result.json"),i,{mode:384,replace:!0}),YA(await XA(r),s).split(QA).join("/")}var Ta=new Set(["context-limit-exceeded","request-token-budget-exceeded","request-dollar-budget-exceeded","run-token-budget-exceeded","run-dollar-budget-exceeded"]),sS={"test-support":"test-support-owned",application:"application-owned",environment:"environment-owned",undetermined:"owner-undetermined"};function aS(r){return r.logicalTests.filter(t=>t.status==="unexpected"||t.status==="flaky").map(t=>t.logicalTestId).sort()}function oS(r,t){switch(r.usability){case"zero-tests":return{reasonCode:"zero-tests",message:"The report contains no tests to diagnose."};case"interrupted":return{reasonCode:"interrupted-run",message:"The run was interrupted, so its failures cannot support a diagnosis."};case"report-errors":return{reasonCode:"report-errors",message:"The report has run-level errors, so its failures cannot support a diagnosis."};case"analysis-ready":return t.length===0?{reasonCode:"no-failures",message:"The run has no failing or flaky tests."}:void 0}}function Aa(r){let t=[...r.hypotheses].sort((e,n)=>e.rank-n.rank)[0];return sS[t?.probableOwner??"undetermined"]??"owner-undetermined"}function dS(r,t){return r==="operation-failed"?"failed":t?"insufficient-evidence":"completed"}async function Sa(r,t){let e=await tt(r.reportPath,{workspaceRoot:r.workspaceRoot,...r.gitRoot===void 0?{}:{gitRoot:r.gitRoot},...r.framework===void 0?{}:{framework:r.framework}});if(e.kind==="unreadable")return{kind:"unreadable",outcome:"inconclusive",reasonCode:e.artifact.availability==="unavailable"?"report-unavailable":"report-unreadable",message:e.diagnostic.message};let n=e.run,i=aS(n),s=(w,x={})=>({kind:"analyzed",stage:{run:n,failing:i,...x,result:w}}),a=await fs(n,{artifactRoot:r.artifactRoot??n.workspace.root,includeCurrentDiff:r.includeCurrentDiff===!0,includeChangeHistory:r.includeChangeHistory===!0,...r.probePath===void 0?{}:{probePath:r.probePath}},{...r.evidencePolicy,workspaceRoot:n.workspace.root});if(a.kind!=="built")return s(a.kind==="invalid-policy"?{outcome:"operation-failed",reasonCode:"invalid-evidence-policy",message:a.message}:{outcome:"inconclusive",reasonCode:"evidence-budget-exceeded",message:a.message,insufficient:!0});let o=a.packet,d=fa(n,o),c=Uc(d),l={packet:o,symptoms:d,clusters:c},u=oS(n,i);if(u!==void 0)return s({outcome:"inconclusive",...u,insufficient:!0},l);if(r.remote===void 0)return s({outcome:"inconclusive",reasonCode:"remote-diagnosis-not-configured",message:"Local evidence analysis completed; no remote diagnosis was configured."},l);let p=await fS(r,n,c,t),f=uS(p);if(f===void 0)return s({outcome:"inconclusive",reasonCode:"no-failures",message:"No failing test produced a symptom to diagnose.",insufficient:!0},l);let h=p.filter(w=>w.result.reasonCode!=="cluster-not-requested"),g=h.filter(w=>w.result.outcome==="diagnosed").length,m=c.clusters.length-h.length,y=c.clusters.length>1?`${g} of ${c.clusters.length} failure groups diagnosed.${m>0?` ${m} not sent: ${cS(p)}`:""}`:f.result.message;return s({...f.result,message:y},{...f.packet===void 0?l:{packet:f.packet},...f.symptoms===void 0?{}:{symptoms:f.symptoms},...f.clusters===void 0?{}:{clusters:f.clusters},clusterStages:[f,...p.filter(w=>w!==f)],representativeId:f.representativeId})}function cS(r){return r.find(e=>e.result.reasonCode==="cluster-not-requested")?.result.message??"at most 6 groups are sent per analysis."}var lS={strong:3,moderate:2,weak:1,insufficient:0};function by(r){let[t]=[...r.result.diagnosis?.hypotheses??[]].sort((e,n)=>e.rank-n.rank);return lS[t?.evidenceGrade??""]??0}function Ea(r){return r.map((t,e)=>({item:t,index:e})).filter(({item:t})=>t.result.outcome==="diagnosed"&&t.result.reasonCode==="test-support-owned").sort((t,e)=>by(e.item)-by(t.item)||e.item.cluster.logicalTestIds.length-t.item.cluster.logicalTestIds.length||t.index-e.index).map(({item:t})=>t)}function uS(r){let t=r.filter(e=>e.result.outcome==="diagnosed");return Ea(r)[0]??t[0]??r[0]}var pS=new Set(["provider-refusal","malformed-response","schema-invalid","citation-or-grading-invalid"]);async function fS(r,t,e,n){let i=r.remote;if(i===void 0)return[];let s=py(e),a=[],o=[];for(let m of s){let y=fy(t,m);if(y===void 0)continue;let w=hy(t,m,y.logicalTestId),x=await fs(w,{artifactRoot:r.artifactRoot??t.workspace.root,includeCurrentDiff:r.includeCurrentDiff===!0,includeChangeHistory:r.includeChangeHistory===!0,...r.probePath===void 0?{}:{probePath:r.probePath}},{...r.evidencePolicy,workspaceRoot:t.workspace.root});if(x.kind!=="built"){a.push({cluster:m,representativeId:y.logicalTestId,result:{outcome:"inconclusive",reasonCode:"evidence-budget-exceeded",message:x.message,insufficient:!0}});continue}let v=fa(w,x.packet);o.push({cluster:m,representativeId:y.logicalTestId,packet:x.packet,symptoms:v,clusters:my(m,v,e)})}let d=[];for(let m of o){let y=r.reuseDiagnosis===!0?await mS(t.workspace.root,t.runId,m.packet,m.symptoms):void 0;y===void 0?d.push(m):a.push(Vt(m,y))}let c=a.some(m=>m.result.reasonCode==="test-support-owned"),l=(m,y)=>{for(let w of m)a.push(Vt(w,{outcome:"inconclusive",reasonCode:"cluster-not-requested",message:y}))};if(r.reuseDiagnosis===!0&&c)return l(d,"A recorded diagnosis of another group already supports a repair."),mi(a,s);let u=i.session===void 0?d.slice(0,1):d;l(d.slice(u.length),"the service counts each request separately, so only the largest group was sent.");let f=(await Promise.all(u.map(async m=>({item:m,prepared:await ya({packet:m.packet,symptoms:m.symptoms,clusters:m.clusters,model:i.model,caps:i.caps,transport:i.transport,now:n()})})))).flatMap(({item:m,prepared:y})=>y.kind==="preview-ready"?[{item:m,prepared:y.prepared}]:(a.push(Vt(m,{outcome:Ta.has(y.reasonCode)?"inconclusive":"operation-failed",reasonCode:y.reasonCode,message:y.message,audit:y.audit})),[]));if(f.length===0)return mi(a,s);let h=f.map(m=>m.prepared.preview),g;if(r.interaction.approveDiagnoses!==void 0)g=await r.interaction.approveDiagnoses(h);else{g=!0;for(let m of h)await r.interaction.approveDiagnosis(m)||(g=!1)}if(!g){for(let m of f)a.push(Vt(m.item,{outcome:"inconclusive",reasonCode:"remote-consent-declined",message:"The developer declined the diagnosis request; no evidence was sent."}));return mi(a,s)}if(i.session!==void 0)try{await i.session.open(f.length)}catch(m){let y=m instanceof Error?m.message:"The analysis session could not be opened.";for(let w of f)a.push(Vt(w.item,{outcome:"operation-failed",reasonCode:"session-unavailable",message:y}));return mi(a,s)}try{let m=await yy(f,3,async y=>{let w=await xy(r,y.prepared,i.transport,n),x=i.escalation;if(x===void 0||!pS.has(w.reasonCode))return Vt(y.item,w);let v=await hS(r,y.item,x,i.transport,n);return v===void 0?Vt(y.item,w):{...Vt(y.item,v),escalated:!0}});a.push(...m)}finally{await i.session?.close().catch(()=>{})}return mi(a,s)}function mi(r,t){let e=new Map(t.map((n,i)=>[n.clusterId,i]));return[...r].sort((n,i)=>(e.get(n.cluster.clusterId)??0)-(e.get(i.cluster.clusterId)??0))}function Vt(r,t){return{cluster:r.cluster,representativeId:r.representativeId,packet:r.packet,symptoms:r.symptoms,clusters:r.clusters,result:t}}async function xy(r,t,e,n){let i=await Xc({prepared:t,authorization:{bindingHash:t.authorizationBindingHash,mode:"interactive",authorizedAt:n(),authorizationId:en()},authorizationStore:r.authorizationStore??new lr,transport:e,now:n()});switch(i.kind){case"diagnosed":return{outcome:"diagnosed",reasonCode:Aa(i.diagnosis),message:"The diagnosis passed schema validation and local grading.",diagnosis:i.diagnosis,grading:i.grading,audit:i.audit};case"abstained":return{outcome:"inconclusive",reasonCode:i.reasonCode,message:"The evidence was insufficient for a supported diagnosis.",diagnosis:i.diagnosis,grading:i.grading,audit:i.audit};default:return{outcome:Ta.has(i.reasonCode)?"inconclusive":"operation-failed",reasonCode:i.reasonCode,message:i.message,audit:i.audit}}}async function hS(r,t,e,n,i){let s=await ya({packet:t.packet,symptoms:t.symptoms,clusters:t.clusters,model:e.model,caps:e.caps,transport:n,now:i()});if(s.kind==="preview-ready"&&await r.interaction.approveDiagnosis(s.prepared.preview))return xy(r,s.prepared,n,i)}async function mS(r,t,e,n){if(/^run_[a-f0-9]{24}$/.test(t))try{let i=await nS(r),s=JSON.parse(await rS(iS(i,".kwikqa","runs",t,"result.json"),"utf8")),a=u=>u==="diagnosed"||u==="inconclusive",o=[...(s.clusters??[]).filter(u=>a(u.outcome)),...a(s.outcome)?[s]:[]].find(u=>u.diagnosis?.packetHash===e.packetHash&&u.diagnosisAudit!==void 0),d=o?.diagnosis;if(o===void 0||d===void 0||o.diagnosisAudit===void 0)return;let c=ui(d,e,n);if(!c.passed)return;let l=o.outcome==="inconclusive";return{outcome:l?"inconclusive":"diagnosed",reasonCode:l?o.reasonCode??"insufficient-evidence":Aa(d),message:"Reused the graded diagnosis recorded for this exact evidence packet.",diagnosis:d,grading:c,audit:o.diagnosisAudit}}catch{return}}function yS(r){return{clusterId:r.cluster.clusterId,logicalTestIds:r.cluster.logicalTestIds,representativeId:r.representativeId,signals:r.cluster.signals,...r.packet===void 0?{}:{packetHash:r.packet.packetHash},outcome:r.result.outcome,reasonCode:r.result.reasonCode,message:r.result.message,...r.result.diagnosis===void 0?{}:{diagnosis:r.result.diagnosis},...r.result.grading===void 0?{}:{grading:r.result.grading},...r.result.audit===void 0?{}:{diagnosisAudit:r.result.audit},...r.escalated===!0?{escalated:!0}:{}}}function Ca(r,t,e,n,i={}){let{run:s,packet:a,symptoms:o,clusters:d}=r,c=r.result;return{schemaVersion:"1.0",recordId:Pa(),command:t,runId:s.runId,createdAt:s.createdAt,recordedAt:n(),workspace:s.workspace,sourceHashes:a?.sourceHashes??s.sourceHashes,usability:s.usability,failingLogicalTestIds:r.failing,analysis:{status:dS(c.outcome,c.insufficient===!0)},proposal:{status:"not-requested"},application:{status:"not-requested"},validation:{status:"not-requested"},...a===void 0?{}:{evidence:{packetHash:a.packetHash,evidence:a.totals.evidence,artifacts:a.totals.artifacts,omissions:a.totals.omissions,redactions:a.totals.redactions,serializedBytes:a.totals.serializedBytes}},...o===void 0||d===void 0?{}:{symptoms:{symptoms:o.symptoms.length,unclassifiedAttempts:o.unclassifiedAttemptIds.length,clusters:d.clusters.length}},...r.clusterStages===void 0||r.clusterStages.length===0?{}:{clusters:r.clusterStages.map(yS)},...c.diagnosis===void 0?{}:{diagnosis:c.diagnosis},...c.grading===void 0?{}:{grading:c.grading},...c.audit===void 0?{}:{diagnosisAudit:c.audit},...i,outcome:e.outcome,reasonCode:e.reasonCode,message:e.message}}async function Na(r,t,e){let n={run:r.run,...r.packet===void 0?{}:{packet:r.packet},...r.symptoms===void 0?{}:{symptoms:r.symptoms},...r.clusters===void 0?{}:{clusters:r.clusters}},i=(s,a)=>({outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s,...a===void 0?{}:{recordPath:a},...n});if(!e)return i(t);try{return i(t,await hi(r.run.workspace.root,t))}catch{return i({...t,outcome:"operation-failed",reasonCode:"record-write-failed",message:"The run record could not be written safely under .kwikqa/runs/."})}}async function cl(r){let t=r.now??(()=>new Date().toISOString()),e=await Sa(r,t);if(e.kind==="unreadable")return{outcome:e.outcome,reasonCode:e.reasonCode,message:e.message};let{stage:n}=e;return Na(n,Ca(n,"analyze",n.result,t),r.persist!==!1)}import{randomUUID as MS}from"node:crypto";import{relative as $S,resolve as _S,sep as FS}from"node:path";import{createHash as vy}from"node:crypto";import{lstat as gS,readFile as wS,realpath as Oa}from"node:fs/promises";import{isAbsolute as bS,join as xS,relative as vS,resolve as kS,sep as IS}from"node:path";var zt=/^[a-f0-9]{64}$/,Iy=/^vld_[a-f0-9]{24}$/,PS=Dt,RS=4*1024*1024,TS=2*1024*1024;function wr(r){return{code:"transaction-unavailable",message:r}}function yi(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function ul(r,t){let e=Object.keys(r).sort(),n=[...t].sort();return e.length===n.length&&e.every((i,s)=>i===n[s])}function ll(r){return Array.isArray(r)&&r.every(t=>typeof t=="string"&&t.length>0&&!t.includes("\0"))}function AS(r,t){let e=vS(r,t);return e===""||!bS(e)&&e!==".."&&!e.startsWith(`..${IS}`)}function SS(r){return typeof r=="string"&&r.length>0&&Number.isFinite(Date.parse(r))}function ky(r){return yi(r)?ul(r,["path","observedBytes","storedBytes","sha256","storedSha256","truncated","redacted"])&&typeof r.path=="string"&&r.path.length>0&&typeof r.sha256=="string"&&zt.test(r.sha256)&&typeof r.storedSha256=="string"&&zt.test(r.storedSha256)&&Number.isInteger(r.observedBytes)&&r.observedBytes>=0&&Number.isInteger(r.storedBytes)&&r.storedBytes>=0&&typeof r.truncated=="boolean"&&typeof r.redacted=="boolean":!1}function Py(r){if(!yi(r))throw new Error("Validation command record is not an object.");let t=r,{recordHash:e,...n}=t;if(!ul(r,["schemaVersion","validationRunId","commandId","commandHash","planHash","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","startedAt","durationMs","termination","stdout","stderr","artifacts","status","recordHash"])||t.schemaVersion!=="1.0"||!Iy.test(t.validationRunId)||!PS.test(t.commandId)||!zt.test(t.commandHash)||!zt.test(t.planHash)||t.timing!=="post-patch"||t.required!==!0||t.executable!==process.execPath||!ll(t.args)||typeof t.kind!="string"||t.kind.length===0||typeof t.workingDirectory!="string"||t.workingDirectory.length===0||!yi(t.environmentDelta)||!Object.entries(t.environmentDelta).every(([i,s])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)&&typeof s=="string"&&!s.includes("\0"))||!Number.isInteger(t.timeoutMs)||t.timeoutMs<=0||typeof t.purpose!="string"||t.purpose.length===0||!ll(t.logicalTestIds)||!ll(t.projectIds)||!SS(t.startedAt)||!Number.isInteger(t.durationMs)||t.durationMs<0||!yi(t.termination)||t.termination.kind!=="exit"||t.termination.exitCode!==0||!ky(t.stdout)||!ky(t.stderr)||t.stdout.truncated||t.stderr.truncated||!Array.isArray(t.artifacts)||!t.artifacts.every(i=>yi(i)&&ul(i,["path","sha256","bytes"])&&typeof i.path=="string"&&i.path.length>0&&typeof i.sha256=="string"&&zt.test(i.sha256)&&Number.isInteger(i.bytes)&&i.bytes>=0)||t.status!=="passed"||!zt.test(e)||N(n)!==e)throw new Error("Validation command record is malformed or non-passing.");return t}function ES(r){let t=Lt(JSON.parse(r));if(t.status!=="passed")throw new Error("Validation manifest is not passing.");for(let e of t.commandRecords)Py(e);return t}async function Ry(r){let[t,e,n,i]=await Promise.all([Oa(r.workspace.workspaceRoot),Oa(r.snapshot.workspaceRoot),Oa(r.workspace.gitRoot),Oa(r.snapshot.gitRoot)]);if(t!==e||n!==i)throw new Error("Validation workspace identity changed.");return t}async function Ty(r,t,e){for(let n of e.manifest.targets){let i=await W(r,n.path,t.maxTargetBytes);if(i.kind!=="read"||i.relativePath!==n.path||i.sha256!==n.resultSha256)return!1}return!0}function Ay(r){return zt.test(r.planHash)&&Iy.test(r.validationRunId)}async function Da(r,t,e){let n=kS(r,t);if(!AS(r,n))throw new Error("Validation record path escapes its run.");let i=await gS(n);if(!i.isFile()||i.isSymbolicLink()||i.size>e)throw new Error("Validation record path is unsafe or unbounded.");return wS(n)}async function CS(r,t,e){let n=new Map(e.requiredCommands.map(i=>[i.commandId,i.commandHash]));for(let i of t.commandRecords){if(i.validationRunId!==t.validationRunId||i.planHash!==t.planHash||n.get(i.commandId)===void 0)return!1;let s=n.get(i.commandId);if(s===void 0||i.commandHash!==s)return!1;let a=await Da(r,`commands/${i.commandId}/result.json`,TS),o=Py(JSON.parse(a.toString("utf8")));if(N(o)!==N(i))return!1;for(let d of[i.stdout,i.stderr]){let c=await Da(r,d.path,nr);if(c.byteLength!==d.storedBytes||vy("sha256").update(c).digest("hex")!==d.storedSha256)return!1}for(let d of i.artifacts){let c=await Da(r,d.path,jr);if(c.byteLength!==d.bytes||vy("sha256").update(c).digest("hex")!==d.sha256)return!1}}return!0}async function pl(r){if(!Ay(r))return{kind:"rejected",reasons:[wr("Validation identity is invalid.")]};let t=r.now??new Date().toISOString(),e;try{let n=await Ry(r.context);e=await Ue(n,{operation:"begin-validation",transactionId:r.transactionId,validationRunId:r.validationRunId,at:t});let i=await xe(n,r.transactionId),s=i.state.history.at(-1);return i.state.phase==="validating"&&s?.type==="validation-started"&&s.planHash===r.planHash&&s.validationRunId===r.validationRunId?{kind:"validating",transaction:Pe(i)}:i.state.phase!=="applied"||i.manifest.preview.authoritativeValidation.planHash!==r.planHash||!await Ty(n,r.context,i)?{kind:"rejected",reasons:[wr("Applied transaction does not match the approved validation handoff.")],transaction:Pe(i)}:(i=await Be({transaction:i,phase:"validating",type:"validation-started",planHash:r.planHash,validationRunId:r.validationRunId,now:t}),{kind:"validating",transaction:Pe(i)})}catch{return{kind:"failed",reasons:[wr("Validation transition failed closed.")]}}finally{await e?.release().catch(()=>{})}}async function fl(r){if(!Ay(r)||!zt.test(r.validationManifestHash))return{kind:"rejected",reasons:[wr("Validation completion identity is invalid.")]};let t=r.now??new Date().toISOString(),e;try{let n=await Ry(r.context);e=await Ue(n,{operation:"complete-validation",transactionId:r.transactionId,validationRunId:r.validationRunId,at:t});let i=await xe(n,r.transactionId),s=i.manifest.preview.authoritativeValidation,a=i.state.history.at(-1);if(i.state.phase==="completed"&&a?.type==="validation-passed"&&a.planHash===r.planHash&&a.validationRunId===r.validationRunId&&a.validationManifestHash===r.validationManifestHash)return{kind:"completed",transaction:Pe(i)};if(i.state.phase!=="validating"||s.planHash!==r.planHash||a?.type!=="validation-started"||a.validationRunId!==r.validationRunId||a.planHash!==r.planHash||!await Ty(n,r.context,i))return{kind:"rejected",reasons:[wr("Transaction is not validating this exact approved run.")],transaction:Pe(i)};let o=xS(i.directory,"validation",r.validationRunId),d=await Da(o,"manifest.json",RS),c=ES(d.toString("utf8")),l=new Set(c.requiredCommandIds),u=new Set(c.commandRecords.map(f=>f.commandId)),p=s.targetHashes;return c.manifestHash!==r.validationManifestHash||c.transactionId!==r.transactionId||c.validationRunId!==r.validationRunId||c.planHash!==r.planHash||c.repositoryFingerprint!==s.repositoryFingerprint||N(c.targetHashes)!==N(p)||l.size!==c.requiredCommandIds.length||u.size!==c.commandRecords.length||s.requiredCommandIds.some(f=>!l.has(f)||!u.has(f))||l.size!==s.requiredCommandIds.length||u.size!==s.requiredCommandIds.length||!await CS(o,c,s)?{kind:"rejected",reasons:[wr("Validation manifest does not prove the exact approved command set.")],transaction:Pe(i)}:(i=await Be({transaction:i,phase:"completed",type:"validation-passed",planHash:r.planHash,validationRunId:r.validationRunId,validationManifestHash:c.manifestHash,now:t}),{kind:"completed",transaction:Pe(i)})}catch{return{kind:"failed",reasons:[wr("Validation completion failed closed.")]}}finally{await e?.release().catch(()=>{})}}import{join as NS}from"node:path";var Sy="1.0",OS=/^rps_[a-f0-9]{24}$/,DS=8*1024*1024;function LS(r){if(typeof r!="object"||r===null)return;let t=r;if(!(typeof t.reportPath!="string"||!Array.isArray(t.logicalTestIds)||!t.logicalTestIds.every(e=>typeof e=="string")||t.framework!==void 0&&!xr.includes(t.framework)))return{reportPath:t.reportPath,...t.framework===void 0?{}:{framework:t.framework},logicalTestIds:t.logicalTestIds}}function Ey(r){if(!OS.test(r))throw new Error("Repair session id is invalid.");return[".kwikqa","repairs",r]}async function Cy(r,t){let e=await Fe(r,Ey(t.repairSessionId));await me(NS(e,`attempt-${t.attempt}.json`),`${le(t)}
87
+ `,{mode:384,replace:!1})}async function Ny(r,t,e){let n=await Fe(r,Ey(t)),i=await or(n,`attempt-${e}.json`,DS),s=gr(i.config);if(i.schemaVersion!==Sy||i.repairSessionId!==t||i.attempt!==e||typeof i.transactionId!="string"||i.workspace===void 0||typeof i.maxTargetBytes!="number"||i.record===void 0||s.kind!=="valid")throw new Error("Repair attempt state is malformed.");let a=LS(i.group);return{schemaVersion:Sy,repairSessionId:t,attempt:e,transactionId:i.transactionId,plan:ir(i.plan),workspace:i.workspace,config:s.config,maxTargetBytes:i.maxTargetBytes,record:i.record,...a===void 0?{}:{group:a}}}import{dirname as Oy,resolve as Dy}from"node:path";function tn(r,t){return{kind:"configuration",path:r.relativePath,sha256:r.sha256,detail:t}}async function Ly(r){let{run:t,test:e,discovery:n}=r,i=t.framework;if(i==="playwright")return{kind:"unavailable",message:"Playwright validation needs no prepared run."};let s=t.configFile??await Ei(r.workspaceRoot,i,e.location.file),a=n.scope==="focused"?[e.location.file]:n.scope==="affected"?n.testPaths:[],o=await Ys(r.workspaceRoot);if(i==="cypress"){let c=await Ci(r.workspaceRoot,s),l=n.scope==="focused"?t.logicalTests.filter(f=>f.location.file===e.location.file&&f.projectId===e.projectId&&f.status==="expected"):[],u=await Qs({workspaceRoot:r.workspaceRoot,runtime:o,...s===void 0?{}:{configFile:s},specs:a,screenshotsDirectory:`${r.artifactRoot}/screenshots`,noRetries:!0,capture:{directory:`${r.artifactRoot}/capture`,supportFile:c,...n.scope==="focused"?{only:[e,...l].map(f=>f.titlePath.join(" "))}:{}}}),p=l.map(f=>f.logicalTestId);return{kind:"prepared",prepared:{args:u.args,workingDirectory:s===void 0?r.workspaceRoot:Oy(Dy(r.workspaceRoot,s)),evidence:[tn(o["cypress-reporter.cjs"],"KwikQA's Cypress reporter."),tn(o["cypress-capture.js"],"KwikQA's Cypress failure capture."),...u.generated.map(f=>tn(f,"Support file KwikQA generated for this validation."))],companionLogicalTestIds:p}}}if(s===void 0)return{kind:"unavailable",message:"No wdio.conf was found for the failing spec, so its validation run is unknown."};let d=await Zs({workspaceRoot:r.workspaceRoot,runtime:o,configFile:s,specs:a,directory:`${r.artifactRoot}/runner`,noRetries:!0,...n.scope==="focused"?{grep:dm(e.titlePath)}:{},capture:!0});return{kind:"prepared",prepared:{args:d.args,workingDirectory:Oy(Dy(r.workspaceRoot,s)),evidence:[tn(o["wdio-reporter.mjs"],"KwikQA's WebdriverIO reporter."),tn(o["wdio-capture.mjs"],"KwikQA's WebdriverIO run wrapper."),...d.generated.map(c=>tn(c,"WebdriverIO config KwikQA generated for this validation."))],companionLogicalTestIds:[]}}}var jS=600*1e3,My=1e6,BS={maxFiles:5e3,maxFileBytes:1024*1024,maxTotalBytes:64*1024*1024,maxImportEdges:5e4,maxImportDepth:20},VS={biome:"@biomejs/biome",prettier:"prettier",typescript:"typescript",eslint:"eslint"};function La(r,t,e,n){let i=r.logicalTests.filter(l=>l.status==="unexpected"||l.status==="flaky"),s=[...t.hypotheses].sort((l,u)=>l.rank-u.rank)[0],a=new Set([...s?.supportingEvidenceIds??[],...t.ownershipEvidenceIds]),o=new Set(e.evidence.filter(l=>a.has(l.evidenceId)&&l.logicalTestId!==void 0).map(l=>l.logicalTestId)),d=i.filter(l=>o.has(l.logicalTestId));if(d.length===1)return d[0];let c=i.find(l=>l.logicalTestId===n);return c!==void 0&&(d.length===0||d.includes(c))?c:i.length===1?i[0]:void 0}function zS(r){return La(r.run,r.diagnosis,r.packet,r.representativeId)}function $y(r){return r.payloadManifestHash===void 0||r.payloadHash===void 0?[]:[{manifestHash:r.payloadManifestHash,payloadHash:r.payloadHash,packetHash:r.packetHash,model:r.model.modelId,provider:r.model.providerId,promptVersion:r.promptVersion,outputSchemaVersion:r.outputSchemaVersion}]}function HS(r){return{maxRequestTokens:r.request.maxInputTokens+r.request.maxOutputTokens,maxRunTokens:r.run.maxInputTokens+r.run.maxOutputTokens,maxRequestDollars:r.request.maxDollars,maxRunDollars:r.run.maxDollars}}var qS={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};async function US(r,t,e,n){let i=async o=>{let d=await Zn({workspaceRoot:r.workspaceRoot,repositoryRoot:r.gitRoot,ownerPath:t,packageName:o});return d.kind==="resolved"?d.tool:void 0},s={},a=await i(qS[e]);a!==void 0&&(s[e]=a);for(let o of new Set(n)){if(o==="kwikqa-babel")continue;let d=await i(VS[o]);d!==void 0&&(s[o]=d)}return s}async function _y(r){let{input:t,now:e,run:n,proposal:i,repository:s}=r,a={repairProposal:i,repairAudit:r.repairAudit},o=(P,C)=>r.finish({outcome:"validation-unavailable",reasonCode:P,message:C},{...a,proposal:{status:"ready"},application:{status:"not-run"},validation:{status:"unavailable"}}),d=zS(r);if(d===void 0)return o("original-test-ambiguous","The repair cannot be validated because the original failing test is ambiguous.");let c=n.projects.find(P=>P.projectId===d.projectId),l=await Cd({workspaceRoot:s.workspaceRoot,targets:i.targets.map(P=>({path:P.path,class:P.class})),originalTestPath:d.location.file,projects:n.projects.map(P=>({id:P.name,testDirectory:P.testDir??"",...n.configFile===void 0?{}:{configPath:n.configFile}})),limits:BS}),u=l.scope==="focused"&&l.projectIds.length===0&&c!==void 0&&c.name!==""?{...l,projectIds:[c.name]}:l,p=await US(s,d.location.file,n.framework,u.staticChecks.map(P=>P.tool)),f=`.kwikqa/validation-artifacts/${i.proposalHash.slice(0,24)}`,h;if(n.framework!=="playwright"&&u.status==="resolved"){let P=await Ly({workspaceRoot:s.workspaceRoot,run:n,test:d,discovery:u,artifactRoot:f});if(P.kind==="unavailable")return o("validation-scope-unavailable",P.message);h=P.prepared}let g=Jd({proposal:i,advisoryPlan:i.validationPlan,discovery:u,tools:p,workspaceRoot:s.workspaceRoot,originalTest:{path:d.location.file,line:d.location.line??1,logicalTestId:d.logicalTestId,projectId:c===void 0||c.name===""?d.projectId:c.name,...n.configFile===void 0?{}:{configPath:n.configFile},environmentEquivalent:t.environmentEquivalent!==!1},artifactRoot:f,timeoutMs:t.validationTimeoutMs??jS,framework:n.framework,...h===void 0?{}:{frameworkRun:{args:h.args,workingDirectory:h.workingDirectory,evidence:h.evidence},companionLogicalTestIds:h.companionLogicalTestIds}}),m=g.plan;if(m.status!=="resolved")return o("validation-scope-unavailable",m.unresolvedReasons.map(P=>P.message).join(" "));if(g.requiredBaselineCommands.length>0)return o("baseline-capture-unavailable","This repair changes shared test support, which needs a pre-patch baseline that cannot be captured yet.");let y=r.retry===void 0?1:2,w=r.retry?.repairSessionId??(await dc({workspaceRoot:s.workspaceRoot,originalRunId:n.runId,originalPacketHash:r.packet.packetHash,now:e()})).repairSessionId,x={config:r.config,snapshot:{workspaceRoot:s.workspaceRoot,gitRoot:s.gitRoot,dirtyPaths:s.dirtyPaths,validation:[]},workspace:{workspaceRoot:s.workspaceRoot,gitRoot:s.gitRoot},maxTargetBytes:My},v={sessionId:`kwikqa-${MS()}`},I=Qd({proposal:i,context:x,payloadManifests:[...r.diagnosisAudit===void 0?[]:$y(r.diagnosisAudit),...$y(r.repairAudit)],costBounds:HS(r.caps),scopes:{baseline:[],validation:[u.scope]},authoritativeValidation:Xd({plan:m,advisoryPlan:i.validationPlan,repairSessionId:w,attemptOrdinal:y}),previewedAt:e(),interactiveSession:v}),R={repairSessionId:w,attempt:y,planHash:m.planHash};if(I.kind!=="preview-ready")return r.finish({outcome:"operation-failed",reasonCode:"application-rejected",message:I.reasons.map(P=>P.message).join(" ")},{...a,proposal:{status:"ready"},application:{status:"blocked"}});if(!await t.interaction.approveApplication(I.preview,m))return r.finish({outcome:"repair-declined",reasonCode:"application-declined",message:"The developer declined the patch and validation plan; nothing was changed."},{...a,proposal:{status:"declined"},application:{status:"not-run"},repair:R});let E=en(),A=e(),O=await tc({preview:I.preview,authorization:{authorizationId:E,bindingHash:Hs(I.preview,E,A,v),authorizedAt:A,interactiveSession:v},context:x,now:A});if(O.kind!=="applied")return r.finish({outcome:"operation-failed",reasonCode:O.kind==="recovery-required"?"application-recovery-required":"application-rejected",message:O.reasons.map(P=>P.message).join(" ")},{...a,proposal:{status:"approved"},application:{status:O.kind==="recovery-required"?"recovery-required":"failed"},repair:R});let j=O.transaction.transactionId;await uc(s.workspaceRoot,w,{ordinal:y,proposalHash:i.proposalHash,transactionId:j,outcome:"applied",recordedAt:e()});let V=(r.memberIds??[]).filter(P=>P!==d.logicalTestId);return await Cy(s.workspaceRoot,{schemaVersion:"1.0",repairSessionId:w,attempt:y,transactionId:j,plan:m,workspace:x.workspace,config:r.config,maxTargetBytes:My,...V.length===0?{}:{group:{reportPath:$S(s.workspaceRoot,_S(s.workspaceRoot,t.reportPath)).split(FS).join("/"),...t.framework===void 0?{}:{framework:t.framework},logicalTestIds:V}},record:{runId:n.runId,createdAt:n.createdAt,workspace:n.workspace,sourceHashes:r.packet.sourceHashes,usability:n.usability,failingLogicalTestIds:n.logicalTests.filter(P=>P.status==="unexpected"||P.status==="flaky").map(P=>P.logicalTestId).sort()}}),r.finish({outcome:"awaiting-validation",reasonCode:"patch-applied",message:"The approved patch was applied. Run `kwikqa validate` to verify it."},{...a,proposal:{status:"approved"},application:{status:"applied"},repair:{...R,transactionId:j}})}import{execFile as GS}from"node:child_process";import{realpath as gi}from"node:fs/promises";import{isAbsolute as KS,relative as WS,resolve as hl,sep as Fy}from"node:path";import{promisify as JS}from"node:util";var XS=JS(GS),YS=3e4,QS=16*1024*1024;async function Ma(r,t){return(await XS("git",["-C",r,"--no-optional-locks",...t],{timeout:YS,maxBuffer:QS,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}function jy(r){let t=r.split("\0"),e=[];for(let n=0;n<t.length;n+=1){let i=t[n]??"";if(i.length<4)continue;let s=i.slice(0,2);if(e.push(i.slice(3)),s.includes("R")||s.includes("C")){let a=t[n+1];a!==void 0&&a.length>0&&e.push(a),n+=1}}return e}function ZS(r,t,e){let n=WS(r,hl(t,e));if(!(n===""||KS(n)||n===".."||n.startsWith(`..${Fy}`)))return n.split(Fy).join("/")}async function $a(r){let t=await gi(r);try{return await gi(hl((await Ma(t,["rev-parse","--show-toplevel"])).trim()))}catch{return t}}async function ml(r){let t=await gi(r);return(await Ma(t,["-c","core.quotePath=false","ls-files","-z"])).split("\0").filter(n=>n.length>0).sort()}async function wi(r){let t,e,n;try{t=await gi(r),e=await gi(hl((await Ma(t,["rev-parse","--show-toplevel"])).trim())),n=await Ma(e,["-c","core.quotePath=false","status","--porcelain=v1","-z","--untracked-files=all","--ignored=no"])}catch(a){let o=a,d=o.code==="ENOENT"?"git executable was not found.":(o.stderr??o.message??"").trim().split(`
88
+ `)[0]??"";return{kind:"unavailable",message:`Repository status could not be read: ${d===""?"git failed.":d}`}}let i=jy(n),s=[...new Set(i.map(a=>ZS(t,e,a)).filter(a=>a!==void 0))].sort();return{kind:"read",status:{workspaceRoot:t,gitRoot:e,dirtyPaths:s,pristine:i.length===0}}}var e0="kwikqa.config.json",t0=256*1024;async function r0(r,t){let e=await W(r,t,t0);if(e.kind==="unavailable")return{kind:"repair-config-missing",message:`Repair requires a reviewed ${t}; none was found in the workspace.`};if(e.kind!=="read")return{kind:"repair-config-invalid",message:`${t} could not be read: ${e.message}`};let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.bytes))}catch{return{kind:"repair-config-invalid",message:`${t} is not valid UTF-8 JSON.`}}let i=gr(n);return i.kind!=="valid"?{kind:"repair-config-invalid",message:i.issues.join(" ")}:i}function n0(r,t,e){let n=new Set(e.map(s=>s.toLocaleLowerCase("en-US"))),i=new Set;for(let s of r.evidence){if(s.locator.type!=="source-range")continue;let a=s.locator.path;ni(a,t.editablePaths)!==void 0&&!ri(a,t)&&!ti(a)&&!n.has(a.toLocaleLowerCase("en-US"))&&i.add(a)}return[...i].sort()}async function yl(r){let t=r.now??(()=>new Date().toISOString()),e=await wi(r.workspaceRoot);if(e.kind==="unavailable")return{outcome:"operation-failed",reasonCode:"repository-status-unavailable",message:e.message};let{workspaceRoot:n,gitRoot:i,dirtyPaths:s,pristine:a}=e.status,o=await r0(n,r.configPath??e0);if(o.kind!=="valid")return{outcome:"operation-failed",reasonCode:o.kind,message:o.message};let d=o.config;if(r.retryRepairSessionId!==void 0&&(await _t(n,r.retryRepairSessionId).catch(()=>{}))?.state!=="retry-approval-required")return{outcome:"operation-failed",reasonCode:"no-retry-available",message:"That repair session has no retry available; only one retry follows a failed validation."};let c=await Sa({...r,workspaceRoot:n,gitRoot:i},t);if(c.kind==="unreadable")return{outcome:c.outcome,reasonCode:c.reasonCode,message:c.message};let{stage:l}=c,u={workspaceRoot:n,gitRoot:i,dirtyPaths:s},p=(g,m=[])=>(y,w={})=>Na(g,Ca(g,"fix",m.length===0?y:{...y,message:`${m.join(" ")} ${y.message}`},t,{repository:{pristine:a,dirtyPaths:s},...w}),r.persist!==!1),f=c0(l,r);if("refusal"in f)return p(l)(f.refusal);if(f.groups.length===0){let{packet:g}=l,{diagnosis:m,grading:y}=l.result;return l.result.outcome!=="diagnosed"||g===void 0||m===void 0||y===void 0?p(l)(l.result):By(r,l,{packet:g,diagnosis:m,grading:y},d,t,p(l),u)}let h=[];f.groups.length>0&&await r.repairSession?.open(f.groups.length);try{let g;for(let m of f.groups){let y=d0(l,m),{packet:w}=y,{diagnosis:x,grading:v}=m.result;if(!(w===void 0||x===void 0||v===void 0)){if(g=await By(r,y,{packet:w,diagnosis:x,grading:v},d,t,p(y,h),u),!a0(g))return g;h.push(`Failure group ${o0(l,m)}: ${g.message}`)}}return g??p(l)(l.result)}finally{await r.repairSession?.close()}}var i0=3,s0=new Set(["model-declined-repair","repair-not-eligible","failure-not-reproduced","insufficient-ownership-evidence","intent-ambiguous","invalid-replacement","unauthorized-target","dirty-target-file","source-hash-mismatch","non-unique-match","overlapping-replacement","forbidden-edit","parse-failed","budget-exceeded","unreadable-target"]);function a0(r){return r.outcome==="abstained-from-repair"?s0.has(r.reasonCode):r.outcome==="validation-unavailable"&&r.record?.application.status==="not-run"}function o0(r,t){return(r.clusterStages??[]).indexOf(t)+1}function d0(r,t){return{...r,...t.packet===void 0?{}:{packet:t.packet},...t.symptoms===void 0?{}:{symptoms:t.symptoms},...t.clusters===void 0?{}:{clusters:t.clusters},result:t.result,clusterStages:[t,...(r.clusterStages??[]).filter(e=>e!==t)],representativeId:t.representativeId}}function c0(r,t){let e=r.clusterStages??[];if(t.group!==void 0){let s=e[t.group-1];return s===void 0?{refusal:{outcome:"operation-failed",reasonCode:"group-not-found",message:`There is no failure group ${t.group}; this run has ${e.length}.`}}:Ea([s]).includes(s)?{groups:[s]}:{refusal:{outcome:"abstained-from-repair",reasonCode:"group-not-repairable",message:`Failure group ${t.group} is not diagnosed as the test's fault (${s.result.reasonCode}); KwikQA repairs only test-side causes.`}}}let n=Ea(e),i=t.repairSession===void 0||t.retryRepairSessionId!==void 0?1:i0;return{groups:n.slice(0,i)}}async function l0(r,t){let{interaction:e}=r;if(e.confirmFailure===void 0||r.retryRepairSessionId!==void 0)return;let n=t.clusterStages?.[0]?.cluster.logicalTestIds??t.failing,i=t.representativeId??n[0];if(i===void 0)return;let s=await e.confirmFailure(t.run,n);if(s.kind==="declined")return{status:"declined",logicalTestIds:n,message:"The developer chose not to re-run the failing tests first."};if(s.kind==="unavailable")return{status:"unavailable",logicalTestIds:n,message:s.message};let a=n.filter(d=>s.failedAgain.includes(d));if(a.includes(i))return{status:"reproduced",logicalTestIds:n,failedAgain:a};let o=t.run.logicalTests.find(d=>d.logicalTestId===i)?.title;return{status:"not-reproduced",logicalTestIds:n,failedAgain:a,message:`${o===void 0?"The failing test":`"${o}"`} passed when re-run, so the failure looks flaky or depends on state the re-run did not have. KwikQA does not patch a test that passes; no repair was requested.`}}async function By(r,t,e,n,i,s,a){let{packet:o,diagnosis:d,grading:c}=e,l=[...d.hypotheses].sort((y,w)=>y.rank-w.rank)[0],u=r.repairCaps??r.remote.caps,p=await el({packet:o,diagnosis:d,grading:c,hypothesisId:l?.hypothesisId??"",editablePaths:n0(o,n,a.dirtyPaths),budgets:n.budgets,model:r.repairModel??r.remote.model,caps:u,transport:r.remote.transport,now:i()});if(p.kind!=="preview-ready"){let y=p.reasonCode==="repair-not-eligible"&&l?.probableOwner!=="test-support"?Aa(d):p.reasonCode,w=p.reasonCode==="repair-not-eligible"||Ta.has(p.reasonCode);return s({outcome:w?"abstained-from-repair":"operation-failed",reasonCode:y,message:p.message},{proposal:{status:w?"not-eligible":"failed"},repairAudit:p.audit})}let f=await l0(r,t),h=(y,w={})=>s(y,{...f===void 0?{}:{confirmation:f},...w});if(f?.status==="not-reproduced")return h({outcome:"abstained-from-repair",reasonCode:"failure-not-reproduced",message:f.message??"The failing test passed when re-run."},{proposal:{status:"not-eligible"}});if(!await r.interaction.approveRepairRequest(p.prepared.preview))return h({outcome:"repair-declined",reasonCode:"remote-consent-declined",message:"The developer declined the repair-proposal request; no evidence was sent."},{proposal:{status:"declined"}});let g=await tl({prepared:p.prepared,authorization:{bindingHash:p.prepared.authorizationBindingHash,mode:"interactive",authorizedAt:i(),authorizationId:en()},authorizationStore:r.authorizationStore??new lr,transport:r.remote.transport,now:i()});if(g.kind==="declined")return h({outcome:"abstained-from-repair",reasonCode:g.reasonCode,message:g.message},{proposal:{status:"not-eligible"},repairAudit:g.audit});if(g.kind!=="proposed")return h({outcome:"operation-failed",reasonCode:g.reasonCode,message:g.message},{proposal:{status:"failed"},repairAudit:g.audit});let m=await dl({packet:o,diagnosis:d,grading:c,config:n,snapshot:{workspaceRoot:a.workspaceRoot,gitRoot:a.gitRoot,dirtyPaths:a.dirtyPaths,validation:[]},intent:g.draft.intent,replacements:g.draft.replacements});if(m.kind==="rejected"){let[y]=m.reasons;return h({outcome:"abstained-from-repair",reasonCode:y?.code??"invalid-replacement",message:m.reasons.map(w=>w.message).join(" ")},{proposal:{status:"not-eligible"},repairAudit:g.audit,proposalRejections:m.reasons})}return r.proposeOnly===!0?h({outcome:"proposal-ready",reasonCode:"test-support-owned",message:"A policy-checked proposal is ready for review; nothing was applied."},{proposal:{status:"ready"},repairAudit:g.audit,repairProposal:m.proposal}):_y({input:r,now:i,run:t.run,packet:o,diagnosis:d,...t.representativeId===void 0?{}:{representativeId:t.representativeId},...t.clusterStages?.[0]===void 0?{}:{memberIds:t.clusterStages[0].cluster.logicalTestIds},proposal:m.proposal,config:n,repository:a,diagnosisAudit:t.result.audit,repairAudit:g.audit,caps:u,...r.retryRepairSessionId===void 0?{}:{retry:{repairSessionId:r.retryRepairSessionId}},finish:h})}import{randomUUID as u0}from"node:crypto";import{realpath as p0}from"node:fs/promises";import{join as f0,relative as h0,sep as gl}from"node:path";var m0={maxStreamBytes:4*1024*1024,maxTotalStreamBytes:16*1024*1024,terminationGraceMs:5e3},y0=32*1024*1024,g0=new Set(["applied","validating"]);function w0(){return`vld_${u0().replaceAll("-","").slice(0,24)}`}function b0(r){return{config:r.config,snapshot:{workspaceRoot:r.workspace.workspaceRoot,gitRoot:r.workspace.gitRoot,dirtyPaths:[],validation:[]},workspace:r.workspace,maxTargetBytes:r.maxTargetBytes}}function x0(r,t,e){let n=i=>h0(r,`${t}${gl}${i.split("/").join(gl)}`).split(gl).join("/");for(let i of e.commandRecords){let s=i.artifacts.find(d=>d.path.endsWith("/report.json"));if(s!==void 0)return n(s.path);let o=i.artifacts.filter(d=>js.test(d.path.split("/").at(-1)??""))[0];if(o!==void 0)return n(o.path.split("/").slice(0,-1).join("/"))}}async function v0(r,t,e){let n=t.group;if(n===void 0||n.logicalTestIds.length===0||r.checkGroup===void 0)return;let{logicalTestIds:i}=n,s=`${i.length} other test${i.length===1?"":"s"}`,a=await tt(f0(e,n.reportPath),{workspaceRoot:e,gitRoot:t.workspace.gitRoot,...n.framework===void 0?{}:{framework:n.framework}}),o=a.kind==="parsed"?new Set(a.run.logicalTests.map(u=>u.logicalTestId)):void 0;if(a.kind!=="parsed"||!i.every(u=>o?.has(u)))return{status:"unavailable",logicalTestIds:i,message:`The report fix read has changed, so the group's ${s} were not re-run.`};let d=await r.checkGroup(a.run,i);if(d.kind==="declined")return{status:"declined",logicalTestIds:i,message:`The group's ${s} were not re-run.`};if(d.kind==="unavailable")return{status:"unavailable",logicalTestIds:i,message:d.message};let c=i.filter(u=>d.failedAgain.includes(u)),l=c.map(u=>a.run.logicalTests.find(p=>p.logicalTestId===u)?.title??u).map(u=>`"${u}"`).join(", ");return{status:"rerun",logicalTestIds:i,stillFailing:c,message:c.length===0?`The group's ${s} pass now as well.`:`${c.length} of the group's ${s} still fail${c.length===1?"s":""}: ${l}. The patch stays; run \`kwikqa fix\` again for them.`}}async function bl(r){let t=r.now??(()=>new Date().toISOString()),e=()=>new Date().toISOString(),n=await p0(r.workspaceRoot),i=await ic(n);if(i.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-recovery-required",message:i.reasons.map(R=>R.message).join(" ")};let s=i.transactions.filter(R=>g0.has(R.phase));if(s.length!==1||s[0]===void 0)return{outcome:"operation-failed",reasonCode:"no-pending-repair",message:s.length===0?"There is no applied repair waiting for validation. Run `kwikqa fix` first.":"More than one repair is waiting for validation; recover the workspace first."};let a=await xe(n,s[0].transactionId),o=a.manifest.preview.authoritativeValidation,d=await Ny(n,o.repairSessionId,o.attemptOrdinal);if(d.transactionId!==a.manifest.transactionId)throw new Error("Repair attempt state does not belong to the pending transaction.");if(d.plan.planHash!==o.planHash)throw new Error("Saved validation plan does not match the approved plan.");let c=b0(d),l=d.transactionId,u=d.plan,p;if(a.state.phase==="validating"){let R=a.state.history.findLast(E=>E.type==="validation-started");if(R?.validationRunId===void 0)throw new Error("Validating transaction has no started validation run.");p=R.validationRunId}else{p=w0();let R=await pl({context:c,transactionId:l,planHash:u.planHash,validationRunId:p,now:e()});if(R.kind==="rejected"||R.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-rejected",message:R.reasons.map(E=>E.message).join(" ")};for(let E of u.commands)if(!(!E.required||E.timing!=="post-patch")){if(r.signal?.aborted===!0)break;await $d({workspaceRoot:n,repositoryRoot:d.workspace.gitRoot,transactionId:l,validationRunId:p,plan:u,commandId:E.commandId,limits:m0,...r.signal===void 0?{}:{signal:r.signal}}).catch(()=>{})}}let f=await Vd({workspaceRoot:n,gitRoot:d.workspace.gitRoot,transactionId:l,validationRunId:p,plan:u,reportMaxBytes:y0,completedAt:e()}),h=f.manifest,g={repairSessionId:d.repairSessionId,attempt:d.attempt,transactionId:l,planHash:u.planHash,validationRunId:p,validationManifestHash:h.manifestHash};if(h.status==="passed"&&(await fl({context:c,transactionId:l,planHash:u.planHash,validationRunId:p,validationManifestHash:h.manifestHash,now:e()})).kind==="completed"){await Js({workspaceRoot:n,repairSessionId:d.repairSessionId,ordinal:d.attempt,validationRunId:p,now:t()});let E=await v0(r,d,n);return wl(r,d,t,{outcome:"repaired",reasonCode:"validation-passed",message:`Every required validation check passed; the repair is complete.${E?.message===void 0?"":` ${E.message}`}`,application:"applied",validation:"passed",repair:g,...E===void 0?{}:{groupCheck:E}})}await Js({workspaceRoot:n,repairSessionId:d.repairSessionId,ordinal:d.attempt,validationRunId:p,now:t()});let m=await sc(c,l,e()),y=h.status==="passed"?"incomplete":h.status,w=y==="failed"?"validation-failed":y==="unavailable"?"validation-unavailable":"validation-incomplete";if(m.kind!=="rolled-back")return wl(r,d,t,{outcome:"repair-failed",reasonCode:"rollback-conflicted",message:"Validation did not pass and the patch could not be rolled back automatically because the files changed; resolve them manually.",application:"recovery-required",validation:y==="blocked"?"incomplete":y,repair:g});let v=(await pc({workspaceRoot:n,repairSessionId:d.repairSessionId,ordinal:d.attempt,proof:{transactionId:l,phase:"rolled-back",transactionRevision:m.transaction.revision},now:t()})).retry!==void 0,I=v?x0(n,f.directory,h):void 0;return wl(r,d,t,{outcome:"repair-failed",reasonCode:w,message:v?"Validation did not pass, so the patch was rolled back. One retry is available.":"Validation did not pass, so the patch was rolled back. No retry remains.",application:"rolled-back",validation:y==="blocked"?"incomplete":y,repair:{...g,retryAvailable:v,...I===void 0?{}:{retryReportPath:I}}})}async function wl(r,t,e,n){let i={schemaVersion:"1.0",recordId:Pa(),command:"validate",...t.record,recordedAt:e(),analysis:{status:"completed"},proposal:{status:"approved"},application:{status:n.application},validation:{status:n.validation},repair:n.repair,...n.groupCheck===void 0?{}:{groupCheck:n.groupCheck},outcome:n.outcome,reasonCode:n.reasonCode,message:n.message};if(r.persist===!1)return{outcome:i.outcome,reasonCode:i.reasonCode,message:i.message,record:i};try{let s=await hi(t.workspace.workspaceRoot,i);return{outcome:i.outcome,reasonCode:i.reasonCode,message:i.message,record:i,recordPath:s}}catch{return{outcome:"operation-failed",reasonCode:"record-write-failed",message:`${i.message} The run record could not be written safely under .kwikqa/runs/.`,record:i}}}var k0=1200*1e3,I0=10,P0=1e3,R0=15e3,T0=3e3,A0=6e4,Vy=3e4,S0=2;function vl(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}async function zy(r){try{let t=await r.json();return vl(t)?t:{}}catch{return{}}}function Hy(r){return typeof r=="number"&&Number.isFinite(r)?Math.min(R0,Math.max(P0,r)):T0}function xl(r){let t=vl(r.error)?r.error:void 0;return typeof t?.message=="string"?t.message:void 0}var _a=class{constructor(t){this.options=t}options;preflight(t){return this.options.preflight.preflight(t)}async complete(t){let e=performance.now(),n=()=>performance.now()-e;for(let i=0;;i+=1){let s=await this.#e(t,n);if(s!=="interrupted")return s;if(i===S0)return{kind:"failed",code:"http-error",message:"The model request was interrupted on our side; nothing was charged. Try again.",httpStatus:503,elapsedMs:n()};this.options.onRestart?.()}}async#e(t,e){let n=(u,p)=>({kind:"failed",code:u,message:p,elapsedMs:e()}),i=Lc(t);if(i!==void 0)return{kind:"failed",code:"invalid-request",message:i,elapsedMs:0};let s;try{s=await this.#t("POST","/v1/jobs",A0,{headers:{...this.options.headers(t.body),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(t.body)})}catch(u){return n("network-error",`The model request could not reach the KwikQA service (${oi(u)}).`)}let a=await zy(s);if(s.status!==202){let u=aa(a);return{kind:"failed",code:"http-error",message:xl(a)??"The KwikQA service refused the model request.",httpStatus:s.status,...u===void 0?{}:{providerCode:u},elapsedMs:e()}}let o=a.jobId;if(typeof o!="string"||o==="")return n("invalid-json","The KwikQA service did not name the job it started.");let d=this.options.sleep??(u=>new Promise(p=>setTimeout(p,u))),c=Hy(a.pollAfterMs),l=0;for(;;){if(e()>(this.options.maxWaitMs??k0))return await this.#r(o),n("timeout","The model did not answer in time; nothing was charged.");await d(c);let u;try{u=await this.#t("GET",`/v1/jobs/${o}`,Vy)}catch{u=new Response(null,{status:599})}if(u.status>=500){if(l+=1,l>I0)return n("network-error","Lost contact with the KwikQA service while the model was working. If it answered, it is given back unused.");continue}l=0;let p=await zy(u);if(u.status===404)return"interrupted";if(!u.ok)return{kind:"failed",code:"http-error",message:xl(p)??"The KwikQA service refused to report the job.",httpStatus:u.status,elapsedMs:e()};if(p.status==="running"){this.options.onProgress?.(e()),c=Hy(p.pollAfterMs);continue}if(p.status==="failed")return vl(p.error)&&p.error.code==="job-interrupted"?"interrupted":{kind:"failed",code:"http-error",message:xl(p)??"The model request was interrupted; nothing was charged.",httpStatus:503,elapsedMs:e()};if(p.status!=="answered")return n("invalid-json","The KwikQA service reported a job state the CLI does not know.");await this.#r(o);let f=typeof p.httpStatus=="number"?p.httpStatus:502,h=p.result,g=f>=200&&f<300;if(!g||Dc(h)){let m=aa(h),y=g?m??502:f;return{kind:"failed",code:"http-error",message:Oc(y,h),httpStatus:y,...m===void 0?{}:{providerCode:m},elapsedMs:e()}}return this.options.onCompletionBody?.(h),{kind:"response",httpStatus:f,body:h,elapsedMs:e()}}}async#r(t){try{await this.#t("DELETE",`/v1/jobs/${t}`,Vy)}catch{}}#t(t,e,n,i={}){return this.options.fetch(`${this.options.baseUrl}${e}`,{method:t,headers:{Accept:"application/json",Authorization:`Bearer ${this.options.token}`,...i.headers},...i.body===void 0?{}:{body:i.body},redirect:"error",signal:AbortSignal.timeout(n)})}};var E0="https://api.kwikqa.com",bi="https://kwikqa.com/dashboard/";function qy(r){return r.hosted??!(r.plan==="byo"||r.plan==="byo-team")}function C0(r){return r?.response_format?.json_schema?.name==="kwikqa_diagnosis"}var ft=class extends Error{constructor(e,n,i){super(i);this.status=e;this.code=n}status;code};function Ht(r,t){return(r.KWIKQA_API_URL??(t===void 0||t===""?E0:t)).replace(/\/+$/,"")}function Uy(r){let t=r?.messages;if(!Array.isArray(t))return;let e=t.find(n=>typeof n=="object"&&n!==null&&n.role==="user"&&typeof n.content=="string");if(e!==void 0)try{let n=JSON.parse(e.content).framework;return n==="playwright"||n==="cypress"||n==="webdriverio"?n:void 0}catch{return}}var ht=class{constructor(t,e,n=fetch){this.baseUrl=t;this.token=e;this.fetchImpl=n}baseUrl;token;fetchImpl;async#e(t,e,n,i,s){let a=()=>this.fetchImpl(`${this.baseUrl}${e}`,{method:t,headers:{Accept:"application/json",...n===void 0?{}:{"Content-Type":"application/json"},...this.token===void 0?{}:{Authorization:`Bearer ${this.token}`},...i===void 0?{}:{"X-KwikQA-Retry-Ticket":i},...s===void 0?{}:{"X-KwikQA-Session":s}},...n===void 0?{}:{body:JSON.stringify(n)},redirect:"error"}),o;try{o=await a().catch(c=>{if(t==="GET")return a();throw c})}catch(c){throw new ft(0,"network-error",`Could not reach the KwikQA service at ${this.baseUrl} (${oi(c)}).`)}let d;try{d=await o.json()}catch{d=void 0}if(!o.ok){let c=d?.error;throw new ft(o.status,c?.code??"http-error",c?.message??`The KwikQA service returned HTTP ${o.status}.`)}return d}startDeviceLogin(){return this.#e("POST","/v1/auth/device")}pollDeviceLogin(t){return this.#e("POST","/v1/auth/token",{deviceCode:t})}status(){return this.#e("GET","/v1/me")}hostedConfig(){return this.#e("GET","/v1/config")}plans(){return this.#e("GET","/v1/plans")}checkout(t,e){return this.#e("POST","/v1/billing/checkout",{plan:t,...e})}billingPortal(){return this.#e("POST","/v1/billing/portal")}reserveUsage(t,e,n){return this.#e("POST","/v1/usage/reserve",t,e,n)}openSession(t,e="diagnosis"){return this.#e("POST","/v1/usage/session",e==="diagnosis"?{requests:t}:{requests:t,kind:e})}async closeSession(t){let n=(await this.#e("DELETE","/v1/usage/session",void 0,void 0,t))?.retryTicket;return typeof n=="string"&&n!==""?{retryTicket:n}:{}}reportInsights(t){return this.#e("POST","/v1/insights",{events:t})}releaseUsage(t,e){return this.#e("POST","/v1/usage/release",{id:t,status:e})}logout(){return this.#e("POST","/v1/auth/logout")}transport(t){let e=s=>{let a=Uy(s),o=C0(s)?t.session?.():t.repairSession?.();return{...t.retryTicket===void 0?{}:{"X-KwikQA-Retry-Ticket":t.retryTicket},...o===void 0?{}:{"X-KwikQA-Session":o},...a===void 0?{}:{"X-KwikQA-Framework":a}}},n=s=>{let a=s?.kwikqa?.retryTicket;typeof a=="string"&&a!==""&&t.onRetryTicket?.(a)},i=new fr({apiRoot:`${this.baseUrl}/v1/openrouter`,credentialName:"A KwikQA login (run `npx kwikqa login`)",readApiKey:()=>this.token,fetch:this.fetchImpl,timeoutMs:6e5,extraHeaders:e,onCompletionBody:n});return t.jobs!==!0||this.token===void 0?i:new _a({baseUrl:this.baseUrl,token:this.token,fetch:this.fetchImpl,preflight:i,headers:e,onCompletionBody:n,...t.onProgress===void 0?{}:{onProgress:t.onProgress},...t.onRestart===void 0?{}:{onRestart:t.onRestart},...t.sleep===void 0?{}:{sleep:t.sleep}})}},Fa=class{constructor(t,e,n={}){this.inner=t;this.client=e;this.options=n}inner;client;options;preflight(t){return this.inner.preflight(t)}async complete(t){let n=t.body.response_format?.json_schema?.name==="kwikqa_repair_proposal"?"repair":"diagnosis",i;try{let a=Uy(t.body);i=await this.client.reserveUsage({kind:n,model:t.route.modelId,provider:t.route.providerSlug,...a===void 0?{}:{framework:a}},this.options.retryTicket,n==="diagnosis"?this.options.session?.():this.options.repairSession?.())}catch(a){if(!(a instanceof ft))throw a;return{kind:"failed",code:"http-error",message:a.message,elapsedMs:0,...a.status===0?{}:{httpStatus:a.status}}}i.retryTicket!==void 0&&this.options.onRetryTicket?.(i.retryTicket);let s=await this.inner.complete(t);return s.kind!=="response"&&await this.client.releaseUsage(i.id,s.httpStatus??599).catch(()=>{}),s}};import{mkdir as N0,readFile as O0,rm as D0,writeFile as L0}from"node:fs/promises";import{homedir as Gy}from"node:os";import{join as xi}from"node:path";function Ky(r){return r.KWIKQA_CONFIG_DIR!==void 0&&r.KWIKQA_CONFIG_DIR!==""?r.KWIKQA_CONFIG_DIR:process.platform==="win32"?xi(r.APPDATA??xi(Gy(),"AppData","Roaming"),"kwikqa"):xi(r.XDG_CONFIG_HOME??xi(Gy(),".config"),"kwikqa")}function kl(r){return xi(Ky(r),"credentials.json")}async function br(r){if(r.KWIKQA_TOKEN!==void 0&&r.KWIKQA_TOKEN.trim()!=="")return{token:r.KWIKQA_TOKEN.trim(),login:"(KWIKQA_TOKEN)",apiUrl:""};try{let t=JSON.parse(await O0(kl(r),"utf8"));return typeof t.token!="string"||t.token===""||typeof t.login!="string"||typeof t.apiUrl!="string"?void 0:{token:t.token,login:t.login,apiUrl:t.apiUrl}}catch{return}}async function Wy(r,t){await N0(Ky(r),{recursive:!0,mode:448}),await L0(kl(r),`${JSON.stringify(t)}
89
+ `,{mode:384})}async function Jy(r){await D0(kl(r),{force:!0})}import{createHash as M0}from"node:crypto";import{basename as $0}from"node:path";var _0=100;function Xy(r){return M0("sha256").update(r).digest("hex")}function Yy(r,t){let e=r.projects.find(s=>s.projectId===t.projectId)?.name??"",n=t.location.file,i=t.titlePath.filter(s=>s!==""&&s!==n&&s!==$0(n));return{key:Xy([e,n,...t.titlePath].join("\0")).slice(0,32),title:(i.length===0?[t.title]:i).join(" \u203A ").slice(0,300),file:n.slice(0,300),project:e.slice(0,100)}}function Qy(r){return r===void 0?void 0:Xy(r).slice(0,32)}function Zy(r){if(r.run===void 0)return;let t=r.run,e=t.logicalTests.filter(n=>n.status==="unexpected"||n.status==="flaky").slice(0,_0).map(n=>({...Yy(t,n),status:n.status==="flaky"?"flaky":"failed"}));return{kind:"analysis",outcome:r.outcome,reasonCode:r.reasonCode,framework:t.framework,tests:e}}function eg(r){let t=r.record,e=r.run===void 0||r.packet===void 0||t?.diagnosis===void 0?void 0:La(r.run,t.diagnosis,r.packet,t.clusters?.[0]?.representativeId),n=Qy(t?.repair?.repairSessionId);return{kind:"fix",outcome:r.outcome,reasonCode:r.reasonCode,...r.run===void 0?{}:{framework:r.run.framework},...n===void 0?{}:{session:n},...t?.repair?.attempt===void 0?{}:{attempt:t.repair.attempt},...e===void 0||r.run===void 0?{}:{test:Yy(r.run,e)},...t?.repairProposal===void 0?{}:{changedFiles:t.repairProposal.changedFiles,changedLines:t.repairProposal.changedLines}}}function tg(r){let t=r.record?.repair,e=Qy(t?.repairSessionId);if(!(e===void 0||t===void 0))return{kind:"validation",outcome:r.outcome,reasonCode:r.reasonCode,session:e,attempt:t.attempt}}async function ja(r,t,e,n){if(n===void 0||e.team?.insights!==!0)return;try{await t.reportInsights([n])}catch{r.print("Team insights: couldn't share this result; nothing else changed.");return}let i=n.kind==="analysis"?`${n.tests.length} failing or flaky test name${n.tests.length===1?"":"s"} and the result`:n.kind==="fix"?"this fix's test and outcome":"the validation result";r.print(`Team insights: shared ${i} with ${e.team.owner}'s team.`)}var F0={npm:"npx",pnpm:"pnpm exec",yarn:"yarn",bun:"bunx"},j0={npm:"npm i -D",pnpm:"pnpm add -D",yarn:"yarn add -D",bun:"bun add -d"};function rg(r){let t=(r.npm_config_user_agent??"").split("/")[0];return t==="pnpm"||t==="yarn"||t==="bun"?t:"npm"}function At(r){return`${F0[rg(r)]} kwikqa`}function Il(r,t){return`${j0[rg(r)]} ${t}`}import{basename as B0}from"node:path";function qt(r,t){return`${r} ${t}${r===1?"":"s"}`}function ng(r){return`$${r.toFixed(r<.1?4:2)}`}function V0(r){let t=r.evidence.flatMap(i=>i.locator.type==="diff-hunk"?[i.locator]:[]);if(t.length===0)return[];let e=new Set(t.flatMap(i=>i.commit===void 0?[]:[i.commit])),n=[...e.size===0?[]:[qt(e.size,"commit")],...t.some(i=>i.commit===void 0)?["uncommitted changes"]:[]].join(" and ");return[` Changes: ${qt(t.length,"changed hunk")} from ${n} that mention the failures (--no-changes leaves them out)`]}function vi(r,t,e){let n=t.model.reasoningEffort===void 0?"":`, effort ${t.model.reasoningEffort}`,i=t.model.zeroDataRetention===!0?", zero data retention":"";return[`${r==="diagnosis"?"Diagnosis":"Repair proposal"} request -> ${e}`,` Model: ${t.model.modelId} via ${t.model.providerId}${n}${i}`,` Evidence: ${qt(t.evidence.length,"redacted item")} from ${t.channels.join(", ")||"the report"}`,` ${qt(t.redactionIds.length,"redaction")} applied, ${qt(t.omissionIds.length,"item")} withheld by policy`,...V0(t),` Estimate: at most ${t.estimate.estimatedInputTokens.toLocaleString("en-US")} input + ${t.estimate.estimatedOutputTokens.toLocaleString("en-US")} output tokens, at most ${ng(t.estimate.estimatedDollars)}`,` Caps: ${ng(t.caps.request.maxDollars)} per request`,` Payload: ${t.payloadManifestHash.slice(0,16)}... (exactly this redacted payload is sent)`]}function ig(r,t){let e=r.proposal,n=["Proposed repair",` Intent: ${e.intent.statement}`,` Preserves: ${e.intent.preservedBehavior}`,` Changes: ${qt(e.changedFiles,"file")}, ${qt(e.changedLines,"line")}`,"",...e.diff.trimEnd().split(`
90
+ `),"","Validation commands (run later by `kwikqa validate`):"],i=new Map;for(let s of t.commands.filter(a=>a.timing==="post-patch")){let a=s.args.map(d=>/\s/.test(d)?JSON.stringify(d):d),o=` ${B0(s.executable)} ${a.join(" ")}`;i.set(o,(i.get(o)??0)+1)}for(let[s,a]of i)n.push(a===1?s:`${s} (${a} runs)`);return r.checkoutPristine||n.push("","Note: this checkout has other uncommitted changes; they are not touched."),n}function sg(r,t){let e=n=>t?.logicalTests.find(i=>i.logicalTestId===n)?.title;return r.flatMap((n,i)=>{let s=n.logicalTestIds.map(d=>e(d)??d),a=s.length<=3?s.join(", "):`${s.slice(0,3).join(", ")} and ${s.length-3} more`,o=`${s.length} test${s.length===1?"":"s"}`;return[`Failure group ${i+1} of ${r.length}: ${o} (${a})${n.escalated===!0?", answered by the stronger model":""}`,...n.diagnosis!==void 0&&n.diagnosis.hypotheses.length>0?Pl(n.diagnosis):[` ${n.outcome} (${n.reasonCode}): ${n.message}`],""]})}function Pl(r){if(r.hypotheses.length===0)return["No cause is supported by the evidence.",` Next: ${r.recommendedNextAction}`];let t=[];for(let e of[...r.hypotheses].sort((n,i)=>n.rank-i.rank))t.push(`#${e.rank} ${e.statement}`,` owner: ${e.probableOwner}, evidence: ${e.evidenceGrade}, cause: ${e.causalCategory}`);return t.push(` Next: ${r.recommendedNextAction}`),t}function ag(r,t,e){switch(t){case"diagnosed":return r?.diagnosis?.repairEligibility==="eligible"?`Run \`${e} fix\` to propose a repair.`:void 0;case"proposal-ready":return`Run \`${e} fix\` without --propose-only to review and apply it.`;case"awaiting-validation":return`Run \`${e} validate\` to verify the patch.`;case"repair-failed":return r?.repair?.retryAvailable===!0?`Run \`${e} fix --retry\` to re-diagnose from the validation evidence (one retry left).`:void 0;default:return}}var z0={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"},H0={"playwright-json":"JSON report","kwikqa-json":"KwikQA reporter","mochawesome-json":"mochawesome report","wdio-json":"@wdio/json-reporter report","junit-xml":"JUnit report"};function og(r){if(r===void 0)return;let t=r.artifact.formatVersion===void 0?"":` ${r.artifact.formatVersion}`,e=H0[r.artifact.format??""],n=r.logicalTests.filter(s=>s.status==="unexpected").length,i=r.logicalTests.filter(s=>s.status==="flaky").length;return`Read a ${z0[r.framework]}${t} run${e===void 0?"":` (${e})`}: ${qt(r.logicalTests.length,"test")}, ${n} failing${i===0?"":`, ${i} flaky`}.`}function dg(r,t){if(r===void 0)return;let e=r.framework==="playwright",n=e?"trace":"kwikqa-capture",i=0,s=0;for(let c of r.logicalTests)for(let l of Fr(c))i+=1,l.attachments.some(u=>u.name===n)&&(s+=1);if(i===0||s===i)return;let a=i-s;return[`Note: ${a===i?i===1?`The failing attempt has no ${e?"Playwright trace":"KwikQA failure capture"}`:`None of the ${i} failing attempts has ${e?"a Playwright trace":"a KwikQA failure capture"}`:`${a} of ${i} failing attempts have no ${e?"Playwright trace":"KwikQA failure capture"}`}, so browser actions, network, console, and DOM were not available to the diagnosis.`,e?` Run \`${t} analyze --capture\` to re-run them with full tracing, or set`:` Run \`${t} analyze --capture\` to re-run the failing specs and record each failure's page.`,...e?[' `use: { trace: "retain-on-failure" }` in playwright.config to keep traces of failures.']:[]].join(`
91
+ `)}var J={ok:0,failed:1,usage:2,account:3},Rl=(()=>{let{workspaceRoot:r,...t}=Bo;return{...t,maxPacketBytes:6e5}})(),W0=.85;function yg(r){if(r===void 0)return Rl;let t=Math.min(r.diagnosis.caps.request.maxInputTokens,r.repairCaps.request.maxInputTokens);return{...Rl,maxPacketBytes:Math.min(Rl.maxPacketBytes,Math.floor(t*W0))}}var fg=["test-results/kwikqa-report.json","test-results/kwikqa","playwright-report/results.json","test-results/results.json","mochawesome-report","cypress/reports","cypress/results","results.json","report.json"],gg=je(".kwikqa","cli-state.json");function Al(r){return`Not signed in. Run \`${At(r.env)} login\` first.`}async function rn(r){return q0(r).then(()=>!0,()=>!1)}async function Sl(r){try{return JSON.parse(await Ba(je(r,gg),"utf8"))}catch{return{}}}async function El(r,t){await G0(je(r,".kwikqa"),{recursive:!0,mode:448}),await mg(je(r,gg),`${JSON.stringify(t)}
92
+ `,{mode:384})}async function wg(r,t,e){if(e!==void 0)return ug(e)?e:pg(r.cwd,e);for(let n of[r.env.PLAYWRIGHT_JSON_OUTPUT_NAME,r.env.KWIKQA_REPORT_DIR])if(n!==void 0&&n!==""){let i=ug(n)?n:pg(t,n);if(await rn(i))return i}for(let n of fg)if(await rn(je(t,n)))return je(t,n);return je(t,fg[0]??"report.json")}async function bg(r){try{if((await lg(r)).isDirectory()){let t=cg("sha256");for(let e of(await K0(r)).sort()){let n=je(r,e);(await lg(n)).isFile()&&t.update(`${e}\0`).update(await Ba(n))}return t.digest("hex")}return cg("sha256").update(await Ba(r)).digest("hex")}catch{return}}async function J0(r,t,e){let n=t.capture;if(n===void 0)return;let i=je(r,n.reportPath);if(await bg(e)!==n.sourceSha256||!await rn(i))return;let s=n.probePath===void 0?void 0:je(r,n.probePath);return{reportPath:i,...s!==void 0&&await rn(s)?{probePath:s}:{}}}async function X0(r,t,e,n){let i=await tt(e,{workspaceRoot:t,...n.framework===void 0?{}:{framework:n.framework}});if(i.kind!=="parsed"){r.io.error(`Capture skipped: ${i.diagnostic.message}`);return}let s=i.run.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest",a=await vc({run:i.run,workspaceRoot:t,repositoryRoot:await $a(t),captureId:s,env:r.env,probe:n.probe});if(a.kind!=="ready"){r.io.print(`Capture skipped: ${a.message}`);return}for(let c of a.prepared.description)r.io.print(c);if(a.prepared.probeUnavailable!==void 0&&r.io.print(`Note: ${a.prepared.probeUnavailable}`),n.yes)r.io.print("Run these tests? yes (--yes)");else if(!await r.io.confirm("Run these tests?")){r.io.print("Capture declined; analyzing the existing report.");return}let o=await kc(a.prepared,r.env);if(r.io.print(o.outcome.message),o.probe!==void 0){let c=o.probe.results.reduce((l,u)=>l+u.candidates.length,0);r.io.print(`Live probe: ${c} Playwright-generated locator${c===1?"":"s"} for ${o.probe.results.length} failing test${o.probe.results.length===1?"":"s"}.`)}if(o.outcome.reportPath===void 0||o.outcome.reproduced===0)return;let d=await bg(e);if(d!==void 0){let c=await Sl(t);await El(t,{...c,capture:{sourceSha256:d,reportPath:Tl(t,o.outcome.reportPath),...o.probePath===void 0?{}:{probePath:Tl(t,o.probePath)}}})}return{reportPath:o.outcome.reportPath,...o.probePath===void 0?{}:{probePath:o.probePath}}}function hg(r,t){if(r===void 0||r==="")return{...t,evaluationStatus:"unverified-model"};let[e,n]=r.split("@");if(e===void 0||n===void 0||n==="")throw new ft(0,"invalid-model",`Model routes look like author/model@provider, not ${r}.`);return{modelId:e,providerId:n,evaluationStatus:"unverified-model"}}async function xg(r,t,e){let n=await br(r.env);if(n===void 0)return r.io.error(Al(r)),{exit:J.account};let i=new ht(Ht(r.env,n.apiUrl),n.token,r.fetch),s=await i.status(),a=await i.hostedConfig(),o=qy(s);if(!o&&(r.env.OPENROUTER_API_KEY??"").trim()==="")return r.io.error("The BYOK plans need OPENROUTER_API_KEY in the environment."),{exit:J.account};let d=t==="analysis"?s.usage.analyses:s.usage.repairs;if(e===void 0&&d.limit!==void 0&&d.used>=d.limit){let v=t==="analysis"?"analyses":"fixes";return r.io.error(`You have used all ${d.limit} ${v} on the ${s.plan} plan until ${s.periodEnd.slice(0,10)}.`),r.io.error(s.team?.role==="member"?`Ask ${s.team.owner}, who manages your team's plan, to add seats.`:`Run \`${At(r.env)} upgrade\` to see plans with more.`),{exit:J.account}}let c,l,u=a.sessions===!0&&e===void 0?{open:async v=>{l=(await i.openSession(v)).sessionTicket},close:async()=>{let v=l;l=void 0,v!==void 0&&await i.closeSession(v)}}:void 0,p,f=a.repairSessions===!0&&e===void 0?{open:async v=>{p=(await i.openSession(v,"repair")).sessionTicket},close:async()=>{let v=p;if(p=void 0,v===void 0)return;let I=await i.closeSession(v);I.retryTicket!==void 0&&(c=I.retryTicket)}}:void 0,h={...e===void 0?{}:{retryTicket:e},onRetryTicket:v=>{c=v},session:()=>l,repairSession:()=>p};if(!o){let v=new Fa(new fr({readApiKey:()=>r.env.OPENROUTER_API_KEY,fetch:r.fetch}),i,h);return{diagnosis:{model:hg(r.env.KWIKQA_DIAGNOSIS_MODEL,a.models.diagnosis),caps:a.caps.diagnosis,transport:v,...u===void 0?{}:{session:u}},repairModel:hg(r.env.KWIKQA_REPAIR_MODEL,a.models.repair),repairCaps:a.caps.repair,...f===void 0?{}:{repairSession:f},destination:"OpenRouter, with your own API key (KwikQA counts the request)",ticket:()=>c,client:i,status:s}}let g=i.transport({...h,jobs:a.jobs===!0,onProgress:Z0(r),onRestart:()=>r.io.print(" The KwikQA service restarted while the model was working; sending the request again (nothing was charged)."),...r.sleep===void 0?{}:{sleep:r.sleep}}),m=e!==void 0&&a.models.escalation!==void 0&&a.caps.escalation!==void 0,y=m?a.models.escalation:void 0,w=m?a.caps.escalation:void 0,x=!m&&u!==void 0&&a.models.escalation!==void 0&&a.caps.escalation!==void 0?{model:a.models.escalation,caps:a.caps.escalation}:void 0;return{diagnosis:{model:y??a.models.diagnosis,caps:w??a.caps.diagnosis,transport:g,...u===void 0?{}:{session:u},...x===void 0?{}:{escalation:x}},repairModel:y??a.models.repair,repairCaps:w??a.caps.repair,...f===void 0?{}:{repairSession:f},destination:"the KwikQA service, which forwards it to OpenRouter",ticket:()=>c,client:i,status:s}}var Y0=3e4;function Q0(r){let t=Math.floor(r/1e3),e=Math.floor(t/60);return e===0?`${t}s`:`${e}m ${String(t%60).padStart(2,"0")}s`}function Z0(r){let t=0;return e=>{let n=Math.floor(e/Y0);n<=t||(t=n,r.io.print(` The model is still working (${Q0(e)})\u2026`))}}function vg(r,t,e){let n=async(i,s)=>{for(let a of i)r.io.print(a);return e?(r.io.print(`${s} yes (--yes)`),!0):r.io.confirm(s)};return{approveDiagnosis:i=>n(vi("diagnosis",i,t),"Send this request?"),approveDiagnoses:i=>{let[s]=i;return i.length===1&&s!==void 0?n(vi("diagnosis",s,t),"Send this request?"):n([`${i.length} diagnosis requests, one for each group of failures with a shared cause:`,...i.flatMap((a,o)=>["",`Request ${o+1} of ${i.length}`,...vi("diagnosis",a,t)])],`Send these ${i.length} requests?`)},approveRepairRequest:i=>n(vi("repair proposal",i,t),"Send this request?"),approveApplication:async(i,s)=>{for(let a of ig(i,s))r.io.print(a);return r.io.confirm("Apply this patch?")}}}async function kg(r,t,e,n,i){let s=new Set(n),a=await vc({run:{...e,logicalTests:e.logicalTests.filter(d=>s.has(d.logicalTestId))},workspaceRoot:t,repositoryRoot:await $a(t),captureId:`${i.purpose}-${e.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest"}`,env:r.env,probe:!1});if(a.kind!=="ready")return{kind:"unavailable",message:a.message};r.io.print(""),r.io.print(i.intro);for(let d of a.prepared.description)r.io.print(d);if(!await r.io.confirm(i.question))return{kind:"declined"};let o=await kc(a.prepared,r.env);return r.io.print(o.outcome.message),o.outcome.kind==="failed"?{kind:"unavailable",message:o.outcome.message}:{kind:"rerun",failedAgain:o.outcome.failedAgain??[]}}function eE(r){return r==="repair-failed"||r==="validation-unavailable"||r==="operation-failed"?J.failed:J.ok}function Cl(r,t){r.io.print("");let e=og("run"in t?t.run:void 0);e!==void 0&&t.record?.command!=="validate"&&r.io.print(e);let n=t.record?.clusters??[];if(n.length>1&&t.record?.command!=="validate")for(let o of sg(n,"run"in t?t.run:void 0))r.io.print(o);else if(t.record?.diagnosis!==void 0&&t.record.command!=="validate"){for(let o of Pl(t.record.diagnosis))r.io.print(o);r.io.print("")}r.io.print(`Result: ${t.outcome} (${t.reasonCode})`),r.io.print(t.message);let i=At(r.env),s=dg("run"in t?t.run:void 0,i);s!==void 0&&r.io.print(s);let a=ag(t.record,t.outcome,i);return a!==void 0&&r.io.print(a),t.recordPath!==void 0&&r.io.print(`Record: ${t.recordPath}`),eE(t.outcome)}async function nn(r,t){try{return await t()}catch(e){if(e instanceof ft)return r.io.error(e.message),[401,402,403,409].includes(e.status)?J.account:J.failed;throw e}}async function Ig(r){return nn(r,async()=>{let t=new ht(Ht(r.env),void 0,r.fetch),e=await t.startDeviceLogin();r.io.print(`Open ${e.verificationUri} and enter the code: ${e.userCode}`);let n=r.sleep??(a=>new Promise(o=>setTimeout(o,a))),i=Math.max(1,e.interval),s=Date.now()+e.expiresIn*1e3;for(;Date.now()<s;){await n(i*1e3);let a=await t.pollDeviceLogin(e.deviceCode);if(a.status==="complete")return await Wy(r.env,{token:a.token,login:a.login,apiUrl:t.baseUrl}),r.io.print(`Signed in as ${a.login}.`),J.ok;if(a.status==="slow_down"&&(i+=5),a.status==="expired"||a.status==="denied")return r.io.error(a.status==="denied"?"Sign-in was denied.":"The code expired."),J.account}return r.io.error("The code expired before sign-in finished."),J.account})}async function Pg(r){let t=(r.env.KWIKQA_TOKEN??"").trim()!=="",e=t?void 0:await br(r.env);if(e!==void 0)try{await new ht(Ht(r.env,e.apiUrl),e.token,r.fetch).logout()}catch{r.io.error(`Could not reach the KwikQA service to revoke this token; revoke it at ${bi}account/.`)}return await Jy(r.env),r.io.print("Signed out."),t&&r.io.print("KWIKQA_TOKEN is still set in this environment; unset it to stop using it."),J.ok}function tE(r){let t=[...r.seats!==void 0&&r.seats>1?[`${r.seats} seats`]:[],...r.interval===void 0?[]:[r.interval==="year"?"billed yearly":"billed monthly"]];return`on the ${r.plan} plan${t.length===0?"":` (${t.join(", ")})`}`}async function Rg(r){return nn(r,async()=>{let t=await br(r.env);if(t===void 0)return r.io.print(Al(r)),J.account;let n=await new ht(Ht(r.env,t.apiUrl),t.token,r.fetch).status(),i=(s,a)=>a===void 0?`${s} (unlimited)`:`${s} of ${a}`;return r.io.print(`Signed in as ${n.login} ${tE(n)}.`),n.team!==void 0&&(r.io.print(n.team.role==="member"?`Team: ${n.team.owner}'s team; usage below is the team's shared pool.`:`Team: yours, with ${n.team.members} member${n.team.members===1?"":"s"}; usage below is the shared pool.`),r.io.print(n.team.insights===!0?"Team insights: on. Test names and fix outcomes from your runs are shared with your team.":"Team insights: off.")),r.io.print(`Analyses this period: ${i(n.usage.analyses.used,n.usage.analyses.limit)}`),r.io.print(`Fixes this period: ${i(n.usage.repairs.used,n.usage.repairs.limit)}`),r.io.print(`Period ends: ${n.periodEnd.slice(0,10)}`),r.io.print(`Manage your account, team, and tokens: ${bi}`),J.ok})}async function Tg(r){let t=await br(r.env);if(t===void 0){r.io.error(Al(r));return}return new ht(Ht(r.env,t.apiUrl),t.token,r.fetch)}function rE(r){let t=r.perSeat?"/seat":"",e=r.monthlyUsd===0?"$0":`$${r.monthlyUsd}${t}/mo or $${r.annualUsd}${t}/yr`,n=r.analyses===void 0?"unlimited analyses and fixes":`${r.analyses} analyses and ${r.repairs} fixes a month${r.perSeat?" per seat, shared":""}`,i=[...r.hosted?[]:["your OpenRouter key"],...r.perSeat?[`${r.minSeats}+ seats`]:[]];return{price:e,limits:i.length===0?n:`${n} (${i.join(", ")})`}}async function Ag(r,t,e={annual:!1}){return nn(r,async()=>{let n=await br(r.env),i=await new ht(Ht(r.env,n?.apiUrl),void 0,r.fetch).plans(),s=i.paidPlansOpen!==!1,o=i.plans.filter(g=>g.id!=="free").find(g=>g.id===t);if(o===void 0||!s){t!==void 0&&o===void 0&&r.io.error(`Unknown plan: ${t}`),r.io.print(`Plans (monthly, or yearly with ${12-i.annualMonthsCharged} months free):`);let g=Math.max(...i.plans.map(m=>m.id.length));for(let m of i.plans){let{price:y,limits:w}=rE(m);r.io.print(` ${m.id.padEnd(g)} ${y}: ${w}`)}if(s)r.io.print(`Run \`${At(r.env)} upgrade <plan> [--annual] [--seats <n>]\` to get a checkout link.`);else if(r.io.print("Paid plans are coming soon. Until they open, every account uses Free."),o!==void 0)return J.account;return t===void 0?J.ok:J.usage}let d;if(e.seats!==void 0&&(d=Number(e.seats),!(o.perSeat?Number.isInteger(d)&&d>=o.minSeats&&d<=i.maxSeats:d===1)))return r.io.error(o.perSeat?`${o.name} needs ${o.minSeats} to ${i.maxSeats} seats.`:`${o.name} is for one person; --seats applies to team plans.`),J.usage;let c=await Tg(r);if(c===void 0)return J.account;let l=await c.status();if(l.team?.role==="member")return r.io.print(`You're on ${l.team.owner}'s team, so ${l.team.owner} manages billing.`),J.ok;if(l.plan!=="free")return r.io.print(`You're on the ${l.plan} plan. Change plans, seats, or billing period in Billing, where you see the charge before you confirm:`),r.io.print(`${bi}billing/`),J.ok;let u=e.annual?"year":"month",p=await c.checkout(o.id,{interval:u,...d===void 0?{}:{seats:d}}),f=o.perSeat?d??o.minSeats:1,h=(e.annual?o.annualUsd:o.monthlyUsd)*f;return r.io.print(`Open this link to subscribe to ${o.name}${o.perSeat?` with ${f} seats`:""} for $${h} a ${e.annual?"year":"month"}:`),r.io.print(p.url),J.ok})}async function Sg(r){return nn(r,async()=>{let t=await Tg(r);if(t===void 0)return J.account;try{let{url:e}=await t.billingPortal();return r.io.print("Open this link to update your payment method or download invoices:"),r.io.print(e),r.io.print(`To change or cancel your plan: ${bi}billing/`),J.ok}catch(e){if(e instanceof ft&&e.code==="no-billing-account")return r.io.print("You don't have a paid subscription yet."),r.io.print(`Run \`${At(r.env)} upgrade <plan>\` to choose one.`),J.ok;if(e instanceof ft&&e.code==="team-member")return r.io.print(e.message),J.ok;throw e}})}async function Eg(r){let t=await Va(r.cwd),e=je(t,"kwikqa.config.json");if(await rn(e))r.io.print("kwikqa.config.json already exists; review it to change what KwikQA may edit.");else{let d=nl({repositoryPaths:await ml(t)});r.io.print("Proposed kwikqa.config.json (what KwikQA may edit when repairing tests):");for(let c of d.canonicalContents.trimEnd().split(`
93
+ `))r.io.print(` ${c}`);for(let c of[...d.reasons,...d.ambiguities])r.io.print(` - ${c}`);await r.io.confirm("Write kwikqa.config.json?")&&(await mg(e,d.canonicalContents,{flag:"wx"}),r.io.print("Wrote kwikqa.config.json. Commit it so the policy is reviewed like code."))}let n=je(t,".gitignore");!(await rn(n)&&/^\/?\.kwikqa\/?$/m.test(await Ba(n,"utf8")))&&await r.io.confirm("Add .kwikqa/ (local run records) to .gitignore?")&&await U0(n,`
94
94
  .kwikqa/
95
- `);let s=new Set((await Ol(t)).map(o=>o.framework)),a=o=>s.size===0||s.has(o);return a("playwright")&&(r.io.print(""),r.io.print("Playwright: add a JSON reporter to playwright.config so KwikQA can read your runs:"),r.io.print(' reporter: [["list"], ["json", { outputFile: "test-results/kwikqa-report.json" }]],'),r.io.print(' use: { trace: "retain-on-failure" },')),a("cypress")&&(r.io.print(""),r.io.print("Cypress: with kwikqa installed (npm i -D kwikqa), set KwikQA's reporter in cypress.config"),r.io.print("so every attempt and its code frame is kept:"),r.io.print(' reporter: "node_modules/kwikqa/dist/cypress-reporter.cjs",'),r.io.print(" Mochawesome and JUnit reports work too: npx kwikqa analyze --report mochawesome-report")),a("webdriverio")&&(r.io.print(""),r.io.print("WebdriverIO: with kwikqa installed (npm i -D kwikqa), add KwikQA's reporter in wdio.conf:"),r.io.print(' import KwikqaReporter from "kwikqa/wdio-reporter";'),r.io.print(' reporters: ["spec", [KwikqaReporter, {}]],'),r.io.print(" @wdio/json-reporter and JUnit reports work too: npx kwikqa analyze --report <directory>")),(s.has("cypress")||s.has("webdriverio"))&&(r.io.print(""),r.io.print("Then `npx kwikqa analyze --capture` re-runs failing specs and records each failure's page.")),W.ok}async function kg(r,t){return rn(r,async()=>{let e=await $a(r.cwd),n=await lg(r,e,t.report);if(t.capture===!0&&!r.io.interactive&&!t.yes)return r.io.error("Capturing re-runs your failing tests: run in a terminal, or pass --yes."),W.usage;let i=t.local?void 0:await pg(r,"analysis");if(i!==void 0&&"exit"in i)return i.exit;if(i!==void 0&&!r.io.interactive&&!t.yes)return r.io.error("Sending evidence needs approval: run in a terminal, or pass --yes, or use --local."),W.usage;let s=t.capture===!0?await H0(r,e,n,{yes:t.yes,probe:t.probe!==!1,...t.framework===void 0?{}:{framework:t.framework}}):void 0,a=s?.reportPath??n,o=await hi(e),d=await nl({reportPath:a,...t.framework===void 0?{}:{framework:t.framework},...s?.probePath===void 0?{}:{probePath:s.probePath},workspaceRoot:e,...o.kind==="read"?{gitRoot:o.status.gitRoot}:{},evidencePolicy:dg(i),includeChangeHistory:t.changes!==!1,...i===void 0?{}:{remote:i.diagnosis},interaction:fg(r,i?.destination??"",t.yes)}),c=Pl(r,d);return i!==void 0&&await La(r.io,i.client,i.status,Gy(d)),c})}async function Ig(r,t){return r.io.interactive?rn(r,async()=>{let e=await $a(r.cwd),n=await kl(e),i=t.retry?n.pendingRetry:void 0;if(t.retry&&i===void 0)return r.io.error("There is no failed validation to retry."),W.usage;let s=i===void 0?void 0:n.tickets?.[i.repairSessionId],a=await pg(r,"repair",s);if("exit"in a)return a.exit;let o=i===void 0?await lg(r,e,t.report):void 0,d=o===void 0?void 0:await z0(e,n,o);d!==void 0&&r.io.print(`Using the evidence captured by \`analyze --capture\`: ${xl(e,d.reportPath)}`);let c=await ul({reportPath:i===void 0?d?.reportPath??o??je(e,"report.json"):je(e,i.reportPath),...t.framework===void 0?{}:{framework:t.framework},...d?.probePath===void 0?{}:{probePath:d.probePath},workspaceRoot:e,evidencePolicy:dg(a),includeChangeHistory:t.changes!==!1,remote:a.diagnosis,repairModel:a.repairModel,repairCaps:a.repairCaps,...a.repairSession===void 0?{}:{repairSession:a.repairSession},...t.group===void 0?{}:{group:t.group},interaction:{...fg(r,a.destination,!1),confirmFailure:(g,m)=>hg(r,e,g,m,{purpose:"confirm",intro:"Before asking for a repair, re-run the failing tests once: a test that passes now is flaky, and KwikQA does not patch it.",question:"Re-run them first?"})},reuseDiagnosis:i===void 0,proposeOnly:t.proposeOnly,...i===void 0?{}:{retryRepairSessionId:i.repairSessionId}}),l=c.record?.repair?.repairSessionId,u=a.ticket(),{pendingRetry:p,...f}=n;await Il(e,{...i===void 0?n:f,...l===void 0||u===void 0?{}:{tickets:{...n.tickets,[l]:u}}});let h=Pl(r,c);return await La(r.io,a.client,a.status,Ky(c)),h}):(r.io.error("`kwikqa fix` needs a terminal: every request and patch is approved by a person."),W.usage)}async function X0(r,t){let e=Wy(t),n=e===void 0?void 0:await gr(r.env);if(n===void 0)return;let i=new ht(zt(r.env,n.apiUrl),n.token,r.fetch),s;try{s=await i.status()}catch{return}await La(r.io,i,s,e)}async function Pg(r){let t=await $a(r.cwd),e=await hl({workspaceRoot:t,checkGroup:(s,a)=>hg(r,t,s,a,{purpose:"group",intro:`The repair passed. ${a.length} other test${a.length===1?"":"s"} failed with the same cause; re-run ${a.length===1?"it":"them"} once to see whether the patch fixed ${a.length===1?"it":"them"} too. The patch stays either way.`,question:"Re-run them now?"})}),n=e.record?.repair;if(n?.retryAvailable===!0&&n.retryReportPath!==void 0){let s=await kl(t);await Il(t,{...s,pendingRetry:{repairSessionId:n.repairSessionId,reportPath:n.retryReportPath}})}let i=Pl(r,e);return await X0(r,e),i}import{createInterface as Y0}from"node:readline/promises";function Rg(){return{interactive:process.stdin.isTTY===!0,print:(r="")=>{process.stdout.write(`${r}
95
+ `);let s=new Set((await Fl(t)).map(d=>d.framework)),a=d=>s.size===0||s.has(d),o=At(r.env);return a("playwright")&&(r.io.print(""),r.io.print("Playwright: add a JSON reporter to playwright.config so KwikQA can read your runs:"),r.io.print(' reporter: [["list"], ["json", { outputFile: "test-results/kwikqa-report.json" }]],'),r.io.print(' use: { trace: "retain-on-failure" },')),a("cypress")&&(r.io.print(""),r.io.print(`Cypress: with kwikqa installed (${Il(r.env,"kwikqa")}), set KwikQA's reporter in cypress.config`),r.io.print("so every attempt and its code frame is kept:"),r.io.print(' reporter: "node_modules/kwikqa/dist/cypress-reporter.cjs",'),r.io.print(` Mochawesome and JUnit reports work too: ${o} analyze --report mochawesome-report`)),a("webdriverio")&&(r.io.print(""),r.io.print(`WebdriverIO: with kwikqa installed (${Il(r.env,"kwikqa")}), add KwikQA's reporter in wdio.conf:`),r.io.print(' import KwikqaReporter from "kwikqa/wdio-reporter";'),r.io.print(' reporters: ["spec", [KwikqaReporter, {}]],'),r.io.print(` @wdio/json-reporter and JUnit reports work too: ${o} analyze --report <directory>`)),(s.has("cypress")||s.has("webdriverio"))&&(r.io.print(""),r.io.print(`Then \`${o} analyze --capture\` re-runs failing specs and records each failure's page.`)),J.ok}async function Cg(r,t){return nn(r,async()=>{let e=await Va(r.cwd),n=await wg(r,e,t.report);if(t.capture===!0&&!r.io.interactive&&!t.yes)return r.io.error("Capturing re-runs your failing tests: run in a terminal, or pass --yes."),J.usage;let i=t.local?void 0:await xg(r,"analysis");if(i!==void 0&&"exit"in i)return i.exit;if(i!==void 0&&!r.io.interactive&&!t.yes)return r.io.error("Sending evidence needs approval: run in a terminal, or pass --yes, or use --local."),J.usage;let s=t.capture===!0?await X0(r,e,n,{yes:t.yes,probe:t.probe!==!1,...t.framework===void 0?{}:{framework:t.framework}}):void 0,a=s?.reportPath??n,o=await wi(e),d=await cl({reportPath:a,...t.framework===void 0?{}:{framework:t.framework},...s?.probePath===void 0?{}:{probePath:s.probePath},workspaceRoot:e,...o.kind==="read"?{gitRoot:o.status.gitRoot}:{},evidencePolicy:yg(i),includeChangeHistory:t.changes!==!1,...i===void 0?{}:{remote:i.diagnosis},interaction:vg(r,i?.destination??"",t.yes)}),c=Cl(r,d);return i!==void 0&&await ja(r.io,i.client,i.status,Zy(d)),c})}async function Ng(r,t){return r.io.interactive?nn(r,async()=>{let e=await Va(r.cwd),n=await Sl(e),i=t.retry?n.pendingRetry:void 0;if(t.retry&&i===void 0)return r.io.error("There is no failed validation to retry."),J.usage;let s=i===void 0?void 0:n.tickets?.[i.repairSessionId],a=await xg(r,"repair",s);if("exit"in a)return a.exit;let o=i===void 0?await wg(r,e,t.report):void 0,d=o===void 0?void 0:await J0(e,n,o);d!==void 0&&r.io.print(`Using the evidence captured by \`analyze --capture\`: ${Tl(e,d.reportPath)}`);let c=await yl({reportPath:i===void 0?d?.reportPath??o??je(e,"report.json"):je(e,i.reportPath),...t.framework===void 0?{}:{framework:t.framework},...d?.probePath===void 0?{}:{probePath:d.probePath},workspaceRoot:e,evidencePolicy:yg(a),includeChangeHistory:t.changes!==!1,remote:a.diagnosis,repairModel:a.repairModel,repairCaps:a.repairCaps,...a.repairSession===void 0?{}:{repairSession:a.repairSession},...t.group===void 0?{}:{group:t.group},interaction:{...vg(r,a.destination,!1),confirmFailure:(g,m)=>kg(r,e,g,m,{purpose:"confirm",intro:"Before asking for a repair, re-run the failing tests once: a test that passes now is flaky, and KwikQA does not patch it.",question:"Re-run them first?"})},reuseDiagnosis:i===void 0,proposeOnly:t.proposeOnly,...i===void 0?{}:{retryRepairSessionId:i.repairSessionId}}),l=c.record?.repair?.repairSessionId,u=a.ticket(),{pendingRetry:p,...f}=n;await El(e,{...i===void 0?n:f,...l===void 0||u===void 0?{}:{tickets:{...n.tickets,[l]:u}}});let h=Cl(r,c);return await ja(r.io,a.client,a.status,eg(c)),h}):(r.io.error("`kwikqa fix` needs a terminal: every request and patch is approved by a person."),J.usage)}async function nE(r,t){let e=tg(t),n=e===void 0?void 0:await br(r.env);if(n===void 0)return;let i=new ht(Ht(r.env,n.apiUrl),n.token,r.fetch),s;try{s=await i.status()}catch{return}await ja(r.io,i,s,e)}async function Og(r){let t=await Va(r.cwd),e=await bl({workspaceRoot:t,checkGroup:(s,a)=>kg(r,t,s,a,{purpose:"group",intro:`The repair passed. ${a.length} other test${a.length===1?"":"s"} failed with the same cause; re-run ${a.length===1?"it":"them"} once to see whether the patch fixed ${a.length===1?"it":"them"} too. The patch stays either way.`,question:"Re-run them now?"})}),n=e.record?.repair;if(n?.retryAvailable===!0&&n.retryReportPath!==void 0){let s=await Sl(t);await El(t,{...s,pendingRetry:{repairSessionId:n.repairSessionId,reportPath:n.retryReportPath}})}let i=Cl(r,e);return await nE(r,e),i}import{createInterface as iE}from"node:readline/promises";function Dg(){return{interactive:process.stdin.isTTY===!0,print:(r="")=>{process.stdout.write(`${r}
96
96
  `)},error:r=>{process.stderr.write(`${r}
97
- `)},confirm:async r=>{if(process.stdin.isTTY!==!0)return!1;let t=Y0({input:process.stdin,output:process.stdout});try{let e=await t.question(`${r} [y/N] `);return/^y(?:es)?$/i.test(e.trim())}finally{t.close()}}}}var Z0="0.1.0",Tg=`KwikQA turns failed Playwright, Cypress, and WebdriverIO runs into evidence-backed diagnoses and safe, validated test repairs.
97
+ `)},confirm:async r=>{if(process.stdin.isTTY!==!0)return!1;let t=iE({input:process.stdin,output:process.stdout});try{let e=await t.question(`${r} [y/N] `);return/^y(?:es)?$/i.test(e.trim())}finally{t.close()}}}}var aE="0.1.1",oE=`KwikQA turns failed Playwright, Cypress, and WebdriverIO runs into evidence-backed diagnoses and safe, validated test repairs.
98
98
 
99
99
  Usage:
100
100
  npx kwikqa init Create kwikqa.config.json and set up your reporter
@@ -120,6 +120,8 @@ Usage:
120
120
  npx kwikqa logout Sign out and revoke this machine's token
121
121
 
122
122
  Docs: https://kwikqa.com/docs/
123
- Dashboard: https://kwikqa.com/dashboard/`;async function eE(r,t){let[e,...n]=r,i;try{i=Q0({args:[...n],allowPositionals:!0,strict:!0,options:{report:{type:"string"},framework:{type:"string"},local:{type:"boolean",default:!1},yes:{type:"boolean",default:!1},capture:{type:"boolean",default:!1},"no-probe":{type:"boolean",default:!1},"no-changes":{type:"boolean",default:!1},group:{type:"string"},retry:{type:"boolean",default:!1},"propose-only":{type:"boolean",default:!1},annual:{type:"boolean",default:!1},seats:{type:"string"},help:{type:"boolean",short:"h",default:!1}}})}catch(d){return t.io.error(d.message),W.usage}let s=i.values;if(s.help||e===void 0||e==="help"||e==="--help")return t.io.print(Tg),W.ok;if(s.framework!==void 0&&!wr.includes(s.framework))return t.io.error(`--framework must be one of: ${wr.join(", ")}`),W.usage;let a=s.framework,o=s.group===void 0?void 0:Number(s.group);if(o!==void 0&&!(Number.isInteger(o)&&o>=1))return t.io.error("--group takes a failure group's number as analyze printed it: 1, 2, ..."),W.usage;switch(e){case"--version":case"version":return t.io.print(Z0),W.ok;case"init":return vg(t);case"login":return mg(t);case"logout":return yg(t);case"status":return gg(t);case"upgrade":return bg(t,i.positionals[0],{annual:s.annual,...s.seats===void 0?{}:{seats:s.seats}});case"billing":return xg(t);case"analyze":return kg(t,{...s.report===void 0?{}:{report:s.report},...a===void 0?{}:{framework:a},local:s.local,yes:s.yes,capture:s.capture,probe:!s["no-probe"],changes:!s["no-changes"]});case"fix":return Ig(t,{...s.report===void 0?{}:{report:s.report},...a===void 0?{}:{framework:a},retry:s.retry,proposeOnly:s["propose-only"],changes:!s["no-changes"],...o===void 0?{}:{group:o}});case"validate":return Pg(t);default:return t.io.error(`Unknown command: ${e}
123
+ Dashboard: https://kwikqa.com/dashboard/`;function Lg(r){let t=At(r),e=" ".repeat(t.length-10);return oE.split(`
124
+ `).map(n=>n.startsWith(" npx kwikqa ")?n.replace("npx kwikqa",t):/^ +\[/.test(n)?`${e}${n}`:n).join(`
125
+ `)}async function dE(r,t){let[e,...n]=r,i;try{i=sE({args:[...n],allowPositionals:!0,strict:!0,options:{report:{type:"string"},framework:{type:"string"},local:{type:"boolean",default:!1},yes:{type:"boolean",default:!1},capture:{type:"boolean",default:!1},"no-probe":{type:"boolean",default:!1},"no-changes":{type:"boolean",default:!1},group:{type:"string"},retry:{type:"boolean",default:!1},"propose-only":{type:"boolean",default:!1},annual:{type:"boolean",default:!1},seats:{type:"string"},help:{type:"boolean",short:"h",default:!1}}})}catch(d){return t.io.error(d.message),J.usage}let s=i.values;if(s.help||e===void 0||e==="help"||e==="--help")return t.io.print(Lg(t.env)),J.ok;if(s.framework!==void 0&&!xr.includes(s.framework))return t.io.error(`--framework must be one of: ${xr.join(", ")}`),J.usage;let a=s.framework,o=s.group===void 0?void 0:Number(s.group);if(o!==void 0&&!(Number.isInteger(o)&&o>=1))return t.io.error("--group takes a failure group's number as analyze printed it: 1, 2, ..."),J.usage;switch(e){case"--version":case"version":return t.io.print(aE),J.ok;case"init":return Eg(t);case"login":return Ig(t);case"logout":return Pg(t);case"status":return Rg(t);case"upgrade":return Ag(t,i.positionals[0],{annual:s.annual,...s.seats===void 0?{}:{seats:s.seats}});case"billing":return Sg(t);case"analyze":return Cg(t,{...s.report===void 0?{}:{report:s.report},...a===void 0?{}:{framework:a},local:s.local,yes:s.yes,capture:s.capture,probe:!s["no-probe"],changes:!s["no-changes"]});case"fix":return Ng(t,{...s.report===void 0?{}:{report:s.report},...a===void 0?{}:{framework:a},retry:s.retry,proposeOnly:s["propose-only"],changes:!s["no-changes"],...o===void 0?{}:{group:o}});case"validate":return Og(t);default:return t.io.error(`Unknown command: ${e}
124
126
 
125
- ${Tg}`),W.usage}}async function Ag(){let r=await eE(process.argv.slice(2),{cwd:process.cwd(),env:process.env,io:Rg(),fetch});process.exitCode=r}await Ag();
127
+ ${Lg(t.env)}`),J.usage}}async function Mg(){let r=await dE(process.argv.slice(2),{cwd:process.cwd(),env:process.env,io:Dg(),fetch});process.exitCode=r}await Mg();