kwikqa 0.2.2 → 0.2.4

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.
Files changed (3) hide show
  1. package/README.md +65 -3
  2. package/dist/kwikqa.mjs +111 -109
  3. package/package.json +1 -1
package/dist/kwikqa.mjs CHANGED
@@ -1,74 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __kwikqaCreateRequire } from "node:module";const require=__kwikqaCreateRequire(import.meta.url);
3
- var ox=Object.create;var np=Object.defineProperty;var dx=Object.getOwnPropertyDescriptor;var cx=Object.getOwnPropertyNames;var lx=Object.getPrototypeOf,ux=Object.prototype.hasOwnProperty;var px=(n,t)=>()=>{try{return t||n((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}};var fx=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of cx(t))!ux.call(n,s)&&s!==e&&np(n,s,{get:()=>t[s],enumerable:!(r=dx(t,s))||r.enumerable});return n};var ri=(n,t,e)=>(e=n!=null?ox(lx(n)):{},fx(t||!n||!n.__esModule?np(e,"default",{value:n,enumerable:!0}):e,n));var Qr=px(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});function bk(n,t){if(n==null)return{};var e={};for(var r in n)if({}.hasOwnProperty.call(n,r)){if(t.indexOf(r)!==-1)continue;e[r]=n[r]}return e}var yt=class{constructor(t,e,r){this.line=void 0,this.column=void 0,this.index=void 0,this.line=t,this.column=e,this.index=r}},Wn=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 Me(n,t){let{line:e,column:r,index:s}=n;return new yt(e,r+t,s+t)}var xf="BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED",xk={ImportMetaOutsideModule:{message:`import.meta may appear only with 'sourceType: "module"'`,code:xf},ImportOutsideModule:{message:`'import' and 'export' may appear only with 'sourceType: "module"'`,code:xf}},vf={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"},Ti=n=>n.type==="UpdateExpression"?vf.UpdateExpression[`${n.prefix}`]:vf[n.type],vk={AccessorIsGenerator:({kind:n})=>`A ${n}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:n})=>`Missing initializer in ${n} 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:n})=>`\`${n}\` 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:n,exportName:t})=>`A string literal cannot be used as an exported binding without \`from\`.
4
- - Did you mean \`export { '${n}' as '${t}' } from 'some-module'\`?`,ExportDefaultFromAsIdentifier:"'from' is not allowed as an identifier after 'export default'.",ForInOfLoopInitializer:({type:n})=>`'${n==="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:n})=>`Unsyntactic ${n==="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:n})=>`A string literal cannot be used as an imported binding.
5
- - Did you mean \`import { "${n}" 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:n})=>`Expected number in radix ${n}.`,InvalidEscapeSequence:"Bad character escape sequence.",InvalidEscapeSequenceTemplate:"Invalid escape sequence in template.",InvalidEscapedReservedWord:({reservedWord:n})=>`Escape sequence in keyword ${n}.`,InvalidIdentifier:({identifierName:n})=>`Invalid identifier ${n}.`,InvalidLhs:({ancestor:n})=>`Invalid left-hand side in ${Ti(n)}.`,InvalidLhsBinding:({ancestor:n})=>`Binding invalid left-hand side in ${Ti(n)}.`,InvalidLhsOptionalChaining:({ancestor:n})=>`Invalid optional chaining in the left-hand side of ${Ti(n)}.`,InvalidNumber:"Invalid number.",InvalidOrMissingExponent:"Floating-point numbers require a valid exponent after the 'e'.",InvalidOrUnexpectedToken:({unexpected:n})=>`Unexpected character '${n}'.`,InvalidParenthesizedAssignment:"Invalid parenthesized assignment pattern.",InvalidPrivateFieldResolution:({identifierName:n})=>`Private name #${n} 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:n})=>`Label '${n}' 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:n})=>`This experimental syntax requires enabling the parser plugin: ${n.map(t=>JSON.stringify(t)).join(", ")}.`,MissingOneOfPlugins:({missingPlugin:n})=>`This experimental syntax requires enabling one of the following parser plugin(s): ${n.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:n})=>`Duplicate key "${n}" is not allowed in module attributes.`,ModuleExportNameHasLoneSurrogate:({surrogateCharCode:n})=>`An export name cannot include a lone surrogate, found '\\u${n.toString(16)}'.`,ModuleExportUndefined:({localName:n})=>`Export '${n}' 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:n})=>`Private names are only allowed in property accesses (\`obj.#${n}\`) or in \`in\` expressions (\`#${n} in obj\`).`,PrivateNameRedeclaration:({identifierName:n})=>`Duplicate private name #${n}.`,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:n})=>`Unexpected keyword '${n}'.`,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:n})=>`Unexpected reserved word '${n}'.`,UnexpectedSuper:"'super' is only allowed in object methods and classes.",UnexpectedToken:({expected:n,unexpected:t})=>`Unexpected token${t?` '${t}'.`:""}${n?`, expected "${n}"`:""}`,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:n,onlyValidPropertyName:t})=>`The only valid meta property for ${n} is ${n}.${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:n})=>`Identifier '${n}' 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."},kk={StrictDelete:"Deleting local variable in strict mode.",StrictEvalArguments:({referenceName:n})=>`Assigning to '${n}' in strict mode.`,StrictEvalArgumentsBinding:({bindingName:n})=>`Binding '${n}' 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."},Rk={ParseExpressionEmptyInput:"Unexpected parseExpression() input: The input is empty or contains only comments.",ParseExpressionExpectsEOF:({unexpected:n})=>`Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(n)}\`.`},Ik=new Set(["ArrowFunctionExpression","AssignmentExpression","ConditionalExpression","YieldExpression"]),Ak=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:n})=>`Invalid topic token ${n}. In order to use ${n} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${n}" }.`,PipeTopicUnused:"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",PipeUnparenthesizedBody:({type:n})=>`Hack-style pipe body cannot be an unparenthesized ${Ti({type:n})}; 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.'}),Pk={UnsupportedBind:"Binding should be performed on object property.",UnsupportedBindRHS:"The right-hand side of binding can not be super or import."},Sk=["message"];function kf(n,t,e){Object.defineProperty(n,t,{enumerable:!1,configurable:!0,value:e})}function Tk({toMessage:n,code:t,reasonCode:e,syntaxPlugin:r}){let s=e==="MissingPlugin"||e==="MissingOneOfPlugins",i={AccessorCannotDeclareThisParameter:"AccesorCannotDeclareThisParameter",AccessorCannotHaveTypeParameters:"AccesorCannotHaveTypeParameters",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference",SetAccessorCannotHaveOptionalParameter:"SetAccesorCannotHaveOptionalParameter",SetAccessorCannotHaveRestParameter:"SetAccesorCannotHaveRestParameter",SetAccessorCannotHaveReturnType:"SetAccesorCannotHaveReturnType"};return i[e]&&(e=i[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=r,s&&(c.missingPlugin=d.missingPlugin),kf(c,"clone",function(u={}){var p;let{line:f,column:h,index:m}=(p=u.loc)!=null?p:o;return a(new yt(f,h,m),Object.assign({},d,u.details))}),kf(c,"details",d),Object.defineProperty(c,"message",{configurable:!0,get(){let l=`${n(d)} (${o.line}:${o.column})`;return this.message=l,l},set(l){Object.defineProperty(this,"message",{value:l,writable:!0})}}),c}}function st(n,t){if(Array.isArray(n))return r=>st(r,n[0]);let e={};for(let r of Object.keys(n)){let s=n[r],i=typeof s=="string"?{message:()=>s}:typeof s=="function"?{message:s}:s,{message:a}=i,o=bk(i,Sk),d=typeof a=="string"?()=>a:a;e[r]=Tk(Object.assign({code:"BABEL_PARSER_SYNTAX_ERROR",reasonCode:r,toMessage:d},t?{syntaxPlugin:t}:{},o))}return e}var b=Object.assign({},st(xk),st(vk),st(kk),st(Rk),st`pipelineOperator`(Ak),st`functionBind`(Pk));function Ek(){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 Ck(n){let t=Ek();if(n==null)return t;if(n.annexB!=null&&n.annexB!==!1)throw new Error("The `annexB` option can only be set to `false`.");for(let e of Object.keys(t))n[e]!=null&&(t[e]=n[e]);if(t.startLine===1)n.startIndex==null&&t.startColumn>0?t.startIndex=t.startColumn:n.startColumn==null&&t.startIndex>0&&(t.startColumn=t.startIndex);else if((n.startColumn==null||n.startIndex==null)&&n.startIndex!=null)throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");if(t.sourceType==="commonjs"){if(n.allowAwaitOutsideFunction!=null)throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.");if(n.allowReturnOutsideFunction!=null)throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.");if(n.allowNewTargetOutsideFunction!=null)throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.")}return t}var{defineProperty:Nk}=Object,Rf=(n,t)=>{n&&Nk(n,t,{enumerable:!1,value:n[t]})};function Hr(n){return Rf(n.loc.start,"index"),Rf(n.loc.end,"index"),n}var Ok=n=>class extends n{parse(){let e=Hr(super.parse());return this.optionFlags&256&&(e.tokens=e.tokens.map(Hr)),e}parseRegExpLiteral({pattern:e,flags:r}){let s=null;try{s=new RegExp(e,r)}catch{}let i=this.estreeParseLiteral(s);return i.regex={pattern:e,flags:r},i}parseBigIntLiteral(e){let r;try{r=BigInt(e)}catch{r=null}let s=this.estreeParseLiteral(r);return s.bigint=String(s.value||e),s}parseDecimalLiteral(e){let s=this.estreeParseLiteral(null);return s.decimal=String(s.value||e),s}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,r){let s=this.startNodeAtNode(e);return s.expression=e,this.finishNodeAt(s,"ChainExpression",r)}directiveToStmt(e){let r=e.value;delete e.value,this.castNodeTo(r,"Literal"),r.raw=r.extra.raw,r.value=r.extra.expressionValue;let s=this.castNodeTo(e,"ExpressionStatement");return s.expression=r,s.directive=r.extra.rawValue,delete r.extra,s}fillOptionalPropertiesForTSESLint(e){}cloneEstreeStringLiteral(e){let{start:r,end:s,loc:i,range:a,raw:o,value:d}=e,c=Object.create(e.constructor.prototype);return c.type="Literal",c.start=r,c.end=s,c.loc=i,c.range=a,c.raw=o,c.value=d,c}initFunction(e,r){super.initFunction(e,r),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 r;return e.type==="ExpressionStatement"&&e.expression.type==="Literal"&&typeof e.expression.value=="string"&&!((r=e.expression.extra)!=null&&r.parenthesized)}parseBlockBody(e,r,s,i,a){super.parseBlockBody(e,r,s,i,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 r=super.getPrivateNameSV(e);return delete e.id,e.name=r,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,r){let s=super.parseLiteral(e,r);return s.raw=s.extra.raw,delete s.extra,s}parseFunctionBody(e,r,s=!1){super.parseFunctionBody(e,r,s),e.expression=e.body.type!=="BlockStatement"}parseMethod(e,r,s,i,a,o,d=!1){let c=this.startNode();c.kind=e.kind,c=super.parseMethod(c,r,s,i,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 r=super.parseClassProperty(...e);return this.getPluginOption("estree","classFeatures")&&this.castNodeTo(r,"PropertyDefinition"),r}parseClassPrivateProperty(...e){let r=super.parseClassPrivateProperty(...e);return this.getPluginOption("estree","classFeatures")&&(this.castNodeTo(r,"PropertyDefinition"),r.computed=!1),r}parseClassAccessorProperty(e){let r=super.parseClassAccessorProperty(e);return this.getPluginOption("estree","classFeatures")&&(r.abstract&&this.hasPlugin("typescript")?(delete r.abstract,this.castNodeTo(r,"TSAbstractAccessorProperty")):this.castNodeTo(r,"AccessorProperty")),r}parseObjectProperty(e,r,s,i){let a=super.parseObjectProperty(e,r,s,i);return a&&(a.kind="init",this.castNodeTo(a,"Property")),a}finishObjectProperty(e){return e.kind="init",this.finishNode(e,"Property")}isValidLVal(e,r,s,i){return e==="Property"?"value":super.isValidLVal(e,r,s,i)}isAssignable(e,r){return e!=null&&this.isObjectProperty(e)?this.isAssignable(e.value,r):super.isAssignable(e,r)}toAssignable(e,r=!1){if(e!=null&&this.isObjectProperty(e)){let{key:s,value:i}=e;this.isPrivateName(s)&&this.classScope.usePrivateName(this.getPrivateNameSV(s),s.loc.start),this.toAssignable(i,r)}else super.toAssignable(e,r)}toAssignableObjectExpressionProp(e,r,s){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,r,s)}finishCallExpression(e,r){let s=super.finishCallExpression(e,r);if(s.callee.type==="Import"){var i,a;this.castNodeTo(s,"ImportExpression"),s.source=s.arguments[0],s.options=(i=s.arguments[1])!=null?i:null,s.attributes=(a=s.arguments[1])!=null?a:null,delete s.arguments,delete s.callee}else s.type==="OptionalCallExpression"?this.castNodeTo(s,"CallExpression"):s.optional=!1;return s}toReferencedArguments(e){e.type!=="ImportExpression"&&super.toReferencedArguments(e)}parseExport(e,r){let s=this.state.lastTokStartLoc,i=super.parseExport(e,r);switch(i.type){case"ExportAllDeclaration":i.exported=null;break;case"ExportNamedDeclaration":i.specifiers.length===1&&i.specifiers[0].type==="ExportNamespaceSpecifier"&&(this.castNodeTo(i,"ExportAllDeclaration"),i.exported=i.specifiers[0].exported,delete i.specifiers);case"ExportDefaultDeclaration":{var a;let{declaration:o}=i;o?.type==="ClassDeclaration"&&((a=o.decorators)==null?void 0:a.length)>0&&o.start===i.start&&this.resetStartLocation(i,s)}break}return i}stopParseSubscript(e,r){let s=super.stopParseSubscript(e,r);return r.optionalChainMember?this.estreeParseChainExpression(s,e.loc.end):s}parseMember(e,r,s,i,a){let o=super.parseMember(e,r,s,i,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,r){let s=super.castNodeTo(e,r);return this.fillOptionalPropertiesForTSESLint(s),s}cloneIdentifier(e){let r=super.cloneIdentifier(e);return this.fillOptionalPropertiesForTSESLint(r),r}cloneStringLiteral(e){return e.type==="Literal"?this.cloneEstreeStringLiteral(e):super.cloneStringLiteral(e)}finishNodeAt(e,r,s){return Hr(super.finishNodeAt(e,r,s))}finishNode(e,r){let s=super.finishNode(e,r);return this.fillOptionalPropertiesForTSESLint(s),s}resetStartLocation(e,r){super.resetStartLocation(e,r),Hr(e)}resetEndLocation(e,r=this.state.lastTokEndLoc){super.resetEndLocation(e,r),Hr(e)}},un=class{constructor(t,e){this.token=void 0,this.preserveSpace=void 0,this.token=t,this.preserveSpace=!!e}},se={brace:new un("{"),j_oTag:new un("<tag"),j_cTag:new un("</tag"),j_expr:new un("<tag>...</tag>",!0)};se.template=new un("`",!0);var W=!0,O=!0,id=!0,zr=!0,_t=!0,$k=!0,Ni=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}},Od=new Map;function ee(n,t={}){t.keyword=n;let e=H(n,t);return Od.set(n,e),e}function De(n,t){return H(n,{beforeExpr:W,binop:t})}var Kr=-1,At=[],$d=[],Dd=[],Md=[],Ld=[],_d=[];function H(n,t={}){var e,r,s,i;return++Kr,$d.push(n),Dd.push((e=t.binop)!=null?e:-1),Md.push((r=t.beforeExpr)!=null?r:!1),Ld.push((s=t.startsExpr)!=null?s:!1),_d.push((i=t.prefix)!=null?i:!1),At.push(new Ni(n,t)),Kr}function J(n,t={}){var e,r,s,i;return++Kr,Od.set(n,Kr),$d.push(n),Dd.push((e=t.binop)!=null?e:-1),Md.push((r=t.beforeExpr)!=null?r:!1),Ld.push((s=t.startsExpr)!=null?s:!1),_d.push((i=t.prefix)!=null?i:!1),At.push(new Ni("name",t)),Kr}var Dk={bracketL:H("[",{beforeExpr:W,startsExpr:O}),bracketHashL:H("#[",{beforeExpr:W,startsExpr:O}),bracketBarL:H("[|",{beforeExpr:W,startsExpr:O}),bracketR:H("]"),bracketBarR:H("|]"),braceL:H("{",{beforeExpr:W,startsExpr:O}),braceBarL:H("{|",{beforeExpr:W,startsExpr:O}),braceHashL:H("#{",{beforeExpr:W,startsExpr:O}),braceR:H("}"),braceBarR:H("|}"),parenL:H("(",{beforeExpr:W,startsExpr:O}),parenR:H(")"),comma:H(",",{beforeExpr:W}),semi:H(";",{beforeExpr:W}),colon:H(":",{beforeExpr:W}),doubleColon:H("::",{beforeExpr:W}),dot:H("."),question:H("?",{beforeExpr:W}),questionDot:H("?."),arrow:H("=>",{beforeExpr:W}),template:H("template"),ellipsis:H("...",{beforeExpr:W}),backQuote:H("`",{startsExpr:O}),dollarBraceL:H("${",{beforeExpr:W,startsExpr:O}),templateTail:H("...`",{startsExpr:O}),templateNonTail:H("...${",{beforeExpr:W,startsExpr:O}),at:H("@"),hash:H("#",{startsExpr:O}),interpreterDirective:H("#!..."),eq:H("=",{beforeExpr:W,isAssign:zr}),assign:H("_=",{beforeExpr:W,isAssign:zr}),slashAssign:H("_=",{beforeExpr:W,isAssign:zr}),xorAssign:H("_=",{beforeExpr:W,isAssign:zr}),moduloAssign:H("_=",{beforeExpr:W,isAssign:zr}),incDec:H("++/--",{prefix:_t,postfix:$k,startsExpr:O}),bang:H("!",{beforeExpr:W,prefix:_t,startsExpr:O}),tilde:H("~",{beforeExpr:W,prefix:_t,startsExpr:O}),doubleCaret:H("^^",{startsExpr:O}),doubleAt:H("@@",{startsExpr:O}),pipeline:De("|>",0),nullishCoalescing:De("??",1),logicalOR:De("||",1),logicalAND:De("&&",2),bitwiseOR:De("|",3),bitwiseXOR:De("^",4),bitwiseAND:De("&",5),equality:De("==/!=/===/!==",6),lt:De("</>/<=/>=",7),gt:De("</>/<=/>=",7),relational:De("</>/<=/>=",7),bitShift:De("<</>>/>>>",8),bitShiftL:De("<</>>/>>>",8),bitShiftR:De("<</>>/>>>",8),plusMin:H("+/-",{beforeExpr:W,binop:9,prefix:_t,startsExpr:O}),modulo:H("%",{binop:10,startsExpr:O}),star:H("*",{binop:10}),slash:De("/",10),exponent:H("**",{beforeExpr:W,binop:11,rightAssociative:!0}),_in:ee("in",{beforeExpr:W,binop:7}),_instanceof:ee("instanceof",{beforeExpr:W,binop:7}),_break:ee("break"),_case:ee("case",{beforeExpr:W}),_catch:ee("catch"),_continue:ee("continue"),_debugger:ee("debugger"),_default:ee("default",{beforeExpr:W}),_else:ee("else",{beforeExpr:W}),_finally:ee("finally"),_function:ee("function",{startsExpr:O}),_if:ee("if"),_return:ee("return",{beforeExpr:W}),_switch:ee("switch"),_throw:ee("throw",{beforeExpr:W,prefix:_t,startsExpr:O}),_try:ee("try"),_var:ee("var"),_const:ee("const"),_with:ee("with"),_new:ee("new",{beforeExpr:W,startsExpr:O}),_this:ee("this",{startsExpr:O}),_super:ee("super",{startsExpr:O}),_class:ee("class",{startsExpr:O}),_extends:ee("extends",{beforeExpr:W}),_export:ee("export"),_import:ee("import",{startsExpr:O}),_null:ee("null",{startsExpr:O}),_true:ee("true",{startsExpr:O}),_false:ee("false",{startsExpr:O}),_typeof:ee("typeof",{beforeExpr:W,prefix:_t,startsExpr:O}),_void:ee("void",{beforeExpr:W,prefix:_t,startsExpr:O}),_delete:ee("delete",{beforeExpr:W,prefix:_t,startsExpr:O}),_do:ee("do",{isLoop:id,beforeExpr:W}),_for:ee("for",{isLoop:id}),_while:ee("while",{isLoop:id}),_as:J("as",{startsExpr:O}),_assert:J("assert",{startsExpr:O}),_async:J("async",{startsExpr:O}),_await:J("await",{startsExpr:O}),_defer:J("defer",{startsExpr:O}),_from:J("from",{startsExpr:O}),_get:J("get",{startsExpr:O}),_let:J("let",{startsExpr:O}),_meta:J("meta",{startsExpr:O}),_of:J("of",{startsExpr:O}),_sent:J("sent",{startsExpr:O}),_set:J("set",{startsExpr:O}),_source:J("source",{startsExpr:O}),_static:J("static",{startsExpr:O}),_using:J("using",{startsExpr:O}),_yield:J("yield",{startsExpr:O}),_asserts:J("asserts",{startsExpr:O}),_checks:J("checks",{startsExpr:O}),_exports:J("exports",{startsExpr:O}),_global:J("global",{startsExpr:O}),_implements:J("implements",{startsExpr:O}),_intrinsic:J("intrinsic",{startsExpr:O}),_infer:J("infer",{startsExpr:O}),_is:J("is",{startsExpr:O}),_mixins:J("mixins",{startsExpr:O}),_proto:J("proto",{startsExpr:O}),_require:J("require",{startsExpr:O}),_satisfies:J("satisfies",{startsExpr:O}),_keyof:J("keyof",{startsExpr:O}),_readonly:J("readonly",{startsExpr:O}),_unique:J("unique",{startsExpr:O}),_abstract:J("abstract",{startsExpr:O}),_declare:J("declare",{startsExpr:O}),_enum:J("enum",{startsExpr:O}),_module:J("module",{startsExpr:O}),_namespace:J("namespace",{startsExpr:O}),_interface:J("interface",{startsExpr:O}),_type:J("type",{startsExpr:O}),_opaque:J("opaque",{startsExpr:O}),name:H("name",{startsExpr:O}),placeholder:H("%%",{startsExpr:O}),string:H("string",{startsExpr:O}),num:H("num",{startsExpr:O}),bigint:H("bigint",{startsExpr:O}),decimal:H("decimal",{startsExpr:O}),regexp:H("regexp",{startsExpr:O}),privateName:H("#name",{startsExpr:O}),eof:H("eof"),jsxName:H("jsxName"),jsxText:H("jsxText",{beforeExpr:W}),jsxTagStart:H("jsxTagStart",{startsExpr:O}),jsxTagEnd:H("jsxTagEnd")};function ie(n){return n>=93&&n<=133}function Mk(n){return n<=92}function it(n){return n>=58&&n<=133}function Mf(n){return n>=58&&n<=137}function Lk(n){return Md[n]}function qr(n){return Ld[n]}function _k(n){return n>=29&&n<=33}function If(n){return n>=129&&n<=131}function jk(n){return n>=90&&n<=92}function jd(n){return n>=58&&n<=92}function Fk(n){return n>=39&&n<=59}function Bk(n){return n===34}function Vk(n){return _d[n]}function Hk(n){return n>=121&&n<=123}function zk(n){return n>=124&&n<=130}function Ft(n){return $d[n]}function Ei(n){return Dd[n]}function Uk(n){return n===57}function Oi(n){return n>=24&&n<=25}function It(n){return At[n]}At[8].updateContext=n=>{n.pop()};At[5].updateContext=At[7].updateContext=At[23].updateContext=n=>{n.push(se.brace)};At[22].updateContext=n=>{n[n.length-1]===se.template?n.pop():n.push(se.template)};At[143].updateContext=n=>{n.push(se.j_expr,se.j_oTag)};var Fd="\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",Lf="\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",qk=new RegExp("["+Fd+"]"),Gk=new RegExp("["+Fd+Lf+"]");Fd=Lf=null;var _f=[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],Kk=[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 ud(n,t){let e=65536;for(let r=0,s=t.length;r<s;r+=2){if(e+=t[r],e>n)return!1;if(e+=t[r+1],e>=n)return!0}return!1}function mt(n){return n<65?n===36:n<=90?!0:n<97?n===95:n<=122?!0:n<=65535?n>=170&&qk.test(String.fromCharCode(n)):ud(n,_f)}function pn(n){return n<48?n===36:n<58?!0:n<65?!1:n<=90?!0:n<97?n===95:n<=122?!0:n<=65535?n>=170&&Gk.test(String.fromCharCode(n)):ud(n,_f)||ud(n,Kk)}var Bd={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"]},Wk=new Set(Bd.keyword),Jk=new Set(Bd.strict),Xk=new Set(Bd.strictBind);function jf(n,t){return t&&n==="await"||n==="enum"}function Ff(n,t){return jf(n,t)||Jk.has(n)}function Bf(n){return Xk.has(n)}function Vf(n,t){return Ff(n,t)||Bf(n)}function Yk(n){return Wk.has(n)}function Qk(n,t,e){return n===64&&t===64&&mt(e)}var Zk=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 eR(n){return Zk.has(n)}var Wr=class{constructor(t){this.flags=0,this.names=new Map,this.firstLexicalName="",this.flags=t}},Jr=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 Wr(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,r){let s=this.currentScope();if(e&8||e&16){this.checkRedeclarationInScope(s,t,e,r);let i=s.names.get(t)||0;e&16?i=i|4:(s.firstLexicalName||(s.firstLexicalName=t),i=i|2),s.names.set(t,i),e&8&&this.maybeExportDefined(s,t)}else if(e&4)for(let i=this.scopeStack.length-1;i>=0&&(s=this.scopeStack[i],this.checkRedeclarationInScope(s,t,e,r),s.names.set(t,(s.names.get(t)||0)|1),this.maybeExportDefined(s,t),!(s.flags&1667));--i);this.parser.inModule&&s.flags&1&&this.undefinedExports.delete(t)}maybeExportDefined(t,e){this.parser.inModule&&t.flags&1&&this.undefinedExports.delete(e)}checkRedeclarationInScope(t,e,r,s){this.isRedeclaredInScope(t,e,r)&&this.parser.raise(b.VarRedeclaration,s,{identifierName:e})}isRedeclaredInScope(t,e,r){if(!(r&1))return!1;if(r&8)return t.names.has(e);let s=t.names.get(e)||0;return r&16?(s&2)>0||!this.treatFunctionsAsVarInScope(t)&&(s&1)>0:(s&2)>0&&!(t.flags&8&&t.firstLexicalName===e)||!this.treatFunctionsAsVarInScope(t)&&(s&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}}},pd=class extends Wr{constructor(...t){super(...t),this.declareFunctions=new Set}},fd=class extends Jr{createScope(t){return new pd(t)}declareName(t,e,r){let s=this.currentScope();if(e&2048){this.checkRedeclarationInScope(s,t,e,r),this.maybeExportDefined(s,t),s.declareFunctions.add(t);return}super.declareName(t,e,r)}isRedeclaredInScope(t,e,r){if(super.isRedeclaredInScope(t,e,r))return!0;if(r&2048&&!t.declareFunctions.has(e)){let s=t.names.get(e);return(s&4)>0||(s&2)>0}return!1}checkLocalExport(t){this.scopeStack[0].declareFunctions.has(t.name)||super.checkLocalExport(t)}},tR=new Set(["_","any","bool","boolean","empty","extends","false","interface","mixed","null","number","static","string","true","typeof","void"]),z=st`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:n})=>`Cannot overwrite reserved type ${n}.`,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:n,enumName:t})=>`Boolean enum members need to be initialized. Use either \`${n} = true,\` or \`${n} = false,\` in enum \`${t}\`.`,EnumDuplicateMemberName:({memberName:n,enumName:t})=>`Enum member names need to be unique, but the name \`${n}\` has already been used before in enum \`${t}\`.`,EnumInconsistentMemberValues:({enumName:n})=>`Enum \`${n}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,EnumInvalidExplicitType:({invalidEnumType:n,enumName:t})=>`Enum type \`${n}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${t}\`.`,EnumInvalidExplicitTypeUnknownSupplied:({enumName:n})=>`Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${n}\`.`,EnumInvalidMemberInitializerPrimaryType:({enumName:n,memberName:t,explicitType:e})=>`Enum \`${n}\` has type \`${e}\`, so the initializer of \`${t}\` needs to be a ${e} literal.`,EnumInvalidMemberInitializerSymbolType:({enumName:n,memberName:t})=>`Symbol enum members cannot be initialized. Use \`${t},\` in enum \`${n}\`.`,EnumInvalidMemberInitializerUnknownType:({enumName:n,memberName:t})=>`The enum member initializer for \`${t}\` needs to be a literal (either a boolean, number, or string) in enum \`${n}\`.`,EnumInvalidMemberName:({enumName:n,memberName:t,suggestion:e})=>`Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${t}\`, consider using \`${e}\`, in enum \`${n}\`.`,EnumNumberMemberNotInitialized:({enumName:n,memberName:t})=>`Number enum members need to be initialized, e.g. \`${t} = 1\` in enum \`${n}\`.`,EnumStringMemberInconsistentlyInitialized:({enumName:n})=>`String enum members need to consistently either all use initializers, or use no initializers, in enum \`${n}\`.`,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:n})=>`Unexpected reserved type ${n}.`,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:n,suggestion:t})=>`\`declare export ${n}\` is not supported. Use \`${t}\` instead.`,UnsupportedStatementInDeclareModule:"Only declares and type imports are allowed inside declare module.",UnterminatedFlowComment:"Unterminated flow-comment."});function nR(n){return n.type==="DeclareExportAllDeclaration"||n.type==="DeclareExportDeclaration"&&(!n.declaration||n.declaration.type!=="TypeAlias"&&n.declaration.type!=="InterfaceDeclaration")}function Af(n){return n.importKind==="type"||n.importKind==="typeof"}var rR={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"};function sR(n,t){let e=[],r=[];for(let s=0;s<n.length;s++)(t(n[s],s,n)?e:r).push(n[s]);return[e,r]}var iR=/\*?\s*@((?:no)?flow)\b/,aR=n=>class extends n{constructor(...e){super(...e),this.flowPragma=void 0}getScopeHandler(){return fd}shouldParseTypes(){return this.getPluginOption("flow","all")||this.flowPragma==="flow"}finishToken(e,r){e!==134&&e!==13&&e!==28&&this.flowPragma===void 0&&(this.flowPragma=null),super.finishToken(e,r)}addComment(e){if(this.flowPragma===void 0){let r=iR.exec(e.value);if(r)if(r[1]==="flow")this.flowPragma="flow";else if(r[1]==="noflow")this.flowPragma="noflow";else throw new Error("Unexpected flow pragma")}super.addComment(e)}flowParseTypeInitialiser(e){let r=this.state.inType;this.state.inType=!0,this.expect(e||14);let s=this.flowParseType();return this.state.inType=r,s}flowParsePredicate(){let e=this.startNode(),r=this.state.startLoc;return this.next(),this.expectContextual(110),this.state.lastTokStartLoc.index>r.index+1&&this.raise(z.UnexpectedSpaceBetweenModuloChecks,r),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 r=null,s=null;return this.match(54)?(this.state.inType=e,s=this.flowParsePredicate()):(r=this.flowParseType(),this.state.inType=e,this.match(54)&&(s=this.flowParsePredicate())),[r,s]}flowParseDeclareClass(e){return this.next(),this.flowParseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")}flowParseDeclareFunction(e){this.next();let r=e.id=this.parseIdentifier(),s=this.startNode(),i=this.startNode();this.match(47)?s.typeParameters=this.flowParseTypeParameterDeclaration():s.typeParameters=null,this.expect(10);let a=this.flowParseFunctionTypeParams();return s.params=a.params,s.rest=a.rest,s.this=a._this,this.expect(11),[s.returnType,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),i.typeAnnotation=this.finishNode(s,"FunctionTypeAnnotation"),r.typeAnnotation=this.finishNode(i,"TypeAnnotation"),this.resetEndLocation(r),this.semicolon(),this.scope.declareName(e.id.name,2048,e.id.loc.start),this.finishNode(e,"DeclareFunction")}flowParseDeclare(e,r){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):(r&&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,r);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 r=e.body=this.startNode(),s=r.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),s.push(super.parseImport(o))):(this.expectContextual(125,z.UnsupportedStatementInDeclareModule),s.push(this.flowParseDeclare(o,!0)))}this.scope.exit(),this.expect(8),this.finishNode(r,"BlockStatement");let i=null,a=!1;return s.forEach(o=>{nR(o)?(i==="CommonJS"&&this.raise(z.AmbiguousDeclareModuleKind,o),i="ES"):o.type==="DeclareModuleExports"&&(a&&this.raise(z.DuplicateDeclareModuleExports,o),i==="ES"&&this.raise(z.AmbiguousDeclareModuleKind,o),i="CommonJS",a=!0)}),e.kind=i||"CommonJS",this.finishNode(e,"DeclareModule")}flowParseDeclareExportDeclaration(e,r){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))&&!r){let s=this.state.value;throw this.raise(z.UnsupportedDeclareExportKind,this.state.startLoc,{unsupportedExportKind:s,suggestion:rR[s]})}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 r=this.flowParseTypeAlias(e);return this.castNodeTo(r,"DeclareTypeAlias"),r}flowParseDeclareOpaqueType(e){this.next();let r=this.flowParseOpaqueType(e,!0);return this.castNodeTo(r,"DeclareOpaqueType"),r}flowParseDeclareInterface(e){return this.next(),this.flowParseInterfaceish(e,!1),this.finishNode(e,"DeclareInterface")}flowParseInterfaceish(e,r){if(e.id=this.flowParseRestrictedIdentifier(!r,!0),this.scope.declareName(e.id.name,r?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(!r&&this.eat(12));if(r){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:r,allowExact:!1,allowSpread:!1,allowProto:r,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,r,s){tR.has(e)&&this.raise(s?z.AssignReservedType:z.UnexpectedReservedType,r,{reservedType:e})}flowParseRestrictedIdentifierName(e,r){return this.checkReservedType(this.state.value,this.state.startLoc,r),this.parseIdentifierName(e)}flowParseRestrictedIdentifier(e,r){let s=this.startNode(),i=this.flowParseRestrictedIdentifierName(e,r);return this.createIdentifier(s,i)}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,r){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,r||(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 r=this.state.startLoc,s=this.startNode(),i=this.flowParseVariance();return s.name=this.flowParseRestrictedIdentifierName(),s.variance=i,s.bound=this.flowParseTypeParameterBound(),this.match(29)?(this.eat(29),s.default=this.flowParseType()):e&&this.raise(z.MissingTypeParamDefault,r),this.finishNode(s,"TypeParameter")}flowParseTypeParameterDeclaration(){let e=this.state.inType,r=this.startNode();r.params=[],this.state.inType=!0,this.match(47)||this.match(143)?this.next():this.unexpected();let s=!1;do{let i=this.flowParseTypeParameter(s);r.params.push(i),i.default&&(s=!0),this.match(48)||this.expect(12)}while(!this.match(48));return this.expect(48),this.state.inType=e,this.finishNode(r,"TypeParameterDeclaration")}flowInTopLevelContext(e){if(this.curContext()!==se.brace){let r=this.state.context;this.state.context=[r[0]];try{return e()}finally{this.state.context=r}}else return e()}flowParseTypeParameterInstantiationInExpression(){if(this.reScan_lt()===47)return this.flowParseTypeParameterInstantiation()}flowParseTypeParameterInstantiation(){let e=this.startNode(),r=this.state.inType;return this.state.inType=!0,e.params=[],this.flowInTopLevelContext(()=>{this.expect(47);let s=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=s}),this.state.inType=r,!this.state.inType&&this.curContext()===se.brace&&this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TypeParameterInstantiation")}flowParseTypeParameterInstantiationCallOrNew(){if(this.reScan_lt()!==47)return null;let e=this.startNode(),r=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=r,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,r,s){return e.static=r,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=s,this.finishNode(e,"ObjectTypeIndexer")}flowParseObjectTypeInternalSlot(e,r){return e.static=r,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,r){let s=this.startNode();return e.static=r,e.value=this.flowParseObjectTypeMethodish(s),this.finishNode(e,"ObjectTypeCallProperty")}flowParseObjectType({allowStatic:e,allowExact:r,allowSpread:s,allowProto:i,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(r&&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,m=null,g=this.startNode();if(i&&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(g,f))):d.indexers.push(this.flowParseObjectTypeIndexer(g,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(g,f));else{let w="init";if(this.isContextual(99)||this.isContextual(104)){let x=this.lookahead();Mf(x.type)&&(w=this.state.value,this.next())}let v=this.flowParseObjectTypeProperty(g,f,h,y,w,s,a??!l);v===null?(u=!0,m=this.state.lastTokStartLoc):d.properties.push(v)}this.flowObjectTypeSemicolon(),m&&!this.match(8)&&!this.match(9)&&this.raise(z.UnexpectedExplicitInexactInObject,m)}this.expect(c),s&&(d.inexact=u);let p=this.finishNode(d,"ObjectTypeAnnotation");return this.state.inType=o,p}flowParseObjectTypeProperty(e,r,s,i,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),i&&this.raise(z.InexactVariance,i),null):(o||this.raise(z.UnexpectedSpreadType,this.state.lastTokStartLoc),s!=null&&this.unexpected(s),i&&this.raise(z.SpreadVariance,i),e.argument=this.flowParseType(),this.finishNode(e,"ObjectTypeSpreadProperty"));{e.key=this.flowParseObjectPropertyKey(),e.static=r,e.proto=s!=null,e.kind=a;let c=!1;return this.match(47)||this.match(10)?(e.method=!0,s!=null&&this.unexpected(s),i&&this.unexpected(i.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=i),e.optional=c,this.finishNode(e,"ObjectTypeProperty")}}flowCheckGetterSetterParams(e){let r=e.kind==="get"?0:1,s=e.value.params.length+(e.value.rest?1:0);e.value.this&&this.raise(e.kind==="get"?z.GetterMayNotHaveThisParam:z.SetterMayNotHaveThisParam,e.value.this),s!==r&&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,r){e??(e=this.state.startLoc);let s=r||this.flowParseRestrictedIdentifier(!0);for(;this.eat(16);){let i=this.startNodeAt(e);i.qualification=s,i.id=this.flowParseRestrictedIdentifier(!0),s=this.finishNode(i,"QualifiedTypeIdentifier")}return s}flowParseGenericType(e,r){let s=this.startNodeAt(e);return s.typeParameters=null,s.id=this.flowParseQualifiedTypeIdentifier(e,r),this.match(47)&&(s.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(s,"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 r=null,s=!1,i=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),r=this.parseIdentifier(d),this.eat(17)&&(s=!0,d&&this.raise(z.ThisParamMayNotBeOptional,a)),i=this.flowParseTypeInitialiser()):i=this.flowParseType(),a.name=r,a.optional=s,a.typeAnnotation=i,this.finishNode(a,"FunctionTypeParam")}reinterpretTypeAsFunctionTypeParam(e){let r=this.startNodeAt(e.loc.start);return r.name=null,r.optional=!1,r.typeAnnotation=e,this.finishNode(r,"FunctionTypeParam")}flowParseFunctionTypeParams(e=[]){let r=null,s=null;for(this.match(78)&&(s=this.flowParseFunctionTypeParam(!0),s.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)&&(r=this.flowParseFunctionTypeParam(!1)),{params:e,rest:r,_this:s}}flowIdentToTypeAnnotation(e,r,s){switch(s.name){case"any":return this.finishNode(r,"AnyTypeAnnotation");case"bool":case"boolean":return this.finishNode(r,"BooleanTypeAnnotation");case"mixed":return this.finishNode(r,"MixedTypeAnnotation");case"empty":return this.finishNode(r,"EmptyTypeAnnotation");case"number":return this.finishNode(r,"NumberTypeAnnotation");case"string":return this.finishNode(r,"StringTypeAnnotation");case"symbol":return this.finishNode(r,"SymbolTypeAnnotation");default:return this.checkNotUnderscore(s.name),this.flowParseGenericType(e,s)}}flowParsePrimaryType(){let e=this.state.startLoc,r=this.startNode(),s,i,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,i=this.flowParseTupleType(),this.state.noAnonFunctionType=o,i;case 47:{let d=this.startNode();return d.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(10),s=this.flowParseFunctionTypeParams(),d.params=s.params,d.rest=s.rest,d.this=s._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(ie(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,i=this.flowParseType(),this.state.noAnonFunctionType=o,this.state.noAnonFunctionType||!(this.match(12)||this.match(11)&&this.lookahead().type===19))return this.expect(11),i;this.eat(12)}return i?s=this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(i)]):s=this.flowParseFunctionTypeParams(),d.params=s.params,d.rest=s.rest,d.this=s._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 r.value=this.match(85),this.next(),this.finishNode(r,"BooleanLiteralTypeAnnotation");case 53:if(this.state.value==="-"){if(this.next(),this.match(135))return this.parseLiteralAtNode(-this.state.value,"NumberLiteralTypeAnnotation",r);if(this.match(136))return this.parseLiteralAtNode(-this.state.value,"BigIntLiteralTypeAnnotation",r);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(r,"VoidTypeAnnotation");case 84:return this.next(),this.finishNode(r,"NullLiteralTypeAnnotation");case 78:return this.next(),this.finishNode(r,"ThisTypeAnnotation");case 55:return this.next(),this.finishNode(r,"ExistsTypeAnnotation");case 87:return this.flowParseTypeofType();default:if(jd(this.state.type)){let d=Ft(this.state.type);return this.next(),super.createIdentifier(r,d)}else if(ie(this.state.type))return this.isContextual(129)?this.flowParseInterfaceType():this.flowIdentToTypeAnnotation(e,r,this.parseIdentifier())}throw this.unexpected()}flowParsePostfixType(){let e=this.state.startLoc,r=this.flowParsePrimaryType(),s=!1;for(;(this.match(0)||this.match(18))&&!this.canInsertSemicolon();){let i=this.startNodeAt(e),a=this.eat(18);s=s||a,this.expect(0),!a&&this.match(3)?(i.elementType=r,this.next(),r=this.finishNode(i,"ArrayTypeAnnotation")):(i.objectType=r,i.indexType=this.flowParseType(),this.expect(3),s?(i.optional=a,r=this.finishNode(i,"OptionalIndexedAccessType")):r=this.finishNode(i,"IndexedAccessType"))}return r}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 r=this.startNodeAt(e.loc.start);return r.params=[this.reinterpretTypeAsFunctionTypeParam(e)],r.rest=null,r.this=null,r.returnType=this.flowParseType(),r.typeParameters=null,this.finishNode(r,"FunctionTypeAnnotation")}return e}flowParseIntersectionType(){let e=this.startNode();this.eat(45);let r=this.flowParseAnonFunctionWithoutParens();for(e.types=[r];this.eat(45);)e.types.push(this.flowParseAnonFunctionWithoutParens());return e.types.length===1?r:this.finishNode(e,"IntersectionTypeAnnotation")}flowParseUnionType(){let e=this.startNode();this.eat(43);let r=this.flowParseIntersectionType();for(e.types=[r];this.eat(43);)e.types.push(this.flowParseIntersectionType());return e.types.length===1?r:this.finishNode(e,"UnionTypeAnnotation")}flowParseType(){let e=this.state.inType;this.state.inType=!0;let r=this.flowParseUnionType();return this.state.inType=e,r}flowParseTypeOrImplicitInstantiation(){if(this.state.type===132&&this.state.value==="_"){let e=this.state.startLoc,r=this.parseIdentifier();return this.flowParseGenericType(e,r)}else return this.flowParseType()}flowParseTypeAnnotation(){let e=this.startNode();return e.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(e,"TypeAnnotation")}flowParseTypeAnnotatableIdentifier(){let e=this.startNode(),r=this.parseIdentifierName();return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),this.createIdentifier(e,r)}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,r,s=!1){if(r){this.forwardNoArrowParamsConversionAt(e,()=>super.parseFunctionBody(e,!0,s));return}super.parseFunctionBody(e,!1,s)}parseFunctionBodyAndFinish(e,r,s=!1){if(this.match(14)){let i=this.startNode();[i.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),e.returnType=i.typeAnnotation?this.finishNode(i,"TypeAnnotation"):null}return super.parseFunctionBodyAndFinish(e,r,s)}parseStatementLike(e){if(this.state.strict&&this.isContextual(129)){let s=this.lookahead();if(it(s.type)){let i=this.startNode();return this.next(),this.flowParseInterface(i)}}else if(this.isContextual(126)){let s=this.startNode();return this.next(),this.flowParseEnumDeclaration(s)}let r=super.parseStatementLike(e);return this.flowPragma===void 0&&!this.isValidDirective(r)&&(this.flowPragma=null),r}parseExpressionStatement(e,r,s){if(r.type==="Identifier"){if(r.name==="declare"){if(this.match(80)||ie(this.state.type)||this.match(68)||this.match(74)||this.match(82))return this.flowParseDeclare(e)}else if(ie(this.state.type)){if(r.name==="interface")return this.flowParseInterface(e);if(r.name==="type")return this.flowParseTypeAlias(e);if(r.name==="opaque")return this.flowParseOpaqueType(e,!1)}}return super.parseExpressionStatement(e,r,s)}shouldParseExportDeclaration(){let{type:e}=this.state;return e===126||If(e)?!this.state.containsEsc:super.shouldParseExportDeclaration()}isExportDefaultSpecifier(){let{type:e}=this.state;return e===126||If(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,r,s){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(s),e}this.expect(17);let i=this.state.clone(),a=this.state.noArrowAt,o=this.startNodeAt(r),{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=i,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,i.startLoc),c&&l.length===1&&(this.state=i,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(),r=!this.match(14);return this.state.noArrowParamsConversionAt.pop(),{consequent:e,failed:r}}getArrowLikeExpressions(e,r){let s=[e],i=[];for(;s.length!==0;){let a=s.pop();a.type==="ArrowFunctionExpression"?(a.typeParameters||!a.returnType?this.finishArrowValidation(a):i.push(a),a.body.type!=="BlockStatement"&&s.push(a.body)):a.type==="ConditionalExpression"&&(s.push(a.consequent),s.push(a.alternate))}return r?(i.forEach(a=>this.finishArrowValidation(a)),[i,[]]):sR(i,a=>a.params.every(o=>this.isAssignable(o,!0)))}finishArrowValidation(e){var r;this.toAssignableList(e.params,(r=e.extra)==null?void 0:r.trailingCommaLoc,!1),this.scope.enter(518),super.checkParams(e,!1,!0),this.scope.exit()}forwardNoArrowParamsConversionAt(e,r){let s;return this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))?(this.state.noArrowParamsConversionAt.push(this.state.start),s=r(),this.state.noArrowParamsConversionAt.pop()):s=r(),s}parseParenItem(e,r){let s=super.parseParenItem(e,r);if(this.eat(17)&&(s.optional=!0,this.resetEndLocation(e)),this.match(14)){let i=this.startNodeAt(r);return i.expression=s,i.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(i,"TypeCastExpression")}return s}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 r=this.startNode();return this.next(),this.match(5)?(e.specifiers=this.parseExportSpecifiers(!0),super.parseExportFrom(e),null):this.flowParseTypeAlias(r)}else if(this.isContextual(131)){e.exportKind="type";let r=this.startNode();return this.next(),this.flowParseOpaqueType(r,!1)}else if(this.isContextual(129)){e.exportKind="type";let r=this.startNode();return this.next(),this.flowParseInterface(r)}else if(this.isContextual(126)){e.exportKind="value";let r=this.startNode();return this.next(),this.flowParseEnumDeclaration(r)}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:r}=this.state,s=super.maybeParseExportNamespaceSpecifier(e);return s&&e.exportKind==="type"&&this.unexpected(r),s}parseClassId(e,r,s){super.parseClassId(e,r,s),this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration())}parseClassMember(e,r,s){let{startLoc:i}=this.state;if(this.isContextual(125)){if(super.parseClassMemberFromModifier(e,r))return;r.declare=!0}super.parseClassMember(e,r,s),r.declare&&(r.type!=="ClassProperty"&&r.type!=="ClassPrivateProperty"&&r.type!=="PropertyDefinition"?this.raise(z.DeclareClassElement,i):r.value&&this.raise(z.DeclareClassFieldInitializer,r.value))}isIterator(e){return e==="iterator"||e==="asyncIterator"}readIterator(){let e=super.readWord1(),r="@@"+e;(!this.isIterator(e)||!this.state.inType)&&this.raise(b.InvalidIdentifier,this.state.curPosition(),{identifierName:r}),this.finishToken(132,r)}getTokenFromCode(e){let r=this.input.charCodeAt(this.state.pos+1);e===123&&r===124?this.finishOp(6,2):this.state.inType&&(e===62||e===60)?this.finishOp(e===62?48:47,1):this.state.inType&&e===63?r===46?this.finishOp(18,2):this.finishOp(17,1):Qk(e,r,this.input.charCodeAt(this.state.pos+2))?(this.state.pos+=2,this.readIterator()):super.getTokenFromCode(e)}isAssignable(e,r){return e.type==="TypeCastExpression"?this.isAssignable(e.expression,r):super.isAssignable(e,r)}toAssignable(e,r=!1){!r&&e.type==="AssignmentExpression"&&e.left.type==="TypeCastExpression"&&(e.left=this.typeCastToParameter(e.left)),super.toAssignable(e,r)}toAssignableList(e,r,s){for(let i=0;i<e.length;i++){let a=e[i];a?.type==="TypeCastExpression"&&(e[i]=this.typeCastToParameter(a))}super.toAssignableList(e,r,s)}toReferencedList(e,r){for(let i=0;i<e.length;i++){var s;let a=e[i];a&&a.type==="TypeCastExpression"&&!((s=a.extra)!=null&&s.parenthesized)&&(e.length>1||!r)&&this.raise(z.TypeCastInPattern,a.typeAnnotation)}return e}parseArrayLike(e,r,s){let i=super.parseArrayLike(e,r,s);return s!=null&&!this.state.maybeInArrowParameters&&this.toReferencedList(i.elements),i}isValidLVal(e,r,s,i){return e==="TypeCastExpression"||super.isValidLVal(e,r,s,i)}parseClassProperty(e){return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassProperty(e)}parseClassPrivateProperty(e){return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassPrivateProperty(e)}isClassMethod(){return this.match(47)||super.isClassMethod()}isClassProperty(){return this.match(14)||super.isClassProperty()}isNonstaticConstructor(e){return!this.match(14)&&super.isNonstaticConstructor(e)}pushClassMethod(e,r,s,i,a,o){if(r.variance&&this.unexpected(r.variance.loc.start),delete r.variance,this.match(47)&&(r.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassMethod(e,r,s,i,a,o),r.params&&a){let d=r.params;d.length>0&&this.isThisParam(d[0])&&this.raise(z.ThisParamBannedInConstructor,r)}else if(r.type==="MethodDefinition"&&a&&r.value.params){let d=r.value.params;d.length>0&&this.isThisParam(d[0])&&this.raise(z.ThisParamBannedInConstructor,r)}}pushClassPrivateMethod(e,r,s,i){r.variance&&this.unexpected(r.variance.loc.start),delete r.variance,this.match(47)&&(r.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassPrivateMethod(e,r,s,i)}parseClassSuper(e){if(super.parseClassSuper(e),e.superClass&&(this.match(47)||this.match(51))&&(e.superTypeParameters=this.flowParseTypeParameterInstantiationInExpression()),this.isContextual(113)){this.next();let r=e.implements=[];do{let s=this.startNode();s.id=this.flowParseRestrictedIdentifier(!0),this.match(47)?s.typeParameters=this.flowParseTypeParameterInstantiation():s.typeParameters=null,r.push(this.finishNode(s,"ClassImplements"))}while(this.eat(12))}}checkGetterSetterParams(e){super.checkGetterSetterParams(e);let r=this.getObjectOrClassMethodParams(e);if(r.length>0){let s=r[0];this.isThisParam(s)&&e.kind==="get"?this.raise(z.GetterMayNotHaveThisParam,s):this.isThisParam(s)&&this.raise(z.SetterMayNotHaveThisParam,s)}}parsePropertyNamePrefixOperator(e){e.variance=this.flowParseVariance()}parseObjPropValue(e,r,s,i,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,r,s,i,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,r){let s=super.parseMaybeDefault(e,r);return s.type==="AssignmentPattern"&&s.typeAnnotation&&s.right.start<s.typeAnnotation.start&&this.raise(z.TypeBeforeInitializer,s.typeAnnotation),s}checkImportReflection(e){super.checkImportReflection(e),e.module&&e.importKind!=="value"&&this.raise(z.ImportReflectionHasImportType,e.specifiers[0].loc.start)}parseImportSpecifierLocal(e,r,s){r.local=Af(e)?this.flowParseRestrictedIdentifier(!0,!0):this.parseIdentifier(),e.specifiers.push(this.finishImportSpecifier(r,s))}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return!0;if(this.isContextual(130)){if(!e)return!0;let r=this.lookaheadCharCode();return r===123||r===42}return!e&&this.isContextual(87)}applyImportPhase(e,r,s,i){if(super.applyImportPhase(e,r,s,i),r){if(!s&&this.match(65))return;e.exportKind=s==="type"?s:"value"}else s==="type"&&this.match(55)&&this.unexpected(),e.importKind=s==="type"||s==="typeof"?s:"value"}parseImportSpecifier(e,r,s,i,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&&!it(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&&it(this.state.type))e.imported=this.parseIdentifier(!0),e.importKind=d;else{if(r)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=Af(e);return s&&l&&this.raise(z.ImportTypeShorthandOnlyInPureImport,e),(s||l)&&this.checkReservedType(e.local.name,e.local.loc.start,!0),c&&!s&&!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,r){let s=e.kind;s!=="get"&&s!=="set"&&this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),super.parseFunctionParams(e,r)}parseVarId(e,r){super.parseVarId(e,r),this.match(14)&&(e.id.typeAnnotation=this.flowParseTypeAnnotation(),this.resetEndLocation(e.id))}parseAsyncArrowFromCallExpression(e,r){if(this.match(14)){let s=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0,e.returnType=this.flowParseTypeAnnotation(),this.state.noAnonFunctionType=s}return super.parseAsyncArrowFromCallExpression(e,r)}shouldParseAsyncArrow(){return this.match(14)||super.shouldParseAsyncArrow()}parseMaybeAssign(e,r){var s;let i=null,a;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){if(i=this.state.clone(),a=this.tryParse(()=>super.parseMaybeAssign(e,r),i),!a.error)return a.node;let{context:c}=this.state,l=c[c.length-1];(l===se.j_oTag||l===se.j_expr)&&c.pop()}if((s=a)!=null&&s.error||this.match(47)){var o,d;i=i||this.state.clone();let c,l=this.tryParse(p=>{var f;c=this.flowParseTypeParameterDeclaration();let h=this.forwardNoArrowParamsConversionAt(c,()=>{let g=super.parseMaybeAssign(e,r);return this.resetStartLocationFromNode(g,c),g});(f=h.extra)!=null&&f.parenthesized&&p();let m=this.maybeUnwrapTypeCastExpression(h);return m.type!=="ArrowFunctionExpression"&&p(),m.typeParameters=c,this.resetStartLocationFromNode(m,c),h},i),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,r)}parseArrow(e){if(this.match(14)){let r=this.tryParse(()=>{let s=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0;let i=this.startNode();return[i.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),this.state.noAnonFunctionType=s,this.canInsertSemicolon()&&this.unexpected(),this.match(19)||this.unexpected(),i});if(r.thrown)return null;r.error&&(this.state=r.failState),e.returnType=r.node.typeAnnotation?this.finishNode(r.node,"TypeAnnotation"):null}return super.parseArrow(e)}shouldParseArrow(e){return this.match(14)||super.shouldParseArrow(e)}setArrowFunctionParameters(e,r){this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))?e.params=r:super.setArrowFunctionParameters(e,r)}checkParams(e,r,s,i=!0){if(!(s&&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,r,s,i)}}parseParenAndDistinguishExpression(e){return super.parseParenAndDistinguishExpression(e&&!this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)))}parseSubscripts(e,r,s){if(e.type==="Identifier"&&e.name==="async"&&this.state.noArrowAt.includes(r.index)){this.next();let i=this.startNodeAt(r);i.callee=e,i.arguments=super.parseCallExpressionArguments(),e=this.finishNode(i,"CallExpression")}else if(e.type==="Identifier"&&e.name==="async"&&this.match(47)){let i=this.state.clone(),a=this.tryParse(d=>this.parseAsyncArrowWithTypeParameters(r)||d(),i);if(!a.error&&!a.aborted)return a.node;let o=this.tryParse(()=>super.parseSubscripts(e,r,s),i);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,r,s)}parseSubscript(e,r,s,i){if(this.match(18)&&this.isLookaheadToken_lt()){if(i.optionalChainMember=!0,s)return i.stop=!0,e;this.next();let a=this.startNodeAt(r);return a.callee=e,a.typeArguments=this.flowParseTypeParameterInstantiationInExpression(),this.expect(10),a.arguments=this.parseCallExpressionArguments(),a.optional=!0,this.finishCallExpression(a,!0)}else if(!s&&this.shouldParseTypes()&&(this.match(47)||this.match(51))){let a=this.startNodeAt(r);a.callee=e;let o=this.tryParse(()=>(a.typeArguments=this.flowParseTypeParameterInstantiationCallOrNew(),this.expect(10),a.arguments=super.parseCallExpressionArguments(),i.optionalChainMember&&(a.optional=!1),this.finishCallExpression(a,i.optionalChainMember)));if(o.node)return o.error&&(this.state=o.failState),o.node}return super.parseSubscript(e,r,s,i)}parseNewCallee(e){super.parseNewCallee(e);let r=null;this.shouldParseTypes()&&this.match(47)&&(r=this.tryParse(()=>this.flowParseTypeParameterInstantiationCallOrNew()).node),e.typeArguments=r}parseAsyncArrowWithTypeParameters(e){let r=this.startNodeAt(e);if(this.parseFunctionParams(r,!1),!!this.parseArrow(r))return super.parseArrowExpression(r,void 0,!0)}readToken_mult_modulo(e){let r=this.input.charCodeAt(this.state.pos+1);if(e===42&&r===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 r=this.input.charCodeAt(this.state.pos+1);if(e===124&&r===125){this.finishOp(9,2);return}super.readToken_pipe_amp(e)}parseTopLevel(e,r){let s=super.parseTopLevel(e,r);return this.state.hasFlowComment&&this.raise(z.UnterminatedFlowComment,this.state.curPosition()),s}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,r=2;for(;[32,9].includes(this.input.charCodeAt(e+r));)r++;let s=this.input.charCodeAt(r+e),i=this.input.charCodeAt(r+e+1);return s===58&&i===58?r+2:this.input.slice(r+e,r+e+12)==="flow-include"?r+12:s===58&&i!==58?r:!1}hasFlowCommentCompletion(){if(this.input.indexOf("*/",this.state.pos)===-1)throw this.raise(b.UnterminatedComment,this.state.curPosition())}flowEnumErrorBooleanMemberNotInitialized(e,{enumName:r,memberName:s}){this.raise(z.EnumBooleanMemberNotInitialized,e,{memberName:s,enumName:r})}flowEnumErrorInvalidMemberInitializer(e,r){return this.raise(r.explicitType?r.explicitType==="symbol"?z.EnumInvalidMemberInitializerSymbolType:z.EnumInvalidMemberInitializerPrimaryType:z.EnumInvalidMemberInitializerUnknownType,e,r)}flowEnumErrorNumberMemberNotInitialized(e,r){this.raise(z.EnumNumberMemberNotInitialized,e,r)}flowEnumErrorStringMemberInconsistentlyInitialized(e,r){this.raise(z.EnumStringMemberInconsistentlyInitialized,e,r)}flowEnumMemberInit(){let e=this.state.startLoc,r=()=>this.match(12)||this.match(8);switch(this.state.type){case 135:{let s=this.parseNumericLiteral(this.state.value);return r()?{type:"number",loc:s.loc.start,value:s}:{type:"invalid",loc:e}}case 134:{let s=this.parseStringLiteral(this.state.value);return r()?{type:"string",loc:s.loc.start,value:s}:{type:"invalid",loc:e}}case 85:case 86:{let s=this.parseBooleanLiteral(this.match(85));return r()?{type:"boolean",loc:s.loc.start,value:s}:{type:"invalid",loc:e}}default:return{type:"invalid",loc:e}}}flowEnumMemberRaw(){let e=this.state.startLoc,r=this.parseIdentifier(!0),s=this.eat(29)?this.flowEnumMemberInit():{type:"none",loc:e};return{id:r,init:s}}flowEnumCheckExplicitTypeMismatch(e,r,s){let{explicitType:i}=r;i!==null&&i!==s&&this.flowEnumErrorInvalidMemberInitializer(e,r)}flowEnumMembers({enumName:e,explicitType:r}){let s=new Set,i={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}),s.has(l)&&this.raise(z.EnumDuplicateMemberName,d,{memberName:l,enumName:e}),s.add(l);let u={enumName:e,explicitType:r,memberName:l};switch(o.id=d,c.type){case"boolean":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"boolean"),o.init=c.value,i.booleanMembers.push(this.finishNode(o,"EnumBooleanMember"));break}case"number":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"number"),o.init=c.value,i.numberMembers.push(this.finishNode(o,"EnumNumberMember"));break}case"string":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"string"),o.init=c.value,i.stringMembers.push(this.finishNode(o,"EnumStringMember"));break}case"invalid":throw this.flowEnumErrorInvalidMemberInitializer(c.loc,u);case"none":switch(r){case"boolean":this.flowEnumErrorBooleanMemberNotInitialized(c.loc,u);break;case"number":this.flowEnumErrorNumberMemberNotInitialized(c.loc,u);break;default:i.defaultedMembers.push(this.finishNode(o,"EnumDefaultedMember"))}}this.match(8)||this.expect(12)}return{members:i,hasUnknownMembers:a}}flowEnumStringMembers(e,r,{enumName:s}){if(e.length===0)return r;if(r.length===0)return e;if(r.length>e.length){for(let i of e)this.flowEnumErrorStringMemberInconsistentlyInitialized(i,{enumName:s});return r}else{for(let i of r)this.flowEnumErrorStringMemberInconsistentlyInitialized(i,{enumName:s});return e}}flowEnumParseExplicitType({enumName:e}){if(!this.eatContextual(102))return null;if(!ie(this.state.type))throw this.raise(z.EnumInvalidExplicitTypeUnknownSupplied,this.state.startLoc,{enumName:e});let{value:r}=this.state;return this.next(),r!=="boolean"&&r!=="number"&&r!=="string"&&r!=="symbol"&&this.raise(z.EnumInvalidExplicitType,this.state.startLoc,{enumName:e,invalidEnumType:r}),r}flowEnumBody(e,r){let s=r.name,i=r.loc.start,a=this.flowEnumParseExplicitType({enumName:s});this.expect(5);let{members:o,hasUnknownMembers:d}=this.flowEnumMembers({enumName:s,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:s}),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:s}),this.expect(8),this.finishNode(e,"EnumStringBody");if(!u&&!p&&l>=f){for(let h of o.defaultedMembers)this.flowEnumErrorBooleanMemberNotInitialized(h.loc.start,{enumName:s,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:s,memberName:h.id.name});return e.members=o.numberMembers,this.expect(8),this.finishNode(e,"EnumNumberBody")}else return this.raise(z.EnumInconsistentMemberValues,i,{enumName:s}),c()}}}flowParseEnumDeclaration(e){let r=this.parseIdentifier();return e.id=r,e.body=this.flowEnumBody(this.startNode(),r),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 r=this.input.charCodeAt(e+1);return r!==60&&r!==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}},oR={__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"},dR=/\r\n|[\r\n\u2028\u2029]/,Pi=new RegExp(dR.source,"g");function Gn(n){switch(n){case 10:case 13:case 8232:case 8233:return!0;default:return!1}}function Pf(n,t,e){for(let r=t;r<e;r++)if(Gn(n.charCodeAt(r)))return!0;return!1}var ad=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,od=/(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;function cR(n){switch(n){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 ln=st`jsx`({AttributeIsEmpty:"JSX attributes must only be assigned a non-empty expression.",MissingClosingTagElement:({openingTagName:n})=>`Expected corresponding JSX closing tag for <${n}>.`,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:n,HTMLEntity:t})=>`Unexpected token \`${n}\`. Did you mean \`${t}\` or \`{'${n}'}\`?`,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 jt(n){return n?n.type==="JSXOpeningFragment"||n.type==="JSXClosingFragment":!1}function qn(n){if(n.type==="JSXIdentifier")return n.name;if(n.type==="JSXNamespacedName")return n.namespace.name+":"+n.name.name;if(n.type==="JSXMemberExpression")return qn(n.object)+"."+qn(n.property);throw new Error("Node had unexpected type: "+n.type)}var lR=n=>class extends n{jsxReadToken(){let e="",r=this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(ln.UnterminatedJsxContent,this.state.startLoc);let s=this.input.charCodeAt(this.state.pos);switch(s){case 60:case 123:if(this.state.pos===this.state.start){s===60&&this.state.canStartJSXElement?(++this.state.pos,this.finishToken(143)):super.getTokenFromCode(s);return}e+=this.input.slice(r,this.state.pos),this.finishToken(142,e);return;case 38:e+=this.input.slice(r,this.state.pos),e+=this.jsxReadEntity(),r=this.state.pos;break;default:Gn(s)?(e+=this.input.slice(r,this.state.pos),e+=this.jsxReadNewLine(!0),r=this.state.pos):++this.state.pos}}}jsxReadNewLine(e){let r=this.input.charCodeAt(this.state.pos),s;return++this.state.pos,r===13&&this.input.charCodeAt(this.state.pos)===10?(++this.state.pos,s=e?`
3
+ var Ex=Object.create;var yp=Object.defineProperty;var Cx=Object.getOwnPropertyDescriptor;var Nx=Object.getOwnPropertyNames;var Ox=Object.getPrototypeOf,$x=Object.prototype.hasOwnProperty;var Dx=(t,n)=>()=>{try{return n||t((n={exports:{}}).exports,n),n.exports}catch(e){throw n=0,e}};var Mx=(t,n,e,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Nx(n))!$x.call(t,s)&&s!==e&&yp(t,s,{get:()=>n[s],enumerable:!(r=Cx(n,s))||r.enumerable});return t};var oi=(t,n,e)=>(e=t!=null?Ex(Ox(t)):{},Mx(n||!t||!t.__esModule?yp(e,"default",{value:t,enumerable:!0}):e,t));var ns=Dx(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});function gR(t,n){if(t==null)return{};var e={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(n.indexOf(r)!==-1)continue;e[r]=t[r]}return e}var gt=class{constructor(n,e,r){this.line=void 0,this.column=void 0,this.index=void 0,this.line=n,this.column=e,this.index=r}},Zn=class{constructor(n,e){this.start=void 0,this.end=void 0,this.filename=void 0,this.identifierName=void 0,this.start=n,this.end=e}};function Me(t,n){let{line:e,column:r,index:s}=t;return new gt(e,r+n,s+n)}var Qf="BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED",wR={ImportMetaOutsideModule:{message:`import.meta may appear only with 'sourceType: "module"'`,code:Qf},ImportOutsideModule:{message:`'import' and 'export' may appear only with 'sourceType: "module"'`,code:Qf}},Zf={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"},Ni=t=>t.type==="UpdateExpression"?Zf.UpdateExpression[`${t.prefix}`]:Zf[t.type],bR={AccessorIsGenerator:({kind:t})=>`A ${t}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:t})=>`Missing initializer in ${t} 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:t})=>`\`${t}\` 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:t,exportName:n})=>`A string literal cannot be used as an exported binding without \`from\`.
4
+ - Did you mean \`export { '${t}' as '${n}' } from 'some-module'\`?`,ExportDefaultFromAsIdentifier:"'from' is not allowed as an identifier after 'export default'.",ForInOfLoopInitializer:({type:t})=>`'${t==="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:t})=>`Unsyntactic ${t==="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:t})=>`A string literal cannot be used as an imported binding.
5
+ - Did you mean \`import { "${t}" 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:t})=>`Expected number in radix ${t}.`,InvalidEscapeSequence:"Bad character escape sequence.",InvalidEscapeSequenceTemplate:"Invalid escape sequence in template.",InvalidEscapedReservedWord:({reservedWord:t})=>`Escape sequence in keyword ${t}.`,InvalidIdentifier:({identifierName:t})=>`Invalid identifier ${t}.`,InvalidLhs:({ancestor:t})=>`Invalid left-hand side in ${Ni(t)}.`,InvalidLhsBinding:({ancestor:t})=>`Binding invalid left-hand side in ${Ni(t)}.`,InvalidLhsOptionalChaining:({ancestor:t})=>`Invalid optional chaining in the left-hand side of ${Ni(t)}.`,InvalidNumber:"Invalid number.",InvalidOrMissingExponent:"Floating-point numbers require a valid exponent after the 'e'.",InvalidOrUnexpectedToken:({unexpected:t})=>`Unexpected character '${t}'.`,InvalidParenthesizedAssignment:"Invalid parenthesized assignment pattern.",InvalidPrivateFieldResolution:({identifierName:t})=>`Private name #${t} 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:t})=>`Label '${t}' 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:t})=>`This experimental syntax requires enabling the parser plugin: ${t.map(n=>JSON.stringify(n)).join(", ")}.`,MissingOneOfPlugins:({missingPlugin:t})=>`This experimental syntax requires enabling one of the following parser plugin(s): ${t.map(n=>JSON.stringify(n)).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:t})=>`Duplicate key "${t}" is not allowed in module attributes.`,ModuleExportNameHasLoneSurrogate:({surrogateCharCode:t})=>`An export name cannot include a lone surrogate, found '\\u${t.toString(16)}'.`,ModuleExportUndefined:({localName:t})=>`Export '${t}' 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:t})=>`Private names are only allowed in property accesses (\`obj.#${t}\`) or in \`in\` expressions (\`#${t} in obj\`).`,PrivateNameRedeclaration:({identifierName:t})=>`Duplicate private name #${t}.`,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:t})=>`Unexpected keyword '${t}'.`,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:t})=>`Unexpected reserved word '${t}'.`,UnexpectedSuper:"'super' is only allowed in object methods and classes.",UnexpectedToken:({expected:t,unexpected:n})=>`Unexpected token${n?` '${n}'.`:""}${t?`, expected "${t}"`:""}`,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:t,onlyValidPropertyName:n})=>`The only valid meta property for ${t} is ${t}.${n}.`,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:t})=>`Identifier '${t}' 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."},xR={StrictDelete:"Deleting local variable in strict mode.",StrictEvalArguments:({referenceName:t})=>`Assigning to '${t}' in strict mode.`,StrictEvalArgumentsBinding:({bindingName:t})=>`Binding '${t}' 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."},vR={ParseExpressionEmptyInput:"Unexpected parseExpression() input: The input is empty or contains only comments.",ParseExpressionExpectsEOF:({unexpected:t})=>`Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(t)}\`.`},kR=new Set(["ArrowFunctionExpression","AssignmentExpression","ConditionalExpression","YieldExpression"]),RR=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:t})=>`Invalid topic token ${t}. In order to use ${t} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${t}" }.`,PipeTopicUnused:"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",PipeUnparenthesizedBody:({type:t})=>`Hack-style pipe body cannot be an unparenthesized ${Ni({type:t})}; 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.'}),IR={UnsupportedBind:"Binding should be performed on object property.",UnsupportedBindRHS:"The right-hand side of binding can not be super or import."},AR=["message"];function eh(t,n,e){Object.defineProperty(t,n,{enumerable:!1,configurable:!0,value:e})}function TR({toMessage:t,code:n,reasonCode:e,syntaxPlugin:r}){let s=e==="MissingPlugin"||e==="MissingOneOfPlugins",i={AccessorCannotDeclareThisParameter:"AccesorCannotDeclareThisParameter",AccessorCannotHaveTypeParameters:"AccesorCannotHaveTypeParameters",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference",SetAccessorCannotHaveOptionalParameter:"SetAccesorCannotHaveOptionalParameter",SetAccessorCannotHaveRestParameter:"SetAccesorCannotHaveRestParameter",SetAccessorCannotHaveReturnType:"SetAccesorCannotHaveReturnType"};return i[e]&&(e=i[e]),function a(o,d){let c=new SyntaxError;return c.code=n,c.reasonCode=e,c.loc=o,c.pos=o.index,c.syntaxPlugin=r,s&&(c.missingPlugin=d.missingPlugin),eh(c,"clone",function(u={}){var p;let{line:f,column:h,index:m}=(p=u.loc)!=null?p:o;return a(new gt(f,h,m),Object.assign({},d,u.details))}),eh(c,"details",d),Object.defineProperty(c,"message",{configurable:!0,get(){let l=`${t(d)} (${o.line}:${o.column})`;return this.message=l,l},set(l){Object.defineProperty(this,"message",{value:l,writable:!0})}}),c}}function it(t,n){if(Array.isArray(t))return r=>it(r,t[0]);let e={};for(let r of Object.keys(t)){let s=t[r],i=typeof s=="string"?{message:()=>s}:typeof s=="function"?{message:s}:s,{message:a}=i,o=gR(i,AR),d=typeof a=="string"?()=>a:a;e[r]=TR(Object.assign({code:"BABEL_PARSER_SYNTAX_ERROR",reasonCode:r,toMessage:d},n?{syntaxPlugin:n}:{},o))}return e}var b=Object.assign({},it(wR),it(bR),it(xR),it(vR),it`pipelineOperator`(RR),it`functionBind`(IR));function PR(){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 SR(t){let n=PR();if(t==null)return n;if(t.annexB!=null&&t.annexB!==!1)throw new Error("The `annexB` option can only be set to `false`.");for(let e of Object.keys(n))t[e]!=null&&(n[e]=t[e]);if(n.startLine===1)t.startIndex==null&&n.startColumn>0?n.startIndex=n.startColumn:t.startColumn==null&&n.startIndex>0&&(n.startColumn=n.startIndex);else if((t.startColumn==null||t.startIndex==null)&&t.startIndex!=null)throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");if(n.sourceType==="commonjs"){if(t.allowAwaitOutsideFunction!=null)throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.");if(t.allowReturnOutsideFunction!=null)throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.");if(t.allowNewTargetOutsideFunction!=null)throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.")}return n}var{defineProperty:ER}=Object,th=(t,n)=>{t&&ER(t,n,{enumerable:!1,value:t[n]})};function Gr(t){return th(t.loc.start,"index"),th(t.loc.end,"index"),t}var CR=t=>class extends t{parse(){let e=Gr(super.parse());return this.optionFlags&256&&(e.tokens=e.tokens.map(Gr)),e}parseRegExpLiteral({pattern:e,flags:r}){let s=null;try{s=new RegExp(e,r)}catch{}let i=this.estreeParseLiteral(s);return i.regex={pattern:e,flags:r},i}parseBigIntLiteral(e){let r;try{r=BigInt(e)}catch{r=null}let s=this.estreeParseLiteral(r);return s.bigint=String(s.value||e),s}parseDecimalLiteral(e){let s=this.estreeParseLiteral(null);return s.decimal=String(s.value||e),s}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,r){let s=this.startNodeAtNode(e);return s.expression=e,this.finishNodeAt(s,"ChainExpression",r)}directiveToStmt(e){let r=e.value;delete e.value,this.castNodeTo(r,"Literal"),r.raw=r.extra.raw,r.value=r.extra.expressionValue;let s=this.castNodeTo(e,"ExpressionStatement");return s.expression=r,s.directive=r.extra.rawValue,delete r.extra,s}fillOptionalPropertiesForTSESLint(e){}cloneEstreeStringLiteral(e){let{start:r,end:s,loc:i,range:a,raw:o,value:d}=e,c=Object.create(e.constructor.prototype);return c.type="Literal",c.start=r,c.end=s,c.loc=i,c.range=a,c.raw=o,c.value=d,c}initFunction(e,r){super.initFunction(e,r),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 r;return e.type==="ExpressionStatement"&&e.expression.type==="Literal"&&typeof e.expression.value=="string"&&!((r=e.expression.extra)!=null&&r.parenthesized)}parseBlockBody(e,r,s,i,a){super.parseBlockBody(e,r,s,i,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 r=super.getPrivateNameSV(e);return delete e.id,e.name=r,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,r){let s=super.parseLiteral(e,r);return s.raw=s.extra.raw,delete s.extra,s}parseFunctionBody(e,r,s=!1){super.parseFunctionBody(e,r,s),e.expression=e.body.type!=="BlockStatement"}parseMethod(e,r,s,i,a,o,d=!1){let c=this.startNode();c.kind=e.kind,c=super.parseMethod(c,r,s,i,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 r=super.parseClassProperty(...e);return this.getPluginOption("estree","classFeatures")&&this.castNodeTo(r,"PropertyDefinition"),r}parseClassPrivateProperty(...e){let r=super.parseClassPrivateProperty(...e);return this.getPluginOption("estree","classFeatures")&&(this.castNodeTo(r,"PropertyDefinition"),r.computed=!1),r}parseClassAccessorProperty(e){let r=super.parseClassAccessorProperty(e);return this.getPluginOption("estree","classFeatures")&&(r.abstract&&this.hasPlugin("typescript")?(delete r.abstract,this.castNodeTo(r,"TSAbstractAccessorProperty")):this.castNodeTo(r,"AccessorProperty")),r}parseObjectProperty(e,r,s,i){let a=super.parseObjectProperty(e,r,s,i);return a&&(a.kind="init",this.castNodeTo(a,"Property")),a}finishObjectProperty(e){return e.kind="init",this.finishNode(e,"Property")}isValidLVal(e,r,s,i){return e==="Property"?"value":super.isValidLVal(e,r,s,i)}isAssignable(e,r){return e!=null&&this.isObjectProperty(e)?this.isAssignable(e.value,r):super.isAssignable(e,r)}toAssignable(e,r=!1){if(e!=null&&this.isObjectProperty(e)){let{key:s,value:i}=e;this.isPrivateName(s)&&this.classScope.usePrivateName(this.getPrivateNameSV(s),s.loc.start),this.toAssignable(i,r)}else super.toAssignable(e,r)}toAssignableObjectExpressionProp(e,r,s){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,r,s)}finishCallExpression(e,r){let s=super.finishCallExpression(e,r);if(s.callee.type==="Import"){var i,a;this.castNodeTo(s,"ImportExpression"),s.source=s.arguments[0],s.options=(i=s.arguments[1])!=null?i:null,s.attributes=(a=s.arguments[1])!=null?a:null,delete s.arguments,delete s.callee}else s.type==="OptionalCallExpression"?this.castNodeTo(s,"CallExpression"):s.optional=!1;return s}toReferencedArguments(e){e.type!=="ImportExpression"&&super.toReferencedArguments(e)}parseExport(e,r){let s=this.state.lastTokStartLoc,i=super.parseExport(e,r);switch(i.type){case"ExportAllDeclaration":i.exported=null;break;case"ExportNamedDeclaration":i.specifiers.length===1&&i.specifiers[0].type==="ExportNamespaceSpecifier"&&(this.castNodeTo(i,"ExportAllDeclaration"),i.exported=i.specifiers[0].exported,delete i.specifiers);case"ExportDefaultDeclaration":{var a;let{declaration:o}=i;o?.type==="ClassDeclaration"&&((a=o.decorators)==null?void 0:a.length)>0&&o.start===i.start&&this.resetStartLocation(i,s)}break}return i}stopParseSubscript(e,r){let s=super.stopParseSubscript(e,r);return r.optionalChainMember?this.estreeParseChainExpression(s,e.loc.end):s}parseMember(e,r,s,i,a){let o=super.parseMember(e,r,s,i,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,r){let s=super.castNodeTo(e,r);return this.fillOptionalPropertiesForTSESLint(s),s}cloneIdentifier(e){let r=super.cloneIdentifier(e);return this.fillOptionalPropertiesForTSESLint(r),r}cloneStringLiteral(e){return e.type==="Literal"?this.cloneEstreeStringLiteral(e):super.cloneStringLiteral(e)}finishNodeAt(e,r,s){return Gr(super.finishNodeAt(e,r,s))}finishNode(e,r){let s=super.finishNode(e,r);return this.fillOptionalPropertiesForTSESLint(s),s}resetStartLocation(e,r){super.resetStartLocation(e,r),Gr(e)}resetEndLocation(e,r=this.state.lastTokEndLoc){super.resetEndLocation(e,r),Gr(e)}},yn=class{constructor(n,e){this.token=void 0,this.preserveSpace=void 0,this.token=n,this.preserveSpace=!!e}},se={brace:new yn("{"),j_oTag:new yn("<tag"),j_cTag:new yn("</tag"),j_expr:new yn("<tag>...</tag>",!0)};se.template=new yn("`",!0);var W=!0,O=!0,wd=!0,Kr=!0,Ft=!0,NR=!0,Di=class{constructor(n,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=n,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}},qd=new Map;function ee(t,n={}){n.keyword=t;let e=z(t,n);return qd.set(t,e),e}function De(t,n){return z(t,{beforeExpr:W,binop:n})}var Yr=-1,St=[],Gd=[],Kd=[],Wd=[],Jd=[],Xd=[];function z(t,n={}){var e,r,s,i;return++Yr,Gd.push(t),Kd.push((e=n.binop)!=null?e:-1),Wd.push((r=n.beforeExpr)!=null?r:!1),Jd.push((s=n.startsExpr)!=null?s:!1),Xd.push((i=n.prefix)!=null?i:!1),St.push(new Di(t,n)),Yr}function J(t,n={}){var e,r,s,i;return++Yr,qd.set(t,Yr),Gd.push(t),Kd.push((e=n.binop)!=null?e:-1),Wd.push((r=n.beforeExpr)!=null?r:!1),Jd.push((s=n.startsExpr)!=null?s:!1),Xd.push((i=n.prefix)!=null?i:!1),St.push(new Di("name",n)),Yr}var OR={bracketL:z("[",{beforeExpr:W,startsExpr:O}),bracketHashL:z("#[",{beforeExpr:W,startsExpr:O}),bracketBarL:z("[|",{beforeExpr:W,startsExpr:O}),bracketR:z("]"),bracketBarR:z("|]"),braceL:z("{",{beforeExpr:W,startsExpr:O}),braceBarL:z("{|",{beforeExpr:W,startsExpr:O}),braceHashL:z("#{",{beforeExpr:W,startsExpr:O}),braceR:z("}"),braceBarR:z("|}"),parenL:z("(",{beforeExpr:W,startsExpr:O}),parenR:z(")"),comma:z(",",{beforeExpr:W}),semi:z(";",{beforeExpr:W}),colon:z(":",{beforeExpr:W}),doubleColon:z("::",{beforeExpr:W}),dot:z("."),question:z("?",{beforeExpr:W}),questionDot:z("?."),arrow:z("=>",{beforeExpr:W}),template:z("template"),ellipsis:z("...",{beforeExpr:W}),backQuote:z("`",{startsExpr:O}),dollarBraceL:z("${",{beforeExpr:W,startsExpr:O}),templateTail:z("...`",{startsExpr:O}),templateNonTail:z("...${",{beforeExpr:W,startsExpr:O}),at:z("@"),hash:z("#",{startsExpr:O}),interpreterDirective:z("#!..."),eq:z("=",{beforeExpr:W,isAssign:Kr}),assign:z("_=",{beforeExpr:W,isAssign:Kr}),slashAssign:z("_=",{beforeExpr:W,isAssign:Kr}),xorAssign:z("_=",{beforeExpr:W,isAssign:Kr}),moduloAssign:z("_=",{beforeExpr:W,isAssign:Kr}),incDec:z("++/--",{prefix:Ft,postfix:NR,startsExpr:O}),bang:z("!",{beforeExpr:W,prefix:Ft,startsExpr:O}),tilde:z("~",{beforeExpr:W,prefix:Ft,startsExpr:O}),doubleCaret:z("^^",{startsExpr:O}),doubleAt:z("@@",{startsExpr:O}),pipeline:De("|>",0),nullishCoalescing:De("??",1),logicalOR:De("||",1),logicalAND:De("&&",2),bitwiseOR:De("|",3),bitwiseXOR:De("^",4),bitwiseAND:De("&",5),equality:De("==/!=/===/!==",6),lt:De("</>/<=/>=",7),gt:De("</>/<=/>=",7),relational:De("</>/<=/>=",7),bitShift:De("<</>>/>>>",8),bitShiftL:De("<</>>/>>>",8),bitShiftR:De("<</>>/>>>",8),plusMin:z("+/-",{beforeExpr:W,binop:9,prefix:Ft,startsExpr:O}),modulo:z("%",{binop:10,startsExpr:O}),star:z("*",{binop:10}),slash:De("/",10),exponent:z("**",{beforeExpr:W,binop:11,rightAssociative:!0}),_in:ee("in",{beforeExpr:W,binop:7}),_instanceof:ee("instanceof",{beforeExpr:W,binop:7}),_break:ee("break"),_case:ee("case",{beforeExpr:W}),_catch:ee("catch"),_continue:ee("continue"),_debugger:ee("debugger"),_default:ee("default",{beforeExpr:W}),_else:ee("else",{beforeExpr:W}),_finally:ee("finally"),_function:ee("function",{startsExpr:O}),_if:ee("if"),_return:ee("return",{beforeExpr:W}),_switch:ee("switch"),_throw:ee("throw",{beforeExpr:W,prefix:Ft,startsExpr:O}),_try:ee("try"),_var:ee("var"),_const:ee("const"),_with:ee("with"),_new:ee("new",{beforeExpr:W,startsExpr:O}),_this:ee("this",{startsExpr:O}),_super:ee("super",{startsExpr:O}),_class:ee("class",{startsExpr:O}),_extends:ee("extends",{beforeExpr:W}),_export:ee("export"),_import:ee("import",{startsExpr:O}),_null:ee("null",{startsExpr:O}),_true:ee("true",{startsExpr:O}),_false:ee("false",{startsExpr:O}),_typeof:ee("typeof",{beforeExpr:W,prefix:Ft,startsExpr:O}),_void:ee("void",{beforeExpr:W,prefix:Ft,startsExpr:O}),_delete:ee("delete",{beforeExpr:W,prefix:Ft,startsExpr:O}),_do:ee("do",{isLoop:wd,beforeExpr:W}),_for:ee("for",{isLoop:wd}),_while:ee("while",{isLoop:wd}),_as:J("as",{startsExpr:O}),_assert:J("assert",{startsExpr:O}),_async:J("async",{startsExpr:O}),_await:J("await",{startsExpr:O}),_defer:J("defer",{startsExpr:O}),_from:J("from",{startsExpr:O}),_get:J("get",{startsExpr:O}),_let:J("let",{startsExpr:O}),_meta:J("meta",{startsExpr:O}),_of:J("of",{startsExpr:O}),_sent:J("sent",{startsExpr:O}),_set:J("set",{startsExpr:O}),_source:J("source",{startsExpr:O}),_static:J("static",{startsExpr:O}),_using:J("using",{startsExpr:O}),_yield:J("yield",{startsExpr:O}),_asserts:J("asserts",{startsExpr:O}),_checks:J("checks",{startsExpr:O}),_exports:J("exports",{startsExpr:O}),_global:J("global",{startsExpr:O}),_implements:J("implements",{startsExpr:O}),_intrinsic:J("intrinsic",{startsExpr:O}),_infer:J("infer",{startsExpr:O}),_is:J("is",{startsExpr:O}),_mixins:J("mixins",{startsExpr:O}),_proto:J("proto",{startsExpr:O}),_require:J("require",{startsExpr:O}),_satisfies:J("satisfies",{startsExpr:O}),_keyof:J("keyof",{startsExpr:O}),_readonly:J("readonly",{startsExpr:O}),_unique:J("unique",{startsExpr:O}),_abstract:J("abstract",{startsExpr:O}),_declare:J("declare",{startsExpr:O}),_enum:J("enum",{startsExpr:O}),_module:J("module",{startsExpr:O}),_namespace:J("namespace",{startsExpr:O}),_interface:J("interface",{startsExpr:O}),_type:J("type",{startsExpr:O}),_opaque:J("opaque",{startsExpr:O}),name:z("name",{startsExpr:O}),placeholder:z("%%",{startsExpr:O}),string:z("string",{startsExpr:O}),num:z("num",{startsExpr:O}),bigint:z("bigint",{startsExpr:O}),decimal:z("decimal",{startsExpr:O}),regexp:z("regexp",{startsExpr:O}),privateName:z("#name",{startsExpr:O}),eof:z("eof"),jsxName:z("jsxName"),jsxText:z("jsxText",{beforeExpr:W}),jsxTagStart:z("jsxTagStart",{startsExpr:O}),jsxTagEnd:z("jsxTagEnd")};function ie(t){return t>=93&&t<=133}function $R(t){return t<=92}function at(t){return t>=58&&t<=133}function fh(t){return t>=58&&t<=137}function DR(t){return Wd[t]}function Jr(t){return Jd[t]}function MR(t){return t>=29&&t<=33}function nh(t){return t>=129&&t<=131}function LR(t){return t>=90&&t<=92}function Yd(t){return t>=58&&t<=92}function _R(t){return t>=39&&t<=59}function jR(t){return t===34}function FR(t){return Xd[t]}function BR(t){return t>=121&&t<=123}function VR(t){return t>=124&&t<=130}function Vt(t){return Gd[t]}function Oi(t){return Kd[t]}function zR(t){return t===57}function Mi(t){return t>=24&&t<=25}function Pt(t){return St[t]}St[8].updateContext=t=>{t.pop()};St[5].updateContext=St[7].updateContext=St[23].updateContext=t=>{t.push(se.brace)};St[22].updateContext=t=>{t[t.length-1]===se.template?t.pop():t.push(se.template)};St[143].updateContext=t=>{t.push(se.j_expr,se.j_oTag)};var Qd="\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",hh="\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",HR=new RegExp("["+Qd+"]"),UR=new RegExp("["+Qd+hh+"]");Qd=hh=null;var mh=[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],qR=[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 Id(t,n){let e=65536;for(let r=0,s=n.length;r<s;r+=2){if(e+=n[r],e>t)return!1;if(e+=n[r+1],e>=t)return!0}return!1}function yt(t){return t<65?t===36:t<=90?!0:t<97?t===95:t<=122?!0:t<=65535?t>=170&&HR.test(String.fromCharCode(t)):Id(t,mh)}function gn(t){return t<48?t===36:t<58?!0:t<65?!1:t<=90?!0:t<97?t===95:t<=122?!0:t<=65535?t>=170&&UR.test(String.fromCharCode(t)):Id(t,mh)||Id(t,qR)}var Zd={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"]},GR=new Set(Zd.keyword),KR=new Set(Zd.strict),WR=new Set(Zd.strictBind);function yh(t,n){return n&&t==="await"||t==="enum"}function gh(t,n){return yh(t,n)||KR.has(t)}function wh(t){return WR.has(t)}function bh(t,n){return gh(t,n)||wh(t)}function JR(t){return GR.has(t)}function XR(t,n,e){return t===64&&n===64&&yt(e)}var YR=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 QR(t){return YR.has(t)}var Qr=class{constructor(n){this.flags=0,this.names=new Map,this.firstLexicalName="",this.flags=n}},Zr=class{constructor(n,e){this.parser=void 0,this.scopeStack=[],this.inModule=void 0,this.undefinedExports=new Map,this.parser=n,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 n=this.currentThisScopeFlags();return(n&64)>0&&(n&2)===0}get inStaticBlock(){for(let n=this.scopeStack.length-1;;n--){let{flags:e}=this.scopeStack[n];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(n){return new Qr(n)}enter(n){this.scopeStack.push(this.createScope(n))}exit(){return this.scopeStack.pop().flags}treatFunctionsAsVarInScope(n){return!!(n.flags&130||!this.parser.inModule&&n.flags&1)}declareName(n,e,r){let s=this.currentScope();if(e&8||e&16){this.checkRedeclarationInScope(s,n,e,r);let i=s.names.get(n)||0;e&16?i=i|4:(s.firstLexicalName||(s.firstLexicalName=n),i=i|2),s.names.set(n,i),e&8&&this.maybeExportDefined(s,n)}else if(e&4)for(let i=this.scopeStack.length-1;i>=0&&(s=this.scopeStack[i],this.checkRedeclarationInScope(s,n,e,r),s.names.set(n,(s.names.get(n)||0)|1),this.maybeExportDefined(s,n),!(s.flags&1667));--i);this.parser.inModule&&s.flags&1&&this.undefinedExports.delete(n)}maybeExportDefined(n,e){this.parser.inModule&&n.flags&1&&this.undefinedExports.delete(e)}checkRedeclarationInScope(n,e,r,s){this.isRedeclaredInScope(n,e,r)&&this.parser.raise(b.VarRedeclaration,s,{identifierName:e})}isRedeclaredInScope(n,e,r){if(!(r&1))return!1;if(r&8)return n.names.has(e);let s=n.names.get(e)||0;return r&16?(s&2)>0||!this.treatFunctionsAsVarInScope(n)&&(s&1)>0:(s&2)>0&&!(n.flags&8&&n.firstLexicalName===e)||!this.treatFunctionsAsVarInScope(n)&&(s&4)>0}checkLocalExport(n){let{name:e}=n;this.scopeStack[0].names.has(e)||this.undefinedExports.set(e,n.loc.start)}currentScope(){return this.scopeStack[this.scopeStack.length-1]}currentVarScopeFlags(){for(let n=this.scopeStack.length-1;;n--){let{flags:e}=this.scopeStack[n];if(e&1667)return e}}currentThisScopeFlags(){for(let n=this.scopeStack.length-1;;n--){let{flags:e}=this.scopeStack[n];if(e&1731&&!(e&4))return e}}},Ad=class extends Qr{constructor(...n){super(...n),this.declareFunctions=new Set}},Td=class extends Zr{createScope(n){return new Ad(n)}declareName(n,e,r){let s=this.currentScope();if(e&2048){this.checkRedeclarationInScope(s,n,e,r),this.maybeExportDefined(s,n),s.declareFunctions.add(n);return}super.declareName(n,e,r)}isRedeclaredInScope(n,e,r){if(super.isRedeclaredInScope(n,e,r))return!0;if(r&2048&&!n.declareFunctions.has(e)){let s=n.names.get(e);return(s&4)>0||(s&2)>0}return!1}checkLocalExport(n){this.scopeStack[0].declareFunctions.has(n.name)||super.checkLocalExport(n)}},ZR=new Set(["_","any","bool","boolean","empty","extends","false","interface","mixed","null","number","static","string","true","typeof","void"]),H=it`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:t})=>`Cannot overwrite reserved type ${t}.`,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:t,enumName:n})=>`Boolean enum members need to be initialized. Use either \`${t} = true,\` or \`${t} = false,\` in enum \`${n}\`.`,EnumDuplicateMemberName:({memberName:t,enumName:n})=>`Enum member names need to be unique, but the name \`${t}\` has already been used before in enum \`${n}\`.`,EnumInconsistentMemberValues:({enumName:t})=>`Enum \`${t}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,EnumInvalidExplicitType:({invalidEnumType:t,enumName:n})=>`Enum type \`${t}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${n}\`.`,EnumInvalidExplicitTypeUnknownSupplied:({enumName:t})=>`Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${t}\`.`,EnumInvalidMemberInitializerPrimaryType:({enumName:t,memberName:n,explicitType:e})=>`Enum \`${t}\` has type \`${e}\`, so the initializer of \`${n}\` needs to be a ${e} literal.`,EnumInvalidMemberInitializerSymbolType:({enumName:t,memberName:n})=>`Symbol enum members cannot be initialized. Use \`${n},\` in enum \`${t}\`.`,EnumInvalidMemberInitializerUnknownType:({enumName:t,memberName:n})=>`The enum member initializer for \`${n}\` needs to be a literal (either a boolean, number, or string) in enum \`${t}\`.`,EnumInvalidMemberName:({enumName:t,memberName:n,suggestion:e})=>`Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${n}\`, consider using \`${e}\`, in enum \`${t}\`.`,EnumNumberMemberNotInitialized:({enumName:t,memberName:n})=>`Number enum members need to be initialized, e.g. \`${n} = 1\` in enum \`${t}\`.`,EnumStringMemberInconsistentlyInitialized:({enumName:t})=>`String enum members need to consistently either all use initializers, or use no initializers, in enum \`${t}\`.`,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:t})=>`Unexpected reserved type ${t}.`,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:t,suggestion:n})=>`\`declare export ${t}\` is not supported. Use \`${n}\` instead.`,UnsupportedStatementInDeclareModule:"Only declares and type imports are allowed inside declare module.",UnterminatedFlowComment:"Unterminated flow-comment."});function eI(t){return t.type==="DeclareExportAllDeclaration"||t.type==="DeclareExportDeclaration"&&(!t.declaration||t.declaration.type!=="TypeAlias"&&t.declaration.type!=="InterfaceDeclaration")}function rh(t){return t.importKind==="type"||t.importKind==="typeof"}var tI={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"};function nI(t,n){let e=[],r=[];for(let s=0;s<t.length;s++)(n(t[s],s,t)?e:r).push(t[s]);return[e,r]}var rI=/\*?\s*@((?:no)?flow)\b/,sI=t=>class extends t{constructor(...e){super(...e),this.flowPragma=void 0}getScopeHandler(){return Td}shouldParseTypes(){return this.getPluginOption("flow","all")||this.flowPragma==="flow"}finishToken(e,r){e!==134&&e!==13&&e!==28&&this.flowPragma===void 0&&(this.flowPragma=null),super.finishToken(e,r)}addComment(e){if(this.flowPragma===void 0){let r=rI.exec(e.value);if(r)if(r[1]==="flow")this.flowPragma="flow";else if(r[1]==="noflow")this.flowPragma="noflow";else throw new Error("Unexpected flow pragma")}super.addComment(e)}flowParseTypeInitialiser(e){let r=this.state.inType;this.state.inType=!0,this.expect(e||14);let s=this.flowParseType();return this.state.inType=r,s}flowParsePredicate(){let e=this.startNode(),r=this.state.startLoc;return this.next(),this.expectContextual(110),this.state.lastTokStartLoc.index>r.index+1&&this.raise(H.UnexpectedSpaceBetweenModuloChecks,r),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 r=null,s=null;return this.match(54)?(this.state.inType=e,s=this.flowParsePredicate()):(r=this.flowParseType(),this.state.inType=e,this.match(54)&&(s=this.flowParsePredicate())),[r,s]}flowParseDeclareClass(e){return this.next(),this.flowParseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")}flowParseDeclareFunction(e){this.next();let r=e.id=this.parseIdentifier(),s=this.startNode(),i=this.startNode();this.match(47)?s.typeParameters=this.flowParseTypeParameterDeclaration():s.typeParameters=null,this.expect(10);let a=this.flowParseFunctionTypeParams();return s.params=a.params,s.rest=a.rest,s.this=a._this,this.expect(11),[s.returnType,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),i.typeAnnotation=this.finishNode(s,"FunctionTypeAnnotation"),r.typeAnnotation=this.finishNode(i,"TypeAnnotation"),this.resetEndLocation(r),this.semicolon(),this.scope.declareName(e.id.name,2048,e.id.loc.start),this.finishNode(e,"DeclareFunction")}flowParseDeclare(e,r){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):(r&&this.raise(H.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,r);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 r=e.body=this.startNode(),s=r.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(H.InvalidNonTypeImportInDeclareModule,this.state.lastTokStartLoc),s.push(super.parseImport(o))):(this.expectContextual(125,H.UnsupportedStatementInDeclareModule),s.push(this.flowParseDeclare(o,!0)))}this.scope.exit(),this.expect(8),this.finishNode(r,"BlockStatement");let i=null,a=!1;return s.forEach(o=>{eI(o)?(i==="CommonJS"&&this.raise(H.AmbiguousDeclareModuleKind,o),i="ES"):o.type==="DeclareModuleExports"&&(a&&this.raise(H.DuplicateDeclareModuleExports,o),i==="ES"&&this.raise(H.AmbiguousDeclareModuleKind,o),i="CommonJS",a=!0)}),e.kind=i||"CommonJS",this.finishNode(e,"DeclareModule")}flowParseDeclareExportDeclaration(e,r){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))&&!r){let s=this.state.value;throw this.raise(H.UnsupportedDeclareExportKind,this.state.startLoc,{unsupportedExportKind:s,suggestion:tI[s]})}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 r=this.flowParseTypeAlias(e);return this.castNodeTo(r,"DeclareTypeAlias"),r}flowParseDeclareOpaqueType(e){this.next();let r=this.flowParseOpaqueType(e,!0);return this.castNodeTo(r,"DeclareOpaqueType"),r}flowParseDeclareInterface(e){return this.next(),this.flowParseInterfaceish(e,!1),this.finishNode(e,"DeclareInterface")}flowParseInterfaceish(e,r){if(e.id=this.flowParseRestrictedIdentifier(!r,!0),this.scope.declareName(e.id.name,r?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(!r&&this.eat(12));if(r){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:r,allowExact:!1,allowSpread:!1,allowProto:r,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(H.UnexpectedReservedUnderscore,this.state.startLoc)}checkReservedType(e,r,s){ZR.has(e)&&this.raise(s?H.AssignReservedType:H.UnexpectedReservedType,r,{reservedType:e})}flowParseRestrictedIdentifierName(e,r){return this.checkReservedType(this.state.value,this.state.startLoc,r),this.parseIdentifierName(e)}flowParseRestrictedIdentifier(e,r){let s=this.startNode(),i=this.flowParseRestrictedIdentifierName(e,r);return this.createIdentifier(s,i)}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,r){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,r||(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 r=this.state.startLoc,s=this.startNode(),i=this.flowParseVariance();return s.name=this.flowParseRestrictedIdentifierName(),s.variance=i,s.bound=this.flowParseTypeParameterBound(),this.match(29)?(this.eat(29),s.default=this.flowParseType()):e&&this.raise(H.MissingTypeParamDefault,r),this.finishNode(s,"TypeParameter")}flowParseTypeParameterDeclaration(){let e=this.state.inType,r=this.startNode();r.params=[],this.state.inType=!0,this.match(47)||this.match(143)?this.next():this.unexpected();let s=!1;do{let i=this.flowParseTypeParameter(s);r.params.push(i),i.default&&(s=!0),this.match(48)||this.expect(12)}while(!this.match(48));return this.expect(48),this.state.inType=e,this.finishNode(r,"TypeParameterDeclaration")}flowInTopLevelContext(e){if(this.curContext()!==se.brace){let r=this.state.context;this.state.context=[r[0]];try{return e()}finally{this.state.context=r}}else return e()}flowParseTypeParameterInstantiationInExpression(){if(this.reScan_lt()===47)return this.flowParseTypeParameterInstantiation()}flowParseTypeParameterInstantiation(){let e=this.startNode(),r=this.state.inType;return this.state.inType=!0,e.params=[],this.flowInTopLevelContext(()=>{this.expect(47);let s=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=s}),this.state.inType=r,!this.state.inType&&this.curContext()===se.brace&&this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TypeParameterInstantiation")}flowParseTypeParameterInstantiationCallOrNew(){if(this.reScan_lt()!==47)return null;let e=this.startNode(),r=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=r,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,r,s){return e.static=r,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=s,this.finishNode(e,"ObjectTypeIndexer")}flowParseObjectTypeInternalSlot(e,r){return e.static=r,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,r){let s=this.startNode();return e.static=r,e.value=this.flowParseObjectTypeMethodish(s),this.finishNode(e,"ObjectTypeCallProperty")}flowParseObjectType({allowStatic:e,allowExact:r,allowSpread:s,allowProto:i,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(r&&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,m=null,g=this.startNode();if(i&&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(g,f))):d.indexers.push(this.flowParseObjectTypeIndexer(g,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(g,f));else{let w="init";if(this.isContextual(99)||this.isContextual(104)){let v=this.lookahead();fh(v.type)&&(w=this.state.value,this.next())}let x=this.flowParseObjectTypeProperty(g,f,h,y,w,s,a??!l);x===null?(u=!0,m=this.state.lastTokStartLoc):d.properties.push(x)}this.flowObjectTypeSemicolon(),m&&!this.match(8)&&!this.match(9)&&this.raise(H.UnexpectedExplicitInexactInObject,m)}this.expect(c),s&&(d.inexact=u);let p=this.finishNode(d,"ObjectTypeAnnotation");return this.state.inType=o,p}flowParseObjectTypeProperty(e,r,s,i,a,o,d){if(this.eat(21))return this.match(12)||this.match(13)||this.match(8)||this.match(9)?(o?d||this.raise(H.InexactInsideExact,this.state.lastTokStartLoc):this.raise(H.InexactInsideNonObject,this.state.lastTokStartLoc),i&&this.raise(H.InexactVariance,i),null):(o||this.raise(H.UnexpectedSpreadType,this.state.lastTokStartLoc),s!=null&&this.unexpected(s),i&&this.raise(H.SpreadVariance,i),e.argument=this.flowParseType(),this.finishNode(e,"ObjectTypeSpreadProperty"));{e.key=this.flowParseObjectPropertyKey(),e.static=r,e.proto=s!=null,e.kind=a;let c=!1;return this.match(47)||this.match(10)?(e.method=!0,s!=null&&this.unexpected(s),i&&this.unexpected(i.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(H.ThisParamBannedInConstructor,e.value.this)):(a!=="init"&&this.unexpected(),e.method=!1,this.eat(17)&&(c=!0),e.value=this.flowParseTypeInitialiser(),e.variance=i),e.optional=c,this.finishNode(e,"ObjectTypeProperty")}}flowCheckGetterSetterParams(e){let r=e.kind==="get"?0:1,s=e.value.params.length+(e.value.rest?1:0);e.value.this&&this.raise(e.kind==="get"?H.GetterMayNotHaveThisParam:H.SetterMayNotHaveThisParam,e.value.this),s!==r&&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,r){e??(e=this.state.startLoc);let s=r||this.flowParseRestrictedIdentifier(!0);for(;this.eat(16);){let i=this.startNodeAt(e);i.qualification=s,i.id=this.flowParseRestrictedIdentifier(!0),s=this.finishNode(i,"QualifiedTypeIdentifier")}return s}flowParseGenericType(e,r){let s=this.startNodeAt(e);return s.typeParameters=null,s.id=this.flowParseQualifiedTypeIdentifier(e,r),this.match(47)&&(s.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(s,"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 r=null,s=!1,i=null,a=this.startNode(),o=this.lookahead(),d=this.state.type===78;return o.type===14||o.type===17?(d&&!e&&this.raise(H.ThisParamMustBeFirst,a),r=this.parseIdentifier(d),this.eat(17)&&(s=!0,d&&this.raise(H.ThisParamMayNotBeOptional,a)),i=this.flowParseTypeInitialiser()):i=this.flowParseType(),a.name=r,a.optional=s,a.typeAnnotation=i,this.finishNode(a,"FunctionTypeParam")}reinterpretTypeAsFunctionTypeParam(e){let r=this.startNodeAt(e.loc.start);return r.name=null,r.optional=!1,r.typeAnnotation=e,this.finishNode(r,"FunctionTypeParam")}flowParseFunctionTypeParams(e=[]){let r=null,s=null;for(this.match(78)&&(s=this.flowParseFunctionTypeParam(!0),s.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)&&(r=this.flowParseFunctionTypeParam(!1)),{params:e,rest:r,_this:s}}flowIdentToTypeAnnotation(e,r,s){switch(s.name){case"any":return this.finishNode(r,"AnyTypeAnnotation");case"bool":case"boolean":return this.finishNode(r,"BooleanTypeAnnotation");case"mixed":return this.finishNode(r,"MixedTypeAnnotation");case"empty":return this.finishNode(r,"EmptyTypeAnnotation");case"number":return this.finishNode(r,"NumberTypeAnnotation");case"string":return this.finishNode(r,"StringTypeAnnotation");case"symbol":return this.finishNode(r,"SymbolTypeAnnotation");default:return this.checkNotUnderscore(s.name),this.flowParseGenericType(e,s)}}flowParsePrimaryType(){let e=this.state.startLoc,r=this.startNode(),s,i,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,i=this.flowParseTupleType(),this.state.noAnonFunctionType=o,i;case 47:{let d=this.startNode();return d.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(10),s=this.flowParseFunctionTypeParams(),d.params=s.params,d.rest=s.rest,d.this=s._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(ie(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,i=this.flowParseType(),this.state.noAnonFunctionType=o,this.state.noAnonFunctionType||!(this.match(12)||this.match(11)&&this.lookahead().type===19))return this.expect(11),i;this.eat(12)}return i?s=this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(i)]):s=this.flowParseFunctionTypeParams(),d.params=s.params,d.rest=s.rest,d.this=s._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 r.value=this.match(85),this.next(),this.finishNode(r,"BooleanLiteralTypeAnnotation");case 53:if(this.state.value==="-"){if(this.next(),this.match(135))return this.parseLiteralAtNode(-this.state.value,"NumberLiteralTypeAnnotation",r);if(this.match(136))return this.parseLiteralAtNode(-this.state.value,"BigIntLiteralTypeAnnotation",r);throw this.raise(H.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(r,"VoidTypeAnnotation");case 84:return this.next(),this.finishNode(r,"NullLiteralTypeAnnotation");case 78:return this.next(),this.finishNode(r,"ThisTypeAnnotation");case 55:return this.next(),this.finishNode(r,"ExistsTypeAnnotation");case 87:return this.flowParseTypeofType();default:if(Yd(this.state.type)){let d=Vt(this.state.type);return this.next(),super.createIdentifier(r,d)}else if(ie(this.state.type))return this.isContextual(129)?this.flowParseInterfaceType():this.flowIdentToTypeAnnotation(e,r,this.parseIdentifier())}throw this.unexpected()}flowParsePostfixType(){let e=this.state.startLoc,r=this.flowParsePrimaryType(),s=!1;for(;(this.match(0)||this.match(18))&&!this.canInsertSemicolon();){let i=this.startNodeAt(e),a=this.eat(18);s=s||a,this.expect(0),!a&&this.match(3)?(i.elementType=r,this.next(),r=this.finishNode(i,"ArrayTypeAnnotation")):(i.objectType=r,i.indexType=this.flowParseType(),this.expect(3),s?(i.optional=a,r=this.finishNode(i,"OptionalIndexedAccessType")):r=this.finishNode(i,"IndexedAccessType"))}return r}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 r=this.startNodeAt(e.loc.start);return r.params=[this.reinterpretTypeAsFunctionTypeParam(e)],r.rest=null,r.this=null,r.returnType=this.flowParseType(),r.typeParameters=null,this.finishNode(r,"FunctionTypeAnnotation")}return e}flowParseIntersectionType(){let e=this.startNode();this.eat(45);let r=this.flowParseAnonFunctionWithoutParens();for(e.types=[r];this.eat(45);)e.types.push(this.flowParseAnonFunctionWithoutParens());return e.types.length===1?r:this.finishNode(e,"IntersectionTypeAnnotation")}flowParseUnionType(){let e=this.startNode();this.eat(43);let r=this.flowParseIntersectionType();for(e.types=[r];this.eat(43);)e.types.push(this.flowParseIntersectionType());return e.types.length===1?r:this.finishNode(e,"UnionTypeAnnotation")}flowParseType(){let e=this.state.inType;this.state.inType=!0;let r=this.flowParseUnionType();return this.state.inType=e,r}flowParseTypeOrImplicitInstantiation(){if(this.state.type===132&&this.state.value==="_"){let e=this.state.startLoc,r=this.parseIdentifier();return this.flowParseGenericType(e,r)}else return this.flowParseType()}flowParseTypeAnnotation(){let e=this.startNode();return e.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(e,"TypeAnnotation")}flowParseTypeAnnotatableIdentifier(){let e=this.startNode(),r=this.parseIdentifierName();return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),this.createIdentifier(e,r)}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,r,s=!1){if(r){this.forwardNoArrowParamsConversionAt(e,()=>super.parseFunctionBody(e,!0,s));return}super.parseFunctionBody(e,!1,s)}parseFunctionBodyAndFinish(e,r,s=!1){if(this.match(14)){let i=this.startNode();[i.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),e.returnType=i.typeAnnotation?this.finishNode(i,"TypeAnnotation"):null}return super.parseFunctionBodyAndFinish(e,r,s)}parseStatementLike(e){if(this.state.strict&&this.isContextual(129)){let s=this.lookahead();if(at(s.type)){let i=this.startNode();return this.next(),this.flowParseInterface(i)}}else if(this.isContextual(126)){let s=this.startNode();return this.next(),this.flowParseEnumDeclaration(s)}let r=super.parseStatementLike(e);return this.flowPragma===void 0&&!this.isValidDirective(r)&&(this.flowPragma=null),r}parseExpressionStatement(e,r,s){if(r.type==="Identifier"){if(r.name==="declare"){if(this.match(80)||ie(this.state.type)||this.match(68)||this.match(74)||this.match(82))return this.flowParseDeclare(e)}else if(ie(this.state.type)){if(r.name==="interface")return this.flowParseInterface(e);if(r.name==="type")return this.flowParseTypeAlias(e);if(r.name==="opaque")return this.flowParseOpaqueType(e,!1)}}return super.parseExpressionStatement(e,r,s)}shouldParseExportDeclaration(){let{type:e}=this.state;return e===126||nh(e)?!this.state.containsEsc:super.shouldParseExportDeclaration()}isExportDefaultSpecifier(){let{type:e}=this.state;return e===126||nh(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,r,s){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(s),e}this.expect(17);let i=this.state.clone(),a=this.state.noArrowAt,o=this.startNodeAt(r),{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=i,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(H.AmbiguousConditionalArrow,i.startLoc),c&&l.length===1&&(this.state=i,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(),r=!this.match(14);return this.state.noArrowParamsConversionAt.pop(),{consequent:e,failed:r}}getArrowLikeExpressions(e,r){let s=[e],i=[];for(;s.length!==0;){let a=s.pop();a.type==="ArrowFunctionExpression"?(a.typeParameters||!a.returnType?this.finishArrowValidation(a):i.push(a),a.body.type!=="BlockStatement"&&s.push(a.body)):a.type==="ConditionalExpression"&&(s.push(a.consequent),s.push(a.alternate))}return r?(i.forEach(a=>this.finishArrowValidation(a)),[i,[]]):nI(i,a=>a.params.every(o=>this.isAssignable(o,!0)))}finishArrowValidation(e){var r;this.toAssignableList(e.params,(r=e.extra)==null?void 0:r.trailingCommaLoc,!1),this.scope.enter(518),super.checkParams(e,!1,!0),this.scope.exit()}forwardNoArrowParamsConversionAt(e,r){let s;return this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))?(this.state.noArrowParamsConversionAt.push(this.state.start),s=r(),this.state.noArrowParamsConversionAt.pop()):s=r(),s}parseParenItem(e,r){let s=super.parseParenItem(e,r);if(this.eat(17)&&(s.optional=!0,this.resetEndLocation(e)),this.match(14)){let i=this.startNodeAt(r);return i.expression=s,i.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(i,"TypeCastExpression")}return s}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 r=this.startNode();return this.next(),this.match(5)?(e.specifiers=this.parseExportSpecifiers(!0),super.parseExportFrom(e),null):this.flowParseTypeAlias(r)}else if(this.isContextual(131)){e.exportKind="type";let r=this.startNode();return this.next(),this.flowParseOpaqueType(r,!1)}else if(this.isContextual(129)){e.exportKind="type";let r=this.startNode();return this.next(),this.flowParseInterface(r)}else if(this.isContextual(126)){e.exportKind="value";let r=this.startNode();return this.next(),this.flowParseEnumDeclaration(r)}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:r}=this.state,s=super.maybeParseExportNamespaceSpecifier(e);return s&&e.exportKind==="type"&&this.unexpected(r),s}parseClassId(e,r,s){super.parseClassId(e,r,s),this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration())}parseClassMember(e,r,s){let{startLoc:i}=this.state;if(this.isContextual(125)){if(super.parseClassMemberFromModifier(e,r))return;r.declare=!0}super.parseClassMember(e,r,s),r.declare&&(r.type!=="ClassProperty"&&r.type!=="ClassPrivateProperty"&&r.type!=="PropertyDefinition"?this.raise(H.DeclareClassElement,i):r.value&&this.raise(H.DeclareClassFieldInitializer,r.value))}isIterator(e){return e==="iterator"||e==="asyncIterator"}readIterator(){let e=super.readWord1(),r="@@"+e;(!this.isIterator(e)||!this.state.inType)&&this.raise(b.InvalidIdentifier,this.state.curPosition(),{identifierName:r}),this.finishToken(132,r)}getTokenFromCode(e){let r=this.input.charCodeAt(this.state.pos+1);e===123&&r===124?this.finishOp(6,2):this.state.inType&&(e===62||e===60)?this.finishOp(e===62?48:47,1):this.state.inType&&e===63?r===46?this.finishOp(18,2):this.finishOp(17,1):XR(e,r,this.input.charCodeAt(this.state.pos+2))?(this.state.pos+=2,this.readIterator()):super.getTokenFromCode(e)}isAssignable(e,r){return e.type==="TypeCastExpression"?this.isAssignable(e.expression,r):super.isAssignable(e,r)}toAssignable(e,r=!1){!r&&e.type==="AssignmentExpression"&&e.left.type==="TypeCastExpression"&&(e.left=this.typeCastToParameter(e.left)),super.toAssignable(e,r)}toAssignableList(e,r,s){for(let i=0;i<e.length;i++){let a=e[i];a?.type==="TypeCastExpression"&&(e[i]=this.typeCastToParameter(a))}super.toAssignableList(e,r,s)}toReferencedList(e,r){for(let i=0;i<e.length;i++){var s;let a=e[i];a&&a.type==="TypeCastExpression"&&!((s=a.extra)!=null&&s.parenthesized)&&(e.length>1||!r)&&this.raise(H.TypeCastInPattern,a.typeAnnotation)}return e}parseArrayLike(e,r,s){let i=super.parseArrayLike(e,r,s);return s!=null&&!this.state.maybeInArrowParameters&&this.toReferencedList(i.elements),i}isValidLVal(e,r,s,i){return e==="TypeCastExpression"||super.isValidLVal(e,r,s,i)}parseClassProperty(e){return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassProperty(e)}parseClassPrivateProperty(e){return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassPrivateProperty(e)}isClassMethod(){return this.match(47)||super.isClassMethod()}isClassProperty(){return this.match(14)||super.isClassProperty()}isNonstaticConstructor(e){return!this.match(14)&&super.isNonstaticConstructor(e)}pushClassMethod(e,r,s,i,a,o){if(r.variance&&this.unexpected(r.variance.loc.start),delete r.variance,this.match(47)&&(r.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassMethod(e,r,s,i,a,o),r.params&&a){let d=r.params;d.length>0&&this.isThisParam(d[0])&&this.raise(H.ThisParamBannedInConstructor,r)}else if(r.type==="MethodDefinition"&&a&&r.value.params){let d=r.value.params;d.length>0&&this.isThisParam(d[0])&&this.raise(H.ThisParamBannedInConstructor,r)}}pushClassPrivateMethod(e,r,s,i){r.variance&&this.unexpected(r.variance.loc.start),delete r.variance,this.match(47)&&(r.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassPrivateMethod(e,r,s,i)}parseClassSuper(e){if(super.parseClassSuper(e),e.superClass&&(this.match(47)||this.match(51))&&(e.superTypeParameters=this.flowParseTypeParameterInstantiationInExpression()),this.isContextual(113)){this.next();let r=e.implements=[];do{let s=this.startNode();s.id=this.flowParseRestrictedIdentifier(!0),this.match(47)?s.typeParameters=this.flowParseTypeParameterInstantiation():s.typeParameters=null,r.push(this.finishNode(s,"ClassImplements"))}while(this.eat(12))}}checkGetterSetterParams(e){super.checkGetterSetterParams(e);let r=this.getObjectOrClassMethodParams(e);if(r.length>0){let s=r[0];this.isThisParam(s)&&e.kind==="get"?this.raise(H.GetterMayNotHaveThisParam,s):this.isThisParam(s)&&this.raise(H.SetterMayNotHaveThisParam,s)}}parsePropertyNamePrefixOperator(e){e.variance=this.flowParseVariance()}parseObjPropValue(e,r,s,i,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,r,s,i,a,o,d);return c&&((l.value||l).typeParameters=c),l}parseFunctionParamType(e){return this.eat(17)&&(e.type!=="Identifier"&&this.raise(H.PatternIsOptional,e),this.isThisParam(e)&&this.raise(H.ThisParamMayNotBeOptional,e),e.optional=!0),this.match(14)?e.typeAnnotation=this.flowParseTypeAnnotation():this.isThisParam(e)&&this.raise(H.ThisParamAnnotationRequired,e),this.match(29)&&this.isThisParam(e)&&this.raise(H.ThisParamNoDefault,e),this.resetEndLocation(e),e}parseMaybeDefault(e,r){let s=super.parseMaybeDefault(e,r);return s.type==="AssignmentPattern"&&s.typeAnnotation&&s.right.start<s.typeAnnotation.start&&this.raise(H.TypeBeforeInitializer,s.typeAnnotation),s}checkImportReflection(e){super.checkImportReflection(e),e.module&&e.importKind!=="value"&&this.raise(H.ImportReflectionHasImportType,e.specifiers[0].loc.start)}parseImportSpecifierLocal(e,r,s){r.local=rh(e)?this.flowParseRestrictedIdentifier(!0,!0):this.parseIdentifier(),e.specifiers.push(this.finishImportSpecifier(r,s))}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return!0;if(this.isContextual(130)){if(!e)return!0;let r=this.lookaheadCharCode();return r===123||r===42}return!e&&this.isContextual(87)}applyImportPhase(e,r,s,i){if(super.applyImportPhase(e,r,s,i),r){if(!s&&this.match(65))return;e.exportKind=s==="type"?s:"value"}else s==="type"&&this.match(55)&&this.unexpected(),e.importKind=s==="type"||s==="typeof"?s:"value"}parseImportSpecifier(e,r,s,i,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&&!at(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&&at(this.state.type))e.imported=this.parseIdentifier(!0),e.importKind=d;else{if(r)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=rh(e);return s&&l&&this.raise(H.ImportTypeShorthandOnlyInPureImport,e),(s||l)&&this.checkReservedType(e.local.name,e.local.loc.start,!0),c&&!s&&!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,r){let s=e.kind;s!=="get"&&s!=="set"&&this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),super.parseFunctionParams(e,r)}parseVarId(e,r){super.parseVarId(e,r),this.match(14)&&(e.id.typeAnnotation=this.flowParseTypeAnnotation(),this.resetEndLocation(e.id))}parseAsyncArrowFromCallExpression(e,r){if(this.match(14)){let s=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0,e.returnType=this.flowParseTypeAnnotation(),this.state.noAnonFunctionType=s}return super.parseAsyncArrowFromCallExpression(e,r)}shouldParseAsyncArrow(){return this.match(14)||super.shouldParseAsyncArrow()}parseMaybeAssign(e,r){var s;let i=null,a;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){if(i=this.state.clone(),a=this.tryParse(()=>super.parseMaybeAssign(e,r),i),!a.error)return a.node;let{context:c}=this.state,l=c[c.length-1];(l===se.j_oTag||l===se.j_expr)&&c.pop()}if((s=a)!=null&&s.error||this.match(47)){var o,d;i=i||this.state.clone();let c,l=this.tryParse(p=>{var f;c=this.flowParseTypeParameterDeclaration();let h=this.forwardNoArrowParamsConversionAt(c,()=>{let g=super.parseMaybeAssign(e,r);return this.resetStartLocationFromNode(g,c),g});(f=h.extra)!=null&&f.parenthesized&&p();let m=this.maybeUnwrapTypeCastExpression(h);return m.type!=="ArrowFunctionExpression"&&p(),m.typeParameters=c,this.resetStartLocationFromNode(m,c),h},i),u=null;if(l.node&&this.maybeUnwrapTypeCastExpression(l.node).type==="ArrowFunctionExpression"){if(!l.error&&!l.aborted)return l.node.async&&this.raise(H.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(H.UnexpectedTokenAfterTypeParameter,c)}return super.parseMaybeAssign(e,r)}parseArrow(e){if(this.match(14)){let r=this.tryParse(()=>{let s=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0;let i=this.startNode();return[i.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),this.state.noAnonFunctionType=s,this.canInsertSemicolon()&&this.unexpected(),this.match(19)||this.unexpected(),i});if(r.thrown)return null;r.error&&(this.state=r.failState),e.returnType=r.node.typeAnnotation?this.finishNode(r.node,"TypeAnnotation"):null}return super.parseArrow(e)}shouldParseArrow(e){return this.match(14)||super.shouldParseArrow(e)}setArrowFunctionParameters(e,r){this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))?e.params=r:super.setArrowFunctionParameters(e,r)}checkParams(e,r,s,i=!0){if(!(s&&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(H.ThisParamMustBeFirst,e.params[a]);super.checkParams(e,r,s,i)}}parseParenAndDistinguishExpression(e){return super.parseParenAndDistinguishExpression(e&&!this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)))}parseSubscripts(e,r,s){if(e.type==="Identifier"&&e.name==="async"&&this.state.noArrowAt.includes(r.index)){this.next();let i=this.startNodeAt(r);i.callee=e,i.arguments=super.parseCallExpressionArguments(),e=this.finishNode(i,"CallExpression")}else if(e.type==="Identifier"&&e.name==="async"&&this.match(47)){let i=this.state.clone(),a=this.tryParse(d=>this.parseAsyncArrowWithTypeParameters(r)||d(),i);if(!a.error&&!a.aborted)return a.node;let o=this.tryParse(()=>super.parseSubscripts(e,r,s),i);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,r,s)}parseSubscript(e,r,s,i){if(this.match(18)&&this.isLookaheadToken_lt()){if(i.optionalChainMember=!0,s)return i.stop=!0,e;this.next();let a=this.startNodeAt(r);return a.callee=e,a.typeArguments=this.flowParseTypeParameterInstantiationInExpression(),this.expect(10),a.arguments=this.parseCallExpressionArguments(),a.optional=!0,this.finishCallExpression(a,!0)}else if(!s&&this.shouldParseTypes()&&(this.match(47)||this.match(51))){let a=this.startNodeAt(r);a.callee=e;let o=this.tryParse(()=>(a.typeArguments=this.flowParseTypeParameterInstantiationCallOrNew(),this.expect(10),a.arguments=super.parseCallExpressionArguments(),i.optionalChainMember&&(a.optional=!1),this.finishCallExpression(a,i.optionalChainMember)));if(o.node)return o.error&&(this.state=o.failState),o.node}return super.parseSubscript(e,r,s,i)}parseNewCallee(e){super.parseNewCallee(e);let r=null;this.shouldParseTypes()&&this.match(47)&&(r=this.tryParse(()=>this.flowParseTypeParameterInstantiationCallOrNew()).node),e.typeArguments=r}parseAsyncArrowWithTypeParameters(e){let r=this.startNodeAt(e);if(this.parseFunctionParams(r,!1),!!this.parseArrow(r))return super.parseArrowExpression(r,void 0,!0)}readToken_mult_modulo(e){let r=this.input.charCodeAt(this.state.pos+1);if(e===42&&r===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 r=this.input.charCodeAt(this.state.pos+1);if(e===124&&r===125){this.finishOp(9,2);return}super.readToken_pipe_amp(e)}parseTopLevel(e,r){let s=super.parseTopLevel(e,r);return this.state.hasFlowComment&&this.raise(H.UnterminatedFlowComment,this.state.curPosition()),s}skipBlockComment(){if(this.hasPlugin("flowComments")&&this.skipFlowComment()){if(this.state.hasFlowComment)throw this.raise(H.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,r=2;for(;[32,9].includes(this.input.charCodeAt(e+r));)r++;let s=this.input.charCodeAt(r+e),i=this.input.charCodeAt(r+e+1);return s===58&&i===58?r+2:this.input.slice(r+e,r+e+12)==="flow-include"?r+12:s===58&&i!==58?r:!1}hasFlowCommentCompletion(){if(this.input.indexOf("*/",this.state.pos)===-1)throw this.raise(b.UnterminatedComment,this.state.curPosition())}flowEnumErrorBooleanMemberNotInitialized(e,{enumName:r,memberName:s}){this.raise(H.EnumBooleanMemberNotInitialized,e,{memberName:s,enumName:r})}flowEnumErrorInvalidMemberInitializer(e,r){return this.raise(r.explicitType?r.explicitType==="symbol"?H.EnumInvalidMemberInitializerSymbolType:H.EnumInvalidMemberInitializerPrimaryType:H.EnumInvalidMemberInitializerUnknownType,e,r)}flowEnumErrorNumberMemberNotInitialized(e,r){this.raise(H.EnumNumberMemberNotInitialized,e,r)}flowEnumErrorStringMemberInconsistentlyInitialized(e,r){this.raise(H.EnumStringMemberInconsistentlyInitialized,e,r)}flowEnumMemberInit(){let e=this.state.startLoc,r=()=>this.match(12)||this.match(8);switch(this.state.type){case 135:{let s=this.parseNumericLiteral(this.state.value);return r()?{type:"number",loc:s.loc.start,value:s}:{type:"invalid",loc:e}}case 134:{let s=this.parseStringLiteral(this.state.value);return r()?{type:"string",loc:s.loc.start,value:s}:{type:"invalid",loc:e}}case 85:case 86:{let s=this.parseBooleanLiteral(this.match(85));return r()?{type:"boolean",loc:s.loc.start,value:s}:{type:"invalid",loc:e}}default:return{type:"invalid",loc:e}}}flowEnumMemberRaw(){let e=this.state.startLoc,r=this.parseIdentifier(!0),s=this.eat(29)?this.flowEnumMemberInit():{type:"none",loc:e};return{id:r,init:s}}flowEnumCheckExplicitTypeMismatch(e,r,s){let{explicitType:i}=r;i!==null&&i!==s&&this.flowEnumErrorInvalidMemberInitializer(e,r)}flowEnumMembers({enumName:e,explicitType:r}){let s=new Set,i={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(H.EnumInvalidMemberName,d,{memberName:l,suggestion:l[0].toUpperCase()+l.slice(1),enumName:e}),s.has(l)&&this.raise(H.EnumDuplicateMemberName,d,{memberName:l,enumName:e}),s.add(l);let u={enumName:e,explicitType:r,memberName:l};switch(o.id=d,c.type){case"boolean":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"boolean"),o.init=c.value,i.booleanMembers.push(this.finishNode(o,"EnumBooleanMember"));break}case"number":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"number"),o.init=c.value,i.numberMembers.push(this.finishNode(o,"EnumNumberMember"));break}case"string":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"string"),o.init=c.value,i.stringMembers.push(this.finishNode(o,"EnumStringMember"));break}case"invalid":throw this.flowEnumErrorInvalidMemberInitializer(c.loc,u);case"none":switch(r){case"boolean":this.flowEnumErrorBooleanMemberNotInitialized(c.loc,u);break;case"number":this.flowEnumErrorNumberMemberNotInitialized(c.loc,u);break;default:i.defaultedMembers.push(this.finishNode(o,"EnumDefaultedMember"))}}this.match(8)||this.expect(12)}return{members:i,hasUnknownMembers:a}}flowEnumStringMembers(e,r,{enumName:s}){if(e.length===0)return r;if(r.length===0)return e;if(r.length>e.length){for(let i of e)this.flowEnumErrorStringMemberInconsistentlyInitialized(i,{enumName:s});return r}else{for(let i of r)this.flowEnumErrorStringMemberInconsistentlyInitialized(i,{enumName:s});return e}}flowEnumParseExplicitType({enumName:e}){if(!this.eatContextual(102))return null;if(!ie(this.state.type))throw this.raise(H.EnumInvalidExplicitTypeUnknownSupplied,this.state.startLoc,{enumName:e});let{value:r}=this.state;return this.next(),r!=="boolean"&&r!=="number"&&r!=="string"&&r!=="symbol"&&this.raise(H.EnumInvalidExplicitType,this.state.startLoc,{enumName:e,invalidEnumType:r}),r}flowEnumBody(e,r){let s=r.name,i=r.loc.start,a=this.flowEnumParseExplicitType({enumName:s});this.expect(5);let{members:o,hasUnknownMembers:d}=this.flowEnumMembers({enumName:s,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:s}),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:s}),this.expect(8),this.finishNode(e,"EnumStringBody");if(!u&&!p&&l>=f){for(let h of o.defaultedMembers)this.flowEnumErrorBooleanMemberNotInitialized(h.loc.start,{enumName:s,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:s,memberName:h.id.name});return e.members=o.numberMembers,this.expect(8),this.finishNode(e,"EnumNumberBody")}else return this.raise(H.EnumInconsistentMemberValues,i,{enumName:s}),c()}}}flowParseEnumDeclaration(e){let r=this.parseIdentifier();return e.id=r,e.body=this.flowEnumBody(this.startNode(),r),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 r=this.input.charCodeAt(e+1);return r!==60&&r!==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}},iI={__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"},aI=/\r\n|[\r\n\u2028\u2029]/,Ei=new RegExp(aI.source,"g");function Yn(t){switch(t){case 10:case 13:case 8232:case 8233:return!0;default:return!1}}function sh(t,n,e){for(let r=n;r<e;r++)if(Yn(t.charCodeAt(r)))return!0;return!1}var bd=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,xd=/(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;function oI(t){switch(t){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 mn=it`jsx`({AttributeIsEmpty:"JSX attributes must only be assigned a non-empty expression.",MissingClosingTagElement:({openingTagName:t})=>`Expected corresponding JSX closing tag for <${t}>.`,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:t,HTMLEntity:n})=>`Unexpected token \`${t}\`. Did you mean \`${n}\` or \`{'${t}'}\`?`,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 Bt(t){return t?t.type==="JSXOpeningFragment"||t.type==="JSXClosingFragment":!1}function Xn(t){if(t.type==="JSXIdentifier")return t.name;if(t.type==="JSXNamespacedName")return t.namespace.name+":"+t.name.name;if(t.type==="JSXMemberExpression")return Xn(t.object)+"."+Xn(t.property);throw new Error("Node had unexpected type: "+t.type)}var dI=t=>class extends t{jsxReadToken(){let e="",r=this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(mn.UnterminatedJsxContent,this.state.startLoc);let s=this.input.charCodeAt(this.state.pos);switch(s){case 60:case 123:if(this.state.pos===this.state.start){s===60&&this.state.canStartJSXElement?(++this.state.pos,this.finishToken(143)):super.getTokenFromCode(s);return}e+=this.input.slice(r,this.state.pos),this.finishToken(142,e);return;case 38:e+=this.input.slice(r,this.state.pos),e+=this.jsxReadEntity(),r=this.state.pos;break;default:Yn(s)?(e+=this.input.slice(r,this.state.pos),e+=this.jsxReadNewLine(!0),r=this.state.pos):++this.state.pos}}}jsxReadNewLine(e){let r=this.input.charCodeAt(this.state.pos),s;return++this.state.pos,r===13&&this.input.charCodeAt(this.state.pos)===10?(++this.state.pos,s=e?`
6
6
  `:`\r
7
- `):s=String.fromCharCode(r),++this.state.curLine,this.state.lineStart=this.state.pos,s}jsxReadString(e){let r="",s=++this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(b.UnterminatedString,this.state.startLoc);let i=this.input.charCodeAt(this.state.pos);if(i===e)break;i===38?(r+=this.input.slice(s,this.state.pos),r+=this.jsxReadEntity(),s=this.state.pos):Gn(i)?(r+=this.input.slice(s,this.state.pos),r+=this.jsxReadNewLine(!1),s=this.state.pos):++this.state.pos}r+=this.input.slice(s,this.state.pos++),this.finishToken(134,r)}jsxReadEntity(){let e=++this.state.pos;if(this.codePointAtPos(this.state.pos)===35){++this.state.pos;let r=10;this.codePointAtPos(this.state.pos)===120&&(r=16,++this.state.pos);let s=this.readInt(r,void 0,!1,"bail");if(s!==null&&this.codePointAtPos(this.state.pos)===59)return++this.state.pos,String.fromCodePoint(s)}else{let r=0,s=!1;for(;r++<10&&this.state.pos<this.length&&!(s=this.codePointAtPos(this.state.pos)===59);)++this.state.pos;if(s){let i=this.input.slice(e,this.state.pos),a=oR[i];if(++this.state.pos,a)return a}}return this.state.pos=e,"&"}jsxReadWord(){let e,r=this.state.pos;do e=this.input.charCodeAt(++this.state.pos);while(pn(e)||e===45);this.finishToken(141,this.input.slice(r,this.state.pos))}jsxParseIdentifier(){let e=this.startNode();return this.match(141)?e.name=this.state.value:jd(this.state.type)?e.name=Ft(this.state.type):this.unexpected(),this.next(),this.finishNode(e,"JSXIdentifier")}jsxParseNamespacedName(){let e=this.state.startLoc,r=this.jsxParseIdentifier();if(!this.eat(14))return r;let s=this.startNodeAt(e);return s.namespace=r,s.name=this.jsxParseIdentifier(),this.finishNode(s,"JSXNamespacedName")}jsxParseElementName(){let e=this.state.startLoc,r=this.jsxParseNamespacedName();if(r.type==="JSXNamespacedName")return r;for(;this.eat(16);){let s=this.startNodeAt(e);s.object=r,s.property=this.jsxParseIdentifier(),r=this.finishNode(s,"JSXMemberExpression")}return r}jsxParseAttributeValue(){let e;switch(this.state.type){case 5:return e=this.startNode(),this.setContext(se.brace),this.next(),e=this.jsxParseExpressionContainer(e,se.j_oTag),e.expression.type==="JSXEmptyExpression"&&this.raise(ln.AttributeIsEmpty,e),e;case 143:case 134:return this.parseExprAtom();default:throw this.raise(ln.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(se.j_expr),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXSpreadChild")}jsxParseExpressionContainer(e,r){if(this.match(8))e.expression=this.jsxParseEmptyExpression();else{let s=this.parseExpression();e.expression=s}return this.setContext(r),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXExpressionContainer")}jsxParseAttribute(){let e=this.startNode();return this.match(5)?(this.setContext(se.brace),this.next(),this.expect(21),e.argument=this.parseMaybeAssignAllowIn(),this.setContext(se.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 r=this.startNodeAt(e);return this.eat(144)?this.finishNode(r,"JSXOpeningFragment"):(r.name=this.jsxParseElementName(),this.jsxParseOpeningElementAfterName(r))}jsxParseOpeningElementAfterName(e){let r=[];for(;!this.match(56)&&!this.match(144);)r.push(this.jsxParseAttribute());return e.attributes=r,e.selfClosing=this.eat(56),this.expect(144),this.finishNode(e,"JSXOpeningElement")}jsxParseClosingElementAt(e){let r=this.startNodeAt(e);return this.eat(144)?this.finishNode(r,"JSXClosingFragment"):(r.name=this.jsxParseElementName(),this.expect(144),this.finishNode(r,"JSXClosingElement"))}jsxParseElementAt(e){let r=this.startNodeAt(e),s=[],i=this.jsxParseOpeningElementAt(e),a=null;if(!i.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}s.push(this.jsxParseElementAt(e));break;case 142:s.push(this.parseLiteral(this.state.value,"JSXText"));break;case 5:{let o=this.startNode();this.setContext(se.brace),this.next(),this.match(21)?s.push(this.jsxParseSpreadChild(o)):s.push(this.jsxParseExpressionContainer(o,se.j_expr));break}default:this.unexpected()}jt(i)&&!jt(a)&&a!==null?this.raise(ln.MissingClosingTagFragment,a):!jt(i)&&jt(a)?this.raise(ln.MissingClosingTagElement,a,{openingTagName:qn(i.name)}):!jt(i)&&!jt(a)&&qn(a.name)!==qn(i.name)&&this.raise(ln.MissingClosingTagElement,a,{openingTagName:qn(i.name)})}if(jt(i)?(r.openingFragment=i,r.closingFragment=a):(r.openingElement=i,r.closingElement=a),r.children=s,this.match(47))throw this.raise(ln.UnwrappedAdjacentJSXElements,this.state.startLoc);return jt(i)?this.finishNode(r,"JSXFragment"):this.finishNode(r,"JSXElement")}jsxParseElement(){let e=this.state.startLoc;return this.next(),this.jsxParseElementAt(e)}setContext(e){let{context:r}=this.state;r[r.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 r=this.curContext();if(r===se.j_expr){this.jsxReadToken();return}if(r===se.j_oTag||r===se.j_cTag){if(mt(e)){this.jsxReadWord();return}if(e===62){++this.state.pos,this.finishToken(144);return}if((e===34||e===39)&&r===se.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:r,type:s}=this.state;if(s===56&&e===143)r.splice(-2,2,se.j_cTag),this.state.canStartJSXElement=!1;else if(s===143)r.push(se.j_oTag);else if(s===144){let i=r[r.length-1];i===se.j_oTag&&e===56||i===se.j_cTag?(r.pop(),this.state.canStartJSXElement=r[r.length-1]===se.j_expr):(this.setContext(se.j_expr),this.state.canStartJSXElement=!0)}else this.state.canStartJSXElement=Lk(s)}},hd=class extends Wr{constructor(...t){super(...t),this.tsNames=new Map}},md=class extends Jr{constructor(...t){super(...t),this.importsStack=[]}createScope(t){return this.importsStack.push(new Set),new hd(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 r=this.importsStack.length;if(this.importsStack[r-1].has(t))return!0;if(!e&&r>1){for(let s=0;s<r-1;s++)if(this.importsStack[s].has(t))return!0}return!1}declareName(t,e,r){if(e&4096){this.hasImport(t,!0)&&this.parser.raise(b.VarRedeclaration,r,{identifierName:t}),this.importsStack[this.importsStack.length-1].add(t);return}let s=this.currentScope(),i=s.tsNames.get(t)||0;if(e&1024){this.maybeExportDefined(s,t),s.tsNames.set(t,i|16);return}super.declareName(t,e,r),e&2&&(e&1||(this.checkRedeclarationInScope(s,t,e,r),this.maybeExportDefined(s,t)),i=i|1),e&256&&(i=i|2),e&512&&(i=i|4),e&128&&(i=i|8),i&&s.tsNames.set(t,i)}isRedeclaredInScope(t,e,r){let s=t.tsNames.get(e);if((s&2)>0){if(r&256){let i=!!(r&512),a=(s&4)>0;return i!==a}return!0}return r&128&&(s&8)>0?t.names.get(e)&2?!!(r&1):!1:r&2&&(s&1)>0?!0:super.isRedeclaredInScope(t,e,r)}checkLocalExport(t){let{name:e}=t;if(this.hasImport(e))return;let r=this.scopeStack.length;for(let s=r-1;s>=0;s--){let a=this.scopeStack[s].tsNames.get(e);if((a&1)>0||(a&16)>0)return}super.checkLocalExport(t)}},yd=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 Ci(n,t){return(n?2:0)|(t?1:0)}var gd=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,r]=t;if(!this.hasPlugin(e))return!1;let s=this.plugins.get(e);for(let i of Object.keys(r))if(s?.[i]!==r[i])return!1;return!0}}getPluginOption(t,e){var r;return(r=this.plugins.get(t))==null?void 0:r[e]}};function Hf(n,t){n.trailingComments===void 0?n.trailingComments=t:n.trailingComments.unshift(...t)}function uR(n,t){n.leadingComments===void 0?n.leadingComments=t:n.leadingComments.unshift(...t)}function Xr(n,t){n.innerComments===void 0?n.innerComments=t:n.innerComments.unshift(...t)}function rt(n,t,e){let r=null,s=t.length;for(;r===null&&s>0;)r=t[--s];r===null||r.start>e.start?Xr(n,e.comments):Hf(r,e.comments)}var wd=class extends gd{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,r=e.length;if(r===0)return;let s=r-1,i=e[s];i.start===t.end&&(i.leadingNode=t,s--);let{start:a}=t;for(;s>=0;s--){let o=e[s],d=o.end;if(d>a)o.containingNode=t,this.finalizeComment(o),e.splice(s,1);else{d===a&&(o.trailingNode=t);break}}}finalizeComment(t){var e;let{comments:r}=t;if(t.leadingNode!==null||t.trailingNode!==null)t.leadingNode!==null&&Hf(t.leadingNode,r),t.trailingNode!==null&&uR(t.trailingNode,r);else{let s=t.containingNode,i=t.start;if(this.input.charCodeAt(this.offsetToSourcePos(i)-1)===44)switch(s.type){case"ObjectExpression":case"ObjectPattern":rt(s,s.properties,t);break;case"CallExpression":case"NewExpression":case"OptionalCallExpression":rt(s,s.arguments,t);break;case"ImportExpression":rt(s,[s.source,(e=s.options)!=null?e:null],t);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":case"ObjectMethod":case"ClassMethod":case"ClassPrivateMethod":case"TSTypeParameterDeclaration":rt(s,s.params,t);break;case"ArrayExpression":case"ArrayPattern":rt(s,s.elements,t);break;case"ExportNamedDeclaration":case"ImportDeclaration":rt(s,s.specifiers,t);break;case"TSEnumDeclaration":rt(s,s.members,t);break;case"TSEnumBody":rt(s,s.members,t);break;case"TSInterfaceBody":rt(s,s.body,t);break;default:{if(s.type==="RecordExpression"){rt(s,s.properties,t);break}if(s.type==="TupleExpression"){rt(s,s.elements,t);break}Xr(s,r)}}else Xr(s,r)}}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:r}=e;if(r===0)return;let s=e[r-1];s.leadingNode===t&&(s.leadingNode=null)}takeSurroundingComments(t,e,r){let{commentStack:s}=this.state,i=s.length;if(i===0)return;let a=i-1;for(;a>=0;a--){let o=s[a],d=o.end;if(o.start===r)o.leadingNode=t;else if(d===e)o.trailingNode=t;else if(d<e)break}}},bd=class n{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=[se.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:r,startLine:s,startColumn:i}){this.strict=t===!1?!1:t===!0?!0:e==="module",this.startIndex=r,this.curLine=s,this.lineStart=-i,this.startLoc=this.endLoc=new yt(s,i,r)}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 yt(this.curLine,this.pos-this.lineStart,this.pos+this.startIndex)}clone(){let t=new n;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}},pR=function(t){return t>=48&&t<=57},Sf={decBinOct:new Set([46,66,69,79,95,98,101,111]),hex:new Set([46,88,95,120])},Si={bin:n=>n===48||n===49,oct:n=>n>=48&&n<=55,dec:n=>n>=48&&n<=57,hex:n=>n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102};function Tf(n,t,e,r,s,i){let a=e,o=r,d=s,c="",l=null,u=e,{length:p}=t;for(;;){if(e>=p){i.unterminated(a,o,d),c+=t.slice(u,e);break}let f=t.charCodeAt(e);if(fR(n,f,t,e)){c+=t.slice(u,e);break}if(f===92){c+=t.slice(u,e);let h=hR(t,e,r,s,n==="template",i);h.ch===null&&!l?l={pos:e,lineStart:r,curLine:s}:c+=h.ch,{pos:e,lineStart:r,curLine:s}=h,u=e}else f===8232||f===8233?(++e,++s,r=e):f===10||f===13?n==="template"?(c+=t.slice(u,e)+`
8
- `,++e,f===13&&t.charCodeAt(e)===10&&++e,++s,u=r=e):i.unterminated(a,o,d):++e}return{pos:e,str:c,firstInvalidLoc:l,lineStart:r,curLine:s,containsInvalid:!!l}}function fR(n,t,e,r){return n==="template"?t===96||t===36&&e.charCodeAt(r+1)===123:t===(n==="double"?34:39)}function hR(n,t,e,r,s,i){let a=!s;t++;let o=c=>({pos:t,ch:c,lineStart:e,curLine:r}),d=n.charCodeAt(t++);switch(d){case 110:return o(`
9
- `);case 114:return o("\r");case 120:{let c;return{code:c,pos:t}=xd(n,t,e,r,2,!1,a,i),o(c===null?null:String.fromCharCode(c))}case 117:{let c;return{code:c,pos:t}=Uf(n,t,e,r,a,i),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:n.charCodeAt(t)===10&&++t;case 10:e=t,++r;case 8232:case 8233:return o("");case 56:case 57:if(s)return o(null);i.strictNumericEscape(t-1,e,r);default:if(d>=48&&d<=55){let c=t-1,u=/^[0-7]+/.exec(n.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=n.charCodeAt(t);if(u!=="0"||f===56||f===57){if(s)return o(null);i.strictNumericEscape(c,e,r)}return o(String.fromCharCode(p))}return o(String.fromCharCode(d))}}function xd(n,t,e,r,s,i,a,o){let d=t,c;return{n:c,pos:t}=zf(n,t,e,r,16,s,i,!1,o,!a),c===null&&(a?o.invalidEscapeSequence(d,e,r):t=d-1),{code:c,pos:t}}function zf(n,t,e,r,s,i,a,o,d,c){let l=t,u=s===16?Sf.hex:Sf.decBinOct,p=s===16?Si.hex:s===10?Si.dec:s===8?Si.oct:Si.bin,f=!1,h=0;for(let m=0,g=i??1/0;m<g;++m){let y=n.charCodeAt(t),w;if(y===95&&o!=="bail"){let v=n.charCodeAt(t-1),x=n.charCodeAt(t+1);if(o){if(Number.isNaN(x)||!p(x)||u.has(v)||u.has(x)){if(c)return{n:null,pos:t};d.unexpectedNumericSeparator(t,e,r)}}else{if(c)return{n:null,pos:t};d.numericSeparatorInEscapeSequence(t,e,r)}++t;continue}if(y>=97?w=y-97+10:y>=65?w=y-65+10:pR(y)?w=y-48:w=1/0,w>=s){if(w<=9&&c)return{n:null,pos:t};if(w<=9&&d.invalidDigit(t,e,r,s))w=0;else if(a)w=0,f=!0;else break}++t,h=h*s+w}return t===l||i!=null&&t-l!==i||f?{n:null,pos:t}:{n:h,pos:t}}function Uf(n,t,e,r,s,i){let a=n.charCodeAt(t),o;if(a===123){if(++t,{code:o,pos:t}=xd(n,t,e,r,n.indexOf("}",t)-t,!0,s,i),++t,o!==null&&o>1114111)if(s)i.invalidCodePoint(t,e,r);else return{code:null,pos:t}}else({code:o,pos:t}=xd(n,t,e,r,4,!1,s,i));return{code:o,pos:t}}function Ur(n,t,e){return new yt(e,n-t,n)}var mR=new Set([103,109,115,105,121,117,100,118]),ht=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 Wn(t.startLoc,t.endLoc)}},vd=class extends wd{constructor(t,e){super(),this.isLookahead=void 0,this.tokens=[],this.errorHandlers_readInt={invalidDigit:(r,s,i,a)=>this.optionFlags&2048?(this.raise(b.InvalidDigit,Ur(r,s,i),{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:(r,s,i)=>{this.recordStrictModeErrors(b.StrictNumericEscape,Ur(r,s,i))},unterminated:(r,s,i)=>{throw this.raise(b.UnterminatedString,Ur(r-1,s,i))}}),this.errorHandlers_readStringContents_template=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:this.errorBuilder(b.StrictNumericEscape),unterminated:(r,s,i)=>{throw this.raise(b.UnterminatedTemplate,Ur(r,s,i))}}),this.state=new bd,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 ht(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 ad.lastIndex=t,ad.test(this.input)?ad.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 od.lastIndex=t,od.test(this.input)?od.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 r=this.input.charCodeAt(t);(r&64512)===56320&&(e=65536+((e&1023)<<10)+(r&1023))}return e}setStrict(t){this.state.strict=t,t&&(this.state.strictErrors.forEach(([e,r])=>this.raise(e,r)),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 r=this.state.pos,s=this.input.indexOf(t,r+2);if(s===-1)throw this.raise(b.UnterminatedComment,this.state.curPosition());for(this.state.pos=s+t.length,Pi.lastIndex=r+2;Pi.test(this.input)&&Pi.lastIndex<=s;)++this.state.curLine,this.state.lineStart=Pi.lastIndex;if(this.isLookahead)return;let i={type:"CommentBlock",value:this.input.slice(r+2,s),start:this.sourceToOffsetPos(r),end:this.sourceToOffsetPos(s+t.length),loc:new Wn(e,this.state.curPosition())};return this.optionFlags&256&&this.pushToken(i),i}skipLineComment(t){let e=this.state.pos,r;this.isLookahead||(r=this.state.curPosition());let s=this.input.charCodeAt(this.state.pos+=t);if(this.state.pos<this.length)for(;!Gn(s)&&++this.state.pos<this.length;)s=this.input.charCodeAt(this.state.pos);if(this.isLookahead)return;let i=this.state.pos,o={type:"CommentLine",value:this.input.slice(e+t,i),start:this.sourceToOffsetPos(e),end:this.sourceToOffsetPos(i),loc:new Wn(r,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 r=this.input.charCodeAt(this.state.pos);switch(r){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 s=this.skipBlockComment("*/");s!==void 0&&(this.addComment(s),e?.push(s));break}case 47:{let s=this.skipLineComment(2);s!==void 0&&(this.addComment(s),e?.push(s));break}default:break e}break;default:if(cR(r))++this.state.pos;else if(r===45&&!this.inModule&&this.optionFlags&8192){let s=this.state.pos;if(this.input.charCodeAt(s+1)===45&&this.input.charCodeAt(s+2)===62&&(t===0||this.state.lineStart>t)){let i=this.skipLineComment(3);i!==void 0&&(this.addComment(i),e?.push(i))}else break e}else if(r===60&&!this.inModule&&this.optionFlags&8192){let s=this.state.pos;if(this.input.charCodeAt(s+1)===33&&this.input.charCodeAt(s+2)===45&&this.input.charCodeAt(s+3)===45){let i=this.skipLineComment(4);i!==void 0&&(this.addComment(i),e?.push(i))}else break e}else break e}}if(e?.length>0){let r=this.state.pos,s={start:this.sourceToOffsetPos(t),end:this.sourceToOffsetPos(r),comments:e,leadingNode:null,trailingNode:null,containingNode:null};this.state.commentStack.push(s)}}finishToken(t,e){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();let r=this.state.type;this.state.type=t,this.state.value=e,this.isLookahead||this.updateContext(r)}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 mt(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;!Gn(t)&&++this.state.pos<this.length;)t=this.input.charCodeAt(this.state.pos);let r=this.input.slice(e+2,this.state.pos);return this.finishToken(28,r),!0}readToken_mult_modulo(t){let e=t===42?55:54,r=1,s=this.input.charCodeAt(this.state.pos+1);t===42&&s===42&&(r++,s=this.input.charCodeAt(this.state.pos+2),e=57),s===61&&!this.state.inType&&(r++,e=t===37?33:30),this.finishOp(e,r)}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 r=this.input.charCodeAt(t+2)===62?3:2;if(this.input.charCodeAt(t+r)===61){this.finishOp(30,r+1);return}this.finishOp(52,r);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(mt(t)){this.readWord(t);return}}throw this.raise(b.InvalidOrUnexpectedToken,this.state.curPosition(),{unexpected:String.fromCodePoint(t)})}finishOp(t,e){let r=this.input.slice(this.state.pos,this.state.pos+e);this.state.pos+=e,this.finishToken(t,r)}readRegexp(){let t=this.state.startLoc,e=this.state.start+1,r,s,{pos:i}=this.state;for(;;++i){if(i>=this.length)throw this.raise(b.UnterminatedRegExp,Me(t,1));let c=this.input.charCodeAt(i);if(Gn(c))throw this.raise(b.UnterminatedRegExp,Me(t,1));if(r)r=!1;else{if(c===91)s=!0;else if(c===93&&s)s=!1;else if(c===47&&!s)break;r=c===92}}let a=this.input.slice(e,i);++i;let o="",d=()=>Me(t,i+2-e);for(;i<this.length;){let c=this.codePointAtPos(i),l=String.fromCharCode(c);if(mR.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(pn(c)||c===92)this.raise(b.MalformedRegExpFlags,d());else break;++i,o+=l}this.state.pos=i,this.finishToken(138,{pattern:a,flags:o})}readInt(t,e,r=!1,s=!0){let{n:i,pos:a}=zf(this.input,this.state.pos,this.state.lineStart,this.state.curLine,t,e,r,s,this.errorHandlers_readInt,!1);return this.state.pos=a,i}readRadixNumber(t){let e=this.state.pos,r=this.state.curPosition(),s=!1;this.state.pos+=2;let i=this.readInt(t);i==null&&this.raise(b.InvalidDigit,Me(r,2),{radix:t});let a=this.input.charCodeAt(this.state.pos);if(a===110)++this.state.pos,s=!0;else if(a===109)throw this.raise(b.InvalidDecimal,r);if(mt(this.codePointAtPos(this.state.pos)))throw this.raise(b.NumberIdentifier,this.state.curPosition());if(s){let o=this.input.slice(e,this.state.pos).replace(/[_n]/g,"");this.finishToken(136,o);return}this.finishToken(135,i)}readNumber(t){let e=this.state.pos,r=this.state.curPosition(),s=!1,i=!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,r),!this.state.strict){let h=f.indexOf("_");h>0&&this.raise(b.ZeroDigitNumericSeparator,Me(r,h))}o=d&&!/[89]/.test(f)}let c=this.input.charCodeAt(this.state.pos);if(c===46&&!o&&(++this.state.pos,this.readInt(10),s=!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,r),s=!0,a=!0,c=this.input.charCodeAt(this.state.pos)),c===110&&((s||d)&&this.raise(b.InvalidBigIntLiteral,r),++this.state.pos,i=!0),c===109){this.expectPlugin("decimal",this.state.curPosition()),(a||d)&&this.raise(b.InvalidDecimal,r),++this.state.pos;var l=!0}if(mt(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(i){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:r}=Uf(this.input,this.state.pos,this.state.lineStart,this.state.curLine,t,this.errorHandlers_readCodePoint);return this.state.pos=r,e}readString(t){let{str:e,pos:r,curLine:s,lineStart:i}=Tf(t===34?"double":"single",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_string);this.state.pos=r+1,this.state.lineStart=i,this.state.curLine=s,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:r,pos:s,curLine:i,lineStart:a}=Tf("template",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_template);this.state.pos=s+1,this.state.lineStart=a,this.state.curLine=i,r&&(this.state.firstInvalidTemplateEscapePos=new yt(r.curLine,r.pos-r.lineStart,this.sourceToOffsetPos(r.pos))),this.input.codePointAt(s)===96?this.finishToken(24,r?null:t+e+"`"):(this.state.pos++,this.finishToken(25,r?null:t+e+"${"))}recordStrictModeErrors(t,e){let r=e.index;this.state.strict&&!this.state.strictErrors.has(r)?this.raise(t,e):this.state.strictErrors.set(r,[t,e])}readWord1(t){this.state.containsEsc=!1;let e="",r=this.state.pos,s=this.state.pos;for(t!==void 0&&(this.state.pos+=t<=65535?1:2);this.state.pos<this.length;){let i=this.codePointAtPos(this.state.pos);if(pn(i))this.state.pos+=i<=65535?1:2;else if(i===92){this.state.containsEsc=!0,e+=this.input.slice(s,this.state.pos);let a=this.state.curPosition(),o=this.state.pos===r?mt:pn;if(this.input.charCodeAt(++this.state.pos)!==117){this.raise(b.MissingUnicodeEscape,this.state.curPosition()),s=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)),s=this.state.pos}else break}return e+this.input.slice(s,this.state.pos)}readWord(t){let e=this.readWord1(t),r=Od.get(e);r!==void 0?this.finishToken(r,Ft(r)):this.finishToken(132,e)}checkKeywordEscapes(){let{type:t}=this.state;jd(t)&&this.state.containsEsc&&this.raise(b.InvalidEscapedReservedWord,this.state.startLoc,{reservedWord:Ft(t)})}raise(t,e,r={}){let s=e instanceof yt?e:e.loc.start,i=t(s,r);if(!(this.optionFlags&2048))throw i;return this.isLookahead||this.state.errors.push(i),i}raiseOverwrite(t,e,r={}){let s=e instanceof yt?e:e.loc.start,i=s.index,a=this.state.errors;for(let o=a.length-1;o>=0;o--){let d=a[o];if(d.loc.index===i)return a[o]=t(s,r);if(d.loc.index<i)break}return this.raise(t,e,r)}updateContext(t){}unexpected(t,e){throw this.raise(b.UnexpectedToken,t??this.state.startLoc,{expected:e?Ft(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,r,s)=>{this.raise(t,Ur(e,r,s))}}},kd=class{constructor(){this.privateNames=new Set,this.loneAccessors=new Map,this.undefinedPrivateNames=new Map}},Rd=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 kd)}exit(){let t=this.stack.pop(),e=this.current();for(let[r,s]of Array.from(t.undefinedPrivateNames))e?e.undefinedPrivateNames.has(r)||e.undefinedPrivateNames.set(r,s):this.parser.raise(b.InvalidPrivateFieldResolution,s,{identifierName:r})}declarePrivateName(t,e,r){let{privateNames:s,loneAccessors:i,undefinedPrivateNames:a}=this.current(),o=s.has(t);if(e&3){let d=o&&i.get(t);if(d){let c=d&4,l=e&4,u=d&3,p=e&3;o=u===p||c!==l,o||i.delete(t)}else o||i.set(t,e)}o&&this.parser.raise(b.PrivateNameRedeclaration,r,{identifierName:t}),s.add(t),a.delete(t)}usePrivateName(t,e){let r;for(r of this.stack)if(r.privateNames.has(t))return;r?r.undefinedPrivateNames.set(t,e):this.parser.raise(b.InvalidPrivateFieldResolution,e,{identifierName:t})}},Jn=class{constructor(t=0){this.type=t}canBeArrowParameterDeclaration(){return this.type===2||this.type===1}isCertainlyParameterDeclaration(){return this.type===3}},$i=class extends Jn{constructor(t){super(t),this.declarationErrors=new Map}recordDeclarationError(t,e){let r=e.index;this.declarationErrors.set(r,[t,e])}clearDeclarationError(t){this.declarationErrors.delete(t)}iterateErrors(t){this.declarationErrors.forEach(t)}},Id=class{constructor(t){this.parser=void 0,this.stack=[new Jn],this.parser=t}enter(t){this.stack.push(t)}exit(){this.stack.pop()}recordParameterInitializerError(t,e){let r=e.loc.start,{stack:s}=this,i=s.length-1,a=s[i];for(;!a.isCertainlyParameterDeclaration();){if(a.canBeArrowParameterDeclaration())a.recordDeclarationError(t,r);else return;a=s[--i]}this.parser.raise(t,r)}recordArrowParameterBindingError(t,e){let{stack:r}=this,s=r[r.length-1],i=e.loc.start;if(s.isCertainlyParameterDeclaration())this.parser.raise(t,i);else if(s.canBeArrowParameterDeclaration())s.recordDeclarationError(t,i);else return}recordAsyncArrowParametersError(t){let{stack:e}=this,r=e.length-1,s=e[r];for(;s.canBeArrowParameterDeclaration();)s.type===2&&s.recordDeclarationError(b.AwaitBindingIdentifier,t),s=e[--r]}validateAsPattern(){let{stack:t}=this,e=t[t.length-1];e.canBeArrowParameterDeclaration()&&e.iterateErrors(([r,s])=>{this.parser.raise(r,s);let i=t.length-2,a=t[i];for(;a.canBeArrowParameterDeclaration();)a.clearDeclarationError(s.index),a=t[--i]})}};function yR(){return new Jn(3)}function gR(){return new $i(1)}function wR(){return new $i(2)}function qf(){return new Jn}var Ad=class extends vd{addExtra(t,e,r,s=!0){if(!t)return;let{extra:i}=t;i==null&&(i={},t.extra=i),s?i[e]=r:Object.defineProperty(i,e,{enumerable:s,value:r})}isContextual(t){return this.state.type===t&&!this.state.containsEsc}isUnparsedContextual(t,e){if(this.input.startsWith(e,t)){let r=this.input.charCodeAt(t+e.length);return!(pn(r)||(r&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 Pf(this.input,this.offsetToSourcePos(this.state.lastTokEndLoc.index),this.state.start)}hasFollowingLineBreak(){return Pf(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 r={node:null};try{let s=t((i=null)=>{throw r.node=i,r});if(this.state.errors.length>e.errors.length){let i=this.state;return this.state=e,this.state.tokensLength=i.tokensLength,{node:s,error:i.errors[e.errors.length],thrown:!1,aborted:!1,failState:i}}return{node:s,error:null,thrown:!1,aborted:!1,failState:null}}catch(s){let i=this.state;if(this.state=e,s instanceof SyntaxError)return{node:null,error:s,thrown:!0,aborted:!1,failState:i};if(s===r)return{node:r.node,error:null,thrown:!1,aborted:!0,failState:i};throw s}}checkExpressionErrors(t,e){if(!t)return!1;let{shorthandAssignLoc:r,doubleProtoLoc:s,privateKeyLoc:i,optionalParametersLoc:a,voidPatternLoc:o}=t,d=!!r||!!s||!!a||!!i||!!o;if(!e)return d;r!=null&&this.raise(b.InvalidCoverInitializedName,r),s!=null&&this.raise(b.DuplicateProto,s),i!=null&&this.raise(b.UnexpectedPrivateField,i),a!=null&&this.unexpected(a),o!=null&&this.raise(b.InvalidCoverDiscardElement,o)}isLiteralPropertyName(){return Mf(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 r=this.exportedIdentifiers;this.exportedIdentifiers=new Set;let s=this.inModule;this.inModule=t;let i=this.scope,a=this.getScopeHandler();this.scope=new a(this,t);let o=this.prodParam;this.prodParam=new yd;let d=this.classScope;this.classScope=new Rd(this);let c=this.expressionScope;return this.expressionScope=new Id(this),()=>{this.state.labels=e,this.exportedIdentifiers=r,this.inModule=s,this.scope=i,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 r=e?514:1;this.optionFlags&4&&(r|=512),this.scope.enter(r)}checkDestructuringPrivate(t){let{privateKeyLoc:e}=t;e!==null&&this.expectPlugin("destructuringPrivate",e)}},Kn=class{constructor(){this.shorthandAssignLoc=null,this.doubleProtoLoc=null,this.privateKeyLoc=null,this.optionalParametersLoc=null,this.voidPatternLoc=null}},Xn=class{constructor(t,e,r){this.type="",this.start=e,this.end=0,this.loc=new Wn(r),t?.optionFlags&128&&(this.range=[e,0]),t!=null&&t.filename&&(this.loc.filename=t.filename)}},Pd=Xn.prototype;Pd.__clone=function(){let n=new Xn(void 0,this.start,this.loc.start),t=Object.keys(this);for(let e=0,r=t.length;e<r;e++){let s=t[e];s!=="leadingComments"&&s!=="trailingComments"&&s!=="innerComments"&&(n[s]=this[s])}return n};var Sd=class extends Ad{startNode(){let t=this.state.startLoc;return new Xn(this,t.index,t)}startNodeAt(t){return new Xn(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,r){return t.type=e,t.end=r.index,t.loc.end=r,this.optionFlags&128&&(t.range[1]=r.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:r,end:s,loc:i,range:a,name:o}=t,d=Object.create(Pd);return d.type=e,d.start=r,d.end=s,d.loc=i,d.range=a,d.name=o,t.extra&&(d.extra=t.extra),d}cloneStringLiteral(t){let{type:e,start:r,end:s,loc:i,range:a,extra:o}=t,d=Object.create(Pd);return d.type=e,d.start=r,d.end=s,d.loc=i,d.range=a,d.extra=o,d.value=t.value,d}},Td=n=>n.type==="ParenthesizedExpression"?Td(n.expression):n,Ed=class extends Sd{toAssignable(t,e=!1){var r,s;let i;switch((t.type==="ParenthesizedExpression"||(r=t.extra)!=null&&r.parenthesized)&&(i=Td(t),e?i.type==="Identifier"?this.expressionScope.recordArrowParameterBindingError(b.InvalidParenthesizedAssignment,t):i.type!=="CallExpression"&&i.type!=="MemberExpression"&&!this.isOptionalMemberExpression(i)&&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,(s=t.extra)==null?void 0:s.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(i,e);break}}toAssignableObjectExpressionProp(t,e,r){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 s=t.argument;this.checkToRestConversion(s,!1),this.toAssignable(s,r),e||this.raise(b.RestTrailingComma,t)}else this.toAssignable(t,r)}toAssignableList(t,e,r){let s=t.length-1;for(let i=0;i<=s;i++){let a=t[i];a&&(this.toAssignableListItem(t,i,r),a.type==="RestElement"&&(i<s?this.raise(b.RestTrailingComma,a):e&&this.raise(b.RestTrailingComma,e)))}}toAssignableListItem(t,e,r){let s=t[e];if(s.type==="SpreadElement"){this.castNodeTo(s,"RestElement");let i=s.argument;this.checkToRestConversion(i,!0),this.toAssignable(i,r)}else this.toAssignable(s,r)}isAssignable(t,e){switch(t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":return!0;case"ObjectExpression":{let r=t.properties.length-1;return t.properties.every((s,i)=>s.type!=="ObjectMethod"&&(i===r||s.type!=="SpreadElement")&&this.isAssignable(s))}case"ObjectProperty":return this.isAssignable(t.value);case"SpreadElement":return this.isAssignable(t.argument);case"ArrayExpression":return t.elements.every(r=>r===null||this.isAssignable(r));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 r of t)r?.type==="ArrayExpression"&&this.toReferencedListDeep(r.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,r){let s=r&1,i=[],a=!0;for(;!this.eat(t);)if(a?a=!1:this.expect(12),s&&this.match(12))i.push(null);else{if(this.eat(t))break;if(this.match(21)){let o=this.parseRestBinding();if((this.hasPlugin("flow")||r&2)&&(o=this.parseFunctionParamType(o)),i.push(o),!this.checkCommaAfterRest(e)){this.expect(t);break}}else{let o=[];if(r&2)for(this.match(26)&&this.hasPlugin("decorators")&&this.raise(b.UnsupportedParameterDecorator,this.state.startLoc);this.match(26);)o.push(this.parseDecorator());i.push(this.parseBindingElement(r,o))}}return i}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 r=this.startNode();return t===139?(this.expectPlugin("destructuringPrivate",e),this.classScope.usePrivateName(this.state.value,e),r.key=this.parsePrivateName()):this.parsePropertyName(r),r.method=!1,this.parseObjPropValue(r,e,!1,!1,!0,!1)}parseBindingElement(t,e){let r=this.parseMaybeDefault();return(this.hasPlugin("flow")||t&2)&&this.parseFunctionParamType(r),e.length&&(r.decorators=e,this.resetStartLocationFromNode(r,e[0])),this.parseMaybeDefault(r.loc.start,r)}parseFunctionParamType(t){return t}parseMaybeDefault(t,e){if(t??(t=this.state.startLoc),e=e??this.parseBindingAtom(),!this.eat(29))return e;let r=this.startNodeAt(t);return e.type==="VoidPattern"&&this.raise(b.VoidPatternInitializer,e),r.left=e,r.right=this.parseMaybeAssignAllowIn(),this.finishNode(r,"AssignmentPattern")}isValidLVal(t,e,r,s){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,r=64,s=!1,i=!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})),r!==64&&this.raise(b.InvalidPropertyBindingPattern,t);return}if(c==="Identifier"){this.checkIdentifier(t,r,i);let{name:y}=t;s&&(s.has(y)?this.raise(b.ParamDupe,t):s.add(y));return}else c==="VoidPattern"&&e.type==="CatchClause"&&this.raise(b.VoidPatternCatchClauseParam,t);let u=Td(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",r);if(p===!0)return;if(p===!1){let y=r===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 m=c==="ArrayPattern"||c==="ObjectPattern"?{type:c}:e,g=t[f];if(Array.isArray(g))for(let y of g)y&&this.checkLVal(y,m,r,s,i,h,!0);else g&&this.checkLVal(g,m,r,s,i,h,o)}checkIdentifier(t,e,r=!1){this.state.strict&&(r?Vf(t.name,this.inModule):Bf(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}},dd=/in(?:stanceof)?|as|satisfies/y;function bR(n){if(n==null)throw new Error(`Unexpected ${n} value.`);return n}function Ef(n){if(!n)throw new Error("Assert fail")}var F=st`typescript`({AbstractMethodHasImplementation:({methodName:n})=>`Method '${n}' cannot have an implementation because it is marked abstract.`,AbstractPropertyHasInitializer:({propertyName:n})=>`Property '${n}' 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:n})=>`'declare' is not allowed in ${n}ters.`,DeclareClassFieldHasInitializer:"Initializers are not allowed in ambient contexts.",DeclareFunctionHasImplementation:"An implementation cannot be declared in ambient contexts.",DuplicateAccessibilityModifier:({modifier:n})=>`Accessibility modifier already seen: '${n}'.`,DuplicateModifier:({modifier:n})=>`Duplicate modifier: '${n}'.`,EmptyHeritageClauseType:({token:n})=>`'${n}' 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:n})=>`'${n[0]}' modifier cannot be used with '${n[1]}' modifier.`,IndexSignatureHasAbstract:"Index signatures cannot have the 'abstract' modifier.",IndexSignatureHasAccessibility:({modifier:n})=>`Index signatures cannot have an accessibility modifier ('${n}').`,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:n})=>`'${n}' list can only include identifiers or qualified-names with optional type arguments.`,InvalidModifierOnAwaitUsingDeclaration:n=>`'${n}' modifier cannot appear on an await using declaration.`,InvalidModifierOnTypeMember:({modifier:n})=>`'${n}' modifier cannot appear on a type member.`,InvalidModifierOnTypeParameter:({modifier:n})=>`'${n}' modifier cannot appear on a type parameter.`,InvalidModifierOnTypeParameterPositions:({modifier:n})=>`'${n}' modifier can only appear on a type parameter of a class, interface or type alias.`,InvalidModifierOnUsingDeclaration:n=>`'${n}' modifier cannot appear on a using declaration.`,InvalidModifiersOrder:({orderedModifiers:n})=>`'${n[0]}' modifier must precede '${n[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:n})=>`Private elements cannot have an accessibility modifier ('${n}').`,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:n})=>`Single type parameter ${n} should have a trailing comma. Example usage: <${n},>.`,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:n})=>`Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${n}.`,UsingDeclarationInAmbientContext:n=>`'${n}' declarations are not allowed in ambient contexts.`});function xR(n){switch(n){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 Cf(n){return n==="private"||n==="public"||n==="protected"}function vR(n){return n==="in"||n==="out"}var kR=n=>class extends n{constructor(...e){super(...e),this.tsParseInOutModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out"],disallowedModifiers:["const","public","private","protected","readonly","declare","abstract","override"],errorTemplate:F.InvalidModifierOnTypeParameter}),this.tsParseConstModifier=this.tsParseModifiers.bind(this,{allowedModifiers:["const"],disallowedModifiers:["in","out"],errorTemplate:F.InvalidModifierOnTypeParameterPositions}),this.tsParseInOutConstModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out","const"],disallowedModifiers:["public","private","protected","readonly","declare","abstract","override"],errorTemplate:F.InvalidModifierOnTypeParameter})}getScopeHandler(){return md}tsIsIdentifier(){return ie(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,r,s){if(!ie(this.state.type)&&this.state.type!==58&&this.state.type!==75)return;let i=this.state.value;if(e.includes(i)){if(s&&this.match(106)||r&&this.tsIsStartOfStaticBlocks())return;if(this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this)))return i}}tsParseModifiers({allowedModifiers:e,disallowedModifiers:r,stopOnStartOfClassStaticBlock:s,errorTemplate:i=F.InvalidModifierOnTypeMember},a){let o=(c,l,u,p)=>{l===u&&a[p]&&this.raise(F.InvalidModifiersOrder,c,{orderedModifiers:[u,p]})},d=(c,l,u,p)=>{(a[u]&&l===p||a[p]&&l===u)&&this.raise(F.IncompatibleModifiers,c,{modifiers:[u,p]})};for(;;){let{startLoc:c}=this.state,l=this.tsParseModifier(e.concat(r??[]),s,a.static);if(!l)break;Cf(l)?a.accessibility?this.raise(F.DuplicateAccessibilityModifier,c,{modifier:l}):(o(c,l,l,"override"),o(c,l,l,"static"),o(c,l,l,"readonly"),a.accessibility=l):vR(l)?(a[l]&&this.raise(F.DuplicateModifier,c,{modifier:l}),a[l]=!0,o(c,l,"in","out")):(hasOwnProperty.call(a,l)?this.raise(F.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),r!=null&&r.includes(l)&&this.raise(i,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,r){let s=[];for(;!this.tsIsListTerminator(e);)s.push(r());return s}tsParseDelimitedList(e,r,s){return bR(this.tsParseDelimitedListWorker(e,r,!0,s))}tsParseDelimitedListWorker(e,r,s,i){let a=[],o=-1;for(;!this.tsIsListTerminator(e);){o=-1;let d=r();if(d==null)return;if(a.push(d),this.eat(12)){o=this.state.lastTokStartLoc.index;continue}if(this.tsIsListTerminator(e))break;s&&this.expect(12);return}return i&&(i.value=o),a}tsParseBracketedList(e,r,s,i,a){i||(s?this.expect(0):this.expect(47));let o=this.tsParseDelimitedList(e,r,a);return s?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(F.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 r=this.startNode();return this.isContextual(76)?(r.method=!1,r.key=this.parseIdentifier(!0),r.computed=!1,r.shorthand=!1):this.unexpected(null,76),this.expect(14),r.value=this.tsParseImportTypeWithPropertyValue(),e.properties=[this.finishObjectProperty(r)],this.eat(12),this.expect(8),this.finishNode(e,"ObjectExpression")}tsParseImportTypeWithPropertyValue(){let e=this.startNode(),r=[];for(this.expect(5);!this.match(8);){let s=this.state.type;ie(s)||s===134?r.push(super.parsePropertyDefinition(null)):this.unexpected(),this.eat(12)}return e.properties=r,this.next(),this.finishNode(e,"ObjectExpression")}tsParseEntityName(e){let r;if(e&1&&this.match(78))if(e&2)r=this.parseIdentifier(!0);else{let s=this.startNode();this.next(),r=this.finishNode(s,"ThisExpression")}else r=this.parseIdentifier(!!(e&1));for(;this.eat(16);){let s=this.startNodeAtNode(r);s.left=r,s.right=this.parseIdentifier(!!(e&1)),r=this.finishNode(s,"TSQualifiedName")}return r}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 r=this.startNodeAtNode(e);return r.parameterName=e,r.typeAnnotation=this.tsParseTypeAnnotation(!1),r.asserts=!1,this.finishNode(r,"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 r=this.startNode();return e(r),r.name=this.tsParseTypeParameterName(),r.constraint=this.tsEatThenParseType(81),r.default=this.tsEatThenParseType(29),this.finishNode(r,"TSTypeParameter")}tsTryParseTypeParameters(e){if(this.match(47))return this.tsParseTypeParameters(e)}tsParseTypeParameters(e){let r=this.startNode();this.match(47)||this.match(143)?this.next():this.unexpected();let s={value:-1};return r.params=this.tsParseBracketedList("TypeParametersOrArguments",this.tsParseTypeParameter.bind(this,e),!1,!0,s),r.params.length===0&&this.raise(F.EmptyTypeParameters,r),s.value!==-1&&this.addExtra(r,"trailingComma",s.value),this.finishNode(r,"TSTypeParameterDeclaration")}tsFillSignature(e,r){let s=e===19,i="parameters",a="typeAnnotation";r.typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier),this.expect(10),r[i]=this.tsParseBindingListForSignature(),s?r[a]=this.tsParseTypeOrTypePredicateAnnotation(e):this.match(e)&&(r[a]=this.tsParseTypeOrTypePredicateAnnotation(e))}tsParseBindingListForSignature(){let e=super.parseBindingList(11,41,2);for(let r of e){let{type:s}=r;(s==="AssignmentPattern"||s==="TSParameterProperty")&&this.raise(F.UnsupportedSignatureParameterKind,r,{type:s})}return e}tsParseTypeMemberSemicolon(){!this.eat(12)&&!this.isLineTerminator()&&this.expect(13)}tsParseSignatureMember(e,r){return this.tsFillSignature(14,r),this.tsParseTypeMemberSemicolon(),this.finishNode(r,e)}tsIsUnambiguouslyIndexSignature(){return this.next(),ie(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 r=this.parseIdentifier();r.typeAnnotation=this.tsParseTypeAnnotation(),this.resetEndLocation(r),this.expect(3),e.parameters=[r];let s=this.tsTryParseTypeAnnotation();return s&&(e.typeAnnotation=s),this.tsParseTypeMemberSemicolon(),this.finishNode(e,"TSIndexSignature")}tsParsePropertyOrMethodSignature(e,r){if(this.eat(17)&&(e.optional=!0),this.match(10)||this.match(47)){r&&this.raise(F.ReadonlyForMethodSignature,e);let s=e;s.kind&&this.match(47)&&this.raise(F.AccessorCannotHaveTypeParameters,this.state.curPosition()),this.tsFillSignature(14,s),this.tsParseTypeMemberSemicolon();let i="parameters",a="typeAnnotation";if(s.kind==="get")s[i].length>0&&(this.raise(b.BadGetterArity,this.state.curPosition()),this.isThisParam(s[i][0])&&this.raise(F.AccessorCannotDeclareThisParameter,this.state.curPosition()));else if(s.kind==="set"){if(s[i].length!==1)this.raise(b.BadSetterArity,this.state.curPosition());else{let o=s[i][0];this.isThisParam(o)&&this.raise(F.AccessorCannotDeclareThisParameter,this.state.curPosition()),o.type==="Identifier"&&o.optional&&this.raise(F.SetAccessorCannotHaveOptionalParameter,this.state.curPosition()),o.type==="RestElement"&&this.raise(F.SetAccessorCannotHaveRestParameter,this.state.curPosition())}s[a]&&this.raise(F.SetAccessorCannotHaveReturnType,s[a])}else s.kind="method";return this.finishNode(s,"TSMethodSignature")}else{let s=e;r&&(s.readonly=!0);let i=this.tsTryParseTypeAnnotation();return i&&(s.typeAnnotation=i),this.tsParseTypeMemberSemicolon(),this.finishNode(s,"TSPropertySignature")}}tsParseTypeMember(){let e=this.startNode();if(this.match(10)||this.match(47))return this.tsParseSignatureMember("TSCallSignatureDeclaration",e);if(this.match(77)){let s=this.startNode();return this.next(),this.match(10)||this.match(47)?this.tsParseSignatureMember("TSConstructSignatureDeclaration",e):(e.key=this.createIdentifier(s,"new"),this.tsParsePropertyOrMethodSignature(e,!1))}this.tsParseModifiers({allowedModifiers:["readonly"],disallowedModifiers:["declare","abstract","private","protected","public","static","override"]},e);let r=this.tsTryParseIndexSignature(e);return r||(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 r=this.startNode();return r.name=this.tsParseTypeParameterName(),r.constraint=this.tsExpectThenParseType(58),e.typeParameter=this.finishNode(r,"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 r=!1;return e.elementTypes.forEach(s=>{let{type:i}=s;r&&i!=="TSRestType"&&i!=="TSOptionalType"&&!(i==="TSNamedTupleMember"&&s.optional)&&this.raise(F.OptionalTypeBeforeRequired,s),r||(r=i==="TSNamedTupleMember"&&s.optional||i==="TSOptionalType")}),this.finishNode(e,"TSTupleType")}tsParseTupleElementType(){let e=this.state.startLoc,r=this.eat(21),{startLoc:s}=this.state,i,a,o,d,l=it(this.state.type)?this.lookaheadCharCode():null;if(l===58)i=!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?(i=!0,a=this.createIdentifier(this.startNodeAt(s),u),this.expect(17),this.expect(14),d=this.tsParseType()):(i=!1,d=p,this.expect(17))}else d=this.tsParseType(),o=this.eat(17),i=this.eat(14);if(i){let u;a?(u=this.startNodeAt(s),u.optional=o,u.label=a,u.elementType=d,this.eat(17)&&(u.optional=!0,this.raise(F.TupleOptionalAfterType,this.state.lastTokStartLoc))):(u=this.startNodeAt(s),u.optional=o,this.raise(F.InvalidTupleMemberLabel,d),u.label=d,u.elementType=this.tsParseType()),d=this.finishNode(u,"TSNamedTupleMember")}else if(o){let u=this.startNodeAt(s);u.typeAnnotation=d,d=this.finishNode(u,"TSOptionalType")}if(r){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,r){let s=this.startNode();return e==="TSConstructorType"&&(s.abstract=!!r,r&&this.next(),this.next()),this.tsInAllowConditionalTypesContext(()=>this.tsFillSignature(19,s)),this.finishNode(s,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(),r=this.lookahead();return r.type!==135&&r.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(ie(e)||e===88||e===84){let r=e===88?"TSVoidKeyword":e===84?"TSNullKeyword":xR(this.state.value);if(r!==void 0&&this.lookaheadCharCode()!==46){let s=this.startNode();return this.next(),this.finishNode(s,r)}return this.tsParseTypeReference()}}}throw this.unexpected()}tsParseArrayTypeOrHigher(){let{startLoc:e}=this.state,r=this.tsParseNonArrayType();for(;!this.hasPrecedingLineBreak()&&this.eat(0);)if(this.match(3)){let s=this.startNodeAt(e);s.elementType=r,this.expect(3),r=this.finishNode(s,"TSArrayType")}else{let s=this.startNodeAt(e);s.objectType=r,s.indexType=this.tsParseType(),this.expect(3),r=this.finishNode(s,"TSIndexedAccessType")}return r}tsParseTypeOperator(){let e=this.startNode(),r=this.state.value;return this.next(),e.operator=r,e.typeAnnotation=this.tsParseTypeOperatorOrHigher(),r==="readonly"&&this.tsCheckTypeAnnotationForReadOnly(e),this.finishNode(e,"TSTypeOperator")}tsCheckTypeAnnotationForReadOnly(e){switch(e.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(F.UnexpectedReadonly,e)}}tsParseInferType(){let e=this.startNode();this.expectContextual(115);let r=this.startNode();return r.name=this.tsParseTypeParameterName(),r.constraint=this.tsTryParse(()=>this.tsParseConstraintForInferType()),e.typeParameter=this.finishNode(r,"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 Hk(this.state.type)&&!this.state.containsEsc?this.tsParseTypeOperator():this.isContextual(115)?this.tsParseInferType():this.tsInAllowConditionalTypesContext(()=>this.tsParseArrayTypeOrHigher())}tsParseUnionOrIntersectionType(e,r,s){let i=this.startNode(),a=this.eat(s),o=[];do o.push(r());while(this.eat(s));return o.length===1&&!a?o[0]:(i.types=o,this.finishNode(i,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(ie(this.state.type)||this.match(78))return this.next(),!0;if(this.match(5)){let{errors:e}=this.state,r=e.length;try{return this.parseObjectLike(8,!0),e.length===r}catch{return!1}}if(this.match(0)){this.next();let{errors:e}=this.state,r=e.length;try{return super.parseBindingList(3,93,1),e.length===r}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 r=this.startNode();this.expect(e);let s=this.startNode(),i=!!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));if(i&&this.match(78)){let d=this.tsParseThisTypeOrThisTypePredicate();return d.type==="TSThisType"?(s.parameterName=d,s.asserts=!0,s.typeAnnotation=null,d=this.finishNode(s,"TSTypePredicate")):(this.resetStartLocationFromNode(d,s),d.asserts=!0),r.typeAnnotation=d,this.finishNode(r,"TSTypeAnnotation")}let a=this.tsIsIdentifier()&&this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));if(!a)return i?(s.parameterName=this.parseIdentifier(),s.asserts=i,s.typeAnnotation=null,r.typeAnnotation=this.finishNode(s,"TSTypePredicate"),this.finishNode(r,"TSTypeAnnotation")):this.tsParseTypeAnnotation(!1,r);let o=this.tsParseTypeAnnotation(!1);return s.parameterName=a,s.typeAnnotation=o,s.asserts=i,r.typeAnnotation=this.finishNode(s,"TSTypePredicate"),this.finishNode(r,"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(),!ie(this.state.type)&&!this.match(78)?!1:(e&&this.raise(b.InvalidEscapedReservedWord,this.state.lastTokStartLoc,{reservedWord:"asserts"}),!0)}tsParseTypeAnnotation(e=!0,r=this.startNode()){return this.tsInType(()=>{e&&this.expect(14),r.typeAnnotation=this.tsParseType()}),this.finishNode(r,"TSTypeAnnotation")}tsParseType(){Ef(this.state.inType);let e=this.tsParseNonConditionalType();if(this.state.inDisallowConditionalTypesContext||this.hasPrecedingLineBreak()||!this.eat(81))return e;let r=this.startNodeAtNode(e);return r.checkType=e,r.extendsType=this.tsInDisallowConditionalTypesContext(()=>this.tsParseNonConditionalType()),this.expect(17),r.trueType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.expect(14),r.falseType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.finishNode(r,"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(F.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 r=this.state.startLoc,s=this.tsParseDelimitedList("HeritageClauseElement",()=>{let i=this.startNode();return i.expression=this.tsParseEntityName(3),this.match(47)&&(i.typeParameters=this.tsParseTypeArguments()),this.finishNode(i,"TSExpressionWithTypeArguments")});return s.length||this.raise(F.EmptyHeritageClauseType,r,{token:e}),s}tsParseInterfaceDeclaration(e,r={}){if(this.hasFollowingLineBreak())return null;this.expectContextual(129),r.declare&&(e.declare=!0),ie(this.state.type)?(e.id=this.parseIdentifier(),this.checkIdentifier(e.id,130)):(e.id=null,this.raise(F.MissingInterfaceName,this.state.startLoc)),e.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers),this.eat(81)&&(e.extends=this.tsParseHeritageClause("extends"));let s=this.startNode();return s.body=this.tsInType(this.tsParseObjectTypeMembers.bind(this)),e.body=this.finishNode(s,"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 r=this.startNode();return this.next(),this.finishNode(r,"TSIntrinsicKeyword")}return this.tsParseType()}),this.semicolon(),this.finishNode(e,"TSTypeAliasDeclaration")}tsInTopLevelContext(e){if(this.curContext()!==se.brace){let r=this.state.context;this.state.context=[r[0]];try{return e()}finally{this.state.context=r}}else return e()}tsInType(e){let r=this.state.inType;this.state.inType=!0;try{return e()}finally{this.state.inType=r}}tsInDisallowConditionalTypesContext(e){let r=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!0;try{return e()}finally{this.state.inDisallowConditionalTypesContext=r}}tsInAllowConditionalTypesContext(e){let r=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!1;try{return e()}finally{this.state.inDisallowConditionalTypesContext=r}}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,r={}){return r.const&&(e.const=!0),r.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,r=!1){if(e.id=this.parseIdentifier(),r||this.checkIdentifier(e.id,1024),this.eat(16)){let s=this.startNode();this.tsParseModuleOrNamespaceDeclaration(s,!0),e.body=s}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,r,s){e.isExport=s||!1,e.id=r||this.parseIdentifier(),this.checkIdentifier(e.id,4096),this.expect(29);let i=this.tsParseModuleReference();return e.importKind==="type"&&i.type!=="TSExternalModuleReference"&&this.raise(F.ImportAliasHasImportType,i),e.moduleReference=i,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 r=this.state.clone(),s=e();return this.state=r,s}tsTryParseAndCatch(e){let r=this.tryParse(s=>e()||s());if(!(r.aborted||!r.node))return r.error&&(this.state=r.failState),r.node}tsTryParse(e){let r=this.state.clone(),s=e();if(s!==void 0&&s!==!1)return s;this.state=r}tsTryParseDeclare(e){if(this.isLineTerminator())return;let r=this.state.type;return this.tsInAmbientContext(()=>{switch(r){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(F.InvalidModifierOnUsingDeclaration,this.state.startLoc,"declare"),e.declare=!0,this.parseVarStatement(e,"using",!0);break;case 96:if(this.isAwaitUsing())return this.raise(F.InvalidModifierOnAwaitUsingDeclaration,this.state.startLoc,"declare"),e.declare=!0,this.next(),this.parseVarStatement(e,"await using",!0);break;case 129:{let s=this.tsParseInterfaceDeclaration(e,{declare:!0});if(s)return s}default:if(ie(r))return this.tsParseDeclaration(e,this.state.type,!0,null)}})}tsTryParseExportDeclaration(){return this.tsParseDeclaration(this.startNode(),this.state.type,!0,null)}tsParseDeclaration(e,r,s,i){switch(r){case 124:if(this.tsCheckLineTerminator(s)&&(this.match(80)||ie(this.state.type)))return this.tsParseAbstractDeclaration(e,i);break;case 127:if(this.tsCheckLineTerminator(s)){if(this.match(134))return this.tsParseAmbientExternalModuleDeclaration(e);if(ie(this.state.type))return e.kind="module",this.tsParseModuleOrNamespaceDeclaration(e)}break;case 128:if(this.tsCheckLineTerminator(s)&&ie(this.state.type))return e.kind="namespace",this.tsParseModuleOrNamespaceDeclaration(e);break;case 130:if(this.tsCheckLineTerminator(s)&&ie(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 r=this.state.maybeInArrowParameters;this.state.maybeInArrowParameters=!0;let s=this.tsTryParseAndCatch(()=>{let i=this.startNodeAt(e);return i.typeParameters=this.tsParseTypeParameters(this.tsParseConstModifier),super.parseFunctionParams(i),i.returnType=this.tsTryParseTypeOrTypePredicateAnnotation(),this.expect(19),i});if(this.state.maybeInArrowParameters=r,!!s)return super.parseArrowExpression(s,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(F.EmptyTypeArguments,e):!this.state.inType&&this.curContext()===se.brace&&this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TSTypeParameterInstantiation")}tsIsDeclarationStart(){return zk(this.state.type)}isExportDefaultSpecifier(){return this.tsIsDeclarationStart()?!1:super.isExportDefaultSpecifier()}parseBindingElement(e,r){let s=r.length?r[0].loc.start:this.state.startLoc,i={};this.tsParseModifiers({allowedModifiers:["public","private","protected","override","readonly"]},i);let a=i.accessibility,o=i.override,d=i.readonly;!(e&4)&&(a||d||o)&&this.raise(F.UnexpectedParameterModifier,s);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(s);return r.length&&(u.decorators=r),a&&(u.accessibility=a),d&&(u.readonly=d),o&&(u.override=o),l.type!=="Identifier"&&l.type!=="AssignmentPattern"&&this.raise(F.UnsupportedParameterPropertyKind,u),u.parameter=l,this.finishNode(u,"TSParameterProperty")}return r.length&&(c.decorators=r),l}isSimpleParameter(e){return e.type==="TSParameterProperty"&&super.isSimpleParameter(e.parameter)||super.isSimpleParameter(e)}tsDisallowOptionalPattern(e){for(let r of e.params)r.type!=="Identifier"&&r.optional&&!this.state.isAmbientContext&&this.raise(F.PatternIsOptional,r)}setArrowFunctionParameters(e,r,s){super.setArrowFunctionParameters(e,r,s),this.tsDisallowOptionalPattern(e)}parseFunctionBodyAndFinish(e,r,s=!1){this.match(14)&&(e.returnType=this.tsParseTypeOrTypePredicateAnnotation(14));let i=r==="FunctionDeclaration"?"TSDeclareFunction":r==="ClassMethod"||r==="ClassPrivateMethod"?"TSDeclareMethod":void 0;return i&&!this.match(5)&&this.isLineTerminator()?this.finishNode(e,i):i==="TSDeclareFunction"&&this.state.isAmbientContext&&(this.raise(F.DeclareFunctionHasImplementation,e),e.declare)?super.parseFunctionBodyAndFinish(e,i,s):(this.tsDisallowOptionalPattern(e),super.parseFunctionBodyAndFinish(e,r,s))}registerFunctionStatementId(e){!e.body&&e.id?this.checkIdentifier(e.id,1024):super.registerFunctionStatementId(e)}tsCheckForInvalidTypeCasts(e){e.forEach(r=>{r?.type==="TSTypeCastExpression"&&this.raise(F.UnexpectedTypeAnnotation,r.typeAnnotation)})}toReferencedList(e,r){return this.tsCheckForInvalidTypeCasts(e),e}parseArrayLike(e,r,s){let i=super.parseArrayLike(e,r,s);return i.type==="ArrayExpression"&&this.tsCheckForInvalidTypeCasts(i.elements),i}parseSubscript(e,r,s,i){if(!this.hasPrecedingLineBreak()&&this.match(35)){this.state.canStartJSXElement=!1,this.next();let o=this.startNodeAt(r);return o.expression=e,this.finishNode(o,"TSNonNullExpression")}let a=!1;if(this.match(18)&&this.lookaheadCharCode()===60){if(s)return i.stop=!0,e;i.optionalChainMember=a=!0,this.next()}if(this.match(47)||this.match(51)){let o,d=this.tsTryParseAndCatch(()=>{if(!s&&this.atPossibleAsyncArrow(e)){let p=this.tsTryParseGenericAsyncArrowFunction(r);if(p)return i.stop=!0,p}let c=this.tsParseTypeArgumentsInExpression();if(!c)return;if(a&&!this.match(10)){o=this.state.curPosition();return}if(Oi(this.state.type)){let p=super.parseTaggedTemplateExpression(e,r,i);return p.typeParameters=c,p}if(!s&&this.eat(10)){let p=this.startNodeAt(r);return p.callee=e,p.arguments=this.parseCallExpressionArguments(),this.tsCheckForInvalidTypeCasts(p.arguments),p.typeParameters=c,i.optionalChainMember&&(p.optional=a),this.finishCallExpression(p,i.optionalChainMember)}let l=this.state.type;if(l===48||l===52||l!==10&&l!==93&&l!==120&&qr(l)&&!this.hasPrecedingLineBreak())return;let u=this.startNodeAt(r);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(F.InvalidPropertyAccessAfterInstantiationExpression,this.state.startLoc),!this.match(16)&&!this.match(18)&&(d.expression=super.stopParseSubscript(e,i))),d}return super.parseSubscript(e,r,s,i)}parseNewCallee(e){var r;super.parseNewCallee(e);let{callee:s}=e;s.type==="TSInstantiationExpression"&&!((r=s.extra)!=null&&r.parenthesized)&&(e.typeParameters=s.typeParameters,e.callee=s.expression)}parseExprOp(e,r,s){let i;if(Ei(58)>s&&!this.hasPrecedingLineBreak()&&(this.isContextual(93)||(i=this.isContextual(120)))){let a=this.startNodeAt(r);return a.expression=e,a.typeAnnotation=this.tsInType(()=>(this.next(),this.match(75)?(i&&this.raise(b.UnexpectedKeyword,this.state.startLoc,{keyword:"const"}),this.tsParseTypeReference()):this.tsParseType())),this.finishNode(a,i?"TSSatisfiesExpression":"TSAsExpression"),this.reScan_lt_gt(),this.parseExprOp(a,r,s)}return super.parseExprOp(e,r,s)}checkReservedWord(e,r,s,i){this.state.isAmbientContext||super.checkReservedWord(e,r,s,i)}checkImportReflection(e){super.checkImportReflection(e),e.module&&e.importKind!=="value"&&this.raise(F.ImportReflectionHasImportType,e.specifiers[0].loc.start)}checkDuplicateExports(){}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return!0;if(this.isContextual(130)){let r=this.lookaheadCharCode();return e?r===123||r===42:r!==61}return!e&&this.isContextual(87)}applyImportPhase(e,r,s,i){super.applyImportPhase(e,r,s,i),r?e.exportKind=s==="type"?"type":"value":e.importKind=s==="type"||s==="typeof"?s:"value"}parseImport(e){if(this.match(134))return e.importKind="value",super.parseImport(e);let r;if(ie(this.state.type)&&this.lookaheadCharCode()===61)return e.importKind="value",this.tsParseImportEqualsDeclaration(e);if(this.isContextual(130)){let s=this.parseMaybeImportPhase(e,!1);if(this.lookaheadCharCode()===61)return this.tsParseImportEqualsDeclaration(e,s);r=super.parseImportSpecifiersAndAfter(e,s)}else r=super.parseImport(e);return r.importKind==="type"&&r.specifiers.length>1&&r.specifiers[0].type==="ImportDefaultSpecifier"&&this.raise(F.TypeImportCannotSpecifyDefaultAndNamed,r),r}parseExport(e,r){if(this.match(83)){let s=e;this.next();let i=null;return this.isContextual(130)&&this.isPotentialImportPhase(!1)?i=this.parseMaybeImportPhase(s,!1):s.importKind="value",this.tsParseImportEqualsDeclaration(s,i,!0)}else if(this.eat(29)){let s=e;return s.expression=super.parseExpression(),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(s,"TSExportAssignment")}else if(this.eatContextual(93)){let s=e;return this.expectContextual(128),s.id=this.parseIdentifier(),this.semicolon(),this.finishNode(s,"TSNamespaceExportDeclaration")}else return super.parseExport(e,r)}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,r,s=!1){let{isAmbientContext:i}=this.state,a=super.parseVarStatement(e,r,s||i);if(!i)return a;if(!e.declare&&(r==="using"||r==="await using"))return this.raiseOverwrite(F.UsingDeclarationInAmbientContext,e,r),a;for(let{id:o,init:d}of a.declarations)d&&(r==="var"||r==="let"||o.typeAnnotation?this.raise(F.InitializerNotAllowedInAmbientContext,d):IR(d,this.hasPlugin("estree"))||this.raise(F.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference,d));return a}parseStatementContent(e,r){if(!this.state.containsEsc)switch(this.state.type){case 75:{if(this.isLookaheadContextual("enum")){let s=this.startNode();return this.expect(75),this.tsParseEnumDeclaration(s,{const:!0})}break}case 124:case 125:{if(this.nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine()){let s=this.state.type,i=this.startNode();this.next();let a=s===125?this.tsTryParseDeclare(i):this.tsParseAbstractDeclaration(i,r);return a?(s===125&&(a.declare=!0),a):(i.expression=this.createIdentifier(this.startNodeAt(i.loc.start),s===125?"declare":"abstract"),this.semicolon(!1),this.finishNode(i,"ExpressionStatement"))}break}case 126:return this.tsParseEnumDeclaration(this.startNode());case 112:{if(this.lookaheadCharCode()===123){let i=this.startNode();return this.tsParseAmbientExternalModuleDeclaration(i)}break}case 129:{let s=this.tsParseInterfaceDeclaration(this.startNode());if(s)return s;break}case 127:{if(this.nextTokenIsIdentifierOrStringLiteralOnSameLine()){let s=this.startNode();return this.next(),this.tsParseDeclaration(s,127,!1,r)}break}case 128:{if(this.nextTokenIsIdentifierOnSameLine()){let s=this.startNode();return this.next(),this.tsParseDeclaration(s,128,!1,r)}break}case 130:{if(this.nextTokenIsIdentifierOnSameLine()){let s=this.startNode();return this.next(),this.tsParseTypeAliasDeclaration(s)}break}}return super.parseStatementContent(e,r)}parseAccessModifier(){return this.tsParseModifier(["public","protected","private"])}tsHasSomeModifiers(e,r){return r.some(s=>Cf(s)?e.accessibility===s:!!e[s])}tsIsStartOfStaticBlocks(){return this.isContextual(106)&&this.lookaheadCharCode()===123}parseClassMember(e,r,s){let i=["declare","private","public","protected","override","abstract","readonly","static"];this.tsParseModifiers({allowedModifiers:i,disallowedModifiers:["in","out"],stopOnStartOfClassStaticBlock:!0,errorTemplate:F.InvalidModifierOnTypeParameterPositions},r);let a=()=>{this.tsIsStartOfStaticBlocks()?(this.next(),this.next(),this.tsHasSomeModifiers(r,i)&&this.raise(F.StaticBlockCannotHaveModifier,this.state.curPosition()),super.parseClassStaticBlock(e,r)):this.parseClassMemberWithIsStatic(e,r,s,!!r.static)};r.declare?this.tsInAmbientContext(a):a()}parseClassMemberWithIsStatic(e,r,s,i){let a=this.tsTryParseIndexSignature(r);if(a){e.body.push(a),r.abstract&&this.raise(F.IndexSignatureHasAbstract,r),r.accessibility&&this.raise(F.IndexSignatureHasAccessibility,r,{modifier:r.accessibility}),r.declare&&this.raise(F.IndexSignatureHasDeclare,r),r.override&&this.raise(F.IndexSignatureHasOverride,r);return}!this.state.inAbstractClass&&r.abstract&&this.raise(F.NonAbstractClassHasAbstractMethod,r),r.override&&(s.hadSuperClass||this.raise(F.OverrideNotInSubClass,r)),super.parseClassMemberWithIsStatic(e,r,s,i)}parsePostMemberNameModifiers(e){this.eat(17)&&(e.optional=!0),e.readonly&&this.match(10)&&this.raise(F.ClassMethodHasReadonly,e),e.declare&&this.match(10)&&this.raise(F.ClassMethodHasDeclare,e)}shouldParseExportDeclaration(){return this.tsIsDeclarationStart()?!0:super.shouldParseExportDeclaration()}parseConditional(e,r,s){if(!this.match(17))return e;if(this.state.maybeInArrowParameters){let i=this.lookaheadCharCode();if(i===44||i===61||i===58||i===41)return this.setOptionalParametersError(s),e}return super.parseConditional(e,r,s)}parseParenItem(e,r){let s=super.parseParenItem(e,r);if(this.eat(17)&&(s.optional=!0,this.resetEndLocation(e)),this.match(14)){let i=this.startNodeAt(r);return i.expression=e,i.typeAnnotation=this.tsParseTypeAnnotation(),this.finishNode(i,"TSTypeCastExpression")}return e}parseExportDeclaration(e){if(!this.state.isAmbientContext&&this.isContextual(125))return this.tsInAmbientContext(()=>this.parseExportDeclaration(e));let r=this.state.startLoc,s=this.eatContextual(125);if(s&&(this.isContextual(125)||!this.shouldParseExportDeclaration()))throw this.raise(F.ExpectedAmbientAfterExportDeclare,this.state.startLoc);let a=ie(this.state.type)&&this.tsTryParseExportDeclaration()||super.parseExportDeclaration(e);return a?((a.type==="TSInterfaceDeclaration"||a.type==="TSTypeAliasDeclaration"||s)&&(e.exportKind="type"),s&&a.type!=="TSImportEqualsDeclaration"&&(this.resetStartLocation(a,r),a.declare=!0),a):null}parseClassId(e,r,s,i){if((!r||s)&&this.isContextual(113))return;super.parseClassId(e,r,s,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 r=this.tsTryParseTypeAnnotation();r&&(e.typeAnnotation=r)}parseClassProperty(e){if(this.parseClassPropertyAnnotation(e),this.state.isAmbientContext&&!(e.readonly&&!e.typeAnnotation)&&this.match(29)&&this.raise(F.DeclareClassFieldHasInitializer,this.state.startLoc),e.abstract&&this.match(29)){let{key:r}=e;this.raise(F.AbstractPropertyHasInitializer,this.state.startLoc,{propertyName:r.type==="Identifier"&&!e.computed?r.name:`[${this.input.slice(this.offsetToSourcePos(r.start),this.offsetToSourcePos(r.end))}]`})}return super.parseClassProperty(e)}parseClassPrivateProperty(e){return e.abstract&&this.raise(F.PrivateElementHasAbstract,e),e.accessibility&&this.raise(F.PrivateElementHasAccessibility,e,{modifier:e.accessibility}),this.parseClassPropertyAnnotation(e),super.parseClassPrivateProperty(e)}parseClassAccessorProperty(e){return this.parseClassPropertyAnnotation(e),e.optional&&this.raise(F.AccessorCannotBeOptional,e),super.parseClassAccessorProperty(e)}pushClassMethod(e,r,s,i,a,o){let d=this.tsTryParseTypeParameters(this.tsParseConstModifier);d&&a&&this.raise(F.ConstructorHasTypeParameters,d);let{declare:c=!1,kind:l}=r;c&&(l==="get"||l==="set")&&this.raise(F.DeclareAccessor,r,{kind:l}),d&&(r.typeParameters=d),super.pushClassMethod(e,r,s,i,a,o)}pushClassPrivateMethod(e,r,s,i){let a=this.tsTryParseTypeParameters(this.tsParseConstModifier);a&&(r.typeParameters=a),super.pushClassPrivateMethod(e,r,s,i)}declareClassPrivateMethodInScope(e,r){e.type!=="TSDeclareMethod"&&(e.type==="MethodDefinition"&&e.value.body==null||super.declareClassPrivateMethodInScope(e,r))}parseClassSuper(e){if(super.parseClassSuper(e),e.superClass)if(e.superClass.type==="TSInstantiationExpression"){let r=e.superClass,s=r.expression;this.takeSurroundingComments(s,s.start,s.end);let i=r.typeParameters;this.takeSurroundingComments(i,i.start,i.end),e.superClass=s,e.superTypeParameters=i}else(this.match(47)||this.match(51))&&(e.superTypeParameters=this.tsParseTypeArgumentsInExpression());this.eatContextual(113)&&(e.implements=this.tsParseHeritageClause("implements"))}parseObjPropValue(e,r,s,i,a,o,d){let c=this.tsTryParseTypeParameters(this.tsParseConstModifier);return c&&(e.typeParameters=c),super.parseObjPropValue(e,r,s,i,a,o,d)}parseFunctionParams(e,r){let s=this.tsTryParseTypeParameters(this.tsParseConstModifier);s&&(e.typeParameters=s),super.parseFunctionParams(e,r)}parseVarId(e,r){super.parseVarId(e,r),e.id.type==="Identifier"&&!this.hasPrecedingLineBreak()&&this.eat(35)&&(e.definite=!0);let s=this.tsTryParseTypeAnnotation();s&&(e.id.typeAnnotation=s,this.resetEndLocation(e.id))}parseAsyncArrowFromCallExpression(e,r){return this.match(14)&&(e.returnType=this.tsParseTypeAnnotation()),super.parseAsyncArrowFromCallExpression(e,r)}parseMaybeAssign(e,r){var s,i,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,r),c),!l.error)return l.node;let{context:h}=this.state,m=h[h.length-1];(m===se.j_oTag||m===se.j_expr)&&h.pop()}if(!((s=l)!=null&&s.error)&&!this.match(47))return super.parseMaybeAssign(e,r);(!c||c===this.state)&&(c=this.state.clone());let p,f=this.tryParse(h=>{var m,g;p=this.tsParseTypeParameters(this.tsParseConstModifier);let y=super.parseMaybeAssign(e,r);return(y.type!=="ArrowFunctionExpression"||(m=y.extra)!=null&&m.parenthesized)&&h(),((g=p)==null?void 0:g.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&&(Ef(!this.hasPlugin("jsx")),u=this.tryParse(()=>super.parseMaybeAssign(e,r),c),!u.error))return u.node;if((i=l)!=null&&i.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 r;e.params.length===1&&!e.params[0].constraint&&!((r=e.extra)!=null&&r.trailingComma)&&this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(F.ReservedArrowTypeParam,e)}parseMaybeUnary(e,r){return!this.hasPlugin("jsx")&&this.match(47)?this.tsParseTypeAssertion():super.parseMaybeUnary(e,r)}parseArrow(e){if(this.match(14)){let r=this.tryParse(s=>{let i=this.tsParseTypeOrTypePredicateAnnotation(14);return(this.canInsertSemicolon()||!this.match(19))&&s(),i});if(r.aborted)return;r.thrown||(r.error&&(this.state=r.failState),e.returnType=r.node)}return super.parseArrow(e)}parseFunctionParamType(e){this.eat(17)&&(e.optional=!0);let r=this.tsTryParseTypeAnnotation();return r&&(e.typeAnnotation=r),this.resetEndLocation(e),e}isAssignable(e,r){switch(e.type){case"TSTypeCastExpression":return this.isAssignable(e.expression,r);case"TSParameterProperty":return!0;default:return super.isAssignable(e,r)}}toAssignable(e,r=!1){switch(e.type){case"ParenthesizedExpression":this.toAssignableParenthesizedExpression(e,r);break;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":r?this.expressionScope.recordArrowParameterBindingError(F.UnexpectedTypeCastInParameter,e):this.raise(F.UnexpectedTypeCastInParameter,e),this.toAssignable(e.expression,r);break;case"AssignmentExpression":!r&&e.left.type==="TSTypeCastExpression"&&(e.left=this.typeCastToParameter(e.left));default:super.toAssignable(e,r)}}toAssignableParenthesizedExpression(e,r){switch(e.expression.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":case"ParenthesizedExpression":this.toAssignable(e.expression,r);break;default:super.toAssignable(e,r)}}checkToRestConversion(e,r){switch(e.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":this.checkToRestConversion(e.expression,!1);break;default:super.checkToRestConversion(e,r)}}isValidLVal(e,r,s,i){switch(e){case"TSTypeCastExpression":return!0;case"TSParameterProperty":return"parameter";case"TSNonNullExpression":return"expression";case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":return(i!==64||!s)&&["expression",!0];default:return super.isValidLVal(e,r,s,i)}}parseBindingAtom(){return this.state.type===78?this.parseIdentifier(!0):super.parseBindingAtom()}parseMaybeDecoratorArguments(e,r){if(this.match(47)||this.match(51)){let s=this.tsParseTypeArgumentsInExpression();if(this.match(10)){let i=super.parseMaybeDecoratorArguments(e,r);return i.typeParameters=s,i}this.unexpected(null,10)}return super.parseMaybeDecoratorArguments(e,r)}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,r){let s=super.parseMaybeDefault(e,r);return s.type==="AssignmentPattern"&&s.typeAnnotation&&s.right.start<s.typeAnnotation.start&&this.raise(F.TypeAnnotationAfterAssign,s.typeAnnotation),s}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,r,s){let i=e[r];i.type==="TSTypeCastExpression"&&(e[r]=this.typeCastToParameter(i)),super.toAssignableListItem(e,r,s)}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(r=>this.isAssignable(r,!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 r=this.tsTryParseAndCatch(()=>this.tsParseTypeArgumentsInExpression());r&&(e.typeParameters=r)}return super.jsxParseOpeningElementAfterName(e)}getGetterSetterExpectedParamCount(e){let r=super.getGetterSetterExpectedParamCount(e),i=this.getObjectOrClassMethodParams(e)[0];return i&&this.isThisParam(i)?r+1:r}parseCatchClauseParam(){let e=super.parseCatchClauseParam(),r=this.tsTryParseTypeAnnotation();return r&&(e.typeAnnotation=r,this.resetEndLocation(e)),e}tsInAmbientContext(e){let{isAmbientContext:r,strict:s}=this.state;this.state.isAmbientContext=!0,this.state.strict=!1;try{return e()}finally{this.state.isAmbientContext=r,this.state.strict=s}}parseClass(e,r,s){let i=this.state.inAbstractClass;this.state.inAbstractClass=!!e.abstract;try{return super.parseClass(e,r,s)}finally{this.state.inAbstractClass=i}}tsParseAbstractDeclaration(e,r){if(this.match(80))return e.abstract=!0,this.maybeTakeDecorators(r,this.parseClass(e,!0,!1));if(this.isContextual(129))return this.hasFollowingLineBreak()?null:(e.abstract=!0,this.raise(F.NonClassMethodPropertyHasAbstractModifier,e),this.tsParseInterfaceDeclaration(e));throw this.unexpected(null,80)}parseMethod(e,r,s,i,a,o,d){let c=super.parseMethod(e,r,s,i,a,o,d);if((c.abstract||c.type==="TSAbstractMethodDefinition")&&(this.hasPlugin("estree")?c.value:c).body){let{key:p}=c;this.raise(F.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,r,s,i){return!r&&i?(this.parseTypeOnlyImportExportSpecifier(e,!1,s),this.finishNode(e,"ExportSpecifier")):(e.exportKind="value",super.parseExportSpecifier(e,r,s,i))}parseImportSpecifier(e,r,s,i,a){return!r&&i?(this.parseTypeOnlyImportExportSpecifier(e,!0,s),this.finishNode(e,"ImportSpecifier")):(e.importKind="value",super.parseImportSpecifier(e,r,s,i,s?4098:4096))}parseTypeOnlyImportExportSpecifier(e,r,s){let i=r?"imported":"local",a=r?"local":"exported",o=e[i],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();it(this.state.type)?(c=!0,o=f,d=r?this.parseIdentifier():this.parseModuleExportName(),l=!1):(d=h,l=!1)}else it(this.state.type)?(l=!1,d=r?this.parseIdentifier():this.parseModuleExportName()):(c=!0,o=f)}else it(this.state.type)&&(c=!0,r?(o=this.parseIdentifier(!0),this.isContextual(93)||this.checkReservedWord(o.name,o.loc.start,!0,!0)):o=this.parseModuleExportName());c&&s&&this.raise(r?F.TypeModifierIsUsedInTypeImports:F.TypeModifierIsUsedInTypeExports,u),e[i]=o,e[a]=d;let p=r?"importKind":"exportKind";e[p]=c?"type":"value",l&&this.eatContextual(93)&&(e[a]=r?this.parseIdentifier():this.parseModuleExportName()),e[a]||(e[a]=this.cloneIdentifier(e[i])),r&&this.checkIdentifier(e[a],c?4098:4096)}fillOptionalPropertiesForTSESLint(e){var r,s,i,a,o,d,c,l,u,p,f,h,m,g,y,w,v,x,R,S,N,E,M,A,C,P,I,$,D,k,T,_,U,K,te,le,X,Ie,Te,kt,Lt,Nr,Or,ni,$r,Dr,Mr,ep,tp;switch(e.type){case"ImportDeclaration":(r=e.phase)!=null||(e.phase=null);return;case"ExpressionStatement":(s=e.directive)!=null||(e.directive=void 0);return;case"RestElement":e.value=void 0;case"Identifier":case"ArrayPattern":case"AssignmentPattern":case"ObjectPattern":(i=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),(m=e.typeParameters)!=null||(e.typeParameters=void 0);return;case"Property":(g=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),(v=e.readonly)!=null||(e.readonly=!1),(x=e.static)!=null||(e.static=!1);return;case"TSAbstractPropertyDefinition":case"PropertyDefinition":case"TSAbstractAccessorProperty":case"AccessorProperty":(R=e.declare)!=null||(e.declare=!1),(S=e.definite)!=null||(e.definite=!1),(N=e.readonly)!=null||(e.readonly=!1),(E=e.typeAnnotation)!=null||(e.typeAnnotation=void 0);case"TSAbstractMethodDefinition":case"MethodDefinition":(M=e.accessibility)!=null||(e.accessibility=void 0),(A=e.decorators)!=null||(e.decorators=[]),(C=e.override)!=null||(e.override=!1),(P=e.optional)!=null||(e.optional=!1);return;case"ClassExpression":(I=e.id)!=null||(e.id=null);case"ClassDeclaration":($=e.abstract)!=null||(e.abstract=!1),(D=e.declare)!=null||(e.declare=!1),(k=e.decorators)!=null||(e.decorators=[]),(T=e.implements)!=null||(e.implements=[]),(_=e.superTypeArguments)!=null||(e.superTypeArguments=void 0),(U=e.typeParameters)!=null||(e.typeParameters=void 0);return;case"TSTypeAliasDeclaration":case"VariableDeclaration":(K=e.declare)!=null||(e.declare=!1);return;case"VariableDeclarator":(te=e.definite)!=null||(e.definite=!1);return;case"TSEnumDeclaration":(le=e.const)!=null||(e.const=!1),(X=e.declare)!=null||(e.declare=!1);return;case"TSEnumMember":(Ie=e.computed)!=null||(e.computed=!1);return;case"TSImportType":(Te=e.qualifier)!=null||(e.qualifier=null),(kt=e.options)!=null||(e.options=null);return;case"TSInterfaceDeclaration":(Lt=e.declare)!=null||(e.declare=!1),(Nr=e.extends)!=null||(e.extends=[]);return;case"TSMappedType":(Or=e.optional)!=null||(e.optional=!1),(ni=e.readonly)!=null||(e.readonly=void 0);return;case"TSModuleDeclaration":($r=e.declare)!=null||(e.declare=!1),(Dr=e.global)!=null||(e.global=e.kind==="global");return;case"TSTypeParameter":(Mr=e.const)!=null||(e.const=!1),(ep=e.in)!=null||(e.in=!1),(tp=e.out)!=null||(e.out=!1);return}}chStartsBindingIdentifierAndNotRelationalOperator(e,r){if(mt(e)){if(dd.lastIndex=r,dd.test(this.input)){let s=this.codePointAtPos(dd.lastIndex);if(!pn(s)&&s!==92)return!1}return!0}else return e===92}nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine(){let e=this.nextTokenInLineStart(),r=this.codePointAtPos(e);return this.chStartsBindingIdentifierAndNotRelationalOperator(r,e)}nextTokenIsIdentifierOrStringLiteralOnSameLine(){let e=this.nextTokenInLineStart(),r=this.codePointAtPos(e);return this.chStartsBindingIdentifier(r,e)||r===34||r===39}};function RR(n){if(n.type!=="MemberExpression")return!1;let{computed:t,property:e}=n;return t&&e.type!=="StringLiteral"&&(e.type!=="TemplateLiteral"||e.expressions.length>0)?!1:Kf(n.object)}function IR(n,t){var e;let{type:r}=n;if((e=n.extra)!=null&&e.parenthesized)return!1;if(t){if(r==="Literal"){let{value:s}=n;if(typeof s=="string"||typeof s=="boolean")return!0}}else if(r==="StringLiteral"||r==="BooleanLiteral")return!0;return!!(Gf(n,t)||AR(n,t)||r==="TemplateLiteral"&&n.expressions.length===0||RR(n))}function Gf(n,t){return t?n.type==="Literal"&&(typeof n.value=="number"||"bigint"in n):n.type==="NumericLiteral"||n.type==="BigIntLiteral"}function AR(n,t){if(n.type==="UnaryExpression"){let{operator:e,argument:r}=n;if(e==="-"&&Gf(r,t))return!0}return!1}function Kf(n){return n.type==="Identifier"?!0:n.type!=="MemberExpression"||n.computed?!1:Kf(n.object)}var Nf=st`placeholders`({ClassNameIsRequired:"A class name is required.",UnexpectedSpace:"Unexpected space in placeholder."}),PR=n=>class extends n{parsePlaceholder(e){if(this.match(133)){let r=this.startNode();return this.next(),this.assertNoSpace(),r.name=super.parseIdentifier(!0),this.assertNoSpace(),this.expect(133),this.finishPlaceholder(r,e)}}finishPlaceholder(e,r){let s=e;return(!s.expectedNode||!s.type)&&(s=this.finishNode(s,"Placeholder")),s.expectedNode=r,s}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,r,s,i){e!==void 0&&super.checkReservedWord(e,r,s,i)}cloneIdentifier(e){let r=super.cloneIdentifier(e);return r.type==="Placeholder"&&(r.expectedNode=e.expectedNode),r}cloneStringLiteral(e){return e.type==="Placeholder"?this.cloneIdentifier(e):super.cloneStringLiteral(e)}parseBindingAtom(){return this.parsePlaceholder("Pattern")||super.parseBindingAtom()}isValidLVal(e,r,s,i){return e==="Placeholder"||super.isValidLVal(e,r,s,i)}toAssignable(e,r){e&&e.type==="Placeholder"&&e.expectedNode==="Expression"?e.expectedNode="Pattern":super.toAssignable(e,r)}chStartsBindingIdentifier(e,r){if(super.chStartsBindingIdentifier(e,r))return!0;let s=this.nextTokenStart();return this.input.charCodeAt(s)===37&&this.input.charCodeAt(s+1)===37}verifyBreakContinue(e,r){var s;((s=e.label)==null?void 0:s.type)!=="Placeholder"&&super.verifyBreakContinue(e,r)}parseExpressionStatement(e,r){var s;if(r.type!=="Placeholder"||(s=r.extra)!=null&&s.parenthesized)return super.parseExpressionStatement(e,r);if(this.match(14)){let a=e;return a.label=this.finishPlaceholder(r,"Identifier"),this.next(),a.body=super.parseStatementOrSloppyAnnexBFunctionDeclaration(),this.finishNode(a,"LabeledStatement")}this.semicolon();let i=e;return i.name=r.name,this.finishPlaceholder(i,"Statement")}parseBlock(e,r,s){return this.parsePlaceholder("BlockStatement")||super.parseBlock(e,r,s)}parseFunctionId(e){return this.parsePlaceholder("Identifier")||super.parseFunctionId(e)}parseClass(e,r,s){let i=r?"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(s||!r)return e.id=null,e.body=this.finishPlaceholder(o,"ClassBody"),this.finishNode(e,i);throw this.raise(Nf.ClassNameIsRequired,this.state.startLoc)}else this.parseClassId(e,r,s);return super.parseClassSuper(e),e.body=this.parsePlaceholder("ClassBody")||super.parseClassBody(!!e.superClass,a),this.finishNode(e,i)}parseExport(e,r){let s=this.parsePlaceholder("Identifier");if(!s)return super.parseExport(e,r);let i=e;if(!this.isContextual(98)&&!this.match(12))return i.specifiers=[],i.source=null,i.declaration=this.finishPlaceholder(s,"Declaration"),this.finishNode(i,"ExportNamedDeclaration");this.expectPlugin("exportDefaultFrom");let a=this.startNode();return a.exported=s,i.specifiers=[this.finishNode(a,"ExportDefaultSpecifier")],super.parseExport(i,r)}isExportDefaultSpecifier(){if(this.match(65)){let e=this.nextTokenStart();if(this.isUnparsedContextual(e,"from")&&this.input.startsWith(Ft(133),this.nextTokenStartSince(e+4)))return!0}return super.isExportDefaultSpecifier()}maybeParseExportDefaultSpecifier(e,r){var s;return(s=e.specifiers)!=null&&s.length?!0:super.maybeParseExportDefaultSpecifier(e,r)}checkExport(e){let{specifiers:r}=e;r!=null&&r.length&&(e.specifiers=r.filter(s=>s.exported.type==="Placeholder")),super.checkExport(e),e.specifiers=r}parseImport(e){let r=this.parsePlaceholder("Identifier");if(!r)return super.parseImport(e);if(e.specifiers=[],!this.isContextual(98)&&!this.match(12))return e.source=this.finishPlaceholder(r,"StringLiteral"),this.semicolon(),this.finishNode(e,"ImportDeclaration");let s=this.startNodeAtNode(r);return s.local=r,e.specifiers.push(this.finishNode(s,"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(Nf.UnexpectedSpace,this.state.lastTokEndLoc)}},SR=n=>class extends n{parseV8Intrinsic(){if(this.match(54)){let e=this.state.startLoc,r=this.startNode();if(this.next(),ie(this.state.type)){let s=this.parseIdentifierName(),i=this.createIdentifier(r,s);if(this.castNodeTo(i,"V8IntrinsicIdentifier"),this.match(10))return i}this.unexpected(e)}}parseExprAtom(e){return this.parseV8Intrinsic()||super.parseExprAtom(e)}},Of=["minimal","fsharp","hack","smart"],$f=["^^","@@","^","%","#"];function TR(n){if(n.has("decorators")){if(n.has("decorators-legacy"))throw new Error("Cannot use the decorators and decorators-legacy plugin together");let r=n.get("decorators").decoratorsBeforeExport;if(r!=null&&typeof r!="boolean")throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");let s=n.get("decorators").allowCallParenthesized;if(s!=null&&typeof s!="boolean")throw new Error("'allowCallParenthesized' must be a boolean.")}if(n.has("flow")&&n.has("typescript"))throw new Error("Cannot combine flow and typescript plugins.");if(n.has("placeholders")&&n.has("v8intrinsic"))throw new Error("Cannot combine placeholders and v8intrinsic plugins.");if(n.has("pipelineOperator")){var t;let r=n.get("pipelineOperator").proposal;if(!Of.includes(r)){let s=Of.map(i=>`"${i}"`).join(", ");throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${s}.`)}if(r==="hack"){var e;if(n.has("placeholders"))throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");if(n.has("v8intrinsic"))throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");let s=n.get("pipelineOperator").topicToken;if(!$f.includes(s)){let i=$f.map(a=>`"${a}"`).join(", ");throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${i}.`)}if(s==="#"&&((e=n.get("recordAndTuple"))==null?void 0:e.syntaxType)==="hash")throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple",n.get("recordAndTuple")])}\`.`)}else if(r==="smart"&&((t=n.get("recordAndTuple"))==null?void 0:t.syntaxType)==="hash")throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple",n.get("recordAndTuple")])}\`.`)}if(n.has("moduleAttributes")){if(n.has("deprecatedImportAssert")||n.has("importAssertions"))throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.");if(n.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(n.has("importAssertions")&&n.has("deprecatedImportAssert"))throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins.");if(n.has("deprecatedImportAssert")||n.has("importAttributes")&&n.get("importAttributes").deprecatedAssertSyntax&&n.set("deprecatedImportAssert",{}),n.has("recordAndTuple")){let r=n.get("recordAndTuple").syntaxType;if(r!=null){let s=["hash","bar"];if(!s.includes(r))throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: "+s.map(i=>`'${i}'`).join(", "))}}if(n.has("asyncDoExpressions")&&!n.has("doExpressions")){let r=new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");throw r.missingPlugins="doExpressions",r}if(n.has("optionalChainingAssign")&&n.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(n.has("discardBinding")&&n.get("discardBinding").syntaxType!=="void")throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'.")}var Wf={estree:Ok,jsx:lR,flow:aR,typescript:kR,v8intrinsic:SR,placeholders:PR},ER=Object.keys(Wf),Cd=class extends Ed{checkProto(t,e,r,s){if(t.type==="SpreadElement"||this.isObjectMethod(t)||t.computed||t.shorthand)return r;let i=t.key;return(i.type==="Identifier"?i.name:i.value)==="__proto__"?e?(this.raise(b.RecordNoProto,i),!0):(r&&(s?s.doubleProtoLoc===null&&(s.doubleProtoLoc=i.loc.start):this.raise(b.DuplicateProto,i)),!0):r}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,r=this.parseMaybeAssign(t);if(this.match(12)){let s=this.startNodeAt(e);for(s.expressions=[r];this.eat(12);)s.expressions.push(this.parseMaybeAssign(t));return this.toReferencedList(s.expressions),this.finishNode(s,"SequenceExpression")}return r}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 r=this.state.startLoc,s=this.isContextual(108);if(s&&this.prodParam.hasYield){this.next();let d=this.parseYield(r);return e&&(d=e.call(this,d,r)),d}let i;t?i=!1:(t=new Kn,i=!0);let{type:a}=this.state;(a===10||ie(a))&&(this.state.potentialArrowAt=this.state.start);let o=this.parseMaybeConditional(t);if(e&&(o=e.call(this,o,r)),_k(this.state.type)){let d=this.startNodeAt(r),c=this.state.value;if(d.operator=c,this.match(29)){this.toAssignable(o,!0),d.left=o;let l=r.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 i&&this.checkExpressionErrors(t,!0);if(s){let{type:d}=this.state;if((this.hasPlugin("v8intrinsic")?qr(d):qr(d)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(b.YieldNotInGeneratorFunction,r),this.parseYield(r)}return o}parseMaybeConditional(t){let e=this.state.startLoc,r=this.state.potentialArrowAt,s=this.parseExprOps(t);return this.shouldExitDescending(s,r)?s:this.parseConditional(s,e,t)}parseConditional(t,e,r){if(this.eat(17)){let s=this.startNodeAt(e);return s.test=t,s.consequent=this.parseMaybeAssignAllowIn(),this.expect(14),s.alternate=this.parseMaybeAssign(),this.finishNode(s,"ConditionalExpression")}return t}parseMaybeUnaryOrPrivate(t){return this.match(139)?this.parsePrivateName():this.parseMaybeUnary(t)}parseExprOps(t){let e=this.state.startLoc,r=this.state.potentialArrowAt,s=this.parseMaybeUnaryOrPrivate(t);return this.shouldExitDescending(s,r)?s:this.parseExprOp(s,e,-1)}parseExprOp(t,e,r){if(this.isPrivateName(t)){let i=this.getPrivateNameSV(t);(r>=Ei(58)||!this.prodParam.hasIn||!this.match(58))&&this.raise(b.PrivateInExpectedIn,t,{identifierName:i}),this.classScope.usePrivateName(i,t.loc.start)}let s=this.state.type;if(Fk(s)&&(this.prodParam.hasIn||!this.match(58))){let i=Ei(s);if(i>r){if(s===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=s===41||s===42,d=s===40;if(d&&(i=Ei(42)),this.next(),s===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(s,i);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,r)}}return t}parseExprOpRightExpr(t,e){let r=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),r)});default:return this.parseExprOpBaseRightExpr(t,e)}}parseExprOpBaseRightExpr(t,e){let r=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnaryOrPrivate(),r,Uk(t)?e-1:e)}parseHackPipeBody(){var t;let{startLoc:e}=this.state,r=this.parseMaybeAssign();return Ik.has(r.type)&&!((t=r.extra)!=null&&t.parenthesized)&&this.raise(b.PipeUnparenthesizedBody,e,{type:r.type}),this.topicReferenceWasUsedInCurrentContext()||this.raise(b.PipeTopicUnused,e),r}checkExponentialAfterUnary(t){this.match(57)&&this.raise(b.UnexpectedTokenUnaryExponentiation,t.argument)}parseMaybeUnary(t,e){let r=this.state.startLoc,s=this.isContextual(96);if(s&&this.recordAwaitIfAllowed()){this.next();let d=this.parseAwait(r);return e||this.checkExponentialAfterUnary(d),d}let i=this.match(34),a=this.startNode();if(Vk(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(!i)return e||this.checkExponentialAfterUnary(a),this.finishNode(a,"UnaryExpression")}let o=this.parseUpdate(a,i,t);if(s){let{type:d}=this.state;if((this.hasPlugin("v8intrinsic")?qr(d):qr(d)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(b.AwaitNotInAsyncContext,r),this.parseAwait(r)}return o}parseUpdate(t,e,r){if(e){let a=t;return this.checkLVal(a.argument,this.finishNode(a,"UpdateExpression")),t}let s=this.state.startLoc,i=this.parseExprSubscripts(r);if(this.checkExpressionErrors(r,!1))return i;for(;Bk(this.state.type)&&!this.canInsertSemicolon();){let a=this.startNodeAt(s);a.operator=this.state.value,a.prefix=!1,a.argument=i,this.next(),this.checkLVal(i,i=this.finishNode(a,"UpdateExpression"))}return i}parseExprSubscripts(t){let e=this.state.startLoc,r=this.state.potentialArrowAt,s=this.parseExprAtom(t);return this.shouldExitDescending(s,r)?s:this.parseSubscripts(s,e)}parseSubscripts(t,e,r){let s={optionalChainMember:!1,maybeAsyncArrow:this.atPossibleAsyncArrow(t),stop:!1};do t=this.parseSubscript(t,e,r,s),s.maybeAsyncArrow=!1;while(!s.stop);return t}parseSubscript(t,e,r,s){let{type:i}=this.state;if(!r&&i===15)return this.parseBind(t,e,s);if(Oi(i))return this.parseTaggedTemplateExpression(t,e,s);let a=!1;if(i===18){if(r&&(this.raise(b.OptionalChainingNoNew,this.state.startLoc),this.lookaheadCharCode()===40))return this.stopParseSubscript(t,s);s.optionalChainMember=a=!0,this.next()}if(!r&&this.match(10))return this.parseCoverCallAndAsyncArrowHead(t,e,s,a);{let o=this.eat(0);return o||a||this.eat(16)?this.parseMember(t,e,s,o,a):this.stopParseSubscript(t,s)}}stopParseSubscript(t,e){return e.stop=!0,t}parseMember(t,e,r,s,i){let a=this.startNodeAt(e);return a.object=t,a.computed=s,s?(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),r.optionalChainMember?(a.optional=i,this.finishNode(a,"OptionalMemberExpression")):this.finishNode(a,"MemberExpression")}parseBind(t,e,r){let s=this.startNodeAt(e);s.object=t,this.next();let i=this.match(83),a=this.parseNoCallExpr();if(a.type==="Super"||i&&a.type==="ImportExpression"||a.type==="Import")throw this.raise(b.UnsupportedBindRHS,a);return s.callee=a,r.stop=!0,this.parseSubscripts(this.finishNode(s,"BindExpression"),e,!1)}parseCoverCallAndAsyncArrowHead(t,e,r,s){let i=this.state.maybeInArrowParameters,a=null;this.state.maybeInArrowParameters=!0,this.next();let o=this.startNodeAt(e);o.callee=t;let{maybeAsyncArrow:d,optionalChainMember:c}=r;d&&(this.expressionScope.enter(wR()),a=new Kn),c&&(o.optional=s),s?o.arguments=this.parseCallExpressionArguments():o.arguments=this.parseCallExpressionArguments(t.type!=="Super",o,a);let l=this.finishCallExpression(o,c);return d&&this.shouldParseAsyncArrow()&&!s?(r.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=i,l}toReferencedArguments(t,e){this.toReferencedListDeep(t.arguments,e)}parseTaggedTemplateExpression(t,e,r){let s=this.startNodeAt(e);return s.tag=t,s.quasi=this.parseTemplate(!0),r.optionalChainMember&&this.raise(b.OptionalChainingNoTemplate,e),this.finishNode(s,"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 r of t.arguments)r.type==="SpreadElement"&&this.raise(b.ImportCallSpreadArgument,r);return this.finishNode(t,e?"OptionalCallExpression":"CallExpression")}parseCallExpressionArguments(t,e,r){let s=[],i=!0,a=this.state.inFSharpPipelineDirectBody;for(this.state.inFSharpPipelineDirectBody=!1;!this.eat(11);){if(i)i=!1;else if(this.expect(12),this.match(11)){e&&this.addTrailingCommaExtraToNode(e),this.next();break}s.push(this.parseExprListItem(11,!1,r,t))}return this.state.inFSharpPipelineDirectBody=a,s}shouldParseAsyncArrow(){return this.match(19)&&!this.canInsertSemicolon()}parseAsyncArrowFromCallExpression(t,e){var r;return this.resetPreviousNodeTrailingComments(e),this.expect(19),this.parseArrowExpression(t,e.arguments,!0,(r=e.extra)==null?void 0:r.trailingCommaLoc),e.innerComments&&Xr(t,e.innerComments),e.callee.trailingComments&&Xr(t,e.callee.trailingComments),t}parseNoCallExpr(){let t=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),t,!0)}parseExprAtom(t){let e,r=null,{type:s}=this.state;switch(s){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 i=this.state.potentialArrowAt===this.state.start;return this.parseParenAndDistinguishExpression(i)}case 0:return this.parseArrayLike(3,!1,t);case 5:return this.parseObjectLike(8,!1,!1,t);case 68:return this.parseFunctionOrFunctionSent();case 26:r=this.parseDecorators();case 80:return this.parseClass(this.maybeTakeDecorators(r,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 i=e.callee=this.parseNoCallExpr();if(i.type==="MemberExpression")return this.finishNode(e,"BindExpression");throw this.raise(b.UnsupportedBind,i)}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 i=this.getPluginOption("pipelineOperator","proposal");if(i)return this.parseTopicReference(i);throw this.unexpected()}case 47:{let i=this.input.codePointAt(this.nextTokenStart());throw mt(i)||i===62?this.expectOnePlugin(["jsx","flow","typescript"]):this.unexpected()}default:if(s===137)return this.parseDecimalLiteral(this.state.value);if(s===2||s===1)return this.parseArrayLike(this.state.type===2?4:3,!0);if(s===6||s===7)return this.parseObjectLike(this.state.type===6?9:8,!1,!0);if(ie(s)){if(this.isContextual(127)&&this.lookaheadInLineCharCode()===123)return this.parseModuleExpression();let i=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(ie(d))return i&&this.lookaheadCharCode()===61?this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(o)):o;if(d===90)return this.resetPreviousNodeTrailingComments(o),this.parseDo(this.startNodeAtNode(o),!0)}return i&&this.match(19)&&!this.canInsertSemicolon()?(this.next(),this.parseArrowExpression(this.startNodeAtNode(o),[o],!1)):o}else throw this.unexpected()}}parseTopicReferenceThenEqualsSign(t,e){let r=this.getPluginOption("pipelineOperator","proposal");if(r)return this.state.type=t,this.state.value=e,this.state.pos--,this.state.end--,this.state.endLoc=Me(this.state.endLoc,-1),this.parseTopicReference(r);throw this.unexpected()}parseTopicReference(t){let e=this.startNode(),r=this.state.startLoc,s=this.state.type;return this.next(),this.finishTopicReference(e,r,t,s)}finishTopicReference(t,e,r,s){if(this.testTopicReferenceConfiguration(r,e,s))return r==="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:Ft(s)})}testTopicReferenceConfiguration(t,e,r){switch(t){case"hack":return this.hasPlugin(["pipelineOperator",{topicToken:Ft(r)}]);case"smart":return r===27;default:throw this.raise(b.PipeTopicRequiresHackPipes,e)}}parseAsyncArrowUnaryFunction(t){this.prodParam.enter(Ci(!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 r=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=r,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(Me(this.state.startLoc,1)),r=this.state.value;return this.next(),t.id=this.createIdentifier(e,r),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,r){t.meta=e;let s=this.state.containsEsc;return t.property=this.parseIdentifier(!0),(t.property.name!==r||s)&&this.raise(b.UnsupportedMetaProperty,t.property,{target:e.name,onlyValidPropertyName:r}),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,r){return this.addExtra(r,"rawValue",t),this.addExtra(r,"raw",this.input.slice(this.offsetToSourcePos(r.start),this.state.end)),r.value=t,this.next(),this.finishNode(r,e)}parseLiteral(t,e){let r=this.startNode();return this.parseLiteralAtNode(t,e,r)}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,r;this.next(),this.expressionScope.enter(gR());let s=this.state.maybeInArrowParameters,i=this.state.inFSharpPipelineDirectBody;this.state.maybeInArrowParameters=!0,this.state.inFSharpPipelineDirectBody=!1;let a=this.state.startLoc,o=[],d=new Kn,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=s,this.state.inFSharpPipelineDirectBody=i;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?(r=this.startNodeAt(a),r.expressions=o,this.finishNode(r,"SequenceExpression"),this.resetEndLocation(r,p)):r=o[0],this.wrapParenthesis(e,r))}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 r=this.startNodeAt(t);return r.expression=e,this.finishNode(r,"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 r=this.parseMetaProperty(t,e,"target");return this.scope.allowNewTarget||this.raise(b.UnexpectedNewTarget,r),r}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),r=this.parseNoCallExpr();t.callee=r,(e&&r.type==="ImportExpression"||r.type==="Import")&&this.raise(b.ImportCallNotNewExpression,r),r.type==="Super"&&this.raise(b.SuperCallNotNewExpression,r)}parseTemplateElement(t){let{start:e,startLoc:r,end:s,value:i}=this.state,a=e+1,o=this.startNodeAt(Me(r,1));i===null&&(t||this.raise(b.InvalidEscapeSequenceTemplate,Me(this.state.firstInvalidTemplateEscapePos,1)));let d=this.match(24),c=d?-1:-2,l=s+c;o.value={raw:this.input.slice(a,l).replace(/\r\n?/g,`
10
- `),cooked:i===null?null:i.slice(1,c)},o.tail=d,this.next();let u=this.finishNode(o,"TemplateElement");return this.resetEndLocation(u,Me(this.state.lastTokEndLoc,c)),u}parseTemplate(t){let e=this.startNode(),r=this.parseTemplateElement(t),s=[r],i=[];for(;!r.tail;)i.push(this.parseTemplateSubstitution()),this.readTemplateContinuation(),s.push(r=this.parseTemplateElement(t));return e.expressions=i,e.quasis=s,this.finishNode(e,"TemplateLiteral")}parseTemplateSubstitution(){return this.parseExpression()}parseObjectLike(t,e,r,s){r&&this.expectPlugin("recordAndTuple");let i=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(s),a=this.checkProto(l,r,a,s)),r&&!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=i;let c="ObjectExpression";return e?c="ObjectPattern":r&&(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 r=this.startNode(),s=!1,i=!1,a;if(this.match(21))return e.length&&this.unexpected(),this.parseSpread();e.length&&(r.decorators=e,e=[]),r.method=!1,t&&(a=this.state.startLoc);let o=this.eat(55);this.parsePropertyNamePrefixOperator(r);let d=this.state.containsEsc;if(this.parsePropertyName(r,t),!o&&!d&&this.maybeAsyncOrAccessorProp(r)){let{key:c}=r,l=c.name;l==="async"&&!this.hasPrecedingLineBreak()&&(s=!0,this.resetPreviousNodeTrailingComments(c),o=this.eat(55),this.parsePropertyName(r)),(l==="get"||l==="set")&&(i=!0,this.resetPreviousNodeTrailingComments(c),r.kind=l,this.match(55)&&(o=!0,this.raise(b.AccessorIsGenerator,this.state.curPosition(),{kind:l}),this.next()),this.parsePropertyName(r))}return this.parseObjPropValue(r,a,o,s,!1,i,t)}getGetterSetterExpectedParamCount(t){return t.kind==="get"?0:1}getObjectOrClassMethodParams(t){return t.params}checkGetterSetterParams(t){var e;let r=this.getGetterSetterExpectedParamCount(t),s=this.getObjectOrClassMethodParams(t);s.length!==r&&this.raise(t.kind==="get"?b.BadGetterArity:b.BadSetterArity,t),t.kind==="set"&&((e=s[s.length-1])==null?void 0:e.type)==="RestElement"&&this.raise(b.BadSetterRestParameter,t)}parseObjectMethod(t,e,r,s,i){if(i){let a=this.parseMethod(t,e,!1,!1,!1,"ObjectMethod");return this.checkGetterSetterParams(a),a}if(r||e||this.match(10))return s&&this.unexpected(),t.kind="method",t.method=!0,this.parseMethod(t,e,r,!1,!1,"ObjectMethod")}parseObjectProperty(t,e,r,s){if(t.shorthand=!1,this.eat(14))return t.value=r?this.parseMaybeDefault(this.state.startLoc):this.parseMaybeAssignAllowInOrVoidPattern(8,s),this.finishObjectProperty(t);if(!t.computed&&t.key.type==="Identifier"){if(this.checkReservedWord(t.key.name,t.key.loc.start,!0,!1),r)t.value=this.parseMaybeDefault(e,this.cloneIdentifier(t.key));else if(this.match(29)){let i=this.state.startLoc;s!=null?s.shorthandAssignLoc===null&&(s.shorthandAssignLoc=i):this.raise(b.InvalidCoverInitializedName,i),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,r,s,i,a,o){let d=this.parseObjectMethod(t,r,s,i,a)||this.parseObjectProperty(t,e,i,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:r,value:s}=this.state,i;if(it(r))i=this.parseIdentifier(!0);else switch(r){case 135:i=this.parseNumericLiteral(s);break;case 134:i=this.parseStringLiteral(s);break;case 136:i=this.parseBigIntLiteral(s);break;case 139:{let a=this.state.startLoc;e!=null?e.privateKeyLoc===null&&(e.privateKeyLoc=a):this.raise(b.UnexpectedPrivateField,a),i=this.parsePrivateName();break}default:if(r===137){i=this.parseDecimalLiteral(s);break}this.unexpected()}t.key=i,r!==139&&(t.computed=!1)}}initFunction(t,e){t.id=null,t.generator=!1,t.async=e}parseMethod(t,e,r,s,i,a,o=!1){this.initFunction(t,r),t.generator=e,this.scope.enter(530|(o?576:0)|(i?32:0)),this.prodParam.enter(Ci(r,t.generator)),this.parseFunctionParams(t,s);let d=this.parseFunctionBodyAndFinish(t,a,!0);return this.prodParam.exit(),this.scope.exit(),d}parseArrayLike(t,e,r){e&&this.expectPlugin("recordAndTuple");let s=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let i=this.startNode();return this.next(),i.elements=this.parseExprList(t,!e,r,i),this.state.inFSharpPipelineDirectBody=s,this.finishNode(i,e?"TupleExpression":"ArrayExpression")}parseArrowExpression(t,e,r,s){this.scope.enter(518);let i=Ci(r,!1);!this.match(5)&&this.prodParam.hasIn&&(i|=8),this.prodParam.enter(i),this.initFunction(t,r);let a=this.state.maybeInArrowParameters;return e&&(this.state.maybeInArrowParameters=!0,this.setArrowFunctionParameters(t,e,s)),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,r){this.toAssignableList(e,r,!1),t.params=e}parseFunctionBodyAndFinish(t,e,r=!1){return this.parseFunctionBody(t,!1,r),this.finishNode(t,e)}parseFunctionBody(t,e,r=!1){let s=e&&!this.match(5);if(this.expressionScope.enter(qf()),s)t.body=this.parseMaybeAssign(),this.checkParams(t,!1,e,!1);else{let i=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=!i&&this.state.strict;this.checkParams(t,!this.state.strict&&!e&&!r&&!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,r=t.length;e<r;e++)if(!this.isSimpleParameter(t[e]))return!1;return!0}checkParams(t,e,r,s=!0){let i=!e&&new Set,a={type:"FormalParameters"};for(let o of t.params)this.checkLVal(o,a,5,i,s)}parseExprList(t,e,r,s){let i=[],a=!0;for(;!this.eat(t);){if(a)a=!1;else if(this.expect(12),this.match(t)){s&&this.addTrailingCommaExtraToNode(s),this.next();break}i.push(this.parseExprListItem(t,e,r))}return i}parseExprListItem(t,e,r,s){let i;if(this.match(12))e||this.raise(b.UnexpectedToken,this.state.curPosition(),{unexpected:","}),i=null;else if(this.match(21)){let a=this.state.startLoc;i=this.parseParenItem(this.parseSpread(r),a)}else if(this.match(17)){this.expectPlugin("partialApplication"),s||this.raise(b.UnexpectedArgumentPlaceholder,this.state.startLoc);let a=this.startNode();this.next(),i=this.finishNode(a,"ArgumentPlaceholder")}else i=this.parseMaybeAssignAllowInOrVoidPattern(t,r,this.parseParenItem);return i}parseIdentifier(t){let e=this.startNode(),r=this.parseIdentifierName(t);return this.createIdentifier(e,r)}createIdentifier(t,e){return t.name=e,t.loc.identifierName=e,this.finishNode(t,"Identifier")}createIdentifierAt(t,e,r){return t.name=e,t.loc.identifierName=e,this.finishNodeAt(t,"Identifier",r)}parseIdentifierName(t){let e,{startLoc:r,type:s}=this.state;it(s)?e=this.state.value:this.unexpected();let i=Mk(s);return t?i&&this.replaceToken(132):this.checkReservedWord(e,r,i,!1),this.next(),e}checkReservedWord(t,e,r,s){if(t.length>10||!eR(t))return;if(r&&Yk(t)){this.raise(b.UnexpectedKeyword,e,{keyword:t});return}if((this.state.strict?s?Vf:Ff:jf)(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||Oi(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 r=!1,s=null;if(!this.hasPrecedingLineBreak())switch(r=this.eat(55),this.state.type){case 13:case 140:case 8:case 11:case 3:case 9:case 14:case 12:if(!r)break;default:s=this.parseMaybeAssign()}return e.delegate=r,e.argument=s,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 r=this.startNodeAt(e);return r.callee=t,this.finishNode(r,"PipelineBareFunction")}else{let r=this.startNodeAt(e);return this.checkSmartPipeTopicBodyEarlyErrors(e),r.expression=t,this.finishNode(r,"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 r=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!0;let s=this.parseExprOp(this.parseMaybeUnaryOrPrivate(),e,t);return this.state.inFSharpPipelineDirectBody=r,s}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 r=this.initializeScopes(!0);this.enterInitialScopes();try{t.body=this.parseProgram(e,8,"module")}finally{r()}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,r){if(e!=null&&this.match(88)){let s=this.lookaheadCharCode();if(s===44||s===(t===3?93:t===8?125:41)||s===61)return this.parseMaybeDefault(this.state.startLoc,this.parseVoidPattern(e))}return this.parseMaybeAssignAllowIn(e,r)}parsePropertyNamePrefixOperator(t){}},cd={kind:1},CR={kind:2},NR=/[\uD800-\uDFFF]/u,ld=/in(?:stanceof)?/y;function OR(n,t,e){for(let r=0;r<n.length;r++){let s=n[r],{type:i}=s;if(typeof i=="number"){if(i===139){let{loc:a,start:o,value:d,end:c}=s,l=o+1,u=Me(a.start,1);n.splice(r,1,new ht({type:It(27),value:"#",start:o,end:l,startLoc:a.start,endLoc:u}),new ht({type:It(132),value:d,start:l,end:c,startLoc:u,endLoc:a.end})),r++;continue}if(Oi(i)){let{loc:a,start:o,value:d,end:c}=s,l=o+1,u=Me(a.start,1),p;t.charCodeAt(o-e)===96?p=new ht({type:It(22),value:"`",start:o,end:l,startLoc:a.start,endLoc:u}):p=new ht({type:It(8),value:"}",start:o,end:l,startLoc:a.start,endLoc:u});let f,h,m,g;i===24?(h=c-1,m=Me(a.end,-1),f=d===null?null:d.slice(1,-1),g=new ht({type:It(22),value:"`",start:h,end:c,startLoc:m,endLoc:a.end})):(h=c-2,m=Me(a.end,-2),f=d===null?null:d.slice(1,-2),g=new ht({type:It(23),value:"${",start:h,end:c,startLoc:m,endLoc:a.end})),n.splice(r,1,p,new ht({type:It(20),value:f,start:l,end:h,startLoc:u,endLoc:m}),g),r+=2;continue}s.type=It(i)}}return n}var Nd=class extends Cd{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=OR(this.tokens,this.input,this.startIndex)),this.finishNode(t,"File")}parseProgram(t,e,r){if(t.sourceType=r,t.interpreter=this.parseInterpreterDirective(),this.parseBlockBody(t,!0,!0,e),this.inModule){if(!(this.optionFlags&64)&&this.scope.undefinedExports.size>0)for(let[i,a]of Array.from(this.scope.undefinedExports))this.raise(b.ModuleExportUndefined,a,{localName:i});this.addExtra(t,"topLevelAwait",this.state.hasTopLevelAwait)}let s;return e===140?s=this.finishNode(t,"Program"):s=this.finishNodeAt(t,"Program",Me(this.state.startLoc,-1)),s}stmtToDirective(t){let e=this.castNodeTo(t,"Directive"),r=this.castNodeTo(t.expression,"DirectiveLiteral"),s=r.value,i=this.input.slice(this.offsetToSourcePos(r.start),this.offsetToSourcePos(r.end)),a=r.value=i.slice(1,-1);return this.addExtra(r,"raw",i),this.addExtra(r,"rawValue",a),this.addExtra(r,"expressionValue",s),e.value=r,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 r=this.lookaheadCharCodeSince(t+2);if(r!==61&&r!==58&&r!==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(mt(t)){if(ld.lastIndex=e,ld.test(this.input)){let r=this.codePointAtPos(ld.lastIndex);if(!pn(r)&&r!==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 r=this.state.type,s=this.startNode(),i=!!(t&2),a=!!(t&4),o=t&1;switch(r){case 60:return this.parseBreakContinueStatement(s,!0);case 63:return this.parseBreakContinueStatement(s,!1);case 64:return this.parseDebuggerStatement(s);case 90:return this.parseDoWhileStatement(s);case 91:return this.parseForStatement(s);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(s,!1,!i&&a);case 80:return i||this.unexpected(),this.parseClass(this.maybeTakeDecorators(e,s),!0);case 69:return this.parseIfStatement(s);case 70:return this.parseReturnStatement(s);case 71:return this.parseSwitchStatement(s);case 72:return this.parseThrowStatement(s);case 73:return this.parseTryStatement(s);case 96:if(this.isAwaitUsing())return this.allowsUsing()?i?this.recordAwaitIfAllowed()||this.raise(b.AwaitUsingNotInAsyncContext,s):this.raise(b.UnexpectedLexicalDeclaration,s):this.raise(b.UnexpectedUsingDeclaration,s),this.next(),this.parseVarStatement(s,"await using");break;case 107:if(this.state.containsEsc||!this.hasInLineFollowingBindingIdentifierOrBrace())break;return this.allowsUsing()?i||this.raise(b.UnexpectedLexicalDeclaration,this.state.startLoc):this.raise(b.UnexpectedUsingDeclaration,this.state.startLoc),this.parseVarStatement(s,"using");case 100:{if(this.state.containsEsc)break;let l=this.nextTokenStart(),u=this.codePointAtPos(l);if(u!==91&&(!i&&this.hasFollowingLineBreak()||!this.chStartsBindingIdentifier(u,l)&&u!==123))break}case 75:i||this.raise(b.UnexpectedLexicalDeclaration,this.state.startLoc);case 74:{let l=this.state.value;return this.parseVarStatement(s,l)}case 92:return this.parseWhileStatement(s);case 76:return this.parseWithStatement(s);case 5:return this.parseBlock();case 13:return this.parseEmptyStatement(s);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 r===83?l=this.parseImport(s):l=this.parseExport(s,e),this.assertModuleNodeAllowed(l),l}default:if(this.isAsyncFunction())return i||this.raise(b.AsyncFunctionInSingleStatementContext,this.state.startLoc),this.next(),this.parseFunctionStatement(s,!0,!i&&a)}let d=this.state.value,c=this.parseExpression();return ie(r)&&c.type==="Identifier"&&this.eat(14)?this.parseLabeledStatement(s,d,c,t):this.parseExpressionStatement(s,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,r){if(t){var s;(s=e.decorators)!=null&&s.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]),r&&this.resetStartLocationFromNode(r,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,r;if(this.match(10)){let s=this.state.startLoc;this.next(),r=this.parseExpression(),this.expect(11),r=this.wrapParenthesis(s,r);let i=this.state.startLoc;t.expression=this.parseMaybeDecoratorArguments(r,s),this.getPluginOption("decorators","allowCallParenthesized")===!1&&t.expression!==r&&this.raise(b.DecoratorArgumentsOutsideParentheses,i)}else{for(r=this.parseIdentifier(!1);this.eat(16);){let s=this.startNodeAt(e);s.object=r,this.match(139)?(this.classScope.usePrivateName(this.state.value,this.state.startLoc),s.property=this.parsePrivateName()):s.property=this.parseIdentifier(!0),s.computed=!1,r=this.finishNode(s,"MemberExpression")}t.expression=this.parseMaybeDecoratorArguments(r,e)}}else t.expression=this.parseExprSubscripts();return this.finishNode(t,"Decorator")}parseMaybeDecoratorArguments(t,e){if(this.eat(10)){let r=this.startNodeAt(e);return r.callee=t,r.arguments=this.parseCallExpressionArguments(),this.toReferencedList(r.arguments),this.finishNode(r,"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 r;for(r=0;r<this.state.labels.length;++r){let s=this.state.labels[r];if((t.label==null||s.name===t.label.name)&&(s.kind!=null&&(e||s.kind===1)||t.label&&e))break}if(r===this.state.labels.length){let s=e?"BreakStatement":"ContinueStatement";this.raise(b.IllegalBreakContinue,t,{type:s})}}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(cd),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(cd);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 r=this.isContextual(100);{let d=this.isAwaitUsing(),c=d||this.isForUsing(),l=r&&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 s=this.isContextual(95),i=new Kn,a=this.parseExpression(!0,i),o=this.isContextual(102);if(o&&(r&&this.raise(b.ForOfLet,a),e===null&&s&&a.type==="Identifier"&&this.raise(b.ForOfAsync,a)),o||this.match(58)){this.checkDestructuringPrivate(i),this.toAssignable(a,!0);let d=o?"ForOfStatement":"ForInStatement";return this.checkLVal(a,{type:d}),this.parseForIn(t,a,e)}else this.checkExpressionErrors(i,!0);return e!==null&&this.unexpected(e),this.parseFor(t,a)}parseFunctionStatement(t,e,r){return this.next(),this.parseFunction(t,1|(r?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(CR),this.scope.enter(256);let r;for(let s;!this.match(8);)if(this.match(61)||this.match(65)){let i=this.match(61);r&&this.finishNode(r,"SwitchCase"),e.push(r=this.startNode()),r.consequent=[],this.next(),i?r.test=this.parseExpression():(s&&this.raise(b.MultipleDefaultsInSwitch,this.state.lastTokStartLoc),s=!0,r.test=null),this.expect(14)}else r?r.consequent.push(this.parseStatementListItem()):this.unexpected();return this.scope.exit(),r&&this.finishNode(r,"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,r=!1){return this.next(),this.parseVar(t,!1,e,r),this.semicolon(),this.finishNode(t,"VariableDeclaration")}parseWhileStatement(t){return this.next(),t.test=this.parseHeaderExpression(),this.state.labels.push(cd),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,r,s){for(let a of this.state.labels)a.name===e&&this.raise(b.LabelRedeclaration,r,{labelName:e});let i=jk(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=i;else break}return this.state.labels.push({name:e,kind:i,statementStart:this.sourceToOffsetPos(this.state.start)}),t.body=s&8?this.parseStatementOrSloppyAnnexBFunctionDeclaration(!0):this.parseStatement(),this.state.labels.pop(),t.label=r,this.finishNode(t,"LabeledStatement")}parseExpressionStatement(t,e,r){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")}parseBlock(t=!1,e=!0,r){let s=this.startNode();return t&&this.state.strictErrors.clear(),this.expect(5),e&&this.scope.enter(0),this.parseBlockBody(s,t,!1,8,r),e&&this.scope.exit(),this.finishNode(s,"BlockStatement")}isValidDirective(t){return t.type==="ExpressionStatement"&&t.expression.type==="StringLiteral"&&!t.expression.extra.parenthesized}parseBlockBody(t,e,r,s,i){let a=t.body=[],o=t.directives=[];this.parseBlockOrModuleBlockBody(a,e?o:void 0,r,s,i)}parseBlockOrModuleBlockBody(t,e,r,s,i){let a=this.state.strict,o=!1,d=!1;for(;!this.match(s);){let c=r?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)}i?.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,r){let s=this.match(58);return this.next(),s?r!==null&&this.unexpected(r):t.await=r!==null,e.type==="VariableDeclaration"&&e.declarations[0].init!=null&&(!s||!this.options.annexB||this.state.strict||e.kind!=="var"||e.declarations[0].id.type!=="Identifier")&&this.raise(b.ForInOfLoopInitializer,e,{type:s?"ForInStatement":"ForOfStatement"}),e.type==="AssignmentPattern"&&this.raise(b.InvalidLhs,e,{ancestor:{type:"ForStatement"}}),t.left=e,t.right=s?this.parseExpression():this.parseMaybeAssignAllowIn(),this.expect(11),t.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.scope.exit(),this.state.labels.pop(),this.finishNode(t,s?"ForInStatement":"ForOfStatement")}parseVar(t,e,r,s=!1){let i=t.declarations=[];for(t.kind=r;;){let a=this.startNode();if(this.parseVarId(a,r),a.init=this.eat(29)?e?this.parseMaybeAssignDisallowIn():this.parseMaybeAssignAllowIn():null,a.init===null&&!s&&(a.id.type!=="Identifier"&&!(e&&(this.match(58)||this.isContextual(102)))?this.raise(b.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:"destructuring"}):(r==="const"||r==="using"||r==="await using")&&!(this.match(58)||this.isContextual(102))&&this.raise(b.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:r})),i.push(this.finishNode(a,"VariableDeclarator")),!this.eat(12))break}return t}parseVarId(t,e){let r=this.parseBindingAtom();e==="using"||e==="await using"?(r.type==="ArrayPattern"||r.type==="ObjectPattern")&&this.raise(b.UsingDeclarationHasBindingPattern,r.loc.start):r.type==="VoidPattern"&&this.raise(b.UnexpectedVoidPattern,r.loc.start),this.checkLVal(r,{type:"VariableDeclarator"},e==="var"?5:8201),t.id=r}parseAsyncFunctionExpression(t){return this.parseFunction(t,8)}parseFunction(t,e=0){let r=e&2,s=!!(e&1),i=s&&!(e&4),a=!!(e&8);this.initFunction(t,a),this.match(55)&&(r&&this.raise(b.GeneratorInSingleStatementContext,this.state.startLoc),this.next(),t.generator=!0),s&&(t.id=this.parseFunctionId(i));let o=this.state.maybeInArrowParameters;return this.state.maybeInArrowParameters=!1,this.scope.enter(514),this.prodParam.enter(Ci(a,t.generator)),s||(t.id=this.parseFunctionId()),this.parseFunctionParams(t,!1),this.withSmartMixTopicForbiddingContext(()=>{this.parseFunctionBodyAndFinish(t,s?"FunctionDeclaration":"FunctionExpression")}),this.prodParam.exit(),this.scope.exit(),s&&!r&&this.registerFunctionStatementId(t),this.state.maybeInArrowParameters=o,t}parseFunctionId(t){return t||ie(this.state.type)?this.parseIdentifier():null}parseFunctionParams(t,e){this.expect(10),this.expressionScope.enter(yR()),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,r){this.next();let s=this.state.strict;return this.state.strict=!0,this.parseClassId(t,e,r),this.parseClassSuper(t),t.body=this.parseClassBody(!!t.superClass,s),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 r={hadConstructor:!1,hadSuperClass:t},s=[],i=this.startNode();if(i.body=[],this.expect(5),this.withSmartMixTopicForbiddingContext(()=>{for(;!this.match(8);){if(this.eat(13)){if(s.length>0)throw this.raise(b.DecoratorSemicolon,this.state.lastTokEndLoc);continue}if(this.match(26)){s.push(this.parseDecorator());continue}let a=this.startNode();s.length&&(a.decorators=s,this.resetStartLocationFromNode(a,s[0]),s=[]),this.parseClassMember(i,a,r),a.kind==="constructor"&&a.decorators&&a.decorators.length>0&&this.raise(b.DecoratorConstructor,a)}}),this.state.strict=e,this.next(),s.length)throw this.raise(b.TrailingDecorator,this.state.startLoc);return this.classScope.exit(),this.finishNode(i,"ClassBody")}parseClassMemberFromModifier(t,e){let r=this.parseIdentifier(!0);if(this.isClassMethod()){let s=e;return s.kind="method",s.computed=!1,s.key=r,s.static=!1,this.pushClassMethod(t,s,!1,!1,!1,!1),!0}else if(this.isClassProperty()){let s=e;return s.computed=!1,s.key=r,s.static=!1,t.body.push(this.parseClassProperty(s)),!0}return this.resetPreviousNodeTrailingComments(r),!1}parseClassMember(t,e,r){let s=this.isContextual(106);if(s){if(this.parseClassMemberFromModifier(t,e))return;if(this.eat(5)){this.parseClassStaticBlock(t,e);return}}this.parseClassMemberWithIsStatic(t,e,r,s)}parseClassMemberWithIsStatic(t,e,r,s){let i=e,a=e,o=e,d=e,c=e,l=i,u=i;if(e.static=s,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(i)&&this.raise(b.ConstructorIsGenerator,i.key),this.pushClassMethod(t,i,!0,!1,!1,!1);return}let p=!this.state.containsEsc&&ie(this.state.type),f=this.parseClassElementName(e),h=p?f.name:null,m=this.isPrivateName(f),g=this.state.startLoc;if(this.parsePostMemberNameModifiers(u),this.isClassMethod()){if(l.kind="method",m){this.pushClassPrivateMethod(t,a,!1,!1);return}let y=this.isNonstaticConstructor(i),w=!1;y&&(i.kind="constructor",r.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(b.DuplicateConstructor,f),y&&this.hasPlugin("typescript")&&e.override&&this.raise(b.OverrideOnConstructor,f),r.hadConstructor=!0,w=r.hadSuperClass),this.pushClassMethod(t,i,!1,!1,y,w)}else if(this.isClassProperty())m?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(g),l.kind="method";let w=this.match(139);this.parseClassElementName(l),this.parsePostMemberNameModifiers(u),w?this.pushClassPrivateMethod(t,a,y,!0):(this.isNonstaticConstructor(i)&&this.raise(b.ConstructorIsAsync,i.key),this.pushClassMethod(t,i,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(i),y?this.pushClassPrivateMethod(t,a,!1,!1):(this.isNonstaticConstructor(i)&&this.raise(b.ConstructorIsAccessor,i.key),this.pushClassMethod(t,i,!1,!1,!1,!1)),this.checkGetterSetterParams(i)}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()?m?this.pushClassPrivateProperty(t,d):this.pushClassProperty(t,o):this.unexpected()}parseClassElementName(t){let{type:e,value:r}=this.state;if((e===132||e===134)&&t.static&&r==="prototype"&&this.raise(b.StaticPrototype,this.state.startLoc),e===139){r==="constructor"&&this.raise(b.ConstructorClassPrivateField,this.state.startLoc);let s=this.parsePrivateName();return t.key=s,s}return this.parsePropertyName(t),t.key}parseClassStaticBlock(t,e){var r;this.scope.enter(720);let s=this.state.labels;this.state.labels=[],this.prodParam.enter(0);let i=e.body=[];this.parseBlockOrModuleBlockBody(i,void 0,!1,8),this.prodParam.exit(),this.scope.exit(),this.state.labels=s,t.body.push(this.finishNode(e,"StaticBlock")),(r=e.decorators)!=null&&r.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 r=this.parseClassPrivateProperty(e);t.body.push(r),this.classScope.declarePrivateName(this.getPrivateNameSV(r.key),0,r.key.loc.start)}pushClassAccessorProperty(t,e,r){!r&&!e.computed&&this.nameIsConstructor(e.key)&&this.raise(b.ConstructorClassField,e.key);let s=this.parseClassAccessorProperty(e);t.body.push(s),r&&this.classScope.declarePrivateName(this.getPrivateNameSV(s.key),0,s.key.loc.start)}pushClassMethod(t,e,r,s,i,a){t.body.push(this.parseMethod(e,r,s,i,a,"ClassMethod",!0))}pushClassPrivateMethod(t,e,r,s){let i=this.parseMethod(e,r,s,!1,!1,"ClassPrivateMethod",!0);t.body.push(i);let a=i.kind==="get"?i.static?6:2:i.kind==="set"?i.static?5:1:0;this.declareClassPrivateMethodInScope(i,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(qf()),this.prodParam.enter(0),t.value=this.eat(29)?this.parseMaybeAssignAllowIn():null,this.expressionScope.exit(),this.prodParam.exit(),this.scope.exit()}parseClassId(t,e,r,s=8331){if(ie(this.state.type))t.id=this.parseIdentifier(),e&&this.declareNameFromIdentifier(t.id,s);else if(r||!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 r=this.parseMaybeImportPhase(t,!0),s=this.maybeParseExportDefaultSpecifier(t,r),i=!s||this.eat(12),a=i&&this.eatExportStar(t),o=a&&this.maybeParseExportNamespaceSpecifier(t),d=i&&(!o||this.eat(12)),c=s||a;if(a&&!o){if(s&&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);s&&i&&!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 r=e||this.parseIdentifier(!0),s=this.startNodeAtNode(r);return s.exported=r,t.specifiers=[this.finishNode(s,"ExportDefaultSpecifier")],!0}return!1}maybeParseExportNamespaceSpecifier(t){if(this.isContextual(93)){var e,r;(r=(e=t).specifiers)!=null||(e.specifiers=[]);let s=this.startNodeAt(this.state.lastTokStartLoc);return this.next(),s.exported=this.parseModuleExportName(),t.specifiers.push(this.finishNode(s,"ExportNamespaceSpecifier")),!0}return!1}maybeParseExportNamedSpecifiers(t){if(this.match(5)){let e=t;e.specifiers||(e.specifiers=[]);let r=e.exportKind==="type";return e.specifiers.push(...this.parseExportSpecifiers(r)),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(ie(t)){if(t===95&&!this.state.containsEsc||t===100)return!1;if((t===130||t===129)&&!this.state.containsEsc){let s=this.nextTokenStart(),i=this.input.charCodeAt(s);if(i===123||this.chStartsBindingIdentifier(i,s)&&!this.input.startsWith("from",s))return this.expectOnePlugin(["flow","typescript"]),!1}}else if(!this.match(65))return!1;let e=this.nextTokenStart(),r=this.isUnparsedContextual(e,"from");if(this.input.charCodeAt(e)===44||ie(this.state.type)&&r)return!0;if(this.match(65)&&r){let s=this.input.charCodeAt(this.nextTokenStartSince(e+4));return s===34||s===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,r,s){if(e){var i;if(r){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((i=t.specifiers)!=null&&i.length)for(let o of t.specifiers){let{exported:d}=o,c=d.type==="Identifier"?d.name:d.value;if(this.checkDuplicateExports(o,c),!s&&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=[],r=!0;for(this.expect(5);!this.eat(8);){if(r)r=!1;else if(this.expect(12),this.eat(8))break;let s=this.isContextual(130),i=this.match(134),a=this.startNode();a.local=this.parseModuleExportName(),e.push(this.parseExportSpecifier(a,i,t,s))}return e}parseExportSpecifier(t,e,r,s){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=NR.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:r})=>r.value==="json"&&(e.type==="Identifier"?e.name==="type":e.value==="type")):!1}checkImportReflection(t){let{specifiers:e}=t,r=e.length===1?e[0].type:null;if(t.phase==="source")r!=="ImportDefaultSpecifier"&&this.raise(b.SourcePhaseImportRequiresDefault,e[0].loc.start);else if(t.phase==="defer")r!=="ImportNamespaceSpecifier"&&this.raise(b.DeferImportRequiresNamespace,e[0].loc.start);else if(t.module){var s;r!=="ImportDefaultSpecifier"&&this.raise(b.ImportReflectionNotBinding,e[0].loc.start),((s=t.assertions)==null?void 0:s.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 r=e.find(s=>{let i;if(s.type==="ExportSpecifier"?i=s.local:s.type==="ImportSpecifier"&&(i=s.imported),i!==void 0)return i.type==="Identifier"?i.name!=="default":i.value!=="default"});r!==void 0&&this.raise(b.ImportJSONBindingNotDefault,r.loc.start)}}}isPotentialImportPhase(t){return t?!1:this.isContextual(105)||this.isContextual(97)||this.isContextual(127)}applyImportPhase(t,e,r,s){e||(r==="module"?(this.expectPlugin("importReflection",s),t.module=!0):this.hasPlugin("importReflection")&&(t.module=!1),r==="source"?(this.expectPlugin("sourcePhaseImports",s),t.phase="source"):r==="defer"?(this.expectPlugin("deferredImportEvaluation",s),t.phase="defer"):this.hasPlugin("sourcePhaseImports")&&(t.phase=null))}parseMaybeImportPhase(t,e){if(!this.isPotentialImportPhase(e))return this.applyImportPhase(t,e,null),null;let r=this.startNode(),s=this.parseIdentifierName(!0),{type:i}=this.state;return(it(i)?i!==98||this.lookaheadCharCode()===102:i!==12)?(this.applyImportPhase(t,e,s,r.loc.start),null):(this.applyImportPhase(t,e,null),this.createIdentifier(r,s))}isPrecedingIdImportPhase(t){let{type:e}=this.state;return ie(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 s=!this.maybeParseDefaultImportSpecifier(t,e)||this.eat(12),i=s&&this.maybeParseStarImportSpecifier(t);return s&&!i&&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,r){e.local=this.parseIdentifier(),t.specifiers.push(this.finishImportSpecifier(e,r))}finishImportSpecifier(t,e,r=8201){return this.checkLVal(t.local,{type:e},r),this.finishNode(t,e)}parseImportAttributes(){this.expect(5);let t=[],e=new Set;do{if(this.match(8))break;let r=this.startNode(),s=this.state.value;if(e.has(s)&&this.raise(b.ModuleAttributesWithDuplicateKeys,this.state.startLoc,{key:s}),e.add(s),this.match(134)?r.key=this.parseStringLiteral(s):r.key=this.parseIdentifier(!0),this.expect(14),!this.match(134))throw this.raise(b.ModuleAttributeInvalidValue,this.state.startLoc);r.value=this.parseStringLiteral(this.state.value),t.push(this.finishNode(r,"ImportAttribute"))}while(this.eat(12));return this.expect(8),t}parseModuleAttributes(){let t=[],e=new Set;do{let r=this.startNode();if(r.key=this.parseIdentifier(!0),r.key.name!=="type"&&this.raise(b.ModuleAttributeDifferentFromType,r.key),e.has(r.key.name)&&this.raise(b.ModuleAttributesWithDuplicateKeys,r.key,{key:r.key.name}),e.add(r.key.name),this.expect(14),!this.match(134))throw this.raise(b.ModuleAttributeInvalidValue,this.state.startLoc);r.value=this.parseStringLiteral(this.state.value),t.push(this.finishNode(r,"ImportAttribute"))}while(this.eat(12));return t}maybeParseImportAttributes(t){let e;var r=!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(),r=!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=[];!r&&this.hasPlugin("importAssertions")?t.assertions=e:t.attributes=e}maybeParseDefaultImportSpecifier(t,e){if(e){let r=this.startNodeAtNode(e);return r.local=e,t.specifiers.push(this.finishImportSpecifier(r,"ImportDefaultSpecifier")),!0}else if(it(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 r=this.startNode(),s=this.match(134),i=this.isContextual(130);r.imported=this.parseModuleExportName();let a=this.parseImportSpecifier(r,s,t.importKind==="type"||t.importKind==="typeof",i,void 0);t.specifiers.push(a)}}parseImportSpecifier(t,e,r,s,i){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",i)}isThisParam(t){return t.type==="Identifier"&&t.name==="this"}},Di=class extends Nd{constructor(t,e,r){let s=Ck(t);super(s,e),this.options=s,this.initializeScopes(),this.plugins=r,this.filename=s.sourceFilename,this.startIndex=s.startIndex;let i=0;s.allowAwaitOutsideFunction&&(i|=1),s.allowReturnOutsideFunction&&(i|=2),s.allowImportExportEverywhere&&(i|=8),s.allowSuperOutsideMethod&&(i|=16),s.allowUndeclaredExports&&(i|=64),s.allowNewTargetOutsideFunction&&(i|=4),s.allowYieldOutsideFunction&&(i|=32),s.ranges&&(i|=128),s.tokens&&(i|=256),s.createImportExpressions&&(i|=512),s.createParenthesizedExpressions&&(i|=1024),s.errorRecovery&&(i|=2048),s.attachComment&&(i|=4096),s.annexB&&(i|=8192),this.optionFlags=i}getScopeHandler(){return Jr}parse(){this.enterInitialScopes();let t=this.startNode(),e=this.startNode();this.nextToken(),t.errors=null;let r=this.parseTopLevel(t,e);return r.errors=this.state.errors,r.comments.length=this.state.commentsLen,r}};function $R(n,t){var e;if(((e=t)==null?void 0:e.sourceType)==="unambiguous"){t=Object.assign({},t);try{t.sourceType="module";let r=Gr(t,n),s=r.parse();if(r.sawUnambiguousESM)return s;if(r.ambiguousScriptDifferentAst)try{return t.sourceType="script",Gr(t,n).parse()}catch{}else s.program.sourceType="script";return s}catch(r){try{return t.sourceType="script",Gr(t,n).parse()}catch{}throw r}}else return Gr(t,n).parse()}function DR(n,t){let e=Gr(t,n);return e.options.strictMode&&(e.state.strict=!0),e.getExpression()}function MR(n){let t={};for(let e of Object.keys(n))t[e]=It(n[e]);return t}var LR=MR(Dk);function Gr(n,t){let e=Di,r=new Map;if(n!=null&&n.plugins){for(let s of n.plugins){let i,a;typeof s=="string"?i=s:[i,a]=s,r.has(i)||r.set(i,a||{})}TR(r),e=_R(r)}return new e(n,t,r)}var Df=new Map;function _R(n){let t=[];for(let s of ER)n.has(s)&&t.push(s);let e=t.join("|"),r=Df.get(e);if(!r){r=Di;for(let s of t)r=Wf[s](r);Df.set(e,r)}return r}Yr.parse=$R;Yr.parseExpression=DR;Yr.tokTypes=LR});import{parseArgs as d2}from"node:util";import{createHash as Db}from"node:crypto";import{access as qO,appendFile as GO,mkdir as KO,readdir as WO,readFile as Eo,realpath as Cr,stat as Mb,writeFile as jb}from"node:fs/promises";import{isAbsolute as Gu,join as ze,relative as ti,resolve as Co,sep as Fb}from"node:path";import{mkdir as sE,writeFile as iE}from"node:fs/promises";import{join as lg}from"node:path";import{lstat as hx,readFile as rp,realpath as Lo}from"node:fs/promises";import{dirname as $o,isAbsolute as mx,join as ii,relative as ai,resolve as si,sep as sp}from"node:path";var ip=["ts","mts","cts","js","mjs","cjs"],ap={playwright:"playwright.config",cypress:"cypress.config",webdriverio:"wdio.conf"},yx={playwright:["@playwright/test"],cypress:["cypress"],webdriverio:["@wdio/cli","webdriverio"]},di={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"};function Do(n,t){let e=ai(n,t);return e===""||!mx(e)&&e!==".."&&!e.startsWith(`..${sp}`)}async function oi(n){return(await hx(n).catch(()=>{}))?.isFile()===!0}function Mo(n){return n.split(sp).join("/")}async function op(n){let t=await Lo(n),e={};try{let s=JSON.parse(await rp(ii(t,"package.json"),"utf8"));e={...s.dependencies,...s.devDependencies}}catch{e={}}let r=[];for(let s of["playwright","cypress","webdriverio"]){let i=yx[s].find(o=>o in e),a;for(let o of ip){let d=`${ap[s]}.${o}`;if(await oi(ii(t,d))){a=d;break}}(i!==void 0||a!==void 0)&&r.push({framework:s,...a===void 0?{}:{configFile:a},...i===void 0?{}:{packageName:i}})}return r}async function ci(n,t,e){let r=await Lo(n),s=$o(si(r,e));for(Do(r,s)||(s=r);;){for(let a of ip){let o=ii(s,`${ap[t]}.${a}`);if(await oi(o))return Mo(ai(r,o))}if(s===r)return;let i=$o(s);if(!Do(r,i))return;s=i}}async function li(n,t){let e=await Lo(n),r=t===void 0?e:$o(si(e,t));if(t!==void 0){let s=await rp(si(e,t),"utf8").catch(()=>"");if(/\bsupportFile\s*:\s*false\b/.test(s))return null;let i=/\bsupportFile\s*:\s*["'`]([^"'`]+)["'`]/.exec(s)?.[1];if(i!==void 0){let a=si(r,i);return Do(e,a)&&await oi(a)?Mo(ai(e,a)):void 0}}for(let s of["ts","js","tsx","jsx"]){let i=ii(r,"cypress","support",`e2e.${s}`);if(await oi(i))return Mo(ai(e,i))}}import{createHash as dp}from"node:crypto";function gx(n){return`${Buffer.byteLength(n,"utf8")}:${n}`}function Ee(n){return dp("sha256").update(n).digest("hex")}function B(n,t){let e=t.map(gx).join("|"),r=dp("sha256").update(e,"utf8").digest("hex");return`${n}_${r.slice(0,24)}`}import{isAbsolute as cp,relative as wx,sep as lp}from"node:path";var ui=["1.55.0","1.64.1"],ft=["playwright","cypress","webdriverio"],_o=["vitest","jest","mocha","pytest","junit","testng","cucumber","unknown"];var jo={playwright:ui,cypress:["16.2.0"],webdriverio:["10.1.0"],vitest:["4.1.11"],jest:["30.5.2"],mocha:["11.8.0"],pytest:["8.4.2"],junit:["6.1.3"],testng:["7.12.0"],cucumber:[],unknown:[]};function Bo(n){return{...n}}function pi(n,t,e){return{errorId:B("err",[t,e]),source:e,...n.message===void 0?{}:{message:n.message},...n.name===void 0?{}:{name:n.name},...n.stack===void 0?{}:{stack:n.stack},...n.snippet===void 0?{}:{snippet:n.snippet},...n.value===void 0?{}:{value:n.value},...n.location===void 0?{}:{location:Bo(n.location)}}}function fp(n){return{type:n.type,...n.description===void 0?{}:{description:n.description},...n.location===void 0?{}:{location:Bo(n.location)}}}function up(n){return"text"in n?{kind:"text",text:n.text}:{kind:"base64",base64:n.buffer}}function bx(n,t,e){return{attachmentId:B("att",[t,String(e)]),name:n.name,contentType:n.contentType,sourceIndex:e,...n.path===void 0?{}:{path:n.path},...n.body===void 0?{}:{bodyBase64:n.body}}}function hp(n,t,e){return{title:n.title,duration:n.duration,...n.error===void 0?{}:{error:pi(n.error,t,`${e}.error`)},steps:n.steps.map((r,s)=>hp(r,t,`${e}.steps[${s}]`))}}function xx(n){let t=[],e=(r,s,i)=>{r.forEach((a,o)=>{let d=`${i}[${o}]`,c=a.title.length===0?s:[...s,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(n.suites,[],"$report.suites"),t}function Fo(n,t){if(!cp(t))return;let e=wx(n,t);if(!(cp(e)||e===".."||e.startsWith(`..${lp}`)))return e.split(lp).join("/")}function vx(n,t){return n.config.projects.map(e=>{let r=e.testDir===void 0?void 0:Fo(t,e.testDir);return{projectId:B("prj",[e.id,e.name]),frameworkProjectId:e.id,name:e.name,repeatEach:e.repeatEach,retries:e.retries,...r===void 0?{}:{testDir:r}}}).sort((e,r)=>e.projectId.localeCompare(r.projectId))}function kx(n,t,e,r){let s=B("atm",[t,String(n.retry),"repeat:unknown",String(e)]),i=[];return n.error!==void 0&&i.push(pi(n.error,s,`${r}.error`)),n.errors.forEach((a,o)=>{i.push(pi(a,s,`${r}.errors[${o}]`))}),{attemptId:s,sourceIndex:e,retry:n.retry,repeat:{state:"unknown",reason:"not-serialized-by-playwright-json-reporter"},status:n.status,duration:n.duration,startTime:new Date(n.startTime).toISOString(),workerIndex:n.workerIndex,parallelIndex:n.parallelIndex,errors:i,stdout:n.stdout.map(up),stderr:n.stderr.map(up),steps:n.steps.map((a,o)=>hp(a,s,`${r}.steps[${o}]`)),attachments:n.attachments.map((a,o)=>bx(a,s,o)),annotations:n.annotations.map(fp),...n.errorLocation===void 0?{}:{errorLocation:Bo(n.errorLocation)}}}function Rx(n,t){return n.length===0?"zero-tests":n.some(e=>e.attempts.some(r=>r.status==="interrupted"))?"interrupted":t.length>0?"report-errors":"analysis-ready"}function mp(n){let{report:t,reportHash:e,artifact:r,options:s}=n,i=s.workspaceRoot,a=vx(t,i),o=t.config.rootDir===void 0?void 0:Fo(i,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:Fo(i,t.config.configFile),l=new Map(a.map(y=>[y.frameworkProjectId,y.projectId])),p=xx(t).map(({spec:y,test:w,titlePath:v,sourcePath:x})=>{let R=l.get(w.projectId);if(R===void 0)throw new Error(`Validated test references unknown project ID: ${w.projectId}`);let S=d(y.file),N=B("tst",[i,R,S,...v]);return{logicalTestId:N,projectId:R,title:y.title,titlePath:v,tags:[...y.tags].sort(),location:{file:S,line:y.line,column:y.column},timeout:w.timeout,expectedStatus:w.expectedStatus,status:w.status,annotations:w.annotations.map(fp),attempts:w.results.map((E,M)=>kx(E,N,M,`${x}.results[${M}]`))}});p.sort((y,w)=>y.logicalTestId.localeCompare(w.logicalTestId));let f=t.errors.map((y,w)=>pi(y,r.artifactId,`$report.errors[${w}]`)),h=p.reduce((y,w)=>y+w.attempts.reduce((v,x)=>v+x.attachments.length,0),0),m=new Date(t.stats.startTime).toISOString(),g=B("run",[e,i,s.gitRoot??"","1.7","1"]);return{schemaVersion:"1.7",runId:g,framework:"playwright",createdAt:m,workspace:{root:i,...s.gitRoot===void 0?{}:{gitRoot:s.gitRoot}},sourceHashes:{report:e},artifact:r,usability:Rx(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:[...n.warnings].sort(),stats:{...t.stats,startTime:m}}}var Vn=class extends Error{constructor(t){super(t),this.name="ReportValidationError"}};function Ne(n,t){throw new Vn(`${n} must be ${t}`)}function ne(n,t){return typeof n!="object"||n===null||Array.isArray(n)?Ne(t,"an object"):n}function tn(n,t){return Array.isArray(n)?n:Ne(t,"an array")}function G(n,t){return typeof n!="string"?Ne(t,"a string"):n}function fe(n,t){return n===void 0?void 0:G(n,t)}function Ge(n,t){return typeof n!="number"||!Number.isFinite(n)?Ne(t,"a finite number"):n}function fi(n,t){let e=Ge(n,t);return Number.isInteger(e)?e:Ne(t,"an integer")}function we(n,t){let e=fi(n,t);return e<0?Ne(t,"a non-negative integer"):e}function Vo(n,t){let e=G(n,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?Ne(t,"an ISO 8601 UTC timestamp with millisecond precision"):e}function yp(n,t){return typeof n!="boolean"?Ne(t,"a boolean"):n}function ue(n,t,e,r){let s=n[t];return s===void 0?void 0:e(s,`${r}.${t}`)}function Z(n,t,e){return tn(n,t).map((r,s)=>e(r,`${t}[${s}]`))}function Ix(n){return n.length===0?!0:n.length%4!==0?!1:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(n)}function Ho(n,t){let e=G(n,t);return Ix(e)?e:Ne(t,"canonical base64")}function nn(n,t,e){let r=G(n,t);return e.has(r)?r:Ne(t,`one of ${[...e].join(", ")}`)}function hi(n,t){return t===void 0?{}:{[n]:t}}function zo(n,t){let e=ne(n,t),r=ue(e,"line",we,t),s=ue(e,"column",we,t);return{file:G(e.file,`${t}.file`),...r===void 0?{}:{line:r},...s===void 0?{}:{column:s}}}function mi(n,t){let e=ne(n,t),r=ue(e,"message",G,t),s=ue(e,"name",G,t),i=ue(e,"stack",G,t),a=ue(e,"snippet",G,t),o=ue(e,"value",G,t),d=ue(e,"location",zo,t);return{...r===void 0?{}:{message:r},...s===void 0?{}:{name:s},...i===void 0?{}:{stack:i},...a===void 0?{}:{snippet:a},...o===void 0?{}:{value:o},...d===void 0?{}:{location:d}}}function wp(n,t){let e=ne(n,t),r=ue(e,"description",G,t),s=ue(e,"location",zo,t);return{type:G(e.type,`${t}.type`),...r===void 0?{}:{description:r},...s===void 0?{}:{location:s}}}function gp(n,t){let e=ne(n,t),r=typeof e.text=="string",s=typeof e.buffer=="string";return r===s?Ne(t,"exactly one of text or buffer"):r?{text:G(e.text,`${t}.text`)}:{buffer:Ho(e.buffer,`${t}.buffer`)}}function Ax(n,t){let e=ne(n,t),r=ue(e,"path",G,t),s=ue(e,"body",Ho,t);return{name:G(e.name,`${t}.name`),contentType:G(e.contentType,`${t}.contentType`),...r===void 0?{}:{path:r},...s===void 0?{}:{body:s}}}function bp(n,t){let e=ne(n,t),r=ue(e,"error",mi,t);return{title:G(e.title,`${t}.title`),duration:Ge(e.duration,`${t}.duration`),...r===void 0?{}:{error:r},steps:Z(e.steps??[],`${t}.steps`,bp)}}var xp=new Set(["passed","failed","timedOut","skipped","interrupted"]),Px=new Set(["expected","unexpected","flaky","skipped"]);function Sx(n,t){let e=ne(n,t),r=ue(e,"error",mi,t),s=ue(e,"errorLocation",zo,t);return{workerIndex:fi(e.workerIndex,`${t}.workerIndex`),parallelIndex:fi(e.parallelIndex,`${t}.parallelIndex`),status:nn(e.status,`${t}.status`,xp),duration:Ge(e.duration,`${t}.duration`),startTime:Vo(e.startTime,`${t}.startTime`),retry:we(e.retry,`${t}.retry`),...r===void 0?{}:{error:r},errors:Z(e.errors??[],`${t}.errors`,mi),stdout:Z(e.stdout??[],`${t}.stdout`,gp),stderr:Z(e.stderr??[],`${t}.stderr`,gp),steps:Z(e.steps??[],`${t}.steps`,bp),attachments:Z(e.attachments??[],`${t}.attachments`,Ax),annotations:Z(e.annotations??[],`${t}.annotations`,wp),...s===void 0?{}:{errorLocation:s}}}function Tx(n,t){let e=ne(n,t);return{timeout:Ge(e.timeout,`${t}.timeout`),annotations:Z(e.annotations??[],`${t}.annotations`,wp),expectedStatus:nn(e.expectedStatus,`${t}.expectedStatus`,xp),projectName:G(e.projectName,`${t}.projectName`),projectId:G(e.projectId,`${t}.projectId`),results:Z(e.results,`${t}.results`,Sx),status:nn(e.status,`${t}.status`,Px)}}function Ex(n,t){let e=ne(n,t);return{title:G(e.title,`${t}.title`),ok:yp(e.ok,`${t}.ok`),tags:Z(e.tags??[],`${t}.tags`,G),tests:Z(e.tests,`${t}.tests`,Tx),file:G(e.file,`${t}.file`),line:we(e.line,`${t}.line`),column:we(e.column,`${t}.column`)}}function vp(n,t){let e=ne(n,t),r=ue(e,"file",G,t),s=ue(e,"line",we,t),i=ue(e,"column",we,t);return{title:G(e.title,`${t}.title`),...r===void 0?{}:{file:r},...s===void 0?{}:{line:s},...i===void 0?{}:{column:i},suites:Z(e.suites??[],`${t}.suites`,vp),specs:Z(e.specs??[],`${t}.specs`,Ex)}}function Cx(n,t){let e=ne(n,t);return{id:G(e.id,`${t}.id`),name:G(e.name,`${t}.name`),repeatEach:we(e.repeatEach,`${t}.repeatEach`),retries:we(e.retries,`${t}.retries`),...hi("testDir",fe(e.testDir,`${t}.testDir`))}}function kp(n){let t=ne(n,"$report"),e=ne(t.config,"$report.config"),r=ne(t.stats,"$report.stats");return{config:{version:G(e.version,"$report.config.version"),projects:Z(e.projects,"$report.config.projects",Cx),...hi("rootDir",fe(e.rootDir,"$report.config.rootDir")),...hi("configFile",fe(e.configFile,"$report.config.configFile"))},suites:Z(t.suites,"$report.suites",vp),errors:Z(t.errors??[],"$report.errors",mi),stats:{startTime:Vo(r.startTime,"$report.stats.startTime"),duration:Ge(r.duration,"$report.stats.duration"),expected:we(r.expected,"$report.stats.expected"),skipped:we(r.skipped,"$report.stats.skipped"),unexpected:we(r.unexpected,"$report.stats.unexpected"),flaky:we(r.flaky,"$report.stats.flaky")}}}var Nx=new TextDecoder("utf-8",{fatal:!0});function rn(n,t,e){return{kind:"unreadable",artifact:{artifactId:B("art",[n??"unavailable",t??"bytes"]),kind:"report",availability:"unreadable",...t===void 0?{}:{path:t},...n===void 0?{}:{sha256:n},warnings:[]},diagnostic:e}}function Ox(n){return new Set(n??ui)}function Hn(n,t){let e=Ee(n);if(n.byteLength===0)return rn(e,t.reportPath,{reasonCode:"empty-input",message:"The Playwright JSON report is empty.",...t.reportPath===void 0?{}:{path:t.reportPath}});let r;try{r=Nx.decode(n)}catch{return rn(e,t.reportPath,{reasonCode:"invalid-utf8",message:"The Playwright JSON report is not valid UTF-8.",...t.reportPath===void 0?{}:{path:t.reportPath}})}let s;try{s=JSON.parse(r)}catch(p){return rn(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 i;try{i=kp(s)}catch(p){return rn(e,t.reportPath,{reasonCode:"invalid-report-shape",message:p instanceof Vn?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 i.config.projects){if(a.has(p.id))return rn(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(i.config.version))return rn(e,t.reportPath,{reasonCode:"incompatible-playwright-version",message:`Playwright ${i.config.version} is configured as incompatible.`,...t.reportPath===void 0?{}:{path:t.reportPath}});let c=Ox(t.testedPlaywrightVersions).has(i.config.version),l=[];c||l.push(`unverified-producer-version:${i.config.version}`),i.config.projects.some(p=>p.repeatEach>1)&&l.push("repeat-index-unavailable");let u={artifactId:B("art",[e]),kind:"report",availability:"present",...t.reportPath===void 0?{}:{path:t.reportPath},sha256:e,format:"playwright-json",formatVersion:i.config.version,versionConfidence:c?"verified":"unverified",warnings:[...l].sort()};try{return{kind:"parsed",run:mp({report:i,reportHash:e,artifact:u,options:t,warnings:l})}}catch(p){return rn(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 ZR}from"node:crypto";import{readdir as eI,readFile as tI,stat as nI}from"node:fs/promises";import{basename as rI,dirname as sI,join as iI}from"node:path";import{resolve as zx}from"node:path";import{readdir as $x,stat as Dx}from"node:fs/promises";import{join as Rp}from"node:path";var Pp=/\.(?:java|kt|groovy|scala)$/,Mx=/^at (?:([\w.$-]+)\/\/?)?([\w$]+(?:\.[\w$]+)*)\.([\w$<>-]+)\(([\w$-]+\.(?:java|kt|groovy|scala)):(\d+)\)\s*$/,Lx=/^(?:java|javax|jdk|sun|com\.sun|org\.junit|junit|org\.testng|org\.openqa\.selenium|org\.assertj|org\.hamcrest|org\.opentest4j|org\.apache\.maven|org\.gradle|worker\.org\.gradle|io\.cucumber|kotlin|kotlinx|scala|groovy|org\.codehaus\.groovy|org\.springframework\.test)\./,_x=["src/test/java","src/main/java","src/it/java","src/test/kotlin","src/main/kotlin","src/test/groovy","src/main/groovy","src/test/scala","src/main/scala"],jx=["src/test/resources","src/main/resources"];function yi(n){return Pp.test(n)}function Ip(n){return n.endsWith(".feature")}function sn(n,t="java"){return`${(n.split("$")[0]??n).replaceAll(".","/")}.${t}`}function Un(n){let t=Mx.exec(n.trim());if(t===null)return;let[,e,r,s,i,a]=t;if(r===void 0||s===void 0||i===void 0||a===void 0||e!==void 0&&e!=="app"||Lx.test(`${r}.`))return;let o=i.replace(Pp,""),d=r.lastIndexOf(`.${o}`),c=d>=0?r.slice(0,d):r.split(".").slice(0,-1).join(".");return{file:`${c===""?"":`${c.replaceAll(".","/")}/`}${i}`,line:Number.parseInt(a,10),className:r,method:s}}async function Ap(n){try{return(await Dx(n)).isFile()}catch{return!1}}async function Fx(n){return(await $x(n,{withFileTypes:!0}).catch(()=>[])).filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&e.name!=="node_modules"&&e.name!=="src"&&e.name!=="target"&&e.name!=="build").map(e=>e.name).sort()}var zn=class{constructor(t){this.workspaceRoot=t}workspaceRoot;modules;found=new Map;find(t){let e=this.found.get(t);return e===void 0&&(e=this.lookup(t),this.found.set(t,e)),e}async resolve(t){return yi(t)||Ip(t)?await this.find(t)??t:t}async lookup(t){if(await Ap(Rp(this.workspaceRoot,t)))return t;let e=Ip(t)?jx:_x;this.modules??=Fx(this.workspaceRoot);let r=[...e,...(await this.modules).flatMap(s=>e.map(i=>`${s}/${i}`))];for(let s of r){let i=`${s}/${t}`;if(await Ap(Rp(this.workspaceRoot,i)))return i}}};var Bx=/(?:\(|\bat\s+|^)((?:webpack:\/\/[^\s()]*|file:\/\/[^\s()]*|(?:[A-Za-z]:)?[^():\s][^():]*?)):(\d+):(\d+)\)?\s*$/,Vx=/^File "([^"]+\.py)", line (\d+)/,Hx=/^((?:[A-Za-z]:)?[^\s:][^:]*\.py):(\d+):(?:\s|$)/;function Tp(n){let t=n,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 Sp(n){return/^https?:\/\//.test(n)||n.includes("/__cypress/")||n.includes("node_modules/")||n.startsWith("node:")||n.startsWith("internal/")||n.includes("site-packages/")||/\/lib\/python\d/.test(n)||n.startsWith("<")}function Ep(n){let t=[];for(let e of n.split(/\r?\n/)){let r=e.trim().replace(/^❯\s+/,""),s=Un(r);if(s!==void 0){t.push({file:s.file,line:s.line,column:1});continue}let i=Vx.exec(r)??Hx.exec(r),a=i===null?Bx.exec(r):[i[0],i[1],i[2],"1"];if(a===null)continue;let[,o,d,c]=a;if(o===void 0||d===void 0||c===void 0||Sp(o))continue;let l=Tp(o);l===""||Sp(l)||t.push({file:l,line:Number.parseInt(d,10),column:Number.parseInt(c,10)})}return t}function xe(n,t){if(n===void 0)return;let e=Ep(n);if(t!==void 0){let r=t.replaceAll("\\","/").replace(/^(?:\.\/)+/,""),s=e.find(i=>{let a=i.file.replaceAll("\\","/");return a===r||a.endsWith(`/${r}`)||r.endsWith(`/${a}`)});if(s!==void 0)return s}return e[0]}var Ux="1",qx="application/vnd.allure.playwright-trace";function qo(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Go(n){return qo(n)&&typeof n.uuid=="string"&&typeof n.status=="string"&&Array.isArray(n.labels)&&(typeof n.historyId=="string"||typeof n.fullName=="string")}function Ko(n){return qo(n)&&typeof n.uuid=="string"&&typeof n.status!="string"&&(Array.isArray(n.children)||Array.isArray(n.befores)||Array.isArray(n.afters))}function Wo(n){return qo(n)&&n.uuid===void 0&&Array.isArray(n.errors)&&Array.isArray(n.attachments)}var Gx={testng:"testng","junit-platform":"junit",junit5:"junit",junit4:"junit",junit:"junit",pytest:"pytest",playwright:"playwright",cypress:"cypress",webdriverio:"webdriverio",jest:"jest",vitest:"vitest",mocha:"mocha"};function Rt(n,t){return n.labels?.find(e=>e.name===t)?.value}var Cp={passed:"passed",failed:"failed",broken:"failed",skipped:"skipped"};function gi(n){return n==="junit"||n==="testng"}function Lr(n,t){let e=n?.message?.trim()||void 0,r=n?.trace?.trim()||void 0;if(e===void 0&&r===void 0)return;let s=xe(r,t);return{...e===void 0?{}:{message:e},...r===void 0?{}:{stack:r},...s===void 0?{}:{location:s}}}function Np(n){for(let t of(n??"").split(`
11
- `)){let e=Un(t);if(e!==void 0)return e}}function Jo(n){return typeof n.start=="number"&&typeof n.stop=="number"&&n.stop>=n.start?n.stop-n.start:0}function Dp(n){let t=typeof n=="number"?new Date(n):void 0;return t===void 0||Number.isNaN(t.getTime())?{}:{startTime:t.toISOString()}}function Xo(n,t){let r=n.status==="failed"||n.status==="broken"?Lr(n.statusDetails,t):void 0;return{title:n.name??"",duration:Jo(n),...r===void 0?{}:{error:r},steps:(n.steps??[]).map(s=>Xo(s,t))}}function Mp(n,t){return[...(n.attachments??[]).flatMap(r=>r.source===void 0?[]:[{name:r.name??r.source,contentType:r.type===qx?"application/zip":r.type??"",path:t===void 0?r.source:zx(t,r.source)}]),...(n.steps??[]).flatMap(r=>Mp(r,t))]}function Kx(n){return n.replace(/^\[/,"").replace(/\]$/,"").split("]/[").map(t=>{let e=t.indexOf(":");return{type:t.slice(0,e),value:t.slice(e+1)}})}function Wx(n){let t=Rt(n,"junit.platform.uniqueid")??n.parameters?.find(a=>a.name==="UniqueId")?.value;if(t===void 0)return;let e=Kx(t),r=e.findIndex(a=>a.type==="test-template"||a.type==="test-factory");if(r<0)return;let s=e.slice(r+1).map(a=>/^#(\d+)$/.exec(a.value)?.[1]);return s.length===0||s.includes(void 0)?void 0:`${(e[r]?.value??"").replace(/\(([^)]*)\)$/,(a,o)=>`(${o.split(",").map(c=>c.trim().split(/[.$]/).at(-1)??"").filter(c=>c!=="").join(", ")})`)}${s.map(a=>`[${a}]`).join("")}`}function Jx(n){let t=n.split(".").filter(r=>r!==""),e=t.length;for(;e>1&&/^[A-Z]/.test(t[e-1]??"");)e-=1;return{file:`${t.slice(0,e).join("/")}.py`,classes:t.slice(e)}}function Xx(n){let t=n.titlePath??[],e=t.findIndex(r=>r.endsWith(".py"));return e>=0?{file:t.slice(0,e+1).join("/"),classes:t.slice(e+1)}:Jx((n.fullName??"").split("#")[0]??"")}function Uo(n,t){return{file:sn(n),titlePath:[...n.split("$").filter(e=>e!==""),t],projectId:""}}function Op(n,t,e){let r=Rt(n,"testClass");if(r!==void 0&&gi(t))return Uo(r,e);if(t==="pytest"){let{file:i,classes:a}=Xx(n);return{file:i,titlePath:[...a,e],projectId:""}}if(t==="playwright"){let i=(n.fullName??e).split(" \u203A ");return{file:Rt(n,"suite")??i[0]??"",titlePath:i.length>1?i.slice(1):[e],projectId:Rt(n,"parentSuite")??""}}let s=Rt(n,"suite");return{file:s!==void 0&&/\.[cm]?[jt]sx?$/.test(s)?s:"",titlePath:[n.fullName??e],projectId:""}}function $p(n,t,e,r){return{status:"failed",retry:t,...Dp(n.start),duration:Jo(n),errors:e===void 0?[]:[e],attachments:[],stdout:[],stderr:[],steps:(n.steps??[]).map(s=>Xo(s,r))}}function Lp(n){let t=[],e=[],r=[];for(let A of n)Go(A.json)?t.push({...A.json,...A.directory===void 0?{}:{directory:A.directory}}):Ko(A.json)?e.push(A.json):Wo(A.json)&&r.push(...A.json.errors);if(t.length===0)throw new Error("The Allure results hold no test result.");let s=new Set(t.map(A=>Gx[Rt(A,"framework")??""]??"unknown")),i=s.size===1?[...s][0]??"unknown":"unknown",a=[];s.size>1&&a.push("allure-mixed-frameworks");let o=new Map;for(let A of t){let C=A.historyId??`uuid:${A.uuid}`,P=o.get(C)??{key:C,results:[]};o.set(C,P),P.results.push(A)}let d=new Map,c=A=>{let C=Rt(A,"testMethod");if(i==="junit")return Wx(A)??C??A.name??"";if(i!=="testng")return A.name??"";let P=C??A.name??"",I=(A.parameters??[]).map(T=>T.value??"");if(I.length===0)return P;let $=`${Rt(A,"testClass")??""}\0${P}`,D=d.get($)??new Map;d.set($,D);let k=D.get(JSON.stringify(I))??D.size;return D.set(JSON.stringify(I),k),`${P}[${k}]`},l=0,u=0,p=new Map,f=[],h=[...o.values()].sort((A,C)=>{let P=I=>Math.min(...I.results.map($=>$.start??0));return P(A)-P(C)||A.key.localeCompare(C.key)});for(let A of h){let C=[...A.results].sort((D,k)=>(D.start??0)-(k.start??0)||D.uuid.localeCompare(k.uuid)),P=C.filter((D,k)=>{let T=D.status==="passed"&&k<C.length-1;return T&&(l+=1),!T}),I=P.at(-1);if(I===void 0)continue;p.set(A.key,I);let $=Op(I,i,c(I));f.push({file:$.file,titlePath:$.titlePath,projectId:$.projectId,attempts:P.map((D,k)=>{let T=k<P.length-1,_=Cp[D.status??""];!T&&_===void 0&&(u+=1);let U=T?"failed":_??"skipped",K=U==="passed"?void 0:Lr(D.statusDetails,$.file);return{status:U,retry:k,...Dp(D.start),duration:Jo(D),errors:K===void 0?[]:[K],attachments:Mp(D,D.directory),stdout:[],stderr:[],steps:(D.steps??[]).map(te=>Xo(te,$.file))}})})}l>0&&a.push(`allure-passed-before-retry-ignored:${l}`),u>0&&a.push(`allure-unknown-status:${u}`);let m=new Map;for(let A of o.values()){let C=p.get(A.key);if(C!==void 0)for(let P of A.results)m.set(P.uuid,C)}let g=new Set;for(let A of e){let C=(A.children??[]).map(I=>m.get(I)).filter(I=>I!==void 0);if(C.some(I=>Cp[I.status??""]==="failed"))continue;let P=[...(A.befores??[]).map(I=>({fixture:I,phase:"setup"})),...(A.afters??[]).map(I=>({fixture:I,phase:"teardown"}))].filter(({fixture:I})=>I.status==="failed"||I.status==="broken");for(let{fixture:I,phase:$}of P){let D=gi(i)?Np(I.statusDetails?.trace):void 0,k=I.name??D?.method??"fixture",T=C[0],_=D?.className??(T===void 0?void 0:Rt(T,"testClass")),U=`${k} (${$})`,K=_!==void 0&&gi(i)?Uo(_,U):T===void 0?void 0:Op(T,i,U);if(K===void 0)continue;let te=`${_??K.file}\0${k}`;g.has(te)||(g.add(te),f.push({...K,attempts:[$p(I,0,Lr(I.statusDetails,K.file),K.file)]}))}}let y=[],w=new Map,v=[...r].sort((A,C)=>(A.timestamp??0)-(C.timestamp??0));for(let A of v){let C=gi(i)?Np(A.trace):void 0;if(C===void 0){let T=Lr(A,"");T!==void 0&&y.push(T);continue}let P=`${C.className}\0${C.method}`;if(g.has(P))continue;let I=/\bdid not run\b/.test(A.message??"")?"setup":"teardown",$=Uo(C.className,`${C.method} (${I})`),D=w.get(P)??{...$,attempts:[]};w.set(P,D);let k=A.timestamp===void 0?{}:{start:A.timestamp};D.attempts.push($p(k,D.attempts.length,Lr(A,$.file),$.file))}f.push(...w.values());let x=new Map;if(i==="playwright")for(let A of f)for(let C of A.attempts.flatMap(P=>P.errors)){let P=C.location?.file;P!==void 0&&!x.has(A.file)&&P.replaceAll("\\","/").endsWith(`/${A.file}`)&&x.set(A.file,P)}let R=f.map(A=>{let C=x.get(A.file);return C===void 0?A:{...A,file:C}}),S=t.flatMap(A=>typeof A.start=="number"?[A.start]:[]),N=t.flatMap(A=>typeof A.stop=="number"?[A.stop]:[]),E=S.length===0?void 0:new Date(Math.min(...S)).toISOString(),M=[...new Set(R.map(A=>A.projectId))].sort();return{framework:i,format:"allure-json",adapterVersion:Ux,...E===void 0?{}:{startTime:E},duration:S.length===0||N.length===0?0:Math.max(...N)-Math.min(...S),projects:(M.length===0?[""]:M).map(A=>({id:A,name:A,retries:0})),tests:R,errors:y,interrupted:!1,warnings:a}}var Yx="1",Qx=["0.2.0","1.0.0"];function _p(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Yo(n){return _p(n)&&n.reportFormat==="CTRF"&&_p(n.results)&&Array.isArray(n.results.tests)}var Zx=[...ft,..._o];function ev(n){let t=n?.trim().toLowerCase()??"";return Zx.includes(t)?t:"unknown"}var tv={passed:"passed",failed:"failed",skipped:"skipped",pending:"skipped"};function Bp(n){if(typeof n!="number")return;let t=new Date(n);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function nv(n,t){let e=n.message?.trim()||void 0,r=n.trace?.trim()||void 0,s=n.snippet?.trimEnd()||void 0;if(e===void 0&&r===void 0)return;let i=xe(r,t);return{...e===void 0?{}:{message:e},...r===void 0?{}:{stack:r},...s===void 0?{}:{snippet:s},...i===void 0?{}:{location:i}}}function rv(n){return(n.attachments??[]).flatMap(t=>t.path===void 0||t.path===""?[]:[{name:t.name??t.path,contentType:t.contentType??"",path:t.path}])}function jp(n,t,e,r,s){let i=Bp(n.start),a=n.duration,o=typeof n.start=="number"&&typeof n.stop=="number"?n.stop-n.start:void 0,d=typeof a=="number"&&a>=0?a:o??0,c=t==="passed"?void 0:nv(n,r);return{status:t,retry:e,...i===void 0?{}:{startTime:i},duration:d>=0?d:0,errors:c===void 0?[]:[c],attachments:rv(n),stdout:n.stdout??[],stderr:n.stderr??[],steps:s}}function Fp(n,t){if(t===void 0||n==="")return!1;let e=t.replaceAll("\\","/"),r=n.replaceAll("\\","/");return e===r||e.endsWith(`/${r}`)}function sv(n,t){let e=(n.suite??[]).filter(o=>o!==""),r=n.name??"",s=e.findIndex(o=>Fp(o,n.filePath)),i=s<0?e:e.slice(s+1),a=s>0?e.slice(0,s).join(" \u203A "):"";if(t==="pytest"&&r.includes("::")){let o=r.split("::");return{titlePath:Fp(o[0]??"",n.filePath)?o.slice(1):o,projectId:a}}if(t==="jest"){let o=`${i.join(" ")} `,d=i.length>0&&r.startsWith(o)?r.slice(o.length):r;return{titlePath:[...i,d],projectId:a}}return{titlePath:[...i,r],projectId:a}}function Vp(n){if(!Yo(n))throw new Error("A CTRF report needs results with a tests array.");let t=n,e=ev(t.results.tool?.name),r=t.results.tool?.version?.trim()||void 0,s=[],i=t.specVersion??"";Qx.includes(i)||s.push(`unverified-ctrf-spec-version:${i===""?"unrecorded":i}`);let a=0,o=0,d=!1,c=m=>{let g=tv[m.status??""];return g===void 0&&(a+=1),g??"skipped"},l=t.results.tests.map(m=>{let g=m.filePath??"",y=sv(m,e),w=m.retryAttempts??[];typeof m.retries=="number"&&m.retries>w.length&&(d=!0);let v=(m.steps??[]).map(S=>({title:S.name??"",duration:0,steps:[]})),x=[...w.map((S,N)=>jp(S,c(S),N,g,[])),jp(m,c(m),w.length,g,v)],R=x.at(-1)?.status==="passed"&&x.slice(0,-1).some(S=>S.status==="failed");return typeof m.flaky=="boolean"&&m.flaky!==R&&(o+=1),{file:g,titlePath:y.titlePath,...typeof m.line=="number"&&m.line>0?{line:m.line}:{},projectId:y.projectId,...m.tags===void 0?{}:{tags:m.tags},attempts:x}});a>0&&s.push(`ctrf-other-status:${a}`),o>0&&s.push(`ctrf-flaky-mismatch:${o}`),d&&s.push("final-attempt-only");let{start:u,stop:p}=t.results.summary??{},f=Bp(u),h=[...new Set(l.map(m=>m.projectId))].sort();return{framework:e,format:"ctrf-json",adapterVersion:Yx,...r===void 0?{}:{frameworkVersion:r},...f===void 0?{}:{startTime:f},duration:typeof u=="number"&&typeof p=="number"&&p>=u?p-u:0,projects:(h.length===0?[""]:h).map(m=>({id:m,name:m,retries:0})),tests:l,errors:[],interrupted:!1,warnings:s}}var iv="1";function av(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Qo(n){return Array.isArray(n)&&n.length>0&&n.every(t=>av(t)&&typeof t.uri=="string"&&typeof t.keyword=="string"&&Array.isArray(t.elements))}function ov(n){return n.startsWith("classpath:")?n.slice(10).replace(/^\/+/,""):n}var zp=new Set(["undefined","ambiguous","pending"]),dv=1e6;function Hp(n){let t=n.result?.duration;return typeof t=="number"&&t>0?t/dv:0}function cv(n,t){return t!==void 0?`${t} hook`:`${(n.keyword??"").trim()} ${n.name??""}`.trim()}function lv(n,t){if(t!==void 0||n.hidden!==!0)return t;let e=(n.keyword??"").trim();return e==="Before"||e==="After"?e:void 0}function uv(n,t,e,r){let s=n.result?.status??"",i=n.result?.error_message?.trim()||void 0,a=typeof n.line=="number"?{file:r,line:n.line}:void 0;if(zp.has(s))return{message:`${s[0]?.toUpperCase()}${s.slice(1)} step: ${t}`,...i===void 0?{}:{stack:i},...a===void 0?{}:{location:a}};if(s!=="failed"||i===void 0)return;let o=i.split(/\r?\n/),d=o.findIndex(u=>/^\s*at\s/.test(u)),c=(d<0?o:o.slice(0,d)).join(`
12
- `).trim()||i,l=xe(i,r)??a;return{message:e===void 0?c:`${e} hook failed: ${c}`,stack:i,...l===void 0?{}:{location:l}}}function pv(n){return(n.embeddings??[]).flatMap(t=>t.data===void 0||t.data===""?[]:[{name:t.name??"attachment",contentType:t.mime_type??t.media?.type??"",body:t.data}])}function fv(n,t,e){let r=n.map(({step:c})=>c.result?.status??""),s=r.some(c=>c==="failed"||zp.has(c))?"failed":r.some(c=>c==="passed")?"passed":"skipped",i=[],a=[],o=[];for(let c of n){let{step:l}=c,u=lv(l,c.hook),p=cv(l,u),f=uv(l,p,u,t);f!==void 0&&a.length===0&&a.push(f),i.push({title:p,duration:Hp(l),...f===void 0?{}:{error:f},steps:[]}),o.push(...pv(l))}let d=e===void 0||Number.isNaN(new Date(e).getTime())?void 0:new Date(e).toISOString();return{status:s,retry:0,...d===void 0?{}:{startTime:d},duration:n.reduce((c,{step:l})=>c+Hp(l),0),errors:a,attachments:o,stdout:[],stderr:[],steps:i}}function hv(...n){return[...new Set(n.flatMap(t=>(t??[]).flatMap(e=>e.name??[])))].sort()}function Up(n){if(!Qo(n))throw new Error("A Cucumber report is an array of features.");let t=[],e=[];for(let s of n){let i=ov(s.uri),a=[],o=[];for(let l of s.elements){if(l.type==="background"){o.push(l);continue}a.push({element:l,background:o}),o=[]}let d=new Map;for(let{element:l}of a){let u=l.name??"";d.set(u,(d.get(u)??0)+1)}let c=new Map;for(let{element:l,background:u}of a){let p=l.name??"",f=(c.get(p)??0)+1;c.set(p,f);let h=[...u.flatMap(m=>(m.before??[]).map(g=>({step:g,hook:"Before"}))),...(l.before??[]).map(m=>({step:m,hook:"Before"})),...u.flatMap(m=>(m.steps??[]).map(g=>({step:g}))),...(l.steps??[]).map(m=>({step:m})),...(l.after??[]).map(m=>({step:m,hook:"After"})),...u.flatMap(m=>(m.after??[]).map(g=>({step:g,hook:"After"})))];l.start_timestamp!==void 0&&e.push(l.start_timestamp),t.push({file:i,titlePath:[s.name??"",p,...(d.get(p)??0)>1?[`Example #${f}`]:[]],...typeof l.line=="number"?{line:l.line}:{},projectId:"",tags:hv(s.tags,l.tags),attempts:[fv(h,i,l.start_timestamp)]})}}let r=e.map(s=>new Date(s)).filter(s=>!Number.isNaN(s.getTime())).map(s=>s.toISOString()).sort()[0];return{framework:"cucumber",format:"cucumber-json",adapterVersion:iv,...r===void 0?{}:{startTime:r},duration:t.reduce((s,i)=>s+(i.attempts[0]?.duration??0),0),projects:[{id:"",name:"",retries:0}],tests:t,errors:[],interrupted:!1,warnings:["final-attempt-only"]}}import{join as mv}from"node:path";var wi="kwikqa-test-report",Zo="1.0",yv="1",gv=new Set(["cypress","webdriverio"]),wv=new Set(["passed","failed","timedOut","skipped","interrupted"]);function qp(n,t){let e=t.replaceAll("\\","/");return/^(?:[A-Za-z]:\/|\/|file:\/\/)/.test(e)?t:mv(n,e.replace(/^(?:\.\/)+/,""))}function bv(n){let t=n.rootDir;return t===void 0?n:{...n,tests:n.tests.map(e=>({...e,file:qp(t,e.file),attempts:e.attempts.map(r=>({...r,attachments:r.attachments.map(s=>s.path===void 0?s:{...s,path:qp(t,s.path)})}))}))}}function Gp(n){return typeof n=="object"&&n!==null&&n.schema===wi}function xv(n,t){let e=ne(n,t),r=ue(e,"line",we,t),s=ue(e,"column",we,t);return{file:G(e.file,`${t}.file`),...r===void 0?{}:{line:r},...s===void 0?{}:{column:s}}}function Kp(n,t,e){let r=ne(n,t),s=fe(r.message,`${t}.message`),i=fe(r.name,`${t}.name`),a=fe(r.stack,`${t}.stack`),o=fe(r.snippet,`${t}.snippet`),d=fe(r.expected,`${t}.expected`),c=fe(r.actual,`${t}.actual`),u=ue(r,"location",xv,t)??xe(a,e);return{...s===void 0?{}:{message:s},...i===void 0?{}:{name:i},...a===void 0?{}:{stack:a},...o===void 0?{}:{snippet:o},...d===void 0&&c===void 0?{}:{value:`Expected: ${d??"(not recorded)"}
13
- Received: ${c??"(not recorded)"}`},...u===void 0?{}:{location:u}}}function vv(n,t,e){let r=ne(n,t),s=fe(r.startTime,`${t}.startTime`);return{status:nn(r.status,`${t}.status`,wv),retry:we(r.retry,`${t}.retry`),...s===void 0?{}:{startTime:s},duration:Ge(r.duration??0,`${t}.duration`),errors:Z(r.errors??[],`${t}.errors`,(i,a)=>Kp(i,a,e)),attachments:Z(r.attachments??[],`${t}.attachments`,(i,a)=>{let o=ne(i,a),d=fe(o.path,`${a}.path`);return{name:G(o.name,`${a}.name`),contentType:G(o.contentType,`${a}.contentType`),...d===void 0?{}:{path:d}}}),stdout:Z(r.stdout??[],`${t}.stdout`,G),stderr:Z(r.stderr??[],`${t}.stderr`,G),steps:[]}}function kv(n,t){let e=ne(n,t),r=G(e.file,`${t}.file`),s=Z(e.titlePath,`${t}.titlePath`,G);s.length===0&&Ne(`${t}.titlePath`,"a non-empty array");let i=ue(e,"line",we,t),a=ue(e,"column",we,t),o=ue(e,"timeout",Ge,t);return{file:r,titlePath:s,...i===void 0?{}:{line:i},...a===void 0?{}:{column:a},projectId:G(e.project,`${t}.project`),...o===void 0?{}:{timeout:o},tags:Z(e.tags??[],`${t}.tags`,G),attempts:Z(e.attempts,`${t}.attempts`,(d,c)=>vv(d,c,r))}}function Wp(n){let t=ne(n,"$report");t.schema!==wi&&Ne("$report.schema",wi),String(t.schemaVersion??"").split(".")[0]!==Zo.split(".")[0]&&Ne("$report.schemaVersion",`a ${Zo.split(".")[0]}.x version`);let r=nn(t.framework,"$report.framework",gv),s=fe(t.frameworkVersion,"$report.frameworkVersion"),i=fe(t.rootDir,"$report.rootDir"),a=fe(t.configFile,"$report.configFile"),o=fe(t.startTime,"$report.startTime"),d=ue(t,"duration",Ge,"$report"),c=Z(t.projects,"$report.projects",(l,u)=>{let p=ne(l,u);return{id:G(p.id,`${u}.id`),name:G(p.name,`${u}.name`),retries:we(p.retries??0,`${u}.retries`)}});return tn(t.tests,"$report.tests"),{framework:r,format:"kwikqa-json",adapterVersion:yv,...s===void 0?{}:{frameworkVersion:s},...i===void 0?{}:{rootDir:i},...a===void 0?{}:{configFile:a},...o===void 0?{}:{startTime:o},...d===void 0?{}:{duration:d},projects:c,tests:Z(t.tests,"$report.tests",kv),errors:Z(t.errors??[],"$report.errors",(l,u)=>Kp(l,u,void 0)),interrupted:t.interrupted===!0,warnings:[]}}function Jp(n){let t=n.map(bv),e=t[0];if(e===void 0)throw new Error("No report parts to merge.");let r=e.framework;if(t.some(l=>l.framework!==r))throw new Error("Report parts come from different frameworks.");let s=[...new Set(t.map(l=>l.frameworkVersion).filter(Boolean))],i=new Map;for(let l of t)for(let u of l.projects){let p=i.get(u.id);(p===void 0||u.retries>p.retries)&&i.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 s.length>1&&c.push(`mixed-framework-versions:${s.join(",")}`),o.length>1&&c.push("mixed-report-roots"),{framework:r,format:e.format,adapterVersion:e.adapterVersion,...s.length===1&&s[0]!==void 0?{frameworkVersion:s[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:[...i.values()],tests:t.flatMap(l=>l.tests),errors:t.flatMap(l=>l.errors),interrupted:t.some(l=>l.interrupted),warnings:c}}import{basename as Sv,dirname as Tv,isAbsolute as Ev,resolve as Cv}from"node:path";var bi=class extends Error{constructor(t){super(t),this.name="XmlError"}},Rv=64,Iv=5e5,Av=/^[A-Za-z_:][\w.:-]*/,Pv={lt:"<",gt:">",amp:"&",quot:'"',apos:"'"};function Xp(n){return n.replace(/&(#x[0-9A-Fa-f]+|#\d+|[A-Za-z]+);/g,(t,e)=>{if(e.startsWith("#x")){let s=Number.parseInt(e.slice(2),16);return s<=1114111?String.fromCodePoint(s):t}if(e.startsWith("#")){let s=Number.parseInt(e.slice(1),10);return s<=1114111?String.fromCodePoint(s):t}let r=Pv[e];if(r===void 0)throw new bi(`Unknown XML entity: &${e};`);return r})}function xi(n){let t=0,e=0,r=n.charCodeAt(0)===65279?n.slice(1):n,s=c=>{throw new bi(`${c} at offset ${t}`)},i=()=>{for(;;){for(;t<r.length&&/\s/.test(r[t]??"");)t+=1;if(r.startsWith("<?",t)){let c=r.indexOf("?>",t);c<0&&s("Unterminated processing instruction"),t=c+2}else if(r.startsWith("<!--",t)){let c=r.indexOf("-->",t);c<0&&s("Unterminated comment"),t=c+3}else if(r.startsWith("<!DOCTYPE",t)||r.startsWith("<!doctype",t))s("Document type declarations are not accepted");else return}},a=()=>{let c=Av.exec(r.slice(t,t+256));return c===null?s("Expected a name"):(t+=c[0].length,c[0])},o=c=>{c>Rv&&s("XML nests too deeply"),e+=1,e>Iv&&s("XML has too many nodes"),r[t]!=="<"&&s("Expected an element"),t+=1;let l=a(),u={};for(;;){for(;/\s/.test(r[t]??"");)t+=1;if(r.startsWith("/>",t))return t+=2,{name:l,attributes:u,children:[]};if(r[t]===">"){t+=1;break}let m=a();for(;/\s/.test(r[t]??"");)t+=1;for(r[t]!=="="&&s(`Expected = after attribute ${m}`),t+=1;/\s/.test(r[t]??"");)t+=1;let g=r[t];if(g!=='"'&&g!=="'")return s("Expected a quoted attribute value");let y=r.indexOf(g,t+1);y<0&&s("Unterminated attribute value");let w=r.slice(t+1,y);w.includes("<")&&s("Attribute values must not contain <"),u[m]=Xp(w),t=y+1}let p=[],f="",h=()=>{f.length>0&&(p.push(f),e+=1,f="")};for(;;){if(t>=r.length&&s(`Unterminated element <${l}>`),r.startsWith("</",t)){t+=2;let y=a();for(y!==l&&s(`Expected </${l}> but found </${y}>`);/\s/.test(r[t]??"");)t+=1;return r[t]!==">"&&s("Expected >"),t+=1,h(),{name:l,attributes:u,children:p}}if(r.startsWith("<![CDATA[",t)){let y=r.indexOf("]]>",t);y<0&&s("Unterminated CDATA section"),f+=r.slice(t+9,y),t=y+3;continue}if(r.startsWith("<!--",t)){let y=r.indexOf("-->",t);y<0&&s("Unterminated comment"),t=y+3;continue}if(r.startsWith("<?",t)){let y=r.indexOf("?>",t);y<0&&s("Unterminated processing instruction"),t=y+2;continue}if(r[t]==="<"){h(),p.push(o(c+1));continue}let m=r.indexOf("<",t),g=m<0?r.length:m;f+=Xp(r.slice(t,g)),t=g}};i();let d=o(0);return i(),t<r.length&&s("Unexpected content after the root element"),d}function Y(n,t){return n.children.filter(e=>typeof e!="string"&&(t===void 0||e.name===t))}function Fe(n){return n.children.map(t=>typeof t=="string"?t:Fe(t)).join("")}var jr="3",Nv=/(?:^|[\\/])cypress[\\/]|\.cy\.[cm]?[jt]sx?$/,Ov=/webpack:\/\/|__cypress|CypressError/;function ef(n){let t=n.slice(0,4096).replace(/^\uFEFF/,"");return/^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<testsuites?\b/.test(t)}function on(n){if(n.name==="testsuite")return[n];if(n.name!=="testsuites")throw new Error("A JUnit report's root must be testsuites.");let t=[],e=r=>{for(let s of Y(r,"testsuite"))t.push(s),e(s)};return e(n),t}function ed(n){let t=new Map;for(let e of Y(n,"properties"))for(let r of Y(e,"property")){let s=r.attributes.name;s!==void 0&&t.set(s,r.attributes.value??Fe(r))}return t}function $v(n,t){if(n.name!=="testsuites"||n.attributes.id===void 0)return!1;let e=t.flatMap(r=>Y(r,"testcase").map(s=>({suite:r,testcase:s})));return e.length>0&&e.every(({suite:r,testcase:s})=>s.attributes.classname===r.attributes.name)}function Dv(n){let t=Object.entries(n.attributes).find(([s])=>s.endsWith("noNamespaceSchemaLocation"))?.[1];if(n.name!=="testsuite"||t===void 0||!t.includes("surefire"))return;let e=ed(n),r=`${e.get("surefire.test.class.path")??""}:${e.get("java.class.path")??""}`;return/[\\/]testng-[\d.]+\.jar/.test(r)?"surefire-testng":"surefire-junit"}var Mv=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/;function Lv(n){let t=n.attributes.name??"",e=Y(n,"properties");return n.name==="testsuite"&&n.attributes.timestamp!==void 0&&n.attributes.hostname!==void 0&&e.length===1&&e.every(r=>Y(r,"property").length===0)&&Mv.test(t)&&Y(n,"testcase").every(r=>r.attributes.classname===t)}function td(n){if(n.some(e=>/\bat org\.testng\./.test(e)))return"testng";let t=e=>/\bat org\.junit\./.test(e)||/<testcase\b[^>]*\bname="[^"]*\(\)"/.test(e);return n.some(t)?"junit":void 0}function _v(n,t){let e=Dv(n);if(e!==void 0)return e;if(Lv(n))return"gradle";let r=on(n),s=n.name==="testsuites"?n.attributes.name:void 0;if(r.some(o=>ed(o).has("capabilities")))return"webdriverio";if(s==="vitest tests")return"vitest";if(s==="jest tests")return"jest";if(s==="pytest tests"||r.some(o=>o.attributes.name==="pytest"))return"pytest";let i=r.some(o=>o.attributes.name==="Root Suite"),a=r.some(o=>Nv.test(o.attributes.file??""));return i&&a||Ov.test(t)?"cypress":i?"mocha":$v(n,r)?"playwright":"unknown"}function dn(n){let t=Number.parseFloat(n??"");return Number.isFinite(t)&&t>=0?Math.round(t*1e3):0}function jv(n){if(n===void 0)return;let t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?$/.test(n)?`${n}Z`:n,e=new Date(t);return Number.isNaN(e.getTime())?void 0:e.toISOString()}function nd(n){return n.map(t=>jv(t.attributes.timestamp)).filter(t=>t!==void 0).sort()[0]}function vi(n,t){return n.name==="testsuites"&&n.attributes.time!==void 0?dn(n.attributes.time):t.reduce((e,r)=>e+dn(r.attributes.time),0)}function ki(n,t,e={retriedAsSkipped:!0}){let r=Y(n,"failure")[0]??Y(n,"error")[0]??void 0,s=Y(n,"system-err").map(i=>Fe(i).trim()).filter(i=>i!=="").join(`
14
- `);if(r!==void 0){let i=Fe(r).trim(),a=i!==""?i:s!==""?s:void 0,o=e.messageFromBody===!0?i.split(`
15
- `)[0]?.trim():void 0,d=r.attributes.message??(o===""?void 0:o),c=xe(a,t);return{status:"failed",errors:[{...d===void 0?{}:{message:d},...r.attributes.type===void 0?{}:{name:r.attributes.type},...a===void 0?{}:{stack:a},...c===void 0?{}:{location:c}}]}}if(Y(n,"skipped").length>0){if(e.retriedAsSkipped===!0&&s!==""){let i=xe(s,t),a=s.split(`
16
- `)[0]?.replace(/^\w*Error:\s*/,"");return{status:"failed",errors:[{...a===void 0?{}:{message:a},stack:s,...i===void 0?{}:{location:i}}]}}return{status:"skipped",errors:[]}}return{status:"passed",errors:[]}}function Fv(n,t,e){if(e===""||n===e||!n.endsWith(` ${e}`))return[n];let r=n.slice(0,-(e.length+1));return t===""||t==="Root Suite"?[r,e]:r===t?[t,e]:r.endsWith(` ${t}`)?[r.slice(0,-(t.length+1)),t,e]:[r,e]}function cn(n,t,e,r,s={}){return{status:n,retry:e,duration:r,errors:t,attachments:s.attachments??[],stdout:s.stdout??[],stderr:s.stderr??[],steps:[]}}var Bv=/^\[\[ATTACHMENT\|(.+)\]\]$/,Vv={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webm":"video/webm",".zip":"application/zip",".md":"text/markdown",".txt":"text/plain",".json":"application/json"};function Hv(n,t){let e=[],r=[];for(let i of Y(n,"system-out")){let a=[];for(let d of Fe(i).split(/\r?\n/)){let c=Bv.exec(d.trim());if(c?.[1]===void 0){a.push(d);continue}let l=c[1],u=Ev(l)||t===void 0?l:Cv(Tv(t),l),p=Sv(l),f=/\.[^.]+$/.exec(p)?.[0]?.toLowerCase()??"";e.push({name:p==="error-context.md"?"error-context":p,contentType:Vv[f]??"application/octet-stream",path:u})}let o=a.join(`
17
- `).trim();o!==""&&r.push(o)}let s=Y(n,"system-err").map(i=>Fe(i).trim()).filter(i=>i!=="");return{attachments:e,stdout:r,stderr:s}}function Yp(n,t){let e=[],r=on(n),s="";for(let a of r){a.attributes.file!==void 0&&a.attributes.file!==""&&(s=a.attributes.file);let o=a.attributes.name??"";for(let d of Y(a,"testcase")){let c=d.attributes.name??"",l=d.attributes.classname??c,u=ki(d,s);e.push({file:s,titlePath:Fv(c,o,l),projectId:"",attempts:[cn(u.status,u.errors,0,dn(d.attributes.time))]})}}let i=nd(r);return{framework:t,format:"junit-xml",adapterVersion:jr,...i===void 0?{}:{startTime:i},duration:vi(n,r),projects:[{id:"",name:"",retries:0}],tests:e,errors:[],interrupted:!1,warnings:["final-attempt-only"]}}function zv(n){let t=[],e=new Set;for(let r of on(n)){let s=ed(r),i=s.get("file")??r.attributes.file??"",a=(s.get("capabilities")??"").split(".")[0]??"";e.add(a);let o=s.get("suiteName")??r.attributes.name??"",d=new Map,c=[];for(let l of Y(r,"testcase")){let u=l.attributes.name??"",p=ki(l,i),f=d.get(u);f===void 0&&(f=[],d.set(u,f),c.push(u)),f.push(cn(p.status,p.errors,f.length,dn(l.attributes.time)))}for(let l of c)t.push({file:i,titlePath:o===""?[l]:[o,l],projectId:a,attempts:d.get(l)??[]})}return{framework:"webdriverio",format:"junit-xml",adapterVersion:jr,projects:[...e].map(r=>({id:r,name:r,retries:0})),tests:t,errors:[],interrupted:!1,warnings:[]}}function _r(n,t,e,r,s={}){let i=on(n),a=[],o=new Set;for(let c of i)for(let l of Y(c,"testcase")){let{file:u,titlePath:p,projectId:f="",line:h}=r(c,l);o.add(f);let m=ki(l,u,s);a.push({file:u,titlePath:p,...h===void 0?{}:{line:h},projectId:f,attempts:[cn(m.status,m.errors,0,dn(l.attributes.time),Hv(l,e))]})}let d=nd(i);return{framework:t,format:"junit-xml",adapterVersion:jr,...d===void 0?{}:{startTime:d},duration:vi(n,i),projects:[...o.size===0?new Set([""]):o].map(c=>({id:c,name:c,retries:0})),tests:a,errors:[],interrupted:!1,warnings:[...s.warnings??[]]}}function Uv(n){let t=n.attributes.name??"";for(let e of Y(n,"testcase")){let r=Y(e,"failure")[0]??Y(e,"error")[0],s=r===void 0?void 0:xe(Fe(r),t)?.file;if(s?.replaceAll("\\","/").endsWith(`/${t}`))return s}return t}function qv(n,t){let e=new Map(on(n).map(r=>[r,Uv(r)]));return _r(n,"playwright",t,(r,s)=>({file:e.get(r)??r.attributes.name??"",titlePath:(s.attributes.name??"").split(" \u203A "),projectId:r.attributes.hostname??""}),{warnings:["final-attempt-only"]})}function Gv(n){let t=(n.attributes.classname??"").split(".").filter(a=>a!==""),e=t.length;for(;e>1&&/^[A-Z]/.test(t[e-1]??"");)e-=1;let r=t.slice(e),s=n.attributes.file,i=Number.parseInt(n.attributes.line??"",10);return{file:s??`${t.slice(0,e).join("/")}.py`,titlePath:[...r,n.attributes.name??""],...Number.isInteger(i)&&i>=0?{line:i+1}:{}}}var tf=new Set(["failure","error"]),Kv=new Set(["rerunFailure","rerunError"]),Wv=new Set(["flakyFailure","flakyError"]);function an(n,t){return Y(n,t).map(e=>Fe(e).trim()).filter(e=>e!=="").join(`
18
- `)}function Qp(n,t,e,r,s){let i=!tf.has(n.name),a=(i?an(n,"stackTrace"):Fe(n).trim())||void 0,o=n.attributes.message,d=xe(a,r);return cn(t,[{...o===void 0?{}:{message:o},...n.attributes.type===void 0?{}:{name:n.attributes.type},...a===void 0?{}:{stack:a},...d===void 0?{}:{location:d}}],e,s,i?{stdout:[an(n,"system-out")].filter(c=>c!==""),stderr:[an(n,"system-err")].filter(c=>c!=="")}:{})}function nf(n,t){let e=Y(n),r=dn(n.attributes.time),s={stdout:[an(n,"system-out")].filter(o=>o!==""),stderr:[an(n,"system-err")].filter(o=>o!=="")},i=e.find(o=>tf.has(o.name));if(i!==void 0){let o=e.filter(d=>Kv.has(d.name));return[i,...o].map((d,c)=>Qp(d,"failed",c,t,r))}let a=e.filter(o=>Wv.has(o.name));return e.some(o=>o.name==="skipped")?[cn("skipped",[],0,r,s)]:[...a.map((o,d)=>Qp(o,"failed",d,t,r)),cn("passed",[],a.length,r,s)]}function Zp(n,t){let e=[];for(let r of on(n))for(let s of Y(r,"testcase")){let i=s.attributes.classname??r.attributes.name??"",a=sn(i),d=[...i.split("$").filter(l=>l!==""),s.attributes.name??""];if(t==="junit"){e.push({file:a,titlePath:d,projectId:"",attempts:nf(s,a)});continue}let c=ki(s,a,{});e.push({file:a,titlePath:d,projectId:"",attempts:[cn(c.status,c.errors,0,dn(s.attributes.time),{stdout:[an(s,"system-out")].filter(l=>l!==""),stderr:[an(s,"system-err")].filter(l=>l!=="")})]})}return{framework:t,format:"junit-xml",adapterVersion:jr,duration:vi(n,on(n)),projects:[{id:"",name:"",retries:0}],tests:e,errors:[],interrupted:!1,warnings:t==="testng"?["testng-retries-uncorrelated"]:[]}}var Jv=/^([\w$]+\[\d+\])\(.*\)$/s;function Xv(n,t){return t==="testng"?Jv.exec(n)?.[1]??n:n.endsWith("()")?n.slice(0,-2):n}function Yv(n,t){let e=new Map;for(let i of Y(n,"testcase")){let a=i.attributes.classname??n.attributes.name??"",o=i.attributes.name??"",d=`${a}\0${o}`,c=e.get(d)??{className:a,name:o,cases:[]};e.set(d,c),c.cases.push(i)}let r=[...e.values()].map(({className:i,name:a,cases:o})=>{let d=sn(i),c=i.split("$").filter(l=>l!=="");return{file:d,titlePath:[...c,Xv(a,t)],projectId:"",attempts:o.flatMap(l=>nf(l,d)).map((l,u)=>({...l,retry:u}))}}),s=nd([n]);return{framework:t,format:"junit-xml",adapterVersion:jr,...s===void 0?{}:{startTime:s},duration:vi(n,[n]),projects:[{id:"",name:"",retries:0}],tests:r,errors:[],interrupted:!1,warnings:[]}}function rf(n,t){let e=xi(n),r=_v(e,n),s=(r==="unknown"||r==="mocha")&&t.framework!==void 0?t.framework:r,i=t.reportPath;switch(s){case"surefire-junit":return Zp(e,"junit");case"surefire-testng":return Zp(e,"testng");case"gradle":return Yv(e,t.jvmFramework??td([n])??"unknown");case"cypress":return Yp(e,"cypress");case"mocha":return Yp(e,"mocha");case"webdriverio":return zv(e);case"playwright":return qv(e,i);case"vitest":return _r(e,"vitest",i,(a,o)=>({file:o.attributes.file??o.attributes.classname??a.attributes.name??"",titlePath:(o.attributes.name??"").split(" > ")}),{warnings:["final-attempt-only"]});case"jest":{let a=_r(e,"jest",i,(o,d)=>({file:d.attributes.file??"",titlePath:[(d.attributes.name??"").trim()]}),{messageFromBody:!0,warnings:["final-attempt-only"]});return a.tests.some(o=>o.file==="")?{...a,warnings:[...a.warnings,"test-file-unrecorded"]}:a}case"pytest":return _r(e,"pytest",i,(a,o)=>Gv(o));case"unknown":return _r(e,"unknown",i,(a,o)=>{let d=o.attributes.classname??"",c=o.attributes.name??"";return{file:o.attributes.file??a.attributes.file??"",titlePath:d===""||d===c?[c]:[d,c]}},{warnings:["final-attempt-only","junit-producer-unknown"]})}}var Qv="1";function af(n){let t=n.slice(0,4096).replace(/^\uFEFF/,"");return/^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<testng-results\b/.test(t)}function of(n){if(n===void 0)return;let t=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?) ?(UTC|GMT|Z|[+-]\d\d:?\d\d)?$/.exec(n.trim());if(t?.[1]===void 0||t[2]===void 0)return;let e=t[2],r=e==="UTC"||e==="GMT"||e==="Z"?"Z":e.includes(":")?e:`${e.slice(0,3)}:${e.slice(3)}`,s=new Date(`${t[1]}${r}`);return Number.isNaN(s.getTime())?void 0:s.toISOString()}function sf(n){if(n===void 0)return;let t=Fe(n).trim();return t===""?void 0:t}function Zv(n,t){let e=Y(n,"exception")[0];if(e===void 0)return[];let r=sf(Y(e,"message")[0]),s=sf(Y(e,"full-stacktrace")[0]),i=xe(s,t);return[{...r===void 0?{}:{message:r},...e.attributes.class===void 0?{}:{name:e.attributes.class},...s===void 0?{}:{stack:s},...i===void 0?{}:{location:i}}]}function ek(n){return Y(n,"params").flatMap(t=>Y(t,"param").map(e=>Fe(Y(e,"value")[0]??e).trim()))}function tk(n){let e=Y(n,"reporter-output").flatMap(r=>Y(r,"line").map(s=>Fe(s).trim())).filter(r=>r!=="").join(`
19
- `);return e===""?[]:[e]}var nk={PASS:"passed",FAIL:"failed",SKIP:"skipped"};function rk(n,t,e){let{method:r}=n,s=of(r.attributes["started-at"]),i=Number.parseInt(r.attributes["duration-ms"]??"",10);return{status:n.retried?"failed":nk[r.attributes.status??""]??"skipped",retry:t,...s===void 0?{}:{startTime:s},duration:Number.isFinite(i)&&i>=0?i:0,errors:Zv(r,e),attachments:[],stdout:tk(r),stderr:[],steps:[]}}function sk(n,t){let e=n.attributes.name??"",r=sn(e),s=new Map,i=new Map;for(let a of Y(n,"test-method")){let o=a.attributes.name??"",d=a.attributes["is-config"]==="true";if(d&&a.attributes.status!=="FAIL")continue;let c=ek(a),l=d?`${o} (configuration)`:o;if(!d&&c.length>0){let p=i.get(o)??new Map;i.set(o,p);let f=JSON.stringify(c),h=p.get(f)??p.size;p.set(f,h),l=`${o}[${h}]`}let u=s.get(l)??[];s.set(l,u),u.push({method:a,retried:a.attributes.retried==="true"})}return[...s].map(([a,o])=>{let d=[...o.filter(c=>c.retried),...o.filter(c=>!c.retried)];return{file:r,titlePath:[e,a],projectId:t,attempts:d.map((c,l)=>rk(c,l,r))}})}function df(n){let t=xi(n);if(t.name!=="testng-results")throw new Error("A TestNG report's root must be testng-results.");let e=Y(t,"suite"),r=e.flatMap(c=>Y(c,"test")),s=r.length>1,i=r.flatMap(c=>Y(c,"class").flatMap(l=>sk(l,s?c.attributes.name??"":""))),a=e.map(c=>of(c.attributes["started-at"])).filter(c=>c!==void 0).sort()[0],o=e.reduce((c,l)=>{let u=Number.parseInt(l.attributes["duration-ms"]??"",10);return c+(Number.isFinite(u)&&u>=0?u:0)},0),d=s?r.map(c=>c.attributes.name??""):[""];return{framework:"testng",format:"testng-xml",adapterVersion:Qv,...a===void 0?{}:{startTime:a},duration:o,projects:[...new Set(d)].map(c=>({id:c,name:c,retries:0})),tests:i,errors:[],interrupted:!1,warnings:[]}}import{dirname as ck,isAbsolute as lk,join as uk}from"node:path";import{isAbsolute as Ii,relative as ik,sep as Fr}from"node:path";var Ri="1970-01-01T00:00:00.000Z";function Br(n,t){switch(n){case"playwright":case"vitest":case"jest":case"mocha":case"pytest":case"junit":case"testng":case"cucumber":case"unknown":return t;case"cypress":return[t.filter(e=>e!=="").join(" ")];case"webdriverio":return t.filter(e=>e!=="").slice(-2)}}function cf(n,t,e,r,s){return B("tst",[t,e,r,...n==="playwright"?[]:[`framework:${n}`],...Br(n,s)])}function Ai(n,t){if(!Ii(t))return;let e=ik(n,t);if(!(Ii(e)||e===".."||e.startsWith(`..${Fr}`)))return e.split(Fr).join("/")}function Vr(n){let t=n.trim();return t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7)).replaceAll("\\","/"),/^\/[A-Za-z]:\//.test(t)&&(t=t.slice(1))),t.replaceAll("\\","/")}function lf(n,t,e){let r=Vr(e),s=Fr==="\\"?r.replaceAll("/","\\"):r;if(Ii(s)||/^[A-Za-z]:\//.test(r))return Ai(n,s)??r;let i=r.replace(/^(?:\.\/)+/,"");if(t===void 0)return i;let a=Ai(n,t);return a===void 0||a===""?i:`${a}/${i}`}function sd(n,t,e,r,s){let i=n.location===void 0?void 0:{...n.location,file:lf(r,s,n.location.file)};return{errorId:B("err",[t,e]),source:e,...n.message===void 0?{}:{message:n.message},...n.name===void 0?{}:{name:n.name},...n.stack===void 0?{}:{stack:n.stack},...n.snippet===void 0?{}:{snippet:n.snippet},...n.value===void 0?{}:{value:n.value},...i===void 0?{}:{location:i}}}function uf(n,t,e,r,s){return{title:n.title,duration:n.duration,...n.error===void 0?{}:{error:sd(n.error,t,`${e}.error`,r,s)},steps:n.steps.map((i,a)=>uf(i,t,`${e}.steps[${a}]`,r,s))}}function ak(n,t){let e=Vr(t),r=Fr==="\\"?e.replaceAll("/","\\"):e;return Ii(r)||n===void 0?r:`${n}${Fr}${r.replace(/^(?:\.[/\\])+/,"")}`}function ok(n){let t=n.filter(r=>r.status!=="skipped");return t.length===0?"skipped":t.at(-1)?.status==="passed"?t.some(r=>r.status!=="passed")?"flaky":"expected":"unexpected"}function dk(n,t,e){return n.length===0?"zero-tests":e||n.some(r=>r.attempts.some(s=>s.status==="interrupted"))?"interrupted":t.length>0?"report-errors":"analysis-ready"}function rd(n){if(n===void 0)return;let t=new Date(n);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function pf(n){let{report:t,reportHash:e,artifact:r,options:s}=n,i=s.workspaceRoot,a=new Set(n.warnings),o=t.projects.map(w=>{let v=w.testDir===void 0?void 0:Ai(i,w.testDir);return{projectId:B("prj",[`framework:${t.framework}`,w.id,w.name]),frameworkProjectId:w.id,name:w.name,repeatEach:1,retries:w.retries,...v===void 0?{}:{testDir:v}}}).sort((w,v)=>w.projectId.localeCompare(v.projectId)),d=new Map(o.map(w=>[w.frameworkProjectId,w.projectId])),c=new Set,l=[];t.tests.forEach((w,v)=>{let x=d.get(w.projectId);if(x===void 0)throw new Error(`Test ${v} references unknown project: ${w.projectId}`);let R=lf(i,t.rootDir,w.file),S=cf(t.framework,i,x,R,w.titlePath);if(c.has(S)){a.add(`duplicate-test-identity:${R}`);return}c.add(S);let N=`$tests[${v}]`,E=w.attempts.map((A,C)=>{let P=B("atm",[S,String(A.retry),"repeat:unknown",String(C)]),I=`${N}.attempts[${C}]`,$=A.errors.map((k,T)=>sd(k,P,`${I}.errors[${T}]`,i,t.rootDir)),D=$.find(k=>k.location!==void 0)?.location;return{attemptId:P,sourceIndex:C,retry:A.retry,repeat:{state:"unknown",reason:"not-serialized-by-report"},status:A.status,duration:A.duration,startTime:rd(A.startTime)??rd(t.startTime)??Ri,workerIndex:0,parallelIndex:0,errors:$,stdout:A.stdout.map(k=>({kind:"text",text:k})),stderr:A.stderr.map(k=>({kind:"text",text:k})),steps:A.steps.map((k,T)=>uf(k,P,`${I}.steps[${T}]`,i,t.rootDir)),attachments:A.attachments.map((k,T)=>({attachmentId:B("att",[P,String(T)]),name:k.name,contentType:k.contentType,sourceIndex:T,...k.path===void 0?{}:{path:ak(t.rootDir,k.path)},...k.body===void 0?{}:{bodyBase64:k.body}})),annotations:[],...D===void 0?{}:{errorLocation:D}}}),M=ok(w.attempts);l.push({logicalTestId:S,projectId:x,title:w.titlePath.at(-1)??"",titlePath:w.titlePath,tags:[...w.tags??[]].sort(),location:{file:R,...w.line===void 0?{}:{line:w.line},...w.column===void 0?{}:{column:w.column}},timeout:w.timeout??0,expectedStatus:M==="skipped"?"skipped":"passed",status:M,annotations:[],attempts:E})}),l.sort((w,v)=>w.logicalTestId.localeCompare(v.logicalTestId));let u=t.errors.map((w,v)=>sd(w,r.artifactId,`$errors[${v}]`,i,t.rootDir)),p=l.reduce((w,v)=>w+v.attempts.reduce((x,R)=>x+R.attachments.length,0),0),f=l.flatMap(w=>w.attempts.map(v=>v.startTime)).filter(w=>w!==Ri).sort()[0],h=rd(t.startTime)??f??Ri;h===Ri&&a.add("start-time-unavailable");let m={expected:0,unexpected:0,flaky:0,skipped:0};for(let w of l)m[w.status]+=1;let g=t.configFile===void 0?void 0:Ai(i,Vr(t.configFile)),y=B("run",[e,i,s.gitRoot??"","1.7",`${t.format}:${t.adapterVersion}`]);return{schemaVersion:"1.7",runId:y,framework:t.framework,createdAt:h,workspace:{root:i,...s.gitRoot===void 0?{}:{gitRoot:s.gitRoot}},sourceHashes:{report:e},artifact:r,usability:dk(l,u,t.interrupted),projects:o,...g===void 0?{}:{configFile:g},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,...m}}}var pk="1",fk=/\.(?:png|jpe?g|webp|gif|mp4|webm)$/i;function hf(n){if(typeof n!="object"||n===null||Array.isArray(n))return!1;let t=n;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 hk(n,t){let e=[],r=s=>{if(typeof s=="string"){let i;try{i=JSON.parse(s)}catch{i=void 0}if(i!==void 0&&typeof i!="string"){r(i);return}let a=typeof i=="string"?i:s;fk.test(a)&&!/^https?:/i.test(a)&&e.push(a);return}if(Array.isArray(s)){for(let i of s)r(i);return}typeof s=="object"&&s!==null&&r(s.value)};return r(n),e.map(s=>{let i=Vr(s);return lk(i)||t===void 0?i:uk(t,i)})}function mk(n){let t=JSON.stringify(n.results??[]).slice(0,2e5);return/webpack:\/\/|__cypress|\bcy\.|Cypress/.test(t)?"cypress":/\bbrowser\.|\$\(|webdriverio|wdio/.test(t)?"webdriverio":"cypress"}function ff(n){return n.pending===!0||n.skipped===!0?"skipped":n.state==="passed"||n.pass===!0?"passed":n.timedOut===!0?"timedOut":n.state==="failed"||n.fail===!0?"failed":"skipped"}function yk(n,t,e){let r=n.err;if(typeof r!="object"||r===null)return[];let s=r,i=fe(s.message,`${t}.err.message`),a=fe(s.estack,`${t}.err.estack`),o=fe(s.diff??void 0,`${t}.err.diff`);if(i===void 0&&a===void 0)return[];let d=xe(a,e);return[{...i===void 0?{}:{message:i},...a===void 0?{}:{stack:a},...o===void 0||o===""?{}:{value:o},...d===void 0?{}:{location:d}}]}function mf(n,t){let e=ne(n,"$report"),r=tn(e.results,"$report.results"),s=ne(e.stats,"$report.stats"),i=t.reportPath===void 0?void 0:ck(t.reportPath),a=t.framework??mk(e),o=[],d=[],c=(u,p,f,h)=>{let m=ne(u,p),g=typeof m.title=="string"?m.title:"",y=(typeof m.file=="string"&&m.file!==""?m.file:void 0)??(typeof m.fullFile=="string"&&m.fullFile!==""?m.fullFile:void 0)??h,w=g===""?f:[...f,g];Z(m.tests??[],`${p}.tests`,(v,x)=>{let R=ne(v,x),S=G(R.title,`${x}.title`),N=yk(R,x,y);if(R.isHook===!0){ff(R)!=="passed"&&d.push(...N);return}let E=hk(R.context,i).map(M=>({name:/\.(?:mp4|webm)$/i.test(M)?"video":"screenshot",contentType:/\.(?:mp4|webm)$/i.test(M)?"video/mp4":/\.png$/i.test(M)?"image/png":"image/jpeg",path:M}));o.push({file:y,titlePath:[...w,S],projectId:"",attempts:[{status:ff(R),retry:0,duration:typeof R.duration=="number"?R.duration:0,errors:N,attachments:E,stdout:[],stderr:[],steps:[]}]})}),Z(m.suites??[],`${p}.suites`,(v,x)=>c(v,x,w,y))};r.forEach((u,p)=>{c(u,`$report.results[${p}]`,[],"")});let l=fe(s.start,"$report.stats.start");return{framework:a,format:"mochawesome-json",adapterVersion:pk,...l===void 0?{}:{startTime:l},...typeof s.duration=="number"?{duration:Ge(s.duration,"$report.stats.duration")}:{},projects:[{id:"",name:"",retries:0}],tests:o,errors:d,interrupted:!1,warnings:["final-attempt-only"]}}var gk="1";function gf(n){if(typeof n!="object"||n===null||Array.isArray(n))return!1;let t=n;return Array.isArray(t.suites)&&Array.isArray(t.specs)&&typeof t.capabilities=="object"&&t.capabilities!==null}function wf(n){if(typeof n!="object"||n===null)return"";let t=n;if(typeof t.browserName=="string")return t.browserName;let e=Object.values(t);return e.length>0&&e.every(r=>typeof r=="object"&&r!==null)?"multiremote":""}function wk(n){switch(n){case"passed":return"passed";case"failed":return"failed";default:return"skipped"}}function yf(n,t,e){if(typeof n!="object"||n===null)return;let r=ne(n,t),s=fe(r.message,`${t}.message`),i=fe(r.name,`${t}.name`),a=fe(r.stack,`${t}.stack`),o=xe(a,e);return{...s===void 0?{}:{message:s},...i===void 0?{}:{name:i},...a===void 0?{}:{stack:a},...o===void 0?{}:{location:o}}}function bf(n){let t=ne(n,"$report"),e=Z(t.specs,"$report.specs",G),r=[];e.length!==1&&r.push("ambiguous-spec-file");let s=e[0]??"",i=wf(t.capabilities),a=t.capabilities,o=typeof a.browserVersion=="string"?a.browserVersion:void 0,d=[];return tn(t.suites,"$report.suites").forEach((c,l)=>{let u=`$report.suites[${l}]`,p=ne(c,u),f=typeof p.name=="string"?p.name:"",h=new Map,m=[];Z(p.tests??[],`${u}.tests`,(g,y)=>{let w=ne(g,y),v=G(w.name,`${y}.name`),x=yf(w.error,`${y}.error`,s),R=h.get(v);R===void 0&&(R=[],h.set(v,R),m.push(v)),R.push({status:wk(w.state),retry:R.length,...typeof w.start=="string"?{startTime:w.start}:{},duration:typeof w.duration=="number"?w.duration:0,errors:x===void 0?[]:[x],attachments:[],stdout:[],stderr:[],steps:[]})}),Z(p.hooks??[],`${u}.hooks`,(g,y)=>{let w=ne(g,y);if(w.state!=="failed")return;let v=yf(w.error,`${y}.error`,s),x=typeof w.title=="string"?w.title:"hook",R=typeof w.associatedTest=="string"&&w.associatedTest!==""?w.associatedTest:x,S={...v??{},message:`${x}: ${v?.message??"failed"}`},N=h.get(R),E=N?.at(-1);if(N!==void 0&&E!==void 0){E.status!=="failed"&&(N[N.length-1]={...E,status:"failed",errors:[S]});return}h.set(R,[{status:"failed",retry:0,...typeof w.start=="string"?{startTime:w.start}:{},duration:typeof w.duration=="number"?w.duration:0,errors:[S],attachments:[],stdout:[],stderr:[],steps:[]}]),m.push(R)});for(let g of m)d.push({file:s,titlePath:f===""?[g]:[f,g],projectId:i,attempts:h.get(g)??[]})}),{framework:"webdriverio",format:"wdio-json",adapterVersion:gk,...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:i,name:i,retries:0}],tests:d,errors:[],interrupted:!1,warnings:[...r,...o===void 0?[]:[`browser-version:${i}@${o}`]]}}var Yf=ri(Qr(),1);import{lstat as jR,readFile as FR,realpath as Jf}from"node:fs/promises";import{isAbsolute as Xf,relative as BR,resolve as VR,sep as HR}from"node:path";var zR=2*1024*1024,UR=new Set(["it","test","specify","xit","fit","xtest","xspecify"]),qR=new Set(["describe","context","suite","xdescribe","fdescribe","xcontext"]),GR=new Set(["only","skip","fixme","serial","parallel","fail","slow"]);function Zr(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.type=="string"}function KR(n){let t=[],e=n;for(;Zr(e)&&e.type==="MemberExpression";){let i=e.property;Zr(i)&&i.type==="Identifier"&&t.unshift(String(i.name)),e=e.object}if(!Zr(e)||e.type!=="Identifier")return;t.unshift(String(e.name));let s=t.filter(i=>!GR.has(i)).at(-1);if(s!==void 0){if(qR.has(s))return"suite";if(UR.has(s))return"test"}}function WR(n){if(Zr(n)){if(n.type==="StringLiteral")return String(n.value);if(n.type==="TemplateLiteral"){let t=n.expressions,e=n.quasis;if(t.length===0&&e.length===1)return e[0]?.value.cooked}}}function JR(n,t){if(!/\.[cm]?[jt]sx?$/i.test(t))return[];let e=[],r=/\.([cm]?[jt]sx?)$/i.exec(t)?.[1]?.toLowerCase()??"ts";r.includes("t")&&e.push("typescript"),(r.endsWith("x")||!r.includes("t"))&&e.push("jsx");let s;try{s=(0,Yf.parse)(n,{sourceType:"unambiguous",errorRecovery:!0,plugins:e})}catch{return[]}let i=[],a=(o,d)=>{if(Array.isArray(o)){for(let c of o)a(c,d);return}if(Zr(o)){if(o.type==="CallExpression"){let c=KR(o.callee),l=o.arguments,u=WR(l[0]);if(c!==void 0&&u!==void 0){if(c==="test"){let p=o.loc;p!==void 0&&i.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(s,[]),i}function XR(n,t){let e=BR(n,t);return e===""||!Xf(e)&&e!==".."&&!e.startsWith(`..${HR}`)}async function YR(n,t){if(!(Xf(t)||t.split("/").includes("..")))try{let e=await Jf(n),r=await Jf(VR(e,t));if(!XR(e,r))return;let s=await jR(r);return!s.isFile()||s.size>zR?void 0:await FR(r,"utf8")}catch{return}}function QR(n,t,e){let r=Br(n,t),s=Br(n,e);return r.length===s.length&&r.every((i,a)=>i===s[a])}async function Vd(n){let t=n.logicalTests.filter(s=>s.location.line===void 0);if(t.length===0)return n;let e=new Map;for(let s of new Set(t.map(i=>i.location.file))){let i=await YR(n.workspace.root,s);e.set(s,i===void 0?[]:JR(i,s))}let r=n.logicalTests.map(s=>{if(s.location.line!==void 0)return s;let i=(e.get(s.location.file)??[]).filter(o=>QR(n.framework,o.titlePath,s.titlePath)),a=i.length===1?i[0]:void 0;return a===void 0?s:{...s,location:{...s.location,line:a.line,column:a.column}}});return{...n,logicalTests:r}}var Qf=5e4,Zf=256*1024*1024,aI=["kwikqa-json","playwright-json","mochawesome-json","wdio-json","allure-json","ctrf-json","testng-xml","cucumber-json","junit-xml"],oI=new TextDecoder("utf-8",{fatal:!0});function dI(n){if(typeof n!="object"||n===null||Array.isArray(n))return!1;let t=n,e=t.config;return typeof e=="object"&&e!==null&&"version"in e&&Array.isArray(t.suites)}function cI(n){if(n.bytes.byteLength===0)return{kind:"unreadable",diagnostic:{reasonCode:"empty-input",message:"The report is empty."}};let t;try{t=oI.decode(n.bytes)}catch{return{kind:"unreadable",diagnostic:{reasonCode:"invalid-utf8",message:"The report is not valid UTF-8."}}}if(af(t))return{kind:"classified",value:{file:n,format:"testng-xml",text:t}};if(ef(t))return{kind:"classified",value:{file:n,format:"junit-xml",text:t}};let e;try{e=JSON.parse(t)}catch(s){return{kind:"unreadable",diagnostic:{reasonCode:"invalid-json",message:s instanceof Error?s.message:"The report is not valid JSON."}}}let r=Gp(e)?"kwikqa-json":dI(e)?"playwright-json":hf(e)?"mochawesome-json":gf(e)?"wdio-json":Go(e)||Ko(e)||Wo(e)?"allure-json":Yo(e)?"ctrf-json":Qo(e)?"cucumber-json":void 0;return r===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, @wdio/json-reporter, Allure results, CTRF, or Cucumber JSON."}}:{kind:"classified",value:{file:n,format:r,text:t,json:e}}}function lI(n,t,e){switch(n.format){case"kwikqa-json":return Wp(n.json);case"mochawesome-json":return mf(n.json,{...n.file.path===void 0?{}:{reportPath:n.file.path},...t.framework===void 0?{}:{framework:t.framework}});case"wdio-json":return bf(n.json);case"ctrf-json":return Vp(n.json);case"cucumber-json":return Up(n.json);case"testng-xml":return df(n.text);case"junit-xml":return rf(n.text,{...t.framework===void 0?{}:{framework:t.framework},...n.file.path===void 0?{}:{reportPath:n.file.path},...e===void 0?{}:{jvmFramework:e}});case"playwright-json":throw new Error("Playwright JSON is read by its own parser.");case"allure-json":throw new Error("Allure results are read as one set.")}}function Ke(n,t,e){let r=e.reasonCode==="missing-report"?"unavailable":"unreadable";return{kind:"unreadable",artifact:{artifactId:B("art",[n??r,t??"bytes"]),kind:"report",availability:r,...t===void 0?{}:{path:t},...n===void 0?{}:{sha256:n},warnings:[]},diagnostic:{...e,...t===void 0?{}:{path:t}}}}function uI(n){if(n.length===1&&n[0]!==void 0)return Ee(n[0].bytes);let t=n.map(e=>`${rI(e.path??"")}\0${Ee(e.bytes)}`).sort();return ZR("sha256").update(t.join(`
20
- `),"utf8").digest("hex")}function Mi(n,t){let e=t.reportPath;if(n.length===0)return Ke(void 0,e,{reasonCode:"missing-report",message:"No report files were found."});let r=uI(n),s=[],i;for(let y of n){let w=cI(y);w.kind==="classified"?s.push(w.value):i??=w.diagnostic}if(s.length===0)return Ke(r,e,i??{reasonCode:"unsupported-report-format",message:"No report was found."});let a=aI.find(y=>s.some(w=>w.format===y)),o=s.filter(y=>y.format===a),d=s.length-o.length+(n.length-s.length),c=d>0?[`ignored-report-files:${d}`]:[];if(a==="playwright-json"){let y=o[0];return o.length!==1||y===void 0?Ke(r,e,{reasonCode:"invalid-report-shape",message:"Found several Playwright JSON reports; point --report at one, or merge them with `npx playwright merge-reports`."}):Hn(y.file.bytes,{...t,...y.file.path===void 0?{}:{reportPath:y.file.path}})}let l=a==="junit-xml"?td(o.map(y=>y.text)):void 0,u;try{u=a==="allure-json"?Lp(o.map(y=>({json:y.json,...y.file.path===void 0?{}:{directory:sI(y.file.path)}}))):Jp(o.map(y=>lI(y,t,l)))}catch(y){return Ke(r,e,{reasonCode:"invalid-report-shape",message:y instanceof Error?y.message:"The report could not be read."})}let p=new Set(jo[u.framework]),f=u.frameworkVersion,h=f!==void 0&&p.has(f),m=[...u.warnings,...c,f===void 0?"producer-version-unrecorded":h?void 0:`unverified-producer-version:${f}`].filter(y=>y!==void 0),g={artifactId:B("art",[r]),kind:"report",availability:"present",...e===void 0?{}:{path:e},sha256:r,format:u.format,...f===void 0?{}:{formatVersion:f},versionConfidence:h?"verified":"unverified",warnings:[...new Set(m)].sort()};try{return{kind:"parsed",run:pf({report:u,reportHash:r,artifact:g,options:t,warnings:m})}}catch(y){return Ke(r,e,{reasonCode:"invalid-report-shape",message:y instanceof Error?y.message:"The report could not be normalized."})}}async function pI(n){return(await eI(n,{withFileTypes:!0})).filter(e=>e.isFile()&&/\.(?:json|xml|log)$/i.test(e.name)).map(e=>iI(n,e.name)).sort()}async function at(n,t){let e;try{e=await nI(n)}catch(o){let d=o.code==="ENOENT";return Ke(void 0,n,{reasonCode:d?"missing-report":"read-failed",message:d?`Test report does not exist: ${n}`:`Could not inspect: ${n}`})}let r;if(e.isDirectory()){try{r=await pI(n)}catch{return Ke(void 0,n,{reasonCode:"read-failed",message:`Could not list report directory: ${n}`})}if(r.length===0)return Ke(void 0,n,{reasonCode:"missing-report",message:`No .json or .xml report files in ${n}`});if(r.length>Qf)return Ke(void 0,n,{reasonCode:"read-failed",message:`${n} holds ${r.length} report files; KwikQA reads at most ${Qf} from one directory.`})}else if(e.isFile())r=[n];else return Ke(void 0,n,{reasonCode:"not-a-file",message:`Test report path is not a regular file or directory: ${n}`});let s=[],i=0;for(let o of r)try{let d=await tI(o);if(i+=d.byteLength,i>Zf)return Ke(void 0,n,{reasonCode:"read-failed",message:`Report files under ${n} exceed ${Zf} bytes.`});s.push({path:o,bytes:d})}catch{return Ke(void 0,n,{reasonCode:"read-failed",message:`Could not read test report: ${o}`})}let a=Mi(s,{...t,reportPath:n});return a.kind!=="parsed"||a.run.artifact.format==="playwright-json"?a:{kind:"parsed",run:await Vd(await fI(a.run))}}async function fI(n){if(n.framework!=="junit"&&n.framework!=="testng"&&n.framework!=="cucumber")return n;let t=new zn(n.workspace.root),e=async a=>{let o=await t.resolve(a.file);return o===a.file?a:{...a,file:o}},r=async a=>a.location===void 0?a:{...a,location:await e(a.location)},s=async a=>({...a,...a.error===void 0?{}:{error:await r(a.error)},steps:await Promise.all(a.steps.map(s))}),i=await Promise.all(n.logicalTests.map(async a=>({...a,location:await e(a.location),attempts:await Promise.all(a.attempts.map(async o=>({...o,errors:await Promise.all(o.errors.map(r)),steps:await Promise.all(o.steps.map(s)),...o.errorLocation===void 0?{}:{errorLocation:await e(o.errorLocation)}})))})));return{...n,logicalTests:i}}var gt={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO",vitest:"Vitest",jest:"Jest",mocha:"Mocha",pytest:"pytest",junit:"JUnit",testng:"TestNG",cucumber:"Cucumber",unknown:"Unidentified framework"},Bt={"playwright-json":"JSON report","kwikqa-json":"KwikQA reporter","mochawesome-json":"mochawesome report","wdio-json":"@wdio/json-reporter report","allure-json":"Allure results","ctrf-json":"CTRF report","testng-xml":"TestNG results","cucumber-json":"Cucumber JSON report","junit-xml":"JUnit report"};var eh={playwright:["playwright-json"],cypress:["kwikqa-json","mochawesome-json","junit-xml"],webdriverio:["kwikqa-json","wdio-json","junit-xml"]};function Hd(n){return ft.includes(n)}function We(n){let{framework:t}=n;if(!Hd(t))return;let e=n.artifact.format;return e!==void 0&&eh[t].includes(e)?t:void 0}function ot(n){let{framework:t}=n;if(t==="unknown")return"KwikQA can't tell which test framework wrote this report, so it diagnoses the run but doesn't capture, repair, or validate it.";if(Hd(t)){let e=eh[t].map(i=>Bt[i]).join(", "),r=n.artifact.format===void 0?void 0:Bt[n.artifact.format],s=r===void 0?"this format":r.endsWith(" results")?r:`a ${r}`;return`KwikQA repairs ${gt[t]} tests from a ${e}, whose test identities its validation can match; it only diagnoses a run read from ${s}.`}return`KwikQA diagnoses ${gt[t]} runs but doesn't capture, repair, or validate them.`}import{readFile as aS,realpath as oS}from"node:fs/promises";import{createRequire as dS}from"node:module";import{delimiter as cS,dirname as jm,isAbsolute as lS,join as wn}from"node:path";function Li(n){return n===null||typeof n!="object"?JSON.stringify(n):Array.isArray(n)?`[${n.map(Li).join(",")}]`:`{${Object.entries(n).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>`${JSON.stringify(e)}:${Li(r)}`).join(",")}}`}function ge(n,t,e,r,s){return B("evd",[n,t,e,Li(r),s])}function ve(n,t,e){return B("art",["m2",n,t,e])}function Yn(n){return Ee(Buffer.from(Li(n),"utf8"))}var zd={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"]},hI=["maxPacketBytes","maxArtifactBytes","maxTraceEntries","maxTraceEvents","maxReportFields","maxStackFrames","maxSteps","maxStdioChunks","maxStdioBytes","maxTraceExpandedBytes","maxConsoleEvents","maxNetworkEvents","maxDomDepth","maxDomNodes","maxDomTextBytes","maxSourceFiles","maxSourceBytes","maxSourceLinesPerFile","maxImportDepth","maxDiffBytes","maxDiffHunks"];function Ud(n){if(n===null||typeof n!="object")return"policy must be an object";if(typeof n.policyVersion!="string")return"policyVersion must be a string";if(n.policyVersion.length===0)return"policyVersion must not be empty";if(typeof n.workspaceRoot!="string")return"workspaceRoot must be a string";if(n.workspaceRoot.length===0)return"workspaceRoot must not be empty";if(typeof n.includeNetworkBodies!="boolean")return"includeNetworkBodies must be a boolean";if(!Array.isArray(n.sensitiveNames)||n.sensitiveNames.some(t=>typeof t!="string"||t.length===0))return"sensitiveNames must be an array of non-empty strings";if(n.sensitiveNames.some(t=>t.trim()!==t))return"sensitiveNames must not contain surrounding whitespace";for(let t of hI){let e=n[t];if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)return`${t} must be a positive safe integer`}if(!Number.isSafeInteger(n.maxNetworkBodyBytes)||n.maxNetworkBodyBytes<0||n.includeNetworkBodies&&n.maxNetworkBodyBytes===0)return"maxNetworkBodyBytes must be positive when network bodies are enabled"}var mI={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"},yI={button:"button",submit:"button",reset:"button",checkbox:"checkbox",radio:"radio",range:"slider",text:"textbox",search:"searchbox",email:"textbox",tel:"textbox",url:"textbox",password:"textbox"},gI=new Set(["script","style","head","title","meta","link"]);function Be(n){let t=n[0];return typeof t=="string"?t.toLowerCase():void 0}function Le(n){let t=n[1];if(typeof t!="object"||t===null||Array.isArray(t))return{};let e={};for(let[r,s]of Object.entries(t))typeof s=="string"&&(e[r.toLowerCase()]=s);return e}function _e(n){let t=typeof n[1]=="object"&&n[1]!==null&&!Array.isArray(n[1]);return n.slice(t?2:1)}function Pt(n,t=0){let e=Be(n);if(e===void 0||gI.has(e)||t>12)return"";let r=[];for(let s of _e(n))typeof s=="string"?r.push(s):Array.isArray(s)&&r.push(Pt(s,t+1));return r.join(" ").replace(/\s+/g," ").trim()}function fn(n){let t=Le(n),e=t.role;if(e!==void 0&&e.length>0)return e.toLowerCase();let r=Be(n);if(r!==void 0)return r==="a"?t.href===void 0?void 0:"link":r==="input"?yI[(t.type??"text").toLowerCase()]:mI[r]}function Fi(n){let t=Le(n),e=t["aria-label"]??t.alt??t.title;return e!==void 0&&e.trim().length>0?e.trim():Pt(n)}function th(n){return n.replace(/\s+/g," ").trim()}function _i(n,t,e){let r=th(n),s=th(t);return e?r===s:r.toLowerCase().includes(s.toLowerCase())}var wI=new Set(["input","textarea","select"]);function rh(n){let t=[];for(let e of _e(n))if(typeof e=="string")t.push(e);else if(Array.isArray(e)){let r=Be(e);if(r!==void 0&&wI.has(r))continue;t.push(Pt(e))}return t.join(" ").replace(/\s+/g," ").trim()}function bI(n,t){let e,r=s=>{if(e===void 0){if(Be(s)==="label"&&Le(s).for===t){e=rh(s);return}for(let i of _e(s))Array.isArray(i)&&r(i)}};return r(n),e}function nh(n,t){let e=Le(n),r=[];for(let i of["aria-label","placeholder","title"]){let a=e[i];a!==void 0&&a.trim().length>0&&r.push(a.trim())}for(let i=t.path.length-1;i>=0;i-=1){let a=ih(t.root,t.path.slice(0,i));if(a===void 0)break;if(Be(a)==="label"){r.push(rh(a));break}}let s=e.id;if(s!==void 0){let i=bI(t.root,s);i!==void 0&&r.push(i)}return r}var xI=`"((?:[^"\\\\]|\\\\.)*)"|'((?:[^'\\\\]|\\\\.)*)'`;function vI(n){return n.replace(/\\(.)/g,"$1")}function ji(n){let t=new RegExp(`^(?:${xI})([is])?$`).exec(n.trim());if(t===null)return;let e=t[1]??t[2];if(e!==void 0)return{value:vI(e),caseSensitive:t[3]!=="i"}}function kI(n){let t=/^\[\s*([\w:-]+)\s*=\s*(.+?)\s*\]$/.exec(n.trim());if(t===null)return;let e=t[1]?.toLowerCase(),r=ji(t[2]??"");if(!(e===void 0||r===void 0))return{describe:`[${e}]`,matches:s=>{let i=Le(s)[e];return i!==void 0&&_i(i,r.value,r.caseSensitive)}}}function RI(n,t){if(n==="role"){let e=/^([\w-]+)(?:\[(.*)\])?$/.exec(t.trim()),r=e?.[1]?.toLowerCase();if(r===void 0)return;let s=e?.[2];if(s===void 0||s.trim()==="")return{describe:`role=${r}`,matches:o=>fn(o)===r};let i=/^name\s*=\s*(.+)$/.exec(s.trim()),a=i===null?void 0:ji(i[1]??"");return a===void 0?void 0:{describe:`role=${r}[name]`,matches:(o,d)=>fn(o)===r&&[Fi(o),...nh(o,d)].some(c=>_i(c,a.value,a.caseSensitive))}}if(n==="label"){let e=ji(t);return e===void 0?void 0:{describe:"label",matches:(r,s)=>nh(r,s).some(i=>_i(i,e.value,e.caseSensitive))}}if(n==="text"){let e=ji(t);if(e===void 0)return;let r=s=>_i(Pt(s),e.value,e.caseSensitive);return{describe:"text",matches:s=>r(s)&&!_e(s).some(i=>Array.isArray(i)&&r(i))}}if(n==="testid"||n==="attr")return kI(t)}function II(n){let t=n.match(/^[A-Za-z][\w-]*|#[\w-]+|\.[\w-]+|\[[^\]]*\]/g);if(t===null||t.join("")!==n)return;let e=[];for(let r of t)if(r.startsWith("#")){let s=r.slice(1);e.push(i=>Le(i).id===s)}else if(r.startsWith(".")){let s=r.slice(1);e.push(i=>(Le(i).class??"").split(/\s+/).includes(s))}else if(r.startsWith("[")){let s=/^\[\s*([\w:-]+)\s*(?:=\s*["']?([^"'\]]*)["']?)?\s*\]$/.exec(r),i=s?.[1]?.toLowerCase();if(i===void 0)return;let a=s?.[2];e.push(o=>{let d=Le(o)[i];return d===void 0?!1:a===void 0||a===""?!0:d===a})}else{let s=r.toLowerCase();e.push(i=>Be(i)===s)}return{describe:n,matches:r=>e.every(s=>s(r))}}function AI(n){let t=n.trim(),e=/^internal:([\w-]+)=([\s\S]+)$/.exec(t);if(e!==null)return RI(e[1]??"",e[2]??"");let r=/^role=([\w-]+)$/.exec(t);if(r!==null){let s=r[1]?.toLowerCase();return s===void 0?void 0:{describe:t,matches:i=>fn(i)===s}}return II(t)}function PI(n){let t=[],e="",r;for(let s=0;s<n.length;s+=1){let i=n[s];if(i!==void 0){if(r!==void 0){if(i==="\\"){e+=i+(n[s+1]??""),s+=1;continue}i===r&&(r=void 0),e+=i;continue}if(i==='"'||i==="'"){r=i,e+=i;continue}if(i===">"&&n[s+1]===">"){t.push(e),e="",s+=1;continue}e+=i}}return t.push(e),t.map(s=>s.trim()).filter(s=>s.length>0)}function SI(n){if(/^(?:internal:|role=)/.test(n))return[n];let t=[],e="",r=0,s;for(let i of n){if(s!==void 0){i===s&&(s=void 0),e+=i;continue}if((i==='"'||i==="'")&&(s=i),(i==="["||i==="(")&&(r+=1),(i==="]"||i===")")&&(r=Math.max(0,r-1)),r===0&&(i===" "||i===">")){e.trim()!==""&&t.push(e.trim()),e="";continue}e+=i}return e.trim()!==""&&t.push(e.trim()),t.length===0?[n]:t}function sh(n,t){let e=[{node:n,path:t}];return _e(n).forEach((r,s)=>{Array.isArray(r)&&e.push(...sh(r,[...t,s]))}),e}function ih(n,t){let e=n;for(let r of t){let s=_e(e)[r];if(!Array.isArray(s))return;e=s}return e}function es(n,t){if(!Array.isArray(n))return{kind:"unsupported",reason:"snapshot root is not an element"};let e=PI(t).flatMap(SI);if(e.length===0)return{kind:"unsupported",reason:"empty selector"};let r=[{node:n,path:[]}];for(let s of e){if(s===".."){let o=new Map;for(let d of r){if(d.path.length===0)continue;let c=d.path.slice(0,-1),l=ih(n,c);l!==void 0&&o.set(c.join("."),{node:l,path:c})}r=[...o.values()];continue}let i=AI(s);if(i===void 0)return{kind:"unsupported",reason:s};let a=new Map;for(let o of r)for(let d of sh(o.node,o.path))i.matches(d.node,{root:n,path:d.path})&&a.set(d.path.join("."),d);if(r=[...a.values()],r.length===0)break}return{kind:"resolved",matches:r}}var TI=/\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001B]*(?:\u0007|\u001B\\))/g;function wt(n){return n.replace(TI,"")}function ce(n,t,e,r){let s=wt(n),i=[];for(let a of[...new Set(r.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(s=s.replace(d,(l,u)=>(c+=1,`${u}[REDACTED]`)),c===0){let l=new RegExp(`(${o}\\s*[:=]\\s*)\\S+`,"gi");s=s.replace(l,(u,p)=>(c+=1,`${p}[REDACTED]`))}c>0&&i.push({redactionId:B("red",[t,e,a]),ruleId:`sensitive-name:${a}`,channel:t,locator:e,action:"mask",count:c})}return{value:s,records:i}}function ts(n,t){let e=n.toLowerCase();return t.map(r=>r.toLowerCase()).sort().find(r=>e===r||e.includes(r))}function Bi(n,t,e,r){let s=[],i=new Map;for(let o of n){let d=ts(o.name,r);if(d===void 0){s.push(o);continue}i.set(d,(i.get(d)??0)+1)}let a=[...i.entries()].sort(([o],[d])=>o.localeCompare(d)).map(([o,d])=>({redactionId:B("red",[t,e,`header:${o}`]),ruleId:`sensitive-header:${o}`,channel:t,locator:e,action:"remove",count:d}));return{value:s,records:a}}function Vt(n,t,e,r){let s;try{s=new URL(n)}catch{return ce(n,t,e,r)}let i=[];(s.username!==""||s.password!=="")&&(s.username="",s.password="",i.push({redactionId:B("red",[t,e,"url-userinfo"]),ruleId:"url-userinfo",channel:t,locator:e,action:"remove",count:1}));let a=new Map;for(let o of[...s.searchParams.keys()]){let d=ts(o,r);d!==void 0&&(s.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)))i.push({redactionId:B("red",[t,e,`query:${o}`]),ruleId:`sensitive-query:${o}`,channel:t,locator:e,action:"mask",count:d});return{value:s.toString(),records:i}}var EI=new Set(["value","data-value","content","__playwright_value_","__playwright_checked_","__playwright_selected_"]),ah=["type","name","id","autocomplete","placeholder","aria-label"];function qd(n,t,e,r){if(n==="")return{value:n,records:[]};let s=t.filter(i=>ah.includes(i.name.toLowerCase())).map(i=>ts(i.value,r)).find(i=>i!==void 0);return s===void 0?{value:n,records:[]}:{value:"[REDACTED]",records:[{redactionId:B("red",["dom",e,`text:${s}`]),ruleId:`sensitive-element-text:${s}`,channel:"dom",locator:e,action:"mask",count:1}]}}function Gd(n,t,e){let r=n.filter(o=>ah.includes(o.name.toLowerCase())).map(o=>ts(o.value,e)).find(o=>o!==void 0),s=[],i=new Map;for(let o of n){let d=ts(o.name,e),c=r!==void 0&&EI.has(o.name.toLowerCase())?r:void 0,l=d??c;if(l===void 0||o.value===""){s.push(o);continue}s.push({name:o.name,value:"[REDACTED]"});let u=d===void 0?`sensitive-element:${l}`:`sensitive-field:${l}`;i.set(u,(i.get(u)??0)+1)}let a=[...i.entries()].sort(([o],[d])=>o.localeCompare(d)).map(([o,d])=>({redactionId:B("red",["dom",t,o]),ruleId:o,channel:"dom",locator:t,action:"mask",count:d}));return{value:s,records:a}}function CI(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function V(n){return typeof n=="string"?n:void 0}function Ae(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function oh(n){return typeof n=="boolean"?n:void 0}function me(n){return CI(n)?n:void 0}function Je(n){return Array.isArray(n)?n:void 0}function Ve(n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return}}function Vi(n){let t=[];return n.split(/\r?\n/).forEach((e,r)=>{let s=e.trim();if(s.length!==0)try{t.push({line:r+1,value:JSON.parse(s),parsed:!0})}catch{t.push({line:r+1,value:void 0,parsed:!1})}}),t}function be(n,t){let e;try{e=typeof n=="string"?n:JSON.stringify(n)??""}catch{return"[unserializable]"}let r=wt(e).replace(/\s+/g," ").trim(),s=Buffer.from(r,"utf8");if(s.byteLength<=t)return r;let i=t;for(;i>0&&((s[i]??0)&192)===128;)i-=1;return`${s.subarray(0,i).toString("utf8")}\u2026`}var ch=new Set(["script","style","noscript","template","head"]),dh=120,NI=200,OI={__playwright_value_:"value",__playwright_checked_:"checked",__playwright_selected_:"selected"},$I=new Set(["button","link","textbox","searchbox","checkbox","radio","combobox","listbox","option","menuitem","tab","switch","slider","spinbutton","heading","dialog","img","cell","row"]),lh=["data-testid","data-test-id","data-test","data-qa","data-cy"],DI=new Set(["internal","role","testid","data","name","text","label","attr","has","nth","visible","true","false","exact","css","xpath","and","the"]);function MI(n){let t=[];for(let[e,r]of Object.entries(Le(n))){let s=OI[e];if(s!==void 0){t.push({name:s,value:be(r,dh)});continue}e.startsWith("__playwright")||/^on[a-z]+$/.test(e)||t.push({name:e,value:be(r,dh)})}return t.sort((e,r)=>e.name.localeCompare(r.name))}function uh(n,t){let e,r=(s,i)=>{if(e===void 0){if(Le(s).__playwright_target__===t){e={node:s,path:i};return}_e(s).forEach((a,o)=>{Array.isArray(a)&&r(a,[...i,o])})}};return r(n,[]),e}function LI(n){return _e(n).filter(t=>typeof t=="string").join(" ").replace(/\s+/g," ").trim()}function ns(n,t,e){let r=[],s=[],i=0,a=0,o=!1,d=(c,l)=>{if(o)return;let u=Be(c);if(u===void 0||ch.has(u))return;if(l>e.maxDepth||a>=e.maxNodes){o=!0;return}let p=`${t}/${a}`,f=MI(c),h=Gd(f,p,e.sensitiveNames),m=qd(be(LI(c),NI),f,p,e.sensitiveNames);s.push(...h.records,...m.records);let g=h.value.map(v=>` ${v.name}="${v.value}"`).join(""),y=`${" ".repeat(l)}<${u}${g}>${m.value===""?"":` ${m.value}`}`,w=Buffer.byteLength(y,"utf8")+1;if(i+w>e.maxBytes){o=!0;return}r.push(y),i+=w,a+=1;for(let v of _e(c))Array.isArray(v)&&d(v,l+1)};return d(n,0),{text:r.join(`
21
- `),redactions:s,nodes:a,truncated:o}}function rs(n,t=[],e){let r=Le(n),s=fn(n),i=Fi(n),a=be(i===""&&e!==void 0?e:i,80),o=[s===void 0?`<${Be(n)??"?"}>`:s];a!==""&&o.push(JSON.stringify(a));for(let c of[...new Set([...t,...lh,"id","name"])]){let l=r[c];l!==void 0&&l!==""&&o.push(`${c}=${be(l,60)}`)}let d=r.placeholder;return d!==void 0&&d!==""&&o.push(`placeholder=${JSON.stringify(be(d,60))}`),o.join(" ")}function Qn(n){let t=n.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(e=>e.length>=3&&!DI.has(e));return[...new Set(t)]}function _I(n){return/(?:^|>>\s*)(?:internal:)?role=([\w-]+)/.exec(n)?.[1]?.toLowerCase()}function jI(n){return[...n.matchAll(/\[\s*([\w:-]+)\s*=/g)].map(t=>t[1]?.toLowerCase()).filter(t=>t!==void 0&&t!=="name")}function Hi(n,t,e,r,s,i){let a=Qn(t),o=_I(t),d=jI(t),c=new Set(e.map(x=>x.path.join("."))),l=[],u=0,p=new Map,f=x=>{if(Be(x)==="label"){let R=Le(x).for;R!==void 0&&p.set(R,Pt(x))}for(let R of _e(x))Array.isArray(R)&&f(R)};f(n);let h=(x,R,S)=>{let N=Be(x);if(N===void 0||ch.has(N))return;let E=Le(x),M=(E.id===void 0?void 0:p.get(E.id))??S,A=fn(x),C=d.some(I=>E[I]!==void 0)||lh.some(I=>E[I]!==void 0);if(A!==void 0&&$I.has(A)||C){let I=rs(x,d,M),$=`${I} ${be(Pt(x),200)}`.toLowerCase(),D=c.has(R.join(".")),k=(D?100:0)+(o!==void 0&&A===o?2:0)+a.filter(T=>$.includes(T)).length*3;l.push({line:`${D?"match: ":""}${I}`,score:k,order:u++})}let P=N==="label"?Pt(x):S;_e(x).forEach((I,$)=>{Array.isArray(I)&&h(I,[...R,$],P)})};h(n,[],void 0);let m=[...l].sort((x,R)=>R.score-x.score||x.order-R.order),g=[],y=[],w=0,v=m.length>s.maxItems;for(let x of m.slice(0,s.maxItems)){let R=ce(x.line,"dom",r,i),S=Buffer.byteLength(R.value,"utf8")+1;if(w+S>s.maxBytes){v=!0;break}y.push(...R.records),g.push(R.value),w+=S}return{text:g.join(`
22
- `),redactions:y,nodes:g.length,truncated:v}}import{open as HI}from"node:fs/promises";import{realpath as ph,stat as FI}from"node:fs/promises";import{isAbsolute as mh,relative as BI,resolve as VI,sep as fh}from"node:path";function hh(n,t){let e=BI(n,t);if(e==="")return"";if(!(e===".."||e.startsWith(`..${fh}`)||mh(e)))return e.split(fh).join("/")}async function ss(n,t){if(t.includes("\0"))return{kind:"unauthorized",message:"Path contains a NUL byte."};let e;try{e=await ph(n)}catch{return{kind:"unreadable",message:"Authorized root could not be resolved."}}let r=mh(t)?t:VI(e,t);if(hh(e,r)===void 0)return{kind:"unauthorized",message:"Path escapes the authorized root."};let s;try{s=await ph(r)}catch(a){return a.code==="ENOENT"?{kind:"unavailable",message:"Authorized artifact does not exist."}:{kind:"unreadable",message:"Authorized artifact could not be resolved."}}let i=hh(e,s);if(i===void 0)return{kind:"unauthorized",message:"Resolved path escapes the authorized root."};try{if(!(await FI(s)).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:s,relativePath:i}}function Kd(n){return n.length===0||n.includes("\0")||n.includes("\\")||n.startsWith("/")||/^[A-Za-z]:/.test(n)?!1:n.split("/").every(e=>e!==".."&&e!==".")}async function Q(n,t,e){let r=await ss(n,t);if(r.kind!=="authorized")return r;let s;try{s=await HI(r.absolutePath,"r");let i=await s.stat();if(i.size>e)return{kind:"over-budget",message:`Artifact exceeds the ${e}-byte limit.`,relativePath:r.relativePath};let a=new Uint8Array(i.size),o=0;for(;o<a.byteLength;){let d=await s.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:r.relativePath}:{kind:"read",bytes:a,sha256:Ee(a),relativePath:r.relativePath}}catch{return{kind:"unreadable",message:"Authorized artifact could not be read.",relativePath:r.relativePath}}finally{await s?.close()}}import{createRequire as zI}from"module";var UI=zI("/"),nr,qI,GI;try{nr=UI("worker_threads"),qI=nr.Worker,GI=nr.isMarkedAsUntransferable}catch{}var Oe=Uint8Array,Zn=Uint16Array,KI=Int32Array,yh=new Oe([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]),gh=new Oe([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]),WI=new Oe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),wh=function(n,t){for(var e=new Zn(31),r=0;r<31;++r)e[r]=t+=1<<n[r-1];for(var s=new KI(e[30]),r=1;r<30;++r)for(var i=e[r];i<e[r+1];++i)s[i]=i-e[r]<<5|r;return{b:e,r:s}},nr=wh(yh,2),bh=nr.b,JI=nr.r;bh[28]=258,JI[258]=28;var xh=wh(gh,0),XI=xh.b,DD=xh.r,Yd=new Zn(32768);for(ae=0;ae<32768;++ae)St=(ae&43690)>>1|(ae&21845)<<1,St=(St&52428)>>2|(St&13107)<<2,St=(St&61680)>>4|(St&3855)<<4,Yd[ae]=((St&65280)>>8|(St&255)<<8)>>1;var St,ae,as=(function(n,t,e){for(var r=n.length,s=0,i=new Zn(t);s<r;++s)n[s]&&++i[n[s]-1];var a=new Zn(t);for(s=1;s<t;++s)a[s]=a[s-1]+i[s-1]<<1;var o;if(e){o=new Zn(1<<t);var d=15-t;for(s=0;s<r;++s)if(n[s])for(var c=s<<4|n[s],l=t-n[s],u=a[n[s]-1]++<<l,p=u|(1<<l)-1;u<=p;++u)o[Yd[u]>>d]=c}else for(o=new Zn(r),s=0;s<r;++s)n[s]&&(o[s]=Yd[a[n[s]-1]++]>>15-n[s]);return o}),ds=new Oe(288);for(ae=0;ae<144;++ae)ds[ae]=8;var ae;for(ae=144;ae<256;++ae)ds[ae]=9;var ae;for(ae=256;ae<280;++ae)ds[ae]=7;var ae;for(ae=280;ae<288;++ae)ds[ae]=8;var ae,vh=new Oe(32);for(ae=0;ae<32;++ae)vh[ae]=5;var ae;var YI=as(ds,9,1);var QI=as(vh,5,1),Wd=function(n){for(var t=n[0],e=1;e<n.length;++e)n[e]>t&&(t=n[e]);return t},dt=function(n,t,e){var r=t/8|0;return(n[r]|n[r+1]<<8)>>(t&7)&e},Jd=function(n,t){var e=t/8|0;return(n[e]|n[e+1]<<8|n[e+2]<<16)>>(t&7)},ZI=function(n){return(n+7)/8|0},os=function(n,t,e){return(t==null||t<0)&&(t=0),(e==null||e>n.length)&&(e=n.length),new Oe(n.subarray(t,e))};var eA=["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"],Pe=function(n,t,e){var r=new Error(t||eA[n]);if(r.code=n,Error.captureStackTrace&&Error.captureStackTrace(r,Pe),!e)throw r;return r},tA=function(n,t,e,r){var s=n.length,i=r?r.length:0;if(!s||t.f&&!t.l)return e||new Oe(0);var a=!e,o=a||t.i!=2,d=t.i;a&&(e=new Oe(s*3));var c=function($r){var Dr=e.length;if($r>Dr){var Mr=new Oe(Math.max(Dr*2,$r));Mr.set(e),e=Mr}},l=t.f||0,u=t.p||0,p=t.b||0,f=t.l,h=t.d,m=t.m,g=t.n,y=s*8;do{if(!f){l=dt(n,u,1);var w=dt(n,u+1,3);if(u+=3,w)if(w==1)f=YI,h=QI,m=9,g=5;else if(w==2){var S=dt(n,u,31)+257,N=dt(n,u+10,15)+4,E=S+dt(n,u+5,31)+1;u+=14;for(var M=new Oe(E),A=new Oe(19),C=0;C<N;++C)A[WI[C]]=dt(n,u+C*3,7);u+=N*3;for(var P=Wd(A),I=(1<<P)-1,$=as(A,P,1),C=0;C<E;){var D=$[dt(n,u,I)];u+=D&15;var v=D>>4;if(v<16)M[C++]=v;else{var k=0,T=0;for(v==16?(T=3+dt(n,u,3),u+=2,k=M[C-1]):v==17?(T=3+dt(n,u,7),u+=3):v==18&&(T=11+dt(n,u,127),u+=7);T--;)M[C++]=k}}var _=M.subarray(0,S),U=M.subarray(S);m=Wd(_),g=Wd(U),f=as(_,m,1),h=as(U,g,1)}else Pe(1);else{var v=ZI(u)+4,x=n[v-4]|n[v-3]<<8,R=v+x;if(R>s){d&&Pe(0);break}o&&c(p+x),e.set(n.subarray(v,R),p),t.b=p+=x,t.p=u=R*8,t.f=l;continue}if(u>y){d&&Pe(0);break}}o&&c(p+131072);for(var K=(1<<m)-1,te=(1<<g)-1,le=u;;le=u){var k=f[Jd(n,u)&K],X=k>>4;if(u+=k&15,u>y){d&&Pe(0);break}if(k||Pe(2),X<256)e[p++]=X;else if(X==256){le=u,f=null;break}else{var Ie=X-254;if(X>264){var C=X-257,Te=yh[C];Ie=dt(n,u,(1<<Te)-1)+bh[C],u+=Te}var kt=h[Jd(n,u)&te],Lt=kt>>4;kt||Pe(3),u+=kt&15;var U=XI[Lt];if(Lt>3){var Te=gh[Lt];U+=Jd(n,u)&(1<<Te)-1,u+=Te}if(u>y){d&&Pe(0);break}o&&c(p+131072);var Nr=p+Ie;if(p<U){var Or=i-U,ni=Math.min(U,Nr);for(Or+p<0&&Pe(3);p<ni;++p)e[p]=r[Or+p]}for(;p<Nr;++p)e[p]=e[p-U]}}t.l=f,t.p=le,t.b=p,t.f=l,f&&(l=1,t.m=m,t.d=h,t.n=g)}while(!l);return p!=e.length&&a?os(e,0,p):e.subarray(0,p)};var is=new Oe(0);var er=function(n,t){return n[t]|n[t+1]<<8},tr=function(n,t){return(n[t]|n[t+1]<<8|n[t+2]<<16|n[t+3]<<24)>>>0},Xd=function(n,t){return tr(n,t)+tr(n,t+4)*4294967296};var nA=(function(){function n(t,e){typeof t=="function"&&(e=t,t={}),this.ondata=e;var r=t&&t.dictionary&&t.dictionary.subarray(-32768);this.s={i:0,b:r?r.length:0},this.o=new Oe(32768),this.p=new Oe(0),r&&this.o.set(r)}return n.prototype.e=function(t){if(this.ondata||Pe(5),this.d&&Pe(4),!this.p.length)this.p=t;else if(t.length){var e=new Oe(this.p.length+t.length);e.set(this.p),e.set(t,this.p.length),this.p=e}},n.prototype.c=function(t){this.s.i=+(this.d=t||!1);var e=this.s.b,r=tA(this.p,this.s,this.o);this.ondata(os(r,e,this.s.b),this.d),this.o=os(r,this.s.b-32768),this.s.b=this.o.length,this.p=os(this.p,this.s.p/8|0),this.s.p&=7},n.prototype.push=function(t,e){this.e(t),this.c(e)},n})();var Qd=typeof TextDecoder<"u"&&new TextDecoder,rA=0;try{Qd.decode(is,{stream:!0}),rA=1}catch{}var sA=function(n){for(var t="",e=0;;){var r=n[e++],s=(r>127)+(r>223)+(r>239);if(e+s>n.length)return{s:t,r:os(n,e-1)};s?s==3?(r=((r&15)<<18|(n[e++]&63)<<12|(n[e++]&63)<<6|n[e++]&63)-65536,t+=String.fromCharCode(55296|r>>10,56320|r&1023)):s&1?t+=String.fromCharCode((r&31)<<6|n[e++]&63):t+=String.fromCharCode((r&15)<<12|(n[e++]&63)<<6|n[e++]&63):t+=String.fromCharCode(r)}};function iA(n,t){if(t){for(var e="",r=0;r<n.length;r+=16384)e+=String.fromCharCode.apply(null,n.subarray(r,r+16384));return e}else{if(Qd)return Qd.decode(n);var s=sA(n),i=s.s,e=s.r;return e.length&&Pe(8),i}}var aA=function(n,t,e,r,s,i,a){var o=s==4294967295,d=i==4294967295,c=a==4294967295,l=t+e,u=o+d+c;if(r&&u){for(;t+4<l;t+=4+er(n,t+2))if(er(n,t)==1)return[o?Xd(n,t+4+8*d):s,d?Xd(n,t+4):i,c?Xd(n,t+4+8*(d+o)):a,1];r<2&&Pe(13)}return[s,i,a,0]};var oA=(function(){function n(){}return n.prototype.push=function(t,e){this.ondata(null,t,e)},n.compression=0,n})();var kh=(function(){function n(){var t=this;this.i=new nA(function(e,r){t.ondata(null,e,r)})}return n.prototype.push=function(t,e){try{this.i.push(t,e)}catch(r){this.ondata(r,null,e)}},n.compression=8,n})();var Rh=(function(){function n(t){this.onfile=t,this.k=[],this.o={0:oA},this.p=is}return n.prototype.push=function(t,e){var r=this;if(this.onfile||Pe(5),this.p||Pe(4),this.c>0){var s=Math.min(this.c,t.length),i=t.subarray(0,s);if(this.c-=s,this.d?this.d.push(i,!this.c):this.k[0].push(i),t=t.subarray(s),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 Oe(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=tr(c,o);if(y==67324752){a=1,d=o,h.d=null,h.c=0;var w=er(c,o+6),v=er(c,o+8),x=w&2048,R=w&8,S=er(c,o+26),N=er(c,o+28);if(l>o+30+S+N){var E=[];h.k.unshift(E),a=2;var M=tr(c,o+18),A=tr(c,o+22),C=iA(c.subarray(o+30,o+=30+S),!x),P=aA(c,o,N,2,M,A,0),I=P[0],$=P[1],D=P[3];R&&(I=-1-D),o+=N,h.c=I;var k,T={name:C,compression:v,start:function(){if(T.ondata||Pe(5),!I)T.ondata(null,is,!0);else{var _=r.o[v];_||T.ondata(Pe(14,"unknown compression type "+v,1),null,!1),k=I<0?new _(C):new _(C,I,$),k.ondata=function(le,X,Ie){T.ondata(le,X,Ie)};for(var U=0,K=E;U<K.length;U++){var te=K[U];k.push(te,!1)}r.k[0]==E&&r.c?r.d=k:k.push(is,!0)}},terminate:function(){k&&k.terminate&&k.terminate()}};I>=0&&(T.size=I,T.originalSize=$),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 m=f();if(m==="break")break}if(this.p=is,u<0){var g=a?c.subarray(0,d-12-(u==-2&&8)-(tr(c,d-16)==134695760&&4)):c.subarray(0,o);p?p.push(g,!!a):this.k[+(a==2)].push(g)}if(a&2)return this.push(c.subarray(o),e);this.p=c.subarray(o)}e&&(this.c&&Pe(13),this.p=null)},n.prototype.register=function(t){this.o[t.compression]=t},n})();var Ih=65536;function dA(n,t){let e=new Uint8Array(t),r=0;for(let s of n)e.set(s,r),r+=s.length;return e}function zi(n,t,e){if(n.byteLength===0)return{kind:"unreadable",message:"Archive is empty."};if(n[0]!==80||n[1]!==75)return{kind:"unreadable",message:"Archive does not begin with a ZIP signature."};let r=new Map,s=[],i=0,a=0,o,d=new Set,c=new Rh;c.register(kh),c.onfile=l=>{let u=l.name,p=typeof l.originalSize=="number"&&l.originalSize>0,f=l.originalSize??0;if(!Kd(u)){s.push({entry:u,reason:"unsafe-entry-name",declaredBytes:f});return}if(!e(u))return;if(d.has(u)){s.push({entry:u,reason:"duplicate-selected-name",declaredBytes:f});return}if(i>=t.maxEntries){s.push({entry:u,reason:"entry-budget-exceeded",declaredBytes:f});return}let h=t.maxExpandedBytes-a;if(p&&f>h){s.push({entry:u,reason:"expanded-budget-exceeded",declaredBytes:f});return}i+=1,d.add(u);let m=[],g=0,y=!1;l.ondata=(w,v,x)=>{if(o!==void 0||y)return;if(w!==null){o=`Archive entry ${u} could not be inflated.`;return}g+=v.length;let R=p&&g>f;if(R||g>h){y=!0,m.length=0,s.push({entry:u,reason:R?"declared-size-mismatch":"expanded-budget-exceeded",declaredBytes:f});return}if(m.push(v.slice()),x){if(p&&g!==f){m.length=0,y=!0,s.push({entry:u,reason:"declared-size-mismatch",declaredBytes:f});return}a+=g,r.set(u,dA(m,g))}},l.start()};try{for(let l=0;l<n.byteLength;l+=Ih){let u=Math.min(l+Ih,n.byteLength);if(c.push(n.subarray(l,u),u===n.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:r,skipped:s}}}var Ah=256,Ph={before:"before",action:"action",input:"action",after:"after"};function Zd(n){return Array.isArray(n)&&typeof n[0]=="string"}function cA(n){return Array.isArray(n)&&Array.isArray(n[0])&&typeof n[0][0]=="number"&&typeof n[0][1]=="number"}function Sh(n){let t=n[1],e=typeof t=="object"&&t!==null&&!Array.isArray(t);return n.slice(e?2:1)}function lA(n){let t=V(n.snapshotName),e=V(n.callId),r=Ph[V(n.phase)??""];if(t!==void 0){let s=t.indexOf("@");s>0&&(r??=Ph[t.slice(0,s)],e??=t.slice(s+1))}return{...e===void 0?{}:{callId:e},...r===void 0?{}:{phase:r},...t===void 0?{}:{name:t}}}var Ui=class{frames=new Map;literals=new Map;byCall=new Map;add(t,e,r){let s=me(r.snapshot);if(s===void 0||s.html===void 0)return;let i=lA(s),a=V(s.frameId)??V(s.pageId)??"unknown-frame",o=`${t}
23
- ${a}`,d=this.frames.get(o)??[],c=V(s.frameUrl),l={entry:t,line:e,frameId:a,index:d.length,snapshotId:i.name??(i.callId===void 0?`${t}#line=${e}`:`${i.phase??"snapshot"}@${i.callId}`),...i.callId===void 0?{}:{callId:i.callId},...i.phase===void 0?{}:{phase:i.phase},...c===void 0?{}:{frameUrl:c},isMainFrame:oh(s.isMainFrame)??!0,html:s.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 r=[],s=(i,a)=>{if(typeof i=="string"){r.push(i);return}if(!(!Zd(i)||a>Ah)){for(let o of Sh(i))s(o,a+1);r.push(i)}};return s(t.html,0),this.literals.set(t,r),r}rebuild(t,e){let r=this.frames.get(`${t.entry}
24
- ${t.frameId}`)??[],s=0,i=!1,a=(d,c,l)=>{if(s>=e||l>Ah){i=!0;return}if(typeof d=="string")return s+=1,d;if(cA(d)){let[h,m]=d[0],g=c-h,y=r[g];if(h<1||y===void 0)return;let w=this.literalNodes(y)[m];return w===void 0?void 0:a(w,g,l)}if(!Zd(d))return;s+=1;let u=d[1],p=typeof u=="object"&&u!==null&&!Array.isArray(u)?u:{},f=[];for(let h of Sh(d)){let m=a(h,c,l+1);m!==void 0&&f.push(m)}return[d[0],p,...f]},o=a(t.html,t.index,0);return{...Zd(o)?{root:o}:{},truncated:i,nodes:s}}};var hn=["trace","console","network","dom","accessibility"],ec=/(?:^|\/)(?:\d+-)?(?:trace|test)\.trace$/,qi=/(?:^|\/)(?:\d+-)?trace\.network$/,tc=/(?:^|\/)(?:\d+-)?trace\.stacks$/,mn=512,sc=2e3,Oh=200,uA=2,nc=5e4,rc=25,pA=new Set(["screencast-frame","object","resource","input"]),re={failure:5,failedCall:4,significant:3,context:2,ordinary:1,afterFailure:0};function fA(n,t){switch(t){case"console":return n.maxConsoleEvents;case"network":return n.maxNetworkEvents;case"dom":case"accessibility":return n.maxDomNodes;default:return n.maxTraceEvents}}function oe(n,t,e,r,s,i){n.omissions.push({omissionId:B("omi",[n.input.attemptId,t,e,s??"",r]),channel:t,reason:e,message:r,...s===void 0?{}:{locator:s},...i===void 0?{}:{cap:i}})}function Gi(n,t,e,r,s,i,a){let o=n.channels[t].artifact,d=ge(n.runId,o.artifactId,e,r,s);n.evidence.push({evidenceId:d,kind:e,artifactId:o.artifactId,logicalTestId:n.input.logicalTestId,attemptId:n.input.attemptId,locator:r,observation:s,availability:s.length===0?"empty":"present",redactionIds:i.map(c=>c.redactionId)}),n.redactions.push(...i),n.priorities.set(d,a),n.channels[t].included+=1}function cs(n,t,e,r){let s=ce(r,t,e,n.policy.sensitiveNames);return{value:s.value,records:s.records}}function Th(n){let t=Je(n);if(t===void 0)return[];let e=[];for(let r of t){let s=me(r),i=V(s?.name);i!==void 0&&e.push({name:i,value:V(s?.value)??""})}return e}function hA(n){let t=V(n.type);if(t==="console")return{type:V(n.messageType)??"log",text:V(n.text)??be(n.args,sc)};if(t!=="event"||!(V(n.class)==="ConsoleMessage"||V(n.method)==="console"))return;let r=me(n.params);return{type:V(r?.type)??V(r?.messageType)??"log",text:V(r?.text)??be(r,sc)}}function ls(n){let t=me(n.error);return V(t?.message)??V(me(t?.error)?.message)}function $h(n){return n===void 0?"unknown":V(n.apiName)??([V(n.class),V(n.method)].filter(Boolean).join(".")||"unknown")}function mA(n){let t=me(n?.params);return V(t?.selector)}function yA(n,t){let e=V(n.type),r=$h(e==="after"?t??n:n),s=V(n.title),i=n.params===void 0?"":` params=${be(n.params,mn)}`,a=ls(n),o=a===void 0?"":` error=${be(a,mn)}`;switch(e){case"before":return`action started: ${r}${s===void 0?"":` "${be(s,120)}"`}${i}`;case"after":return`action finished: ${r}${o}`;case"action":return`action: ${r}${i}${o}`;case"log":return`log: ${be(n.message,mn)}`;case"error":return`error: ${be(n.message,mn)}`;case"stdout":case"stderr":return`${e}: ${be(n.text,mn)}`;case"context-options":return`context options: ${be({browserName:V(n.browserName),platform:V(n.platform),playwrightVersion:V(n.playwrightVersion),sdkLanguage:V(n.sdkLanguage)},mn)}`;case"event":return`event: ${r}${i}`;default:return}}function gA(n){return Ae(n.startTime)??Ae(n.endTime)??Ae(n.time)}function wA(n,t,e){let r=Ve(e);if(r===void 0){n.channels.trace.failed=!0,oe(n,"trace","unreadable",`${t} is not valid UTF-8.`,t);return}let s=Vi(r);s.length===0&&(n.channels.trace.parsed=!0);let i=new Set;for(let a of s){let o=`${t}#line=${a.line}`;if(!a.parsed){n.channels.trace.failed=!0,oe(n,"trace","parse-failed",`${o} is not valid JSON.`,o);continue}let d=me(a.value),c=V(d?.type);if(d===void 0||c===void 0){n.channels.trace.failed=!0,oe(n,"trace","unrecognized",`${o} is not a typed trace event.`,o);continue}if(n.channels.trace.parsed=!0,c==="frame-snapshot"){n.snapshots.add(t,a.line,d)===void 0&&oe(n,"dom","unrecognized",`${o} does not carry a readable frame snapshot.`,o);continue}if(c==="resource-snapshot"){Mh(n,t,a.line,d,new Map);continue}let l=gA(d);if(c==="error"){l!==void 0&&n.errorTimes.push(l);for(let y of Je(d.stack)??[]){if(n.seeds.length>=Oh)break;let w=me(y),v=V(w?.file),x=Ae(w?.line);if(v===void 0||x===void 0)continue;let R=Ae(w?.column);n.seeds.push({file:v,line:x,...R===void 0?{}:{column:R},origin:`${t}#line=${a.line}:error`,logicalTestId:n.input.logicalTestId,attemptId:n.input.attemptId})}}let u=hA(d);if(u!==void 0){let y=cs(n,"console",o,`console.${u.type}: ${be(u.text,sc)}`);n.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:n.candidates.length,...l===void 0?{}:{time:l},error:u.type==="error"||u.type==="warning"});continue}if(pA.has(c))continue;let p=V(d.callId),f=p===void 0?void 0:`${t}
25
- ${p}`;if(f!==void 0&&p!==void 0){if(c==="before")n.actions.set(f,{callId:p,entry:t,before:{line:a.line,event:d}});else if(c==="after"){let y=n.actions.get(f)??{callId:p,entry:t};y.after={line:a.line,event:d},n.actions.set(f,y);let w=Ae(d.endTime);ls(d)!==void 0&&w!==void 0&&n.errorTimes.push(w)}}let h=f===void 0?void 0:n.actions.get(f)?.before,m=yA(d,h?.event);if(m===void 0){i.add(c);continue}let g=cs(n,"trace",o,m);n.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:g.value,redactions:g.records,order:n.candidates.length,...l===void 0?{}:{time:l},...p===void 0?{}:{callId:p},error:c==="error"||ls(d)!==void 0})}for(let a of[...i].sort())oe(n,"trace","unrecognized",`Trace event type ${a} is not interpreted by this adapter.`,t)}function bA(n){let t=[];for(let e of n.actions.values()){let r=mA(e.before?.event);if(r===void 0||e.before===void 0||V(e.before.event.class)==="Test")continue;let s=e.after!==void 0&&ls(e.after.event)!==void 0,i=e.after===void 0;!s&&!i||t.push({callId:e.callId,entry:e.entry,selector:r,apiName:$h(e.before.event),time:Ae(e.before.event.startTime)??0,unfinished:i})}return t.sort((e,r)=>r.time-e.time||e.callId.localeCompare(r.callId))}function xA(n){let t={after:3,action:2,before:1};return[...n].filter(e=>e.isMainFrame||n.length===1).sort((e,r)=>(t[r.phase??"before"]??0)-(t[e.phase??"before"]??0)||r.line-e.line)[0]}function vA(n,t){let e=xA(n.snapshots.forCall(t.callId)),r=`${t.apiName} on ${t.selector}`;if(e===void 0){oe(n,"dom","unavailable",`No DOM snapshot was recorded for the failed ${r}.`,`${t.entry}#${t.callId}`);return}let s=n.snapshots.rebuild(e,nc),i=`${e.entry}#${e.snapshotId}`;if(s.root===void 0){oe(n,"dom","unreadable",`Snapshot ${e.snapshotId} could not be rebuilt.`,i);return}s.truncated&&oe(n,"dom","budget-exceeded",`Snapshot ${e.snapshotId} was rebuilt only up to ${nc} nodes.`,i,nc);let a={maxDepth:n.policy.maxDomDepth,maxNodes:n.policy.maxDomNodes,maxBytes:n.policy.maxDomTextBytes,sensitiveNames:n.policy.sensitiveNames},o=uh(s.root,t.callId),d=es(s.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],m=ns(h.node,i,a);Gi(n,"dom","dom-subtree",{type:"dom-node",snapshotId:e.snapshotId,nodePath:h.path},`${u} snapshot of the element targeted by the failed ${r}:
26
- ${m.text}`,m.redactions,re.failure),m.truncated&&oe(n,"dom","budget-exceeded",`The target subtree in ${e.snapshotId} was cut at ${a.maxDepth} levels, ${a.maxNodes} elements, or ${a.maxBytes} bytes.`,i,a.maxNodes);let g=cs(n,"accessibility",i,rs(h.node));Gi(n,"accessibility","accessibility-node",{type:"dom-node",snapshotId:e.snapshotId,nodePath:h.path},`target of the failed ${t.apiName}: ${g.value}`,g.records,re.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=Hi(s.root,t.selector,l,i,{maxItems:rc,maxBytes:a.maxBytes},n.policy.sensitiveNames);Gi(n,"dom","dom-candidates",{type:"dom-node",snapshotId:e.snapshotId,nodePath:[]},`In the ${u} snapshot of the failed ${r}, the locator ${p}. Elements most like it, best first:
27
- ${f.text}`,f.redactions,re.failure),f.truncated&&oe(n,"dom","budget-exceeded",`Only the ${rc} closest candidates in ${e.snapshotId} were listed.`,i,rc)}function kA(n,t){let e=new Set(t.map(i=>i.callId));for(let i of n.actions.values())i.after!==void 0&&ls(i.after.event)!==void 0&&e.add(i.callId);let r=n.errorTimes.length>0?Math.min(...n.errorTimes):t.length>0?Math.min(...t.map(i=>i.time)):void 0,s=i=>i.error?i.channel==="trace"?re.failedCall+.95:re.significant:i.callId!==void 0&&e.has(i.callId)?re.failedCall:r!==void 0&&i.time!==void 0&&i.time>r+1?re.afterFailure:i.channel==="trace"?re.context:re.ordinary;for(let i of["trace","console","network"]){let a=n.candidates.filter(l=>l.channel===i),o=fA(n.policy,i),d=a.map(l=>({candidate:l,priority:s(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);Gi(n,i,l.kind,l.locator,l.observation,l.redactions,u+p)}d.length>o&&oe(n,i,"budget-exceeded",`Kept the ${o} ${i} observations closest to the failure; ${d.length-o} earlier or less relevant ones were not included.`,d[o]?.candidate.locatorText,o)}}function Dh(n){let t=me(n.snapshot)??n,e=me(t.response),r=me(e?.content);return V(r?._sha1)??V(r?.sha1)}function Mh(n,t,e,r,s){let i=me(r.snapshot)??r,a=me(i.request),o=V(a?.url),d=`${t}#line=${e}`;if(o===void 0){oe(n,"network","unrecognized",`${d} has no request URL.`,d);return}let c=Vt(o,"network",d,n.policy.sensitiveNames),l=Bi(Th(a?.headers),"network",`${d}/request-headers`,n.policy.sensitiveNames),u=me(i.response),p=Bi(Th(u?.headers),"network",`${d}/response-headers`,n.policy.sensitiveNames),f=V(a?.method)??"GET",h=Ae(u?.status),m=me(u?.content),g=[`${f} ${c.value}`,h===void 0||h<=0?"-> (no response)":`-> ${h} ${V(u?.statusText)??""}`.trim()],y=V(m?.mimeType),w=Ae(m?.size);(y!==void 0||w!==void 0)&&g.push(`(${y??"unknown"}, ${w??"unknown"} bytes)`);let v=V(m?.text)??V(u?.body),x=Dh(r);if(v===void 0&&x!==void 0&&n.policy.includeNetworkBodies){let I=s.get(x)??s.get(`resources/${x}`);I===void 0?oe(n,"network","unavailable",`Referenced response resource ${x} was not present in the trace archive.`,d):I.byteLength>n.policy.maxNetworkBodyBytes?oe(n,"network","budget-exceeded",`Referenced response resource ${x} exceeds the network body byte limit.`,d,n.policy.maxNetworkBodyBytes):(v=Ve(I),v===void 0&&oe(n,"network","irrelevant",`Referenced response resource ${x} is not textual UTF-8.`,d))}let R=y?.toLowerCase()??"",S=R.startsWith("image/")||R.startsWith("audio/")||R.startsWith("video/")||R.includes("multipart")||R.includes("octet-stream"),N=[];if(n.policy.includeNetworkBodies)if(v!==void 0&&!S){let I=cs(n,"network",`${d}/body`,be(v,n.policy.maxNetworkBodyBytes));N.push(...I.records),g.push(`body=${I.value}`)}else v!==void 0&&S&&oe(n,"network","irrelevant","Response body omitted because it is binary or multipart.",d);else(v!==void 0||m!==void 0)&&oe(n,"network","policy-disabled","Response body withheld because includeNetworkBodies is disabled.",d);let E=Ae(i.time);E!==void 0&&g.push(`time=${E}ms`);let M=V(i._failureText);M!==void 0&&g.push(`failure=${be(M,mn)}`);let A=cs(n,"network",d,g.join(" ")),C=V(i._requestref)??B("req",[f,c.value,String(e)]),P=Ae(i._monotonicTime);n.candidates.push({channel:"network",kind:"network-event",locator:{type:"network-request",requestId:C,eventIndex:e},locatorText:d,observation:A.value,redactions:[...A.records,...N,...c.records,...l.records,...p.records],order:n.candidates.length,...P===void 0?{}:{time:P},error:M!==void 0||h!==void 0&&(h>=400||h<=0)})}function RA(n,t,e){let r=Ve(e);if(r===void 0){n.channels.trace.failed=!0,oe(n,"trace","unreadable",`${t} is not valid UTF-8.`,t);return}let s;try{s=JSON.parse(r),n.channels.trace.parsed=!0}catch{n.channels.trace.failed=!0,oe(n,"trace","parse-failed",`${t} is not valid JSON.`,t);return}let i=me(s),a=Je(i?.files)??[],o=Je(i?.stacks)??[];for(let d of o){let c=Je(d),l=V(c?.[0])??"unknown";for(let u of Je(c?.[1])??[]){if(n.seeds.length>=Oh)return;let p=Je(u),f=Ae(p?.[0]),h=Ae(p?.[1]);if(f===void 0||h===void 0)continue;let m=V(a[f]);if(m===void 0)continue;let g=Ae(p?.[2]);n.seeds.push({file:m,line:h,...g===void 0?{}:{column:g},origin:`${t}:${l}`,logicalTestId:n.input.logicalTestId,attemptId:n.input.attemptId})}}}function Eh(n,t,e,r){let s={};for(let i of hn)s[i]={artifact:{artifactId:ve(n,i,`${t.attemptId}:${t.attachmentId}`),channel:i,availability:e,...r.path===void 0?{}:{path:r.path},...r.sha256===void 0?{}:{sha256:r.sha256},format:r.format??"playwright-trace-zip",...r.producerVersion===void 0?{}:{producerVersion:r.producerVersion},attemptId:t.attemptId,warnings:r.warnings},included:0,parsed:!1,failed:!1};return s}function Ch(n,t,e,r){return{runId:n,policy:t,input:e,channels:r,evidence:[],redactions:[],omissions:[],seeds:[],priorities:new Map,candidates:[],actions:new Map,snapshots:new Ui,errorTimes:[]}}function Nh(n,t){return{artifacts:n,evidence:[],redactions:[],omissions:t,seeds:[],priorities:new Map,failedSelectors:[]}}async function Lh(n,t,e,r){let s=await Q(r,e.path,t.maxArtifactBytes);if(s.kind!=="read"){let f=s.kind==="unavailable"?"unavailable":"unreadable",h=s.kind==="over-budget"?"budget-exceeded":s.kind==="unauthorized"?"unauthorized-path":s.kind,m=Eh(n,e,f,{warnings:[s.message]}),g=Ch(n,t,e,m);for(let y of hn)oe(g,y,h,s.message,e.path);return Nh(hn.map(y=>m[y].artifact),g.omissions)}let a=zi(s.bytes,{maxEntries:t.maxTraceEntries,maxExpandedBytes:t.maxTraceExpandedBytes},f=>ec.test(f)||qi.test(f)||tc.test(f)),o=e.info?.producerVersion===void 0,d=Eh(n,e,"present",{path:s.relativePath,sha256:s.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=Ch(n,t,e,d);if(a.kind!=="read"){let f=a.message;for(let h of hn)oe(c,h,"unreadable",f,s.relativePath);return Nh(hn.map(h=>({...d[h].artifact,availability:"unreadable",warnings:[f]})),c.omissions)}o&&oe(c,"trace","unrecognized","Trace producer version was not supplied; parsed evidence is not version-qualified.",s.relativePath);let l=new Set;if(t.includeNetworkBodies){for(let[f,h]of a.contents.entries){if(!qi.test(f))continue;let m=Ve(h);if(m!==void 0)for(let g of Vi(m)){let y=me(g.value);if(y===void 0)continue;let w=Dh(y);w!==void 0&&(l.add(w),l.add(`resources/${w}`))}}if(l.size>0){let f=zi(s.bytes,{maxEntries:t.maxTraceEntries,maxExpandedBytes:t.maxTraceExpandedBytes},h=>ec.test(h)||qi.test(h)||tc.test(h)||l.has(h));f.kind==="read"?a=f:oe(c,"network","unreadable",f.message,s.relativePath)}}for(let f of a.contents.skipped){let h=f.reason==="unsafe-entry-name"?"unauthorized-path":"budget-exceeded";oe(c,"trace",h,`Archive entry ${f.entry} was not read (${f.reason}, ${f.declaredBytes} declared bytes).`,`${s.relativePath}!${f.entry}`)}let u=[...a.contents.entries.keys()].sort();for(let f of u.filter(h=>tc.test(h)))RA(c,f,a.contents.entries.get(f));for(let f of u.filter(h=>ec.test(h)))wA(c,f,a.contents.entries.get(f));for(let f of u.filter(h=>qi.test(h))){let h=Ve(a.contents.entries.get(f));if(h===void 0){c.channels.network.failed=!0,oe(c,"network","unreadable",`${f} is not valid UTF-8.`,f);continue}let m=Vi(h);m.length===0&&(c.channels.network.parsed=!0);for(let g of m){if(!g.parsed){c.channels.network.failed=!0,oe(c,"network","parse-failed",`${f}#line=${g.line} is not valid JSON.`,`${f}#line=${g.line}`);continue}let y=me(g.value);if(y===void 0){c.channels.network.failed=!0,oe(c,"network","unrecognized",`${f}#line=${g.line} is not a network record.`,`${f}#line=${g.line}`);continue}c.channels.network.parsed=!0,Mh(c,f,g.line,y,a.contents.entries)}}let p=bA(c);kA(c,p);for(let f of p.slice(0,uA))vA(c,f);if(p.length===0&&c.snapshots.size>0&&oe(c,"dom","irrelevant","No failed action targeted an element, so no DOM snapshot was examined.",s.relativePath),u.length===0)for(let f of hn)d[f].failed=!0,oe(c,f,"unreadable","Archive contained no Playwright trace, network, or stacks entry.",s.relativePath);return{artifacts:hn.map(f=>{let h=d[f],m=h.included>0?"present":h.failed&&!h.parsed?"unreadable":"empty";return{...h.artifact,availability:m}}),evidence:c.evidence,redactions:c.redactions,omissions:c.omissions,seeds:c.seeds,priorities:c.priorities,failedSelectors:p.map(f=>wt(f.selector))}}var IA="application/vnd.kwikqa.capture+json",_h=["trace","console","network","dom","accessibility"],jh=25,AA=2,PA=25,ic=600,SA=new Set(["type","setValue","addValue","keys"]),TA=new Set(["get","find","contains","$","$$","within"]),EA=/pass|secret|token|otp|pin\b|card|cvv|cvc|ssn|credential|auth/i;function ac(n){return n.name==="kwikqa-capture"||n.contentType.toLowerCase().split(";")[0]?.trim()===IA}function Tt(n,t=""){return typeof n=="string"?n:t}function CA(n){if(typeof n!="object"||n===null||Array.isArray(n))return;let t=n;if(t.schema!=="kwikqa-capture"||String(t.schemaVersion??"").split(".")[0]!=="1")return;let e=t.framework==="webdriverio"?"webdriverio":"cypress",r=s=>Array.isArray(t[s])?t[s].filter(i=>typeof i=="object"&&i!==null&&!Array.isArray(i)):[];return{framework:e,url:Tt(t.url),title:Tt(t.title),...Array.isArray(t.dom)?{dom:t.dom}:{},domTruncated:t.domTruncated===!0,commands:r("commands").map(s=>({name:Tt(s.name),...typeof s.displayName=="string"?{displayName:s.displayName}:{},message:Tt(s.message),state:Tt(s.state),...typeof s.error=="string"?{error:s.error}:{},...typeof s.repeated=="number"?{repeated:s.repeated}:{}})),console:r("console").map(s=>({level:Tt(s.level,"log"),text:Tt(s.text)})),network:r("network").map(s=>({message:Tt(s.message),state:Tt(s.state),...typeof s.url=="string"?{url:s.url}:{}}))}}function NA(n){let t=/^([A-Z]+)\s+(\d{3})\s+(\S+)/.exec(n.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(n.trim());return e!==null&&/^https?:|^\//.test(e[3]??"")?{method:e[1]??"GET",url:e[3]??"",failure:e[2]??"failed"}:{method:"",url:n}}function OA(n){for(let t of _e(n))if(Array.isArray(t)&&Be(t)==="body")return t;return n}function $A(n){let t=/^([a-z][\w-]*)\*?=/i.exec(n);return t!==null&&!n.includes("[")?t[1]??n:n}async function Fh(n,t,e,r){let{attachment:s}=e,i=`${e.attemptId}.attachments[${s.sourceIndex}]`,a=Object.fromEntries(_h.map(k=>[k,ve(n,k,`${e.attemptId}:${s.attachmentId}`)])),o=[],d=[],c=[],l=new Map,u=[],p=(k,T,_,U)=>{c.push({omissionId:B("omi",[e.attemptId,k,T,i,_]),channel:k,reason:T,message:_,locator:i,...U===void 0?{}:{cap:U}})},f=(k,T={})=>_h.map(_=>({artifactId:a[_],channel:_,availability:k(_),format:"kwikqa-capture",attemptId:e.attemptId,warnings:[],...T}));if(s.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 Q(r,s.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:s.path,warnings:[h.message]}),evidence:o,redactions:d,omissions:c,priorities:l,failedSelectors:u}}let m=Ee(h.bytes),g=Ve(h.bytes),y;try{y=g===void 0?void 0:CA(JSON.parse(g))}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:m}),evidence:o,redactions:d,omissions:c,priorities:l,failedSelectors:u};let w=(k,T,_,U,K,te)=>{let le=ge(n,a[k],T,_,U);o.push({evidenceId:le,kind:T,artifactId:a[k],logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:_,observation:U,availability:"present",redactionIds:K.map(X=>X.redactionId)}),d.push(...K),l.set(le,te)},v=(k,T,_)=>ce(wt(T),k,_,t.sensitiveNames),x=y.framework==="cypress"?"cy":"browser",R=y.commands.filter(k=>k.name!==""&&k.state!=="pending"),S=R.findIndex(k=>k.state==="failed"),N=S<0?R.length:S+1,E=Math.max(0,N-jh);E>0&&p("trace","budget-exceeded",`Kept the ${N-E} commands up to the failure; ${E} earlier ones were left out.`,jh);let M="";R.slice(E,Math.min(R.length,N+3)).forEach((k,T)=>{let _=E+T,U=k.state==="failed",le=SA.has(k.name)&&(EA.test(M)||t.sensitiveNames.some(Lt=>M.toLowerCase().includes(Lt.toLowerCase())))?`<${k.message.length} typed characters, not shown>`:k.message;TA.has(k.name)&&k.message!==""&&(M=k.message),U&&M!==""&&u.push(M.split(",")[0]?.trim()??M);let Ie=k.repeated===void 0?"":` (x${k.repeated})`,Te=`${U?"command failed":_>=N?"command after the failure":"command"}: ${x}.${k.displayName??k.name}(${le.slice(0,ic)})${Ie}${k.error===void 0?"":` error=${k.error.slice(0,ic)}`}`,kt=v("trace",Te,`${i}#commands[${_}]`);w("trace","trace-event",{type:"trace-event",entry:`${s.attachmentId}#commands`,line:_+1,eventType:U?"command-failed":"command"},kt.value,kt.records,U?re.failure:_>=N?re.afterFailure:re.context+(_-E)/1e3)}),R.length===0&&p("trace","unavailable","The capture recorded no commands."),y.console.slice(0,t.maxConsoleEvents).forEach((k,T)=>{let _=k.level==="pageerror"?"uncaught page error":`console.${k.level}`,U=v("console",`${_}: ${k.text.slice(0,ic)}`,`${i}#console[${T}]`);w("console","console-event",{type:"trace-event",entry:`${s.attachmentId}#console`,line:T+1,eventType:"console"},U.value,U.records,k.level==="error"||k.level==="pageerror"?re.significant:re.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 _=NA(k.message),U=Vt(k.url??_.url,"network",`${i}#network[${T}]`,t.sensitiveNames),K=_.status!==void 0?`-> ${_.status}`:_.failure!==void 0?`failure=${_.failure}`:`(${k.state})`,te=`${_.method===""?"request":_.method} ${U.value} ${K}`,le=(_.status??0)>=400||_.failure!==void 0;w("network","network-event",{type:"network-request",requestId:`${s.attachmentId}#${T}`,eventIndex:T},te,U.records,le?re.significant:re.ordinary)}),y.network.length>t.maxNetworkEvents&&p("network","budget-exceeded",`Kept ${t.maxNetworkEvents} of ${y.network.length} network responses.`,t.maxNetworkEvents);let A=y.dom,C=`${s.attachmentId}#dom`,P=Vt(y.url,"dom",`${i}#url`,t.sensitiveNames);d.push(...P.records);let I=`the page ${P.value}${y.title===""?"":` ("${y.title.slice(0,120)}")`} when the attempt failed`,$={maxDepth:t.maxDomDepth,maxNodes:t.maxDomNodes,maxBytes:t.maxDomTextBytes,sensitiveNames:t.sensitiveNames};if(A===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($A).filter(T=>T!=="").slice(0,AA);for(let T of k){let _=es(A,T),U=_.kind==="resolved"?_.matches:[];if(U.length===1&&U[0]!==void 0){let le=U[0],X=ns(le.node,`${i}#dom`,$);w("dom","dom-subtree",{type:"dom-node",snapshotId:C,nodePath:le.path},`In ${I}, the element ${T} selects:
28
- ${X.text}`,X.redactions,re.failure);let Ie=v("accessibility",rs(le.node),`${i}#a11y`);w("accessibility","accessibility-node",{type:"dom-node",snapshotId:C,nodePath:le.path},`element selected by ${T}: ${Ie.value}`,Ie.records,re.failure);continue}let K=_.kind==="unsupported"?`uses a selector form (${_.reason}) the local DOM adapter does not evaluate`:`matched ${U.length} elements`,te=Hi(A,T,U,`${i}#dom`,{maxItems:PA,maxBytes:$.maxBytes},t.sensitiveNames);w("dom","dom-candidates",{type:"dom-node",snapshotId:C,nodePath:[]},`In ${I}, the selector ${T} ${K}. Elements most like it, best first:
29
- ${te.text}`,te.redactions,re.failure)}if(k.length===0){let T=ns(OA(A),`${i}#dom`,$);w("dom","dom-subtree",{type:"dom-node",snapshotId:C,nodePath:[]},`Outline of ${I}:
30
- ${T.text}`,T.redactions,re.significant),T.truncated&&p("dom","budget-exceeded",`The page outline was cut at ${$.maxNodes} elements or ${$.maxBytes} bytes.`,$.maxNodes)}}let D=new Set(o.map(k=>k.artifactId));return{artifacts:f(k=>D.has(a[k])?"present":"empty",{path:h.relativePath,sha256:m}),evidence:o,redactions:d,omissions:c,priorities:l,failedSelectors:u}}import{execFile as VA}from"node:child_process";import{isAbsolute as HA,relative as zA,resolve as pc,sep as Vh}from"node:path";import{promisify as UA}from"node:util";import{execFile as DA}from"node:child_process";import{promisify as MA}from"node:util";import{isAbsolute as LA,relative as oc,resolve as Ki,sep as dc}from"node:path";var _A=MA(DA),jA=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/,FA=1e4;function Wi(n){let t=[],e,r,s=()=>{if(r===void 0||e===void 0)return;let[,i,a,o,d]=r.header;t.push({path:e,oldStart:Number.parseInt(i??"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:r.lines.join(`
31
- `)}),r=void 0};for(let i of n.split(/\r?\n/)){if(i.startsWith("diff --git ")){s(),e=void 0;continue}if(i.startsWith("+++ ")){s();let o=i.slice(4).trim();e=o==="/dev/null"?void 0:o.replace(/^b\//,"");continue}let a=jA.exec(i);if(a!==null){s(),r={header:a,lines:[i]};continue}r!==void 0&&r.lines.push(i)}return s(),t}function yn(n,t,e,r){return{omissionId:B("omi",["diff",n,e??"",t]),channel:"diff",reason:n,message:t,...e===void 0?{}:{locator:e},...r===void 0?{}:{cap:r}}}async function BA(n,t,e){let r=["-C",n,"--no-optional-locks","-c","core.quotePath=false","diff","--no-color","--no-ext-diff","--no-renames","--unified=3","HEAD","--",...t];try{return{text:(await _A("git",r,{timeout:FA,maxBuffer:e,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}}catch(s){let i=s;if(i.code==="ENOENT")return{error:"git executable was not found."};let a=(i.stderr??i.message??"").trim().split(`
32
- `)[0]??"";return{error:a===""?"git diff failed.":a}}}async function Bh(n,t,e,r){let s=ve(n,"diff",r.gitRoot??t.workspaceRoot),i=(x,R=[])=>({artifactId:s,channel:"diff",availability:x,...r.gitRoot===void 0?{}:{path:r.gitRoot},format:"git-unified-diff",warnings:R});if(!r.authorized)return{artifacts:[i("unavailable")],evidence:[],redactions:[],omissions:[yn("policy-disabled","Current-diff selection was not authorized for this run.")]};if(r.gitRoot===void 0)return{artifacts:[i("unavailable")],evidence:[],redactions:[],omissions:[yn("unavailable","The workspace has no containing git repository root.")]};let a=Ki(r.workspaceRoot??r.gitRoot),o=Ki(r.gitRoot),d=oc(o,a);if(d===".."||d.startsWith(`..${dc}`))return{artifacts:[i("unavailable")],evidence:[],redactions:[],omissions:[yn("unauthorized-path","The authorized workspace is outside the configured git root.",a)]};let c=[...new Set(e.map(x=>{let R=LA(x)?Ki(x):Ki(a,x),S=oc(o,R).split(dc).join("/");return S===""||S.startsWith("../")||S===".."?void 0:S}).filter(x=>x!==void 0))].sort();if(c.length===0)return{artifacts:[i("empty")],evidence:[],redactions:[],omissions:[yn("irrelevant","No evidence-bearing file was eligible for diff selection.")]};let l=Math.max(t.maxDiffBytes*4,1e6),u=await BA(o,c,l);if("error"in u)return{artifacts:[i("unreadable",[u.error])],evidence:[],redactions:[],omissions:[yn("unreadable",u.error,r.gitRoot)]};let p=a===o?"":`${oc(o,a).split(dc).join("/")}/`,f=Wi(u.text).map(x=>({...x,path:p!==""&&x.path.startsWith(p)?x.path.slice(p.length):x.path}));if(f.length===0)return{artifacts:[i("empty")],evidence:[],redactions:[],omissions:[]};let h=[],m=[],g=[],y=0,w=!1,v=!1;for(let x of f){if(h.length>=t.maxDiffHunks){w||(w=!0,g.push(yn("budget-exceeded",`Reached the ${t.maxDiffHunks}-hunk limit; later hunks were not included.`,x.path,t.maxDiffHunks)));break}let R=`${x.path}@${x.newStart}`,S=ce(x.body,"diff",R,t.sensitiveNames),N=Buffer.byteLength(S.value,"utf8");if(y+N>t.maxDiffBytes){v||(v=!0,g.push(yn("budget-exceeded",`Reached the ${t.maxDiffBytes}-byte diff limit; later hunks were not included.`,x.path,t.maxDiffBytes)));break}y+=N,m.push(...S.records);let E={type:"diff-hunk",path:x.path,oldStart:x.oldStart,oldLines:x.oldLines,newStart:x.newStart,newLines:x.newLines};h.push({evidenceId:ge(n,s,"diff-hunk",E,S.value),kind:"diff-hunk",artifactId:s,locator:E,observation:S.value,availability:"present",redactionIds:S.records.map(M=>M.redactionId)})}return{artifacts:[i("present")],evidence:h,redactions:m,omissions:g}}var qA=UA(VA),GA=1e4,KA=4e6,WA=16,Yh=3,JA=120,Hh=50,zh=20,Uh=30,cc=12,qh=24e3,lc=40,Qh=20,Gh=120,Zh=1440*60*1e3,XA=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"]),em=/\.(?:[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,tm=/(?:^|\/)(?: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$/,YA=/\u001b\[[0-9;]*m/g,Kh=/"([^"\n]{3,120})"|'([^'\n]{3,120})'|`([^`\n]{3,120})`/g,QA=/^\s*(?:Expected|Received)(?: string| pattern| value)?:\s*(.+)$/gm,ZA=/^(?:[A-Z]+|request) (\S+) (?:-> (\d{3})|failure=)/;function eP(n){let t=n.trim();return/^(["'`])(.*)\1$/.exec(t)?.[2]??t}function Wh(n){let t=n.trim();if(!(t.length<Yh||t.length>JA)&&!XA.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 uc(n){let t=[];for(let e of n.matchAll(/\[[\w-]+[~|^$*]?=\s*["']?([^"'\]]+)["']?\]/g))t.push(e[1]??"");for(let e of n.matchAll(/[#.]([A-Za-z][\w-]{2,})/g))t.push(e[1]??"");return t}var tP=8;function nP(n){let t=n.trim().split(/\s+/);if(t.length<3)return[];let e=[];for(let r=0;r+1<t.length;r+=1){let s=`${t[r]} ${t[r+1]}`;(s.match(new RegExp("\\p{L}","gu"))??[]).length>=tP&&e.push(s)}return e}function rP(n){let t;try{t=new URL(n,"http://localhost").pathname}catch{return}if(/\.(?:js|css|png|jpe?g|gif|svg|ico|woff2?|map)$/i.test(t))return;let e=[];for(let s of t.split("/").filter(Boolean)){if(/^\d+$|^[0-9a-f-]{16,}$|^[0-9a-f]{8,}$/i.test(s))break;e.push(s)}let r=`/${e.join("/")}`;return e.length===0?void 0:r}function nm(n,t,e=[]){let r=[],s=[];for(let c of n){for(let l of t(c)){for(let u of l.matchAll(Kh)){let p=u[1]??u[2]??u[3]??"";r.push(p,...uc(p))}/[('"`]/.test(l)||r.push(...uc(l))}for(let l of c.errors){let u=(l.message??"").replace(YA,"");for(let f of u.matchAll(QA)){let h=eP(f[1]??"");r.push(h),s.push(h)}let p=u.split(`
33
- `).slice(0,6).join(`
34
- `);for(let f of p.matchAll(Kh)){let h=f[1]??f[2]??f[3]??"",m=/^[[#.]/.test(h)?uc(h):[];r.push(...m.length>0?m:[h]),m.length===0&&s.push(h)}}}let i=[];for(let c of e){let l=ZA.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=rP(l[1]??"");p!==void 0&&p.length>=Yh&&i.push(p)}let a=c=>[...new Set(c)].sort((l,u)=>u.length-l.length||l.localeCompare(u)),o=a([...r.map(Wh).filter(c=>c!==void 0),...i]),d=a(s.flatMap(nP).map(Wh).filter(c=>c!==void 0&&!o.includes(c)));return[...o,...d].slice(0,WA)}function sP(n){return n.map(t=>t.replace(/[.[\]{}()\\*+?^$|]/g,"\\$&")).join("|")}async function rr(n,t){try{return{text:(await qA("git",["-C",n,"--no-optional-locks","-c","core.quotePath=false",...t],{timeout:GA,maxBuffer:KA,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}}catch(e){let r=e;if(r.code==="ENOENT")return{error:"git executable was not found."};if(r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{error:"The matching changes are too large to read."};let s=(r.stderr??r.message??"").trim().split(`
35
- `)[0]??"";return{error:s===""?"git failed.":s}}}async function us(n,t){let e=await rr(n,t);if("error"in e)return;let r=e.text.trim();return r===""?void 0:r}async function iP(n){let t=await us(n,["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 us(n,["rev-parse","--verify","--quiet",`${e}^{commit}`])!==void 0)return e}async function aP(n,t){let e=await us(n,["rev-parse","--verify","--quiet","HEAD^{commit}"]);if(e===void 0)return;let r=await iP(n),s=r===void 0?void 0:await us(n,["merge-base","HEAD",r]);if(r!==void 0&&s!==void 0&&s!==e)return{logArgs:[`--max-count=${Hh}`,`${s}..HEAD`],description:`the commits on this branch since it left ${r} (at most ${Hh})`};let i=Date.parse(t),a=new Date((Number.isNaN(i)?0:i)-Uh*Zh).toISOString();return{logArgs:[`--max-count=${zh}`,`--since=${a}`,"HEAD"],description:`the last ${zh} commits from the ${Uh} days before the run`}}function rm(n,t){let e=Date.parse(t);if(Number.isNaN(e))return"";let r=Math.floor((e-n)/Zh);return r<0?", after the run":r===0?", the day of the run":`, ${r} day${r===1?"":"s"} before the run`}function oP(n,t){let e=n.split(`
36
- `);if(e.length<=lc+1)return n;let[r,...s]=e,i=Math.max(0,s.findIndex(t)),a=Math.max(0,Math.min(i-10,s.length-lc)),o=s.slice(a,a+lc),d=a,c=s.length-a-o.length;return[r??"",...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(`
37
- `)}function sm(n,t,e){let r=pc(n,e),s=zA(t,r);if(!(s===""||s===".."||s.startsWith(`..${Vh}`)||HA(s)))return s.split(Vh).join("/")}function Jh(n,t,e,r,s){let i=a=>(a.startsWith("+")||a.startsWith("-"))&&r.some(o=>a.includes(o));return Wi(n).flatMap(a=>{let o=sm(t,e,a.path);return o===void 0||!em.test(o)||tm.test(o)?[]:a.body.split(`
38
- `).slice(1).some(i)?[{...s===void 0?{}:{commit:s.id},heading:s?.heading??"Uncommitted change",path:o,oldStart:a.oldStart,oldLines:a.oldLines,newStart:a.newStart,newLines:a.newLines,body:oP(a.body,i)}]:[]})}async function dP(n,t,e){let r=await rr(n,["log","--no-merges","--no-show-signature","--format=%h%x1f%ct%x1f%s",...t.logArgs,"--"]);if("error"in r)return{listed:[],total:0};let s=r.text.split(`
39
- `).filter(a=>a.includes(""));return{listed:s.slice(0,Qh).map(a=>{let[o="",d="0",c=""]=a.split(""),l=c.length>Gh?`${c.slice(0,Gh)}\u2026`:c;return`${o}${rm(Number(d)*1e3,e)}: ${l}`}),total:s.length}}async function cP(n,t){let e=await rr(n,["diff","--name-only","--no-renames","HEAD","--"]),r=await rr(n,["ls-files","--others","--exclude-standard","--"]),s=[e,r].flatMap(i=>"error"in i?[]:i.text.split(`
40
- `).filter(a=>a!==""));return[...new Set(s.map(i=>sm(n,t,i)).filter(i=>i!==void 0&&em.test(i)&&!tm.test(i)))].sort().slice(0,Qh)}var Xh=["--no-color","--no-ext-diff","--no-renames","--unified=3","--src-prefix=a/","--dst-prefix=b/"];function Ji(n,t,e,r){return{omissionId:B("omi",["changes",n,e??"",t]),channel:"diff",reason:n,message:t,...e===void 0?{}:{locator:e},...r===void 0?{}:{cap:r}}}async function im(n,t,e,r,s){let i=ve(n,"diff",`changes:${s.gitRoot??s.workspaceRoot}`),a=(P,I=[])=>({artifactId:i,channel:"diff",availability:P,...s.gitRoot===void 0?{}:{path:s.gitRoot},format:"git-change-search",warnings:I}),o=(P,I)=>({artifacts:[a(P==="irrelevant"?"empty":"unavailable")],evidence:[],redactions:[],omissions:[Ji(P,I)]});if(!s.authorized)return o("policy-disabled","Recent changes were not included (--no-changes).");if(s.gitRoot===void 0)return o("unavailable","The workspace is not in a git repository, so no changes were searched.");if(r.length===0)return o("irrelevant","The failures name no locator, value, or request path to look for in recent changes.");let d=pc(s.gitRoot),c=pc(s.workspaceRoot),l=sP(r),u=[];await us(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 rr(d,["diff",...Xh,`-G${l}`,"HEAD","--"]);"error"in h?f.push(h.error):p.push(...Jh(h.text,d,c,r,void 0));let m=await aP(d,t),g=0;if(m!==void 0){let P=await rr(d,["log",...Xh,"--no-merges","--no-show-signature","--format=%x1e%h%x1f%ct%x1f%s",`-G${l}`,...m.logArgs,"--"]);if("error"in P)f.push(P.error);else for(let I of P.text.split("").slice(1)){let $=I.indexOf(`
41
- `),[D="",k="0",T=""]=($===-1?I:I.slice(0,$)).split(""),_=Jh(I.slice($+1),d,c,r,{id:D,heading:`Commit ${D}${rm(Number(k)*1e3,t)}: ${T}`});_.length>0&&(g+=1),p.push(..._)}}if(f.length>0&&p.length===0)return{artifacts:[a("unreadable",f)],evidence:[],redactions:[],omissions:f.map(P=>Ji("unreadable",P,s.gitRoot))};let y=[],w=[],v=f.map(P=>Ji("unreadable",P,s.gitRoot)),x=0;for(let P of p){if(y.length>=cc||x>=qh){let k=p.length-y.length;v.push(Ji("budget-exceeded",`${k} more matching hunk${k===1?" was":"s were"} left out at the ${cc}-hunk, ${qh}-byte limit for recent changes.`,void 0,cc));break}let I=`${P.commit??"worktree"}:${P.path}@${P.newStart}`,$=ce(`${P.heading}
42
- ${P.path}
43
- ${P.body}`,"diff",I,e.sensitiveNames);x+=Buffer.byteLength($.value,"utf8"),w.push(...$.records);let D={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:ge(n,i,"diff-hunk",D,$.value),kind:"diff-hunk",artifactId:i,locator:D,observation:$.value,availability:"present",redactionIds:$.records.map(k=>k.redactionId)})}let R=["uncommitted changes",...m===void 0?[]:[m.description]].join(" and "),S=m===void 0?{listed:[],total:0}:await dP(d,m,t),N=await cP(d,c),E=[...S.listed.length===0?[]:[`${S.total>S.listed.length?`The newest ${S.listed.length} of the ${S.total} commits searched`:"Commits searched, newest first"}: ${S.listed.join("; ")}.`],...N.length===0?[]:[`Source files with uncommitted changes: ${N.join(", ")}.`]],M=y.length,A=ce(`Searched ${R} for changed lines containing any of: ${r.map(P=>JSON.stringify(P)).join(", ")}. ${M===0?"No change mentioned them.":`${M} changed hunk${M===1?"":"s"} matched${g>0?`, from ${g} commit${g===1?"":"s"}`:""}${p.some(P=>P.commit===void 0)?" and uncommitted changes":""}.`}${E.map(P=>` ${P}`).join("")} A matching change shows what changed, not who owns the failure.`,"diff","changes:search",e.sensitiveNames);w.push(...A.records);let C={type:"report-field",path:"changes"};return y.push({evidenceId:ge(n,i,"change-search",C,A.value),kind:"change-search",artifactId:i,locator:C,observation:A.value,availability:"present",redactionIds:A.records.map(P=>P.redactionId)}),{artifacts:[a(M===0?"empty":"present",u)],evidence:y,redactions:w,omissions:v}}var lP=[137,80,78,71,13,10,26,10];function uP(n){return n<192||n>207?!1:n!==196&&n!==200&&n!==204}function pP(n){if(n.byteLength<24||lP.some((e,r)=>n[r]!==e))return;let t=new DataView(n.buffer,n.byteOffset,n.byteLength);if(String.fromCharCode(...n.subarray(12,16))==="IHDR")return{width:t.getUint32(16,!1),height:t.getUint32(20,!1)}}function fP(n){if(n.byteLength<4||n[0]!==255||n[1]!==216)return;let t=new DataView(n.buffer,n.byteOffset,n.byteLength),e=2;for(;e+9<n.byteLength;){if(n[e]!==255){e+=1;continue}let r=n[e+1];if(r===void 0)return;if(r===216||r===1||r>=208&&r<=215){e+=2;continue}let s=t.getUint16(e+2,!1);if(uP(r))return{height:t.getUint16(e+5,!1),width:t.getUint16(e+7,!1)};if(s<2)return;e+=2+s}}function hP(n){if(n.byteLength<30)return;let t=(s,i)=>String.fromCharCode(...n.subarray(s,i));if(t(0,4)!=="RIFF"||t(8,12)!=="WEBP")return;let e=new DataView(n.buffer,n.byteOffset,n.byteLength),r=t(12,16);if(r==="VP8X"){let s=1+(e.getUint16(24,!0)|e.getUint8(26)<<16),i=1+(e.getUint16(27,!0)|e.getUint8(29)<<16);return{width:s,height:i}}if(r==="VP8 ")return{width:e.getUint16(26,!0)&16383,height:e.getUint16(28,!0)&16383};if(r==="VP8L"){let s=e.getUint32(21,!0);return{width:1+(s&16383),height:1+(s>>14&16383)}}}function om(n){return pP(n)??fP(n)??hP(n)}function mP(n){let t=n.toLowerCase().split(";")[0]?.trim()??"";if(t.startsWith("image/"))return"screenshot";if(t.startsWith("video/"))return"video"}function am(n,t,e,r,s){return{omissionId:B("omi",[n.attemptId,t,e,s,r]),channel:t,reason:e,message:r,locator:s}}async function dm(n,t,e,r){let{attachment:s}=e,i=mP(s.contentType);if(i===void 0)return{artifacts:[],evidence:[],redactions:[],omissions:[]};let a=`${e.attemptId}.attachments[${s.sourceIndex}]`,o=ve(n,i,`${e.attemptId}:${s.attachmentId}`),d={artifactId:o,channel:i,attemptId:e.attemptId,format:s.contentType},c,l,u;if(s.path!==void 0){let v=await Q(r,s.path,t.maxArtifactBytes);v.kind==="read"?(c=v.bytes,l=v.relativePath):u={reason:v.kind==="over-budget"?"budget-exceeded":v.kind==="unauthorized"?"unauthorized-path":v.kind,message:v.message}}else if(s.bodyBase64!==void 0&&s.bodyBase64.length>0){let v=Buffer.from(s.bodyBase64,"base64");v.byteLength>t.maxArtifactBytes?u={reason:"budget-exceeded",message:`Inline attachment exceeds the ${t.maxArtifactBytes}-byte limit.`}:c=new Uint8Array(v)}else u={reason:"unavailable",message:"Attachment supplied neither a path nor a body."};let p=ce(s.name,i,a,t.sensitiveNames);if(c===void 0){let v=u?.reason??"unavailable";return{artifacts:[{...d,availability:v==="unavailable"?"unavailable":"unreadable",...s.path===void 0?{}:{path:s.path},warnings:u===void 0?[]:[u.message]}],evidence:[],redactions:p.records,omissions:[am(e,i,v,u?.message??"Attachment is unavailable.",a)]}}let f=Ee(c),h=i==="screenshot"?om(c):void 0,m=[`${i} name=${p.value}`,`contentType=${s.contentType}`,`bytes=${c.byteLength}`,...i==="screenshot"?[h===void 0?"dimensions=unknown":`dimensions=${h.width}x${h.height}`]:[],`sha256=${f}`],g={type:"media",attachmentId:s.attachmentId,sha256:f},y=m.join(" "),w=[];return i==="screenshot"&&h===void 0&&w.push(am(e,i,"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:ge(n,o,i==="screenshot"?"image-metadata":"video-metadata",g,y),kind:i==="screenshot"?"image-metadata":"video-metadata",artifactId:o,logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:g,observation:y,availability:"present",redactionIds:p.records.map(v=>v.redactionId)}],redactions:p.records,omissions:w}}var yP=new Set(["textbox","searchbox","combobox","spinbutton"]),gP=/\s\[(?:ref=[^\]]+|cursor=[^\]]+)\]/g,cm=/^#{1,3}\s+page snapshot\s*$/i,wP=/^#{1,3}\s+\S/,lm=2;function um(n){let t=n.contentType.toLowerCase().split(";")[0]?.trim()??"";return n.name==="error-context"?!0:t==="text/markdown"&&(n.path?.endsWith("error-context.md")??!1)}function bP(n){let t=n.split(/\r?\n/),e=t.some(i=>cm.test(i.trim())),r=!e,s;for(let i=0;i<t.length;i+=1){let o=(t[i]??"").trim();if(s===void 0){if(cm.test(o)){r=!0;continue}if(wP.test(o)){if(r&&e)break;continue}r&&/^```ya?ml\s*$/i.test(o)&&(s=i+1);continue}if(o==="```")return{scope:e?"page":"element",lines:t.slice(s,i),startLine:s+1,endLine:i}}}function fc(n){return n.length-n.trimStart().length}function hc(n,t,e){let r=[],s=n,i=/^(\s*-\s+)([\w-]+)(\s+"((?:[^"\\]|\\.)*)")(.*?):\s+(.+)$/.exec(s);if(i!==null&&yP.has(i[2]??"")){let d=(i[4]??"").toLowerCase(),c=[...e].map(l=>l.toLowerCase()).sort().find(l=>d.includes(l));c!==void 0&&(s=`${i[1]}${i[2]}${i[3]}${i[5]}: [REDACTED]`,r.push({redactionId:B("red",["accessibility",t,`field:${c}`]),ruleId:`sensitive-field:${c}`,channel:"accessibility",locator:t,action:"mask",count:1}))}let a=/^(\s*-\s+\/url:\s+)(.+)$/.exec(s);if(a!==null){let d=(a[2]??"").replace(/^"(.*)"$/,"$1"),c=Vt(d,"accessibility",t,e);s=`${a[1]}${c.value}`,r.push(...c.records)}let o=ce(s,"accessibility",t,e);return{value:o.value,records:[...r,...o.records]}}function xP(n,t,e){if(n.reduce((u,p)=>u+Buffer.byteLength(p,"utf8")+1,0)<=e)return{lines:n,dropped:0};let s=[...new Set(t.flatMap(u=>Qn(u)))],i=new Set,a=u=>{i.add(u);let p=fc(n[u]??"");for(let f=u-1;f>=0&&p>0;f-=1){let h=fc(n[f]??"");h<p&&(i.add(f),p=h)}};n.forEach((u,p)=>{let f=u.toLowerCase();if(s.some(h=>f.includes(h)))for(let h=Math.max(0,p-lm);h<=Math.min(n.length-1,p+lm);h+=1)a(h)});let o=[...i].reduce((u,p)=>u+Buffer.byteLength(n[p]??"","utf8")+1,0);for(let u=0;u<n.length&&o<e;u+=1){if(i.has(u))continue;let p=Buffer.byteLength(n[u]??"","utf8")+1;if(o+p>e)break;i.add(u),o+=p}let d=[],c=!1,l=0;for(let u=0;u<n.length;u+=1){if(!i.has(u)){c=!0;continue}let p=n[u]??"",f=Buffer.byteLength(p,"utf8")+1;if(l+f>e){c=!0;break}c&&d.push(`${" ".repeat(fc(p))}\u2026`),c=!1,d.push(p),l+=f}return c&&d.push("\u2026"),{lines:d,dropped:n.length-d.filter(u=>u.trim()!=="\u2026").length}}async function pm(n,t,e,r){let{attachment:s}=e,i=ve(n,"accessibility",`${e.attemptId}:${s.attachmentId}`),a=`${e.attemptId}.attachments[${s.sourceIndex}]`,o={artifactId:i,channel:"accessibility",availability:"present",format:"playwright-error-context",attemptId:e.attemptId,warnings:[]},d=(R,S,N)=>({omissionId:B("omi",[e.attemptId,"accessibility",R,a,S]),channel:"accessibility",reason:R,message:S,locator:a,...N===void 0?{}:{cap:N}}),c,l;if(s.path!==void 0){let R=await Q(r,s.path,t.maxArtifactBytes);if(R.kind!=="read"){let S=R.kind==="over-budget"?"budget-exceeded":R.kind==="unauthorized"?"unauthorized-path":R.kind;return{artifacts:[{...o,availability:R.kind==="unavailable"?"unavailable":"unreadable",path:s.path,warnings:[R.message]}],evidence:[],redactions:[],omissions:[d(S,R.message)]}}c=R.bytes,l=R.relativePath}else s.bodyBase64!==void 0&&s.bodyBase64.length>0&&(c=new Uint8Array(Buffer.from(s.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=Ee(c),p={...o,sha256:u,...l===void 0?{}:{path:l}},f=Ve(c),h=f===void 0?void 0:bP(wt(f));if(h===void 0||h.lines.every(R=>R.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 m=[],g=h.lines.map((R,S)=>{let N=hc(R.replace(gP,""),`${a}#line=${h.startLine+S}`,t.sensitiveNames);return m.push(...N.records),N.value}),y=xP(g,e.focus,t.maxDomTextBytes),w=[];y.dropped>0&&w.push(d("budget-exceeded",`Kept ${g.length-y.dropped} of ${g.length} page snapshot lines, favouring those that mention the failed locator.`,t.maxDomTextBytes));let v=`${h.scope==="page"?"Accessibility snapshot of the page when the test failed":"Accessibility snapshot of the element the failed assertion checked"}:
44
- ${y.lines.join(`
45
- `)}`,x={type:"attachment-text",attachmentId:s.attachmentId,sha256:u,startLine:h.startLine,endLine:h.endLine};return{artifacts:[p],evidence:[{evidenceId:ge(n,i,"page-snapshot",x,v),kind:"page-snapshot",artifactId:i,logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:x,observation:v,availability:"present",redactionIds:m.map(R=>R.redactionId)}],redactions:m,omissions:w}}var vP=256*1024,kP=10,fm=200;async function hm(n,t,e,r){let s=ve(n.runId,"probe",e),i=(h,m,g=e)=>({omissionId:B("omi",[n.runId,"probe",h,g,m]),channel:"probe",reason:h,message:m,locator:g}),a=await Q(r,e,vP);if(a.kind!=="read")return{artifacts:[{artifactId:s,channel:"probe",availability:"unavailable",warnings:[a.message]}],evidence:[],redactions:[],omissions:[i("unavailable",a.message)]};let o={artifactId:s,channel:"probe",availability:"present",path:a.relativePath,sha256:a.sha256,format:"kwikqa-playwright-cli-probe",warnings:[]},d;try{d=me(JSON.parse(Ve(a.bytes)??""))}catch{d=void 0}if(d===void 0||V(d.schemaVersion)!=="1.0")return{artifacts:[{...o,availability:"unreadable"}],evidence:[],redactions:[],omissions:[i("unrecognized","The probe results are not in a recognized format.")]};let c=me(d.tool),l=`Playwright CLI ${V(c?.version)??"unknown"}, Playwright ${V(d.playwrightVersion)??"unknown"}`,u=[],p=[],f=[];return Je(d.results)?.forEach((h,m)=>{let g=me(h);if(g===void 0)return;let y=V(g.logicalTestId),w=n.logicalTests.find(P=>P.logicalTestId===y)??n.logicalTests.find(P=>P.title===V(g.title)&&P.location.file===V(g.file)&&P.location.line===Ae(g.line)),v=w?.attempts.at(-1),x=`${a.relativePath}#results[${m}]`;for(let P of Je(g.issues)??[]){let I=V(P);I!==void 0&&f.push(i("unavailable",`Live probe of "${V(g.title)??"a test"}": ${I}`,x))}let R=(Je(g.candidates)??[]).map(P=>me(P)).filter(P=>P!==void 0).slice(0,kP);if(w===void 0||R.length===0)return;let S=[],N=[];R.forEach((P,I)=>{let $=hc(`- ${(V(P.element)??"").slice(0,fm)}`,`${x}/candidates[${I}]`,t.sensitiveNames),D=ce((V(P.locator)??"").slice(0,fm),"probe",`${x}/candidates[${I}]/locator`,t.sensitiveNames);p.push(...$.records,...D.records),N.push(...$.records.map(k=>k.redactionId),...D.records.map(k=>k.redactionId)),S.push(`${$.value.replace(/^- /,"")} \u2192 ${D.value}`)});let E=V(g.locator),A=[`Live page paused at ${`${V(g.file)??w.location.file}:${Ae(g.failingLine)??"?"}`}, before the failing step (${l}).${E===void 0?"":` The failed locator was ${E}.`} Locators Playwright generated for the elements most like it:`,...S].join(`
46
- `),C={type:"report-field",path:`probe.results[${m}]`};u.push({evidenceId:ge(n.runId,s,"locator-suggestion",C,A),kind:"locator-suggestion",artifactId:s,logicalTestId:w.logicalTestId,...v===void 0?{}:{attemptId:v.attemptId},locator:C,observation:A,availability:"present",redactionIds:N})}),{artifacts:[{...o,availability:u.length>0?"present":"empty"}],evidence:u,redactions:p,omissions:f}}var RP=/(?:\(|\bat\s+|^)((?:[A-Za-z]:)?[^():\s][^():]*?):(\d+):(\d+)\)?\s*$/,IP=/^File "([^"]+\.py)", line (\d+)/,AP=/^((?:[A-Za-z]:)?[^\s:][^:]*\.py):(\d+):(?:\s|$)/,PP=/(?:^|[\\/])(?:node_modules|site-packages|\.venv|venv)[\\/]|[\\/]lib[\\/]python\d|^node:|^internal\//;function mc(n,t,e){let r=[];return n.split(/\r?\n/).forEach((s,i)=>{let a=s.trim().replace(/webpack:\/\/[^/\s()]*\//g,"").replace(/^❯\s+/,""),o=Un(a);if(o!==void 0){r.push({file:o.file,line:o.line,origin:`${t}#frame=${i+1}`,...e});return}let d=IP.exec(a)??AP.exec(a),c=d===null?RP.exec(a):[d[0],d[1],d[2],"1"];if(c===null)return;let[,l,u,p]=c;l===void 0||u===void 0||p===void 0||PP.test(l)||r.push({file:l.replace(/^file:\/\//,"").replace(/^(?:\.\/)+/,""),line:Number.parseInt(u,10),column:Number.parseInt(p,10),origin:`${t}#frame=${i+1}`,...e})}),r}async function mm(n,t){if(!n.some(s=>yi(s.file)))return n;let e=new zn(t);return(await Promise.all(n.map(async s=>{if(!yi(s.file))return s;let i=await e.find(s.file);return i===void 0?void 0:{...s,file:i}}))).filter(s=>s!==void 0)}function ps(n,t,e,r,s,i,a){let o=`${r}:${s}`;if(e.reported.has(o))return;e.reported.add(o);let d=`Reached the ${i}-${s} limit; later observations were not included.`;t.push({omissionId:B("omi",[n.runId,r,"budget-exceeded",a,d]),channel:r,reason:"budget-exceeded",message:d,locator:a,cap:i})}function yc(n,t,e){return n===void 0?[]:[{file:n.file,line:n.line??1,...n.column===void 0?{}:{column:n.column},origin:t,...e}]}function gc(n,t,e){let r=[...yc(n.location,`${t}.location`,e)];return n.stack!==void 0&&r.push(...mc(n.stack,`${t}.stack`,e)),r}function ym(n,t,e){let r=[];return n.forEach((s,i)=>{let a=`${t}[${i}]`;s.error!==void 0&&r.push(...gc(s.error,a,e)),r.push(...ym(s.steps,`${a}.steps`,e))}),r}function SP(n){let t=[];for(let e of n.logicalTests){for(let r of e.attempts){let s={logicalTestId:e.logicalTestId,attemptId:r.attemptId};t.push(...yc(r.errorLocation,`${r.attemptId}.errorLocation`,s));for(let i of r.errors)t.push(...gc(i,i.source,s));t.push(...ym(r.steps,`${r.attemptId}.steps`,s))}t.push(...yc(e.location,`${e.logicalTestId}.location`,{logicalTestId:e.logicalTestId}))}for(let e of n.reportErrors)t.push(...gc(e,e.source,{}));return t}function Xi(n,t,e,r,s,i,a,o,d,c,l){if(c.reportFields>=t.maxReportFields){ps(n,d,c,"report","field",t.maxReportFields,s);return}c.reportFields+=1;let u=ce(i,e.channel,s,t.sensitiveNames);o.push(...u.records);let p={type:"report-field",path:s};a.push({evidenceId:ge(n.runId,e.artifactId,r,p,u.value),kind:r,artifactId:e.artifactId,...l,locator:p,observation:u.value,availability:u.value.length===0?"empty":"present",redactionIds:u.records.map(f=>f.redactionId)})}function wc(n,t,e,r,s,i,a,o,d){let c=[["name",r.name],["message",r.message],["value",r.value],["snippet",r.snippet]];for(let[l,u]of c)u!==void 0&&Xi(n,t,e,"error-field",`${r.source}.${l}`,u,s,i,a,o,d);r.stack!==void 0&&(Xi(n,t,e,"error-field",`${r.source}.stack`,r.stack,s,i,a,o,d),r.stack.split(/\r?\n/).forEach((l,u)=>{if(l.trim().length===0)return;let p=`${r.source}.stack#line=${u+1}`;if(o.stackFrames>=t.maxStackFrames){ps(n,a,o,"report","stack-frame",t.maxStackFrames,p);return}o.stackFrames+=1,Xi(n,t,e,"stack-frame",p,l,s,i,a,o,d)}))}function gm(n,t,e,r,s,i,a,o,d,c){r.forEach((l,u)=>{let p=`${s}[${u}]`;if(d.steps>=t.maxSteps){ps(n,o,d,"report","step",t.maxSteps,p);return}d.steps+=1,Xi(n,t,e,"step",`${p}.title`,l.title,i,a,o,d,c),l.error!==void 0&&wc(n,t,e,l.error,i,a,o,d,c),gm(n,t,e,l.steps,`${p}.steps`,i,a,o,d,c)})}function TP(n){if(n.kind==="text")return n.text;let t=Buffer.from(n.base64,"base64");return`binary stdio: sha256=${Ee(t)} bytes=${t.byteLength}`}function wm(n,t){let e={artifactId:ve(n.runId,"report",n.artifact.artifactId),channel:"report",availability:n.artifact.availability,...n.artifact.path===void 0?{}:{path:n.artifact.path},...n.artifact.sha256===void 0?{}:{sha256:n.artifact.sha256},...n.artifact.formatVersion===void 0?{}:{producerVersion:n.artifact.formatVersion},warnings:n.artifact.warnings},r=[e],s=[],i=[],a=[],o={reportFields:0,stackFrames:0,steps:0,stdioChunks:0,stdioBytes:0,reported:new Set};n.reportErrors.forEach(d=>{wc(n,t,e,d,s,i,a,o,{})});for(let d of n.logicalTests)for(let c of d.attempts){let l={logicalTestId:d.logicalTestId,attemptId:c.attemptId};c.errors.forEach(u=>{wc(n,t,e,u,s,i,a,o,l)}),gm(n,t,e,c.steps,`${c.attemptId}.steps`,s,i,a,o,l);for(let u of["stdout","stderr"]){let p=c[u],f={artifactId:ve(n.runId,u,c.attemptId),channel:u,availability:p.length===0?"empty":"present",attemptId:c.attemptId,warnings:[]};r.push(f);let h=0;p.forEach((m,g)=>{let y=m.kind==="text"?Buffer.byteLength(m.text,"utf8"):Buffer.from(m.base64,"base64").byteLength,w=`${c.attemptId}.${u}[${g}]`;if(o.stdioChunks>=t.maxStdioChunks){ps(n,a,o,u,"stdio-chunk",t.maxStdioChunks,w),h+=y;return}if(o.stdioBytes+y>t.maxStdioBytes){ps(n,a,o,u,"stdio-byte",t.maxStdioBytes,w),h+=y;return}o.stdioChunks+=1,o.stdioBytes+=y;let v=TP(m),x=ce(v,u,w,t.sensitiveNames);i.push(...x.records);let R={type:"stdio",stream:u,chunk:g,startByte:h,endByte:h+y};h+=y,s.push({evidenceId:ge(n.runId,f.artifactId,"stdio-chunk",R,x.value),kind:"stdio-chunk",artifactId:f.artifactId,...l,locator:R,observation:x.value,availability:v.length===0?"empty":"present",redactionIds:x.records.map(S=>S.redactionId)})})}}return{artifacts:r,evidence:s,redactions:i,omissions:a,seeds:SP(n)}}var Im=ri(Qr(),1);import{dirname as EP,extname as Rm,join as bm}from"node:path/posix";var CP=new Set(["test","it","describe","suite","step","beforeEach","afterEach","beforeAll","afterAll"]),xm=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],NP=new Set([".js",".mjs",".cjs"]),OP=[".ts",".tsx",".mts",".cts"];function $P(n){return n.split("/").includes("node_modules")}function Xe(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.type=="string"}function fs(n,t,e=new Set){if(!e.has(n)){e.add(n),t(n);for(let r of Object.keys(n)){if(r==="loc")continue;let s=n[r];if(Array.isArray(s))for(let i of s)Xe(i)&&fs(i,t,e);else Xe(s)&&fs(s,t,e)}}}function gn(n){if(Xe(n)&&n.type==="Identifier")return typeof n.name=="string"?n.name:void 0}function sr(n){if(Xe(n)){if(n.type==="Identifier"&&typeof n.name=="string")return n.name;if(n.type==="StringLiteral"&&typeof n.value=="string")return n.value}}function Am(n){if(Xe(n)){if(n.type==="Identifier")return typeof n.name=="string"?n.name:void 0;if(n.type==="MemberExpression"){let t=Am(n.object),e=sr(n.property);return t===void 0||e===void 0?void 0:`${t}.${e}`}}}function DP(n){let t=Am(n.callee);if(t===void 0)return;let e=t.split(".").pop()??t;if(!CP.has(e))return;let s=(Array.isArray(n.arguments)?n.arguments:[])[0];if(!(!Xe(s)||s.type!=="StringLiteral"||typeof s.value!="string"))return`${t}("${s.value}")`}function Pm(n){switch(n.type){case"FunctionDeclaration":case"ClassDeclaration":case"TSInterfaceDeclaration":case"TSTypeAliasDeclaration":case"TSEnumDeclaration":case"TSModuleDeclaration":return gn(n.id);case"ClassMethod":case"ObjectMethod":case"ClassProperty":case"PropertyDefinition":return sr(n.key);case"VariableDeclarator":return gn(n.id);case"CallExpression":return DP(n);default:return}}function MP(n,t){let e=n.loc;return e==null?!1:e.start.line<=t&&e.end.line>=t}function LP(n,t){let e;return fs(n,r=>{let s=Pm(r);if(s===void 0||!MP(r,t))return;let i=r.loc;if(i==null)return;let a={name:s,startLine:i.start.line,endLine:i.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 _P(n){let t=Pm(n);return t!==void 0&&n.type!=="CallExpression"?[t]:n.type==="VariableDeclaration"&&Array.isArray(n.declarations)?n.declarations.map(e=>Xe(e)?gn(e.id):void 0).filter(e=>e!==void 0):[]}function jP(n,t){let e=Array.isArray(n.program)?[]:n.program?.body,r=Array.isArray(e)?e:[],s=[];for(let i of r){if(!Xe(i))continue;let a=i.loc;if(a==null)continue;if(i.type==="ExportDefaultDeclaration"&&t.has("default")){s.push({name:"default",startLine:a.start.line,endLine:a.end.line});continue}if(i.type==="ExportNamedDeclaration"&&Array.isArray(i.specifiers))for(let d of i.specifiers){if(!Xe(d))continue;let c=sr(d.exported);c!==void 0&&t.has(c)&&s.push({name:c,startLine:a.start.line,endLine:a.end.line})}let o=i.type==="ExportNamedDeclaration"&&Xe(i.declaration)?i.declaration:i;for(let d of _P(o))t.has(d)&&s.push({name:d,startLine:a.start.line,endLine:a.end.line})}return s}function FP(n){let t=[];return fs(n,e=>{if(e.type!=="ImportDeclaration"&&e.type!=="ExportNamedDeclaration"&&e.type!=="ExportAllDeclaration")return;let r=Xe(e.source)?e.source.value:void 0;if(typeof r!="string")return;let s=[],i;for(let a of Array.isArray(e.specifiers)?e.specifiers:[])if(Xe(a)){if(e.type==="ExportNamedDeclaration"){let o=sr(a.exported),d=sr(a.local);o!==void 0&&d!==void 0&&s.push({imported:d,local:o})}else if(a.type==="ImportDefaultSpecifier"){let o=gn(a.local);o!==void 0&&s.push({imported:"default",local:o})}else if(a.type==="ImportNamespaceSpecifier")i=gn(a.local);else if(a.type==="ImportSpecifier"){let o=sr(a.imported)??gn(a.local),d=gn(a.local);o!==void 0&&d!==void 0&&s.push({imported:o,local:d})}}t.push({specifier:r,bindings:s,...i===void 0?{}:{namespaceLocal:i},exportStar:e.type==="ExportAllDeclaration"})}),t}function vm(n,t,e){let r=new Set;return fs(n,s=>{let i=s.loc;i==null||i.end.line<t||i.start.line>e||s.type==="Identifier"&&typeof s.name=="string"&&r.add(s.name)}),r}function BP(n){let t=Rm(n).toLowerCase();return t===".tsx"?["typescript","jsx"]:[".ts",".mts",".cts"].includes(t)?["typescript"]:["jsx"]}var Sm=/\.[cm]?[jt]sx?$/i,VP=10;function HP(n,t){if(!Sm.test(t))return{};try{return{ast:(0,Im.parse)(n,{sourceType:"module",allowReturnOutsideFunction:!0,errorRecovery:!1,plugins:BP(t)})}}catch(e){return{error:e instanceof Error?e.message:"Source could not be parsed."}}}function zP(n,t){if(!n.startsWith("./")&&!n.startsWith("../"))return[];let e=bm(t,n),r=[e],s=Rm(e).toLowerCase();if(NP.has(s)){let i=e.slice(0,e.length-s.length);for(let a of OP)r.push(`${i}${a}`)}if(s===""){for(let i of xm)r.push(`${e}${i}`);for(let i of xm)r.push(bm(e,`index${i}`))}return r}function ct(n,t,e,r,s){n.omissions.push({omissionId:B("omi",["source",t,r,e]),channel:"source",reason:t,message:e,locator:r,...s===void 0?{}:{cap:s}})}async function Tm(n,t){let e=await ss(n.workspaceRoot,t);if(e.kind!=="authorized"){ct(n,e.kind==="unauthorized"?"unauthorized-path":e.kind,e.message,t);return}if($P(e.relativePath)){ct(n,"policy-disabled","Dependency source under node_modules is out of scope for evidence.",e.relativePath);return}let r=n.files.get(e.relativePath);if(r!==void 0)return r;if(n.files.size>=n.policy.maxSourceFiles){n.filesReported||(n.filesReported=!0,ct(n,"budget-exceeded",`Reached the ${n.policy.maxSourceFiles}-file source limit; later files were not read.`,e.relativePath,n.policy.maxSourceFiles));return}let s=await Q(n.workspaceRoot,e.relativePath,n.policy.maxArtifactBytes);if(s.kind!=="read"){let c=s.kind==="over-budget"?"budget-exceeded":s.kind==="unauthorized"?"unauthorized-path":s.kind;ct(n,c,s.message,e.relativePath);return}let i=Ve(s.bytes);if(i===void 0){ct(n,"unreadable","Source file is not valid UTF-8.",s.relativePath);return}let a=HP(i,s.relativePath);a.error!==void 0&&ct(n,"parse-failed",`Symbol boundaries are unavailable: ${a.error}`,s.relativePath);let o={artifactId:ve(n.runId,"source",s.relativePath),channel:"source",availability:"present",path:s.relativePath,sha256:s.sha256,warnings:a.error===void 0?[]:[a.error]},d={relativePath:s.relativePath,sha256:s.sha256,lines:i.split(/\r?\n/),ast:a.ast,artifact:o};return n.files.set(s.relativePath,d),n.artifacts.push(o),d}function km(n,t,e,r,s){let i=n.policy.maxSourceLinesPerFile,a=Math.max(1,e.startLine),o=Math.min(t.lines.length,e.endLine);if(o<a)return;o-a+1>i&&(o=a+i-1,ct(n,"budget-exceeded",`Symbol context in ${t.relativePath} was truncated to ${i} lines.`,`${t.relativePath}:${a}`,i));let d=`${t.relativePath}:${a}:${o}:${s.logicalTestId??""}:${s.attemptId??""}:${r}`;if(n.emitted.has(d))return;n.emitted.add(d);let c=t.lines.slice(a-1,o).join(`
47
- `),l=ce(c,"source",`${t.relativePath}:${a}-${o}`,n.policy.sensitiveNames),u=Buffer.byteLength(l.value,"utf8");if(n.emittedBytes+u>n.policy.maxSourceBytes){n.bytesReported||(n.bytesReported=!0,ct(n,"budget-exceeded",`Reached the ${n.policy.maxSourceBytes}-byte source limit; later ranges were not included.`,t.relativePath,n.policy.maxSourceBytes));return}n.emittedBytes+=u,n.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=`${r}
48
- ${l.value}`;n.evidence.push({evidenceId:ge(n.runId,t.artifact.artifactId,"source-range",f,h),kind:"source-range",artifactId:t.artifact.artifactId,...s,locator:f,observation:h,availability:"present",redactionIds:l.records.map(m=>m.redactionId)})}async function UP(n,t,e){for(let r of zP(t,e)){let s=await ss(n.workspaceRoot,r);if(s.kind==="authorized")return await Tm(n,s.relativePath)}ct(n,"unavailable",`Relative import ${t} did not resolve to a readable workspace file.`,e)}async function Em(n,t,e,r){let s={runId:n,policy:t,workspaceRoot:r,files:new Map,artifacts:[],evidence:[],redactions:[],omissions:[],emitted:new Set,traversed:new Set,emittedBytes:0,filesReported:!1,bytesReported:!1},i=new Set,a=[];for(let d of e){let c=`${d.file}:${d.line}:${d.logicalTestId??""}:${d.attemptId??""}:${d.origin}`;if(i.has(c))continue;i.add(c);let l=await Tm(s,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:LP(l.ast,d.line),f=Sm.test(l.relativePath)?Math.floor(t.maxSourceLinesPerFile/2):VP,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:vm(l.ast,h.startLine,h.endLine)}),km(s,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 FP(u.ast)){let f=new Set(p.bindings.filter(v=>l.referenced.has(v.local)).map(v=>v.imported));if(p.namespaceLocal!==void 0&&l.referenced.has(p.namespaceLocal)){ct(s,"policy-disabled",`Namespace import of ${p.specifier} was not expanded; only named symbols are followed.`,u.relativePath);continue}if(p.exportStar){ct(s,"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 UP(s,p.specifier,EP(u.relativePath));if(h===void 0||h.ast===void 0)continue;let m=l.linkage,g=`${h.relativePath}:${[...f].sort().join(",")}:${m.logicalTestId??""}:${m.attemptId??""}`;if(s.traversed.has(g))continue;s.traversed.add(g);let y=jP(h.ast,f),w=new Set;for(let v of y){for(let x of vm(h.ast,v.startLine,v.endLine))w.add(x);km(s,h,{startLine:v.startLine,endLine:v.endLine,symbol:v.name},`${h.relativePath} exports ${v.name}, imported by ${u.relativePath} (depth ${d})`,m)}c.some(v=>v.file===h&&v.linkage.attemptId===m.attemptId)||c.push({file:h,linkage:m,referenced:w})}}if(o=c,o.length===0)break}return{artifacts:s.artifacts,evidence:s.evidence,redactions:s.redactions,omissions:s.omissions}}var qP=["report","trace","stdout","stderr","screenshot","video","dom","accessibility","console","network","source","diff","probe"],GP=["trace","console","network","dom","accessibility"],KP=8,WP=12,JP=5,XP=/\b(?:getBy\w+|locator|frameLocator)\((?:[^()]|\([^()]*\))*\)/g,YP=[/Unable to locate element: \{"method":"[^"]+","selector":"((?:[^"\\]|\\.)+)"\}/g,/\b(By\.\w+: [^,\s)]+)/g,/Expected to find element: `([^`]+)`/g,/within the selector: '([^']+)'/g,/expected '<([a-z][\w-]*(?:[#.][\w-]+)*)>'/gi,/\bselector "([^"]+)"/g,/\belement \("([^"]+)"\)/g,/\${1,2}\(`([^`]+)`\)/g];function hs(n){return Buffer.byteLength(JSON.stringify(n),"utf8")}function Yi(n,t){return[...n].sort((e,r)=>t(e).localeCompare(t(r)))}function QP(n){return n.length===0?"unavailable":n.some(t=>t.availability==="present")?"present":n.some(t=>t.availability==="empty")?"empty":n.some(t=>t.availability==="unreadable")?"unreadable":"unavailable"}function ZP(n,t,e,r,s){let i=t.filter(l=>l.channel===n),a=new Set(i.map(l=>l.artifactId)),o=e.filter(l=>a.has(l.artifactId)),d=r.filter(l=>l.channel===n),c=s.filter(l=>l.channel===n);return{channel:n,availability:QP(i),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:hs({artifacts:i,evidence:o,redactions:c,omissions:d})}}function Cm(n,t,e){return{omissionId:B("omi",[n,t,"unavailable",e]),channel:t,reason:"unavailable",message:e,locator:n}}function Nm(n,t){return t?.[n.attachmentId]!==void 0?!0:n.name==="trace"&&n.contentType==="application/zip"}function ir(n){return n.attempts.filter(t=>t.status==="interrupted"?!0:n.status==="unexpected"?t.status!=="skipped":n.status==="flaky"?t.status!=="passed"&&t.status!=="skipped":!1)}function eS(n){return{...n,logicalTests:n.logicalTests.map(t=>({...t,attempts:ir(t)})).filter(t=>t.attempts.length>0)}}function tS(n,t){let e={expected:0,unexpected:0,flaky:0,skipped:0};for(let a of n.logicalTests)e[a.status]+=1;let r=t.logicalTests.reduce((a,o)=>a+o.attempts.length,0),s=[...new Set(n.logicalTests.map(a=>a.projectId))].length,i=n.artifact.formatVersion===void 0?"":` ${n.artifact.formatVersion}`;return[`${gt[n.framework]}${i} run of ${n.logicalTests.length} tests in ${s} project${s===1?"":"s"}`,`${e.expected} passed, ${e.unexpected} failed, ${e.flaky} flaky, ${e.skipped} skipped`,`evidence covers the ${r} failing attempt${r===1?"":"s"} of ${t.logicalTests.length} test${t.logicalTests.length===1?"":"s"}; passing tests are only counted.`].join("; ")}function ms(n){let t=n.errors.map(r=>`${r.message??""}
49
- ${r.stack??""}`),e=t.flatMap(r=>YP.flatMap(s=>[...r.matchAll(s)].map(i=>(i[1]??"").replace(/\\(.)/g,"$1"))));return[...new Set([...t.flatMap(r=>r.match(XP)??[]),...e.filter(r=>r!=="")])]}function nS(n,t,e,r,s){let i=n.attemptId===void 0?0:r.get(n.attemptId)??0;if(s.has(n.evidenceId))return re.afterFailure;switch(n.kind){case"error-field":case"run-summary":case"change-search":return re.failure;case"locator-suggestion":return re.failedCall+.95-Math.min(.5,i/1e3);case"page-snapshot":case"dom-subtree":case"dom-candidates":case"accessibility-node":{let o=n.kind==="accessibility-node"?.5:.9;return i<JP?re.failedCall+o-i/1e3:re.context+o-Math.min(.8,i/1e3)}default:break}let a=t.get(n.evidenceId);if(a!==void 0)return a;switch(n.kind){case"stack-frame":return/node_modules|node:internal/.test(n.observation)?re.ordinary:re.failedCall;case"source-range":{let o=e.get(n.evidenceId)??0;return re.significant-Math.min(.9,o/100)}case"diff-hunk":return re.failedCall+.9;case"step":return re.context;default:return re.ordinary}}async function Qi(n,t,e){let r=Ud(e);if(r!==void 0)return{kind:"invalid-policy",message:r};if(e.workspaceRoot!==n.workspace.root)return{kind:"invalid-policy",message:"Evidence policy workspaceRoot must match the normalized run workspace root."};let s=t.artifactRoot??n.workspace.root,i=eS(n),a=wm(i,e),o=[...a.artifacts],d=[...a.evidence],c=[...a.redactions],l=[...a.omissions],u=[...a.seeds],p=new Map,f=a.artifacts.find(E=>E.channel==="report");if(f!==void 0&&n.logicalTests.length>0){let E={type:"report-field",path:"stats"},M=tS(n,i);d.push({evidenceId:ge(n.runId,f.artifactId,"run-summary",E,M),kind:"run-summary",artifactId:f.artifactId,locator:E,observation:M,availability:"present",redactionIds:[]})}for(let E of i.logicalTests)for(let M of E.attempts){let A=0,C=0,P=0,I=[...ms(M)];for(let $ of M.attachments){if(!Nm($,t.tracePaths))continue;let D=t.tracePaths?.[$.attachmentId]??$.path;if(D===void 0){l.push(Cm(M.attemptId,"trace","Trace attachment supplied no path; inline trace bodies are not read."));continue}A+=1;let k=await Lh(n.runId,e,{attachmentId:$.attachmentId,logicalTestId:E.logicalTestId,attemptId:M.attemptId,path:D,info:{...n.artifact.formatVersion===void 0?{}:{producerVersion:n.artifact.formatVersion},format:"playwright-trace-zip"}},s);o.push(...k.artifacts),d.push(...k.evidence),c.push(...k.redactions),l.push(...k.omissions),u.push(...k.seeds),I.push(...k.failedSelectors);for(let[T,_]of k.priorities)p.set(T,_)}for(let $ of M.attachments){if(!ac($))continue;C+=1;let D=await Fh(n.runId,e,{logicalTestId:E.logicalTestId,attemptId:M.attemptId,attachment:$,focus:I},s);o.push(...D.artifacts),d.push(...D.evidence),c.push(...D.redactions),l.push(...D.omissions),I.push(...D.failedSelectors);for(let[k,T]of D.priorities)p.set(k,T)}for(let $ of M.attachments){if(Nm($,t.tracePaths)||ac($))continue;if(um($)){P+=1;let k=await pm(n.runId,e,{logicalTestId:E.logicalTestId,attemptId:M.attemptId,attachment:$,focus:I},s);o.push(...k.artifacts),d.push(...k.evidence),c.push(...k.redactions),l.push(...k.omissions);continue}let D=await dm(n.runId,e,{logicalTestId:E.logicalTestId,attemptId:M.attemptId,attachment:$},s);o.push(...D.artifacts),d.push(...D.evidence),c.push(...D.redactions),l.push(...D.omissions)}if(A===0&&C===0){let $=n.framework==="playwright"?"Attempt produced no trace attachment.":"Attempt has no KwikQA failure capture; run `kwikqa analyze --capture` to record the page.";for(let D of GP)D==="accessibility"&&P>0||l.push(Cm(M.attemptId,D,$))}}if(t.probePath!==void 0){let E=await hm(i,e,t.probePath,n.workspace.root);o.push(...E.artifacts),d.push(...E.evidence),c.push(...E.redactions),l.push(...E.omissions)}let h=await Em(n.runId,e,await mm(u,n.workspace.root),n.workspace.root);o.push(...h.artifacts),d.push(...h.evidence),c.push(...h.redactions),l.push(...h.omissions);let m=new Map(h.evidence.map((E,M)=>[E.evidenceId,M])),g=h.artifacts.map(E=>E.path).filter(E=>E!==void 0),y=await Bh(n.runId,e,g,{authorized:t.includeCurrentDiff===!0,workspaceRoot:n.workspace.root,...n.workspace.gitRoot===void 0?{}:{gitRoot:n.workspace.gitRoot}});o.push(...y.artifacts),d.push(...y.evidence),c.push(...y.redactions),l.push(...y.omissions);let w=await im(n.runId,n.createdAt,e,nm(i.logicalTests.flatMap(E=>E.attempts),ms,d.filter(E=>E.kind==="network-event").map(E=>E.observation)),{authorized:t.includeChangeHistory===!0,workspaceRoot:n.workspace.root,...n.workspace.gitRoot===void 0?{}:{gitRoot:n.workspace.gitRoot}});o.push(...w.artifacts),d.push(...w.evidence),c.push(...w.redactions),l.push(...w.omissions);let v=Yi(o,E=>E.artifactId),x=new Map(v.map(E=>[E.artifactId,E.channel])),R=(E,M,A)=>{let C=Yi(E,T=>T.evidenceId),P=Yi(M,T=>T.redactionId),I=Yi(A,T=>T.omissionId),$=qP.map(T=>ZP(T,v,C,I,P)),D=T=>{let _={schemaVersion:"1.2",runId:n.runId,framework:n.framework,createdAt:n.createdAt,workspace:n.workspace,sourceHashes:n.sourceHashes,policy:e,artifacts:v,evidence:C,redactions:P,omissions:I,accounting:$,totals:{artifacts:v.length,evidence:C.length,redactions:P.length,omissions:I.length,serializedBytes:T}};return{..._,packetHash:Yn(_)}},k=D(0);for(let T=0;T<KP;T+=1){let _=hs(k);if(k.totals.serializedBytes===_)break;k=D(_)}return k},S=R(d,c,l),N=hs(S);if(N>e.maxPacketBytes){let E=new Set(d.flatMap(k=>k.redactionIds)),M=new Map(d.map(k=>[k.evidenceId,k])),A=new Map(i.logicalTests.flatMap(k=>k.attempts).map((k,T)=>[k.attemptId,T])),C=new Set,P=new Set;for(let k of[...d].sort((T,_)=>(A.get(T.attemptId??"")??0)-(A.get(_.attemptId??"")??0)||T.evidenceId.localeCompare(_.evidenceId))){if(k.kind==="error-field"||k.kind==="run-summary"||k.kind==="change-search")continue;let T=`${k.kind}
50
- ${k.observation}`;P.has(T)?C.add(k.evidenceId):P.add(T)}let I=d.map(k=>({item:k,priority:nS(k,p,m,A,C)})).filter(k=>k.priority<re.failure).sort((k,T)=>k.priority-T.priority||k.item.evidenceId.localeCompare(T.item.evidenceId)),$=new Set,D=0;for(let k=0;k<WP&&N>e.maxPacketBytes;k+=1){let T=N-e.maxPacketBytes*.97;for(;T>0&&D<I.length;){let X=I[D++];if(X===void 0)break;$.add(X.item.evidenceId),T-=hs(X.item)+64}let _=d.filter(X=>!$.has(X.evidenceId)),U=new Set(_.flatMap(X=>X.redactionIds)),K=c.filter(X=>!E.has(X.redactionId)||U.has(X.redactionId)),te=new Map;for(let X of $){let Ie=M.get(X),Te=Ie===void 0?void 0:x.get(Ie.artifactId);Te!==void 0&&te.set(Te,(te.get(Te)??0)+1)}let le=[...te.entries()].map(([X,Ie])=>{let Te=`Dropped ${Ie} lower-priority ${X} observation${Ie===1?"":"s"} to fit the ${e.maxPacketBytes}-byte packet budget; observations closest to the failure were kept.`;return{omissionId:B("omi",[n.runId,X,"budget-exceeded","packet",Te]),channel:X,reason:"budget-exceeded",message:Te,locator:"packet",cap:e.maxPacketBytes}});if(S=R(_,K,[...l,...le]),N=hs(S),D>=I.length)break}}return N>e.maxPacketBytes?{kind:"budget-exceeded",message:`Even the evidence closest to the failure is ${N} bytes, exceeding maxPacketBytes=${e.maxPacketBytes}; raise the explicit policy limit or narrow the authorized inputs.`}:{kind:"built",packet:S}}import{spawn as Lm}from"node:child_process";var rS=["KWIKQA_TOKEN","KWIKQA_API_URL","OPENROUTER_API_KEY"],$m=256*1024,sS=8e3;function Zi(n,t={}){let e={...n,...t};for(let r of rS)delete e[r];return e}function Dm(n){return n.pid===void 0||n.exitCode!==null||n.signalCode!==null}function Mm(n,t){if(n.pid!==void 0)try{process.kill(-n.pid,t)}catch{n.kill(t)}}async function iS(n,t){if(!Dm(n)){if(process.platform==="win32"){await new Promise(e=>{let r=Lm("taskkill",["/pid",String(n.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});r.on("exit",()=>e()),r.on("error",()=>e())});return}Mm(n,"SIGINT"),await Promise.race([t,new Promise(e=>setTimeout(e,sS))]),Dm(n)||Mm(n,"SIGKILL")}}function bc(n,t,e){let r=Lm(n,[...t],{cwd:e.cwd,env:e.env,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),s="",i=o=>{s+=o.toString("utf8"),s.length>$m&&(s=s.slice(-$m))};r.stdout?.on("data",i),r.stderr?.on("data",i);let a=new Promise(o=>{r.on("exit",d=>o(d??void 0)),r.on("error",()=>o(void 0))});return{child:r,output:()=>s,exited:a,stop:async()=>{await iS(r,a),await Promise.race([a,new Promise(o=>setTimeout(o,2e3))])}}}async function ea(n,t,e){let r=bc(n,t,e),s=!1,i=setTimeout(()=>{s=!0,r.stop()},e.timeoutMs),a=await r.exited;return clearTimeout(i),{...a===void 0?{}:{exitCode:a},timedOut:s,output:r.output()}}async function _m(n,t,e){let r=Date.now()+e,s=!1;for(n.exited.then(()=>{s=!0});Date.now()<r;){let i=t.exec(n.output());if(i!==null)return i;if(s)return t.exec(n.output())??void 0;await new Promise(a=>setTimeout(a,100))}}var Bm="1.0",xc=[1,59],uS=5,pS=6e4,fS=3e4,hS=12e4,mS=new Set(["generic","text","list","group","none","presentation"]),yS=new Set(["banner","navigation","main","contentinfo","complementary","region","form","search"]);function vc(n){let[t=0,e=0]=n.split(".").map(r=>Number.parseInt(r,10));return t>xc[0]||t===xc[0]&&e>=xc[1]}async function Fm(n){try{let t=JSON.parse(await aS(wn(n,"package.json"),"utf8"));return t.name==="@playwright/cli"&&typeof t.version=="string"?t.version:void 0}catch{return}}async function Vm(n,t){try{let r=dS(wn(n,"package.json")).resolve("@playwright/cli/package.json"),s=jm(r),i=await Fm(s);if(i!==void 0)return{entryPath:wn(s,"playwright-cli.js"),version:i,source:"project"}}catch{}let e=process.platform==="win32"?["playwright-cli.cmd"]:["playwright-cli"];for(let r of(t.PATH??"").split(cS).filter(Boolean))for(let s of e){let i=wn(r,s);try{let a=process.platform==="win32"?wn(r,"node_modules","@playwright","cli"):jm(await oS(i)),o=await Fm(a);if(o!==void 0)return{entryPath:wn(a,"playwright-cli.js"),version:o,source:"path"}}catch{}}}function kc(n){return n.split(/\r?\n/).filter(t=>!/[║╔╚═]/.test(t)).join(`
51
- `)}function Hm(n){return/```yaml\r?\n([\s\S]*?)\r?\n```/.exec(kc(n))?.[1]?.split(/\r?\n/)}function zm(n){let t=kc(n).split(/\r?\n/),e=t.findIndex(r=>r.trim()==="### Result");if(!(e<0))return t.slice(e+1).map(r=>r.trim()).find(r=>r!==""&&!r.startsWith("###"))}function gS(n){return/getByRole\(\s*['"]([\w-]+)['"]/.exec(n??"")?.[1]?.toLowerCase()}function Um(n){return n.trim().replace(/^-\s+/,"").replace(/\s\[(?:ref|cursor)=[^\]]+\]/g,"").replace(/:$/,"").trim()}function qm(n,t,e=uS){let r=Qn(t??""),s=gS(t);return n.map((a,o)=>{let d=/\[ref=(e\d+)\]/.exec(a)?.[1],c=Um(a),l=/^([\w-]+)/.exec(c)?.[1]?.toLowerCase()??"";if(d===void 0||mS.has(l))return;let u=c.toLowerCase(),p=r.filter(f=>u.includes(f)).length*3+(s!==void 0&&l===s?2:0);if(!(yS.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 Gm(n){let{target:t}=n,e=[],r={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{...r,candidates:[],issues:["The report does not say which line failed."]};let s=Zi(n.env,{PLAYWRIGHT_HTML_OPEN:"never"}),i=bc(n.playwright.executable,[...n.playwright.nodeArguments,"test",`${t.file}:${t.line}`,...t.project===void 0?[]:[`--project=${t.project}`],...n.configPath===void 0?[]:[`--config=${n.configPath}`],"--debug=cli","--timeout=0","--retries=0","--workers=1","--reporter=line"],{cwd:n.workspaceRoot,env:s}),a=(c,l=fS)=>ea(process.execPath,[n.cli.entryPath,...c],{cwd:n.scratchDirectory,env:s,timeoutMs:l}),o,d=[];try{if(o=(await _m(i,/playwright-cli attach ([\w-]+)/,pS))?.[1],o===void 0)return e.push("The test did not stop in the debugger."),{...r,candidates:d,issues:e};if((await a(["attach",o])).exitCode!==0)return e.push("Playwright CLI could not attach to the paused test."),{...r,candidates:d,issues:e};let u=lS(t.file)?t.file:wn(n.workspaceRoot,t.file),p=await a([`-s=${o}`,"pause-at",`${u}:${t.failingLine}`],hS);if(p.exitCode!==0||!/### Paused/.test(p.output))return e.push(`The test did not reach line ${t.failingLine}.`),{...r,candidates:d,issues:e};let f=Hm((await a([`-s=${o}`,"snapshot"])).output);if(f===void 0)return e.push("Playwright CLI returned no page snapshot."),{...r,candidates:d,issues:e};for(let h of qm(f,t.locator)){let m=zm((await a([`-s=${o}`,"generate-locator",h.ref])).output);m!==void 0&&d.push({element:h.element,locator:m})}return d.length===0&&e.push("No locator could be generated for any candidate."),{...r,candidates:d,issues:e}}catch(c){return e.push(`The probe stopped: ${c instanceof Error?c.message:String(c)}`),{...r,candidates:d,issues:e}}finally{o!==void 0&&await a([`-s=${o}`,"detach"],1e4).catch(()=>{}),await i.stop()}}import{mkdir as ig,rm as sg}from"node:fs/promises";import{dirname as X0,join as mr,relative as Y0,resolve as Q0}from"node:path";import{createHash as wS}from"node:crypto";function Rc(n,t){if(n===null||typeof n=="string"||typeof n=="boolean")return n;if(typeof n=="number"){if(!Number.isFinite(n))throw new TypeError("canonical JSON cannot contain non-finite numbers");return n}if(Array.isArray(n))return n.map(e=>Rc(e,t));if(typeof n!="object")throw new TypeError(`canonical JSON cannot contain ${typeof n}`);if(t.has(n))throw new TypeError("canonical JSON cannot contain cycles");t.add(n);try{let e=n,r={};for(let s of Object.keys(e).sort()){let i=e[s];if(i===void 0)throw new TypeError(`canonical JSON cannot contain undefined at ${JSON.stringify(s)}`);r[s]=Rc(i,t)}return r}finally{t.delete(n)}}function pe(n){return JSON.stringify(Rc(n,new Set))}function L(n){return wS("sha256").update(pe(n),"utf8").digest("hex")}function Km(n){let t=new Map;for(let e of n){if(t.has(e.logicalTestId))throw new Error("Logical test observation is duplicated.");t.set(e.logicalTestId,e.status)}return t}function Wm(n){return n!==void 0&&n!=="passed"}function Ic(n){let t=new Set(n.targetLogicalTestIds);if(t.size===0||t.size!==n.targetLogicalTestIds.length)throw new Error("Target logical test identities must be unique and nonempty.");let e=Km(n.baseline),r=[],s=new Set;for(let l of n.blockingReasons??[]){if(l.length===0)throw new Error("Blocking validation reasons must be nonempty.");r.push({classification:"incomplete-check",message:l})}for(let l of[...n.commands].sort((u,p)=>u.commandId.localeCompare(p.commandId))){if(!l.required)continue;if(l.timing==="post-patch")for(let p of l.expectedLogicalTestIds)s.add(p);if(!l.fresh){r.push({classification:"incomplete-check",commandId:l.commandId,message:"Required command evidence is not fresh."});continue}if(l.status==="unavailable"){r.push({classification:"unavailable-check",commandId:l.commandId,message:"Required command was unavailable."});continue}if(l.status==="incomplete"){r.push({classification:"incomplete-check",commandId:l.commandId,message:"Required command did not produce authoritative evidence."});continue}if(l.timing==="baseline")continue;let u=Km(l.observations);for(let p of l.expectedLogicalTestIds){let f=u.get(p);if(f===void 0){r.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)){r.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"&&r.push({classification:Wm(h)?"unchanged-pre-existing-failure":"newly-introduced-failure",logicalTestId:p,commandId:l.commandId,message:Wm(h)?"An affected test remains non-passing from its baseline.":"An affected test newly became non-passing."})}}for(let l of[...t].sort())s.has(l)||r.push({classification:"incomplete-check",logicalTestId:l,message:"No fresh focused evidence covers the target logical test."});let i=r.sort((l,u)=>`${l.classification}\0${l.logicalTestId??""}\0${l.commandId??""}`.localeCompare(`${u.classification}\0${u.logicalTestId??""}\0${u.commandId??""}`)),a=new Set(i.map(l=>l.classification)),o=[...t].every(l=>i.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")||n.commands.some(l=>l.required&&l.status==="failed")?"failed":"passed",classifications:i};return{...c,summaryHash:L(c)}}var na="1.1",Ac="1.0",ra="1.1";var sa="1.0",Ht=/^[a-z][a-z0-9_-]{0,63}$/,ar=32*1024*1024,bn=16*1024*1024,gs="report.json",Xm=["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 or(n){return Xm.includes(n)}var ke=/^[a-f0-9]{64}$/,ws=Ht;function $e(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Ym(n){return Array.isArray(n)&&n.every(t=>typeof t=="string")}function ys(n,t=!0){return Ym(n)&&(t||n.length>0)&&n.every(e=>e.length>0&&!e.includes("\0"))&&new Set(n).size===n.length}function Ce(n,t){let e=Object.keys(n).sort(),r=[...t].sort();return e.length===r.length&&e.every((s,i)=>s===r[i])}function bS(n){if(!$e(n))return!1;let t=["outputDirectory","maxArtifacts","maxArtifactBytes"];return n.reportFile!==void 0&&t.push("reportFile"),Ce(n,t)&&typeof n.outputDirectory=="string"&&n.outputDirectory.length>0&&!n.outputDirectory.includes("\0")&&(n.reportFile===void 0||typeof n.reportFile=="string"&&n.reportFile.length>0&&!n.reportFile.includes("\0"))&&Number.isInteger(n.maxArtifacts)&&n.maxArtifacts>0&&Number.isInteger(n.maxArtifactBytes)&&n.maxArtifactBytes>0&&n.maxArtifactBytes<=ar}function xS(n){if(!$e(n))return!1;let t=["kind","path","detail"];return n.sha256!==void 0&&t.push("sha256"),Ce(n,t)&&["package-root","package-manifest","package-entry","configuration","pnp-loader","source-graph","scope-escalation"].includes(String(n.kind))&&typeof n.path=="string"&&n.path.length>0&&!n.path.includes("\0")&&typeof n.detail=="string"&&n.detail.length>0&&(n.sha256===void 0||typeof n.sha256=="string"&&ke.test(n.sha256))}function Qm(n){return!$e(n)||!ws.test(String(n.commandId))||!Ce(n,["commandId","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","artifactPolicy","resolutionEvidence"])||!(or(String(n.kind))||["parse","format","typecheck","lint"].includes(String(n.kind)))||n.timing!=="baseline"&&n.timing!=="post-patch"||typeof n.executable!="string"||n.executable.length===0||!Ym(n.args)||n.args.some(t=>t.includes("\0"))||typeof n.workingDirectory!="string"||n.workingDirectory.length===0||n.workingDirectory.includes("\0")||!Number.isInteger(n.timeoutMs)||n.timeoutMs<=0||n.required!==!0||typeof n.purpose!="string"||n.purpose.length===0||!ys(n.logicalTestIds)||!ys(n.projectIds)||!$e(n.environmentDelta)||!bS(n.artifactPolicy)||!Array.isArray(n.resolutionEvidence)||!n.resolutionEvidence.every(xS)?!1:Object.entries(n.environmentDelta).every(([t,e])=>/^[A-Z][A-Z0-9_]*$/.test(t)&&typeof e=="string"&&!e.includes("\0"))}function Pc(n){return $e(n)&&Ce(n,["path","sourceSha256","resultSha256"])&&typeof n.path=="string"&&n.path.length>0&&!n.path.includes("\0")&&typeof n.sourceSha256=="string"&&ke.test(n.sourceSha256)&&typeof n.resultSha256=="string"&&ke.test(n.resultSha256)}function vS(n){return $e(n)&&Ce(n,["baselineId","commandId","logicalTestIds","reason"])&&/^baseline_[a-f0-9]{24}$/.test(String(n.baselineId))&&ws.test(String(n.commandId))&&ys(n.logicalTestIds,!1)&&typeof n.reason=="string"&&n.reason.length>0}function kS(n){if(!$e(n))return!1;let t=["code","message"];return n.path!==void 0&&t.push("path"),Ce(n,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(n.code))&&typeof n.message=="string"&&n.message.length>0&&(n.path===void 0||typeof n.path=="string"&&!n.path.includes("\0"))}function Zm(n){return L({purpose:"kwikqa-validation-baseline",...n})}function ia(n){return L({purpose:"kwikqa-validation-run",...n})}function ta(n){return typeof n=="string"&&n.length>0&&Number.isFinite(Date.parse(n))}function RS(n){if(!$e(n)||typeof n.kind!="string")return!1;if(n.kind==="exit")return Ce(n,["kind","exitCode"])&&Number.isInteger(n.exitCode);if(n.kind==="signal")return Ce(n,["kind","signal"])&&typeof n.signal=="string";if(n.kind==="spawn-error"){let t=["kind",...n.code===void 0?[]:["code"]];return Ce(n,t)&&(n.code===void 0||typeof n.code=="string")}return(n.kind==="timeout"||n.kind==="cancelled")&&Ce(n,["kind"])}function Jm(n){return $e(n)&&Ce(n,["path","sha256","storedSha256","observedBytes","storedBytes","truncated","redacted"])&&typeof n.path=="string"&&n.path.length>0&&typeof n.sha256=="string"&&ke.test(n.sha256)&&typeof n.storedSha256=="string"&&ke.test(n.storedSha256)&&Number.isInteger(n.observedBytes)&&n.observedBytes>=0&&Number.isInteger(n.storedBytes)&&n.storedBytes>=0&&typeof n.truncated=="boolean"&&typeof n.redacted=="boolean"}function IS(n){return $e(n)&&Ce(n,["path","sha256","bytes"])&&typeof n.path=="string"&&n.path.length>0&&typeof n.sha256=="string"&&ke.test(n.sha256)&&Number.isInteger(n.bytes)&&n.bytes>=0}function Sc(n){if(!Tc(n))throw new Error("Validation command record is malformed or failed integrity validation.");return n}function AS(n){if(!$e(n))return!1;let t=["classification",...n.logicalTestId===void 0?[]:["logicalTestId"],...n.commandId===void 0?[]:["commandId"],"message"];return Ce(n,t)&&["fixed-target-failure","still-failing-target","unchanged-pre-existing-failure","newly-introduced-failure","unavailable-check","incomplete-check"].includes(String(n.classification))&&(n.logicalTestId===void 0||typeof n.logicalTestId=="string"&&n.logicalTestId.length>0)&&(n.commandId===void 0||typeof n.commandId=="string"&&ws.test(n.commandId))&&typeof n.message=="string"&&n.message.length>0}function Tc(n){if(!$e(n))return!1;let t=n,{recordHash:e,...r}=t;return Ce(n,["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===Ac&&/^vld_[a-f0-9]{24}$/.test(t.validationRunId)&&ws.test(t.commandId)&&ke.test(t.commandHash)&&ke.test(t.planHash)&&t.required===!0&&Qm({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:[]})&&ta(t.startedAt)&&Number.isInteger(t.durationMs)&&t.durationMs>=0&&RS(t.termination)&&Jm(t.stdout)&&Jm(t.stderr)&&Array.isArray(t.artifacts)&&t.artifacts.every(IS)&&["blocked","passed","failed","unavailable","incomplete"].includes(t.status)&&ke.test(e)&&L(r)===e}function bs(n){if(!$e(n))throw new Error("Baseline manifest is not an object.");let t=n,{baselineHash:e,...r}=t;if(!Ce(n,["schemaVersion","planHash","repositoryFingerprint","targetHashes","commandRecords","logicalTestOutcomes","capturedAt","baselineHash"])||t.schemaVersion!==Ac||!ke.test(t.planHash)||!ke.test(t.repositoryFingerprint)||!Array.isArray(t.targetHashes)||!t.targetHashes.every(Pc)||!Array.isArray(t.commandRecords)||!t.commandRecords.every(Tc)||!$e(t.logicalTestOutcomes)||!Object.entries(t.logicalTestOutcomes).every(([s,i])=>s.length>0&&typeof i=="string"&&["passed","failed","skipped","interrupted"].includes(i))||!ta(t.capturedAt)||!ke.test(e)||Zm(r)!==e)throw new Error("Baseline manifest is malformed or failed integrity validation.");return t}function zt(n){if(!$e(n))throw new Error("Validation run manifest is not an object.");let t=n,{manifestHash:e,...r}=t;if(!Ce(n,["schemaVersion","validationRunId","transactionId","planHash","repositoryFingerprint","targetHashes","requiredCommandIds","status","commandRecords","classifications","startedAt","completedAt","manifestHash"])||t.schemaVersion!==ra||!/^vld_[a-f0-9]{24}$/.test(t.validationRunId)||!/^txn_[a-f0-9]{24}$/.test(t.transactionId)||!ke.test(t.planHash)||!ke.test(t.repositoryFingerprint)||!Array.isArray(t.targetHashes)||!t.targetHashes.every(Pc)||!ys(t.requiredCommandIds,!1)||!t.requiredCommandIds.every(s=>ws.test(s))||!Array.isArray(t.commandRecords)||!t.commandRecords.every(Tc)||!Array.isArray(t.classifications)||!t.classifications.every(AS)||!["blocked","passed","failed","unavailable","incomplete"].includes(t.status)||!ta(t.startedAt)||!ta(t.completedAt)||Date.parse(t.completedAt)<Date.parse(t.startedAt)||!ke.test(e)||ia(r)!==e)throw new Error("Validation run manifest is malformed or failed integrity validation.");if(new Set(t.targetHashes.map(s=>s.path)).size!==t.targetHashes.length||new Set(t.commandRecords.map(s=>s.commandId)).size!==t.commandRecords.length||t.commandRecords.some(s=>s.validationRunId!==t.validationRunId||s.planHash!==t.planHash))throw new Error("Validation run manifest contains inconsistent evidence.");if(!PS(t))throw new Error("Validation run manifest status is inconsistent with its evidence.");return t}function PS(n){let t=new Set(n.requiredCommandIds),e=new Set(n.commandRecords.map(s=>s.commandId)),r=new Set(n.classifications.map(s=>s.classification));if(n.commandRecords.some(s=>!t.has(s.commandId)||s.timing!=="post-patch")||n.requiredCommandIds.some(s=>!e.has(s)&&!n.classifications.some(i=>i.classification==="incomplete-check"&&i.commandId===s)))return!1;switch(n.status){case"passed":return n.classifications.length>0&&[...r].every(s=>s==="fixed-target-failure")&&e.size===t.size&&n.commandRecords.every(s=>s.status==="passed");case"incomplete":return r.has("incomplete-check");case"unavailable":return!r.has("incomplete-check")&&r.has("unavailable-check");case"failed":return!r.has("incomplete-check")&&!r.has("unavailable-check");default:return!0}}function aa(n){return L({purpose:"kwikqa-resolved-validation-plan",...n})}function xn(n){if(!$e(n))throw new Error("Resolved validation plan is not an object.");if(!Ce(n,["schemaVersion","policyVersion","status",...n.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=n,{planHash:e,...r}=t;if(t.schemaVersion!==na||t.policyVersion!==sa||t.status!=="resolved"&&t.status!=="unavailable"||!ke.test(t.proposalHash)||!ys(t.targetLogicalTestIds,!1)||!ke.test(t.advisoryPlanHash)||!ke.test(t.repositoryFingerprint)||!Array.isArray(t.commands)||!t.commands.every(Qm)||t.transactionId!==void 0&&!/^txn_[a-f0-9]{24}$/.test(t.transactionId)||!Array.isArray(t.targetHashes)||!t.targetHashes.every(Pc)||!Array.isArray(t.baselineRequirements)||!t.baselineRequirements.every(vS)||!Array.isArray(t.unresolvedReasons)||!t.unresolvedReasons.every(kS)||!ke.test(e)||aa(r)!==e)throw new Error("Resolved validation plan is malformed or failed integrity validation.");if(new Set(t.commands.map(i=>i.commandId)).size!==t.commands.length)throw new Error("Resolved validation plan contains duplicate command ids.");if(new Set(t.targetHashes.map(i=>i.path)).size!==t.targetHashes.length)throw new Error("Resolved validation plan contains duplicate targets.");if(new Set(t.baselineRequirements.map(i=>i.baselineId)).size!==t.baselineRequirements.length)throw new Error("Resolved validation plan contains duplicate baseline ids.");let s=new Map(t.commands.map(i=>[i.commandId,i]));if(t.baselineRequirements.some(i=>{let a=s.get(i.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 sy=ri(Qr(),1);import{readdir as SS,realpath as ny}from"node:fs/promises";import{extname as TS,isAbsolute as ry,join as ES,relative as CS,resolve as NS,sep as ey}from"node:path";import{dirname as OS,extname as Oc,join as ty}from"node:path/posix";var Ec=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],iy=new Set(Ec),$S=new Set([".js",".mjs",".cjs"]),DS=[".ts",".tsx",".mts",".cts"],MS=/(?:^|\/)(?:[^/]+\.)?(?:spec|test|cy|e2e)\.(?:[cm]?[jt]sx?)$/i,LS=new Set([".git",".kwikqa","node_modules",".yarn",".pnpm-store","coverage","dist","build","out","test-results","playwright-report"]);function xs(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.type=="string"}function Cc(n,t,e=new Set){if(!e.has(n)){e.add(n),t(n);for(let[r,s]of Object.entries(n))if(r!=="loc")if(Array.isArray(s))for(let i of s)xs(i)&&Cc(i,t,e);else xs(s)&&Cc(s,t,e)}}function _S(n){let t=Oc(n).toLowerCase();return t===".tsx"?["typescript","jsx"]:[".ts",".mts",".cts"].includes(t)?["typescript"]:["jsx"]}function oa(n){return xs(n)&&n.type==="StringLiteral"&&typeof n.value=="string"?n.value:void 0}function jS(n,t){try{let e=(0,sy.parse)(n,{sourceType:"unambiguous",allowReturnOutsideFunction:!0,errorRecovery:!1,plugins:_S(t)}),r=new Set,s=!1;return Cc(e,i=>{if(i.type==="ImportDeclaration"||i.type==="ExportNamedDeclaration"||i.type==="ExportAllDeclaration"){let c=oa(i.source);c!==void 0&&r.add(c),i.type==="ExportAllDeclaration"&&(s=!0);return}if(i.type==="ImportExpression"){let c=oa(i.source);c===void 0?s=!0:r.add(c);return}if(i.type!=="CallExpression")return;let a=i.callee,o=Array.isArray(i.arguments)?i.arguments:[];if(xs(a)&&a.type==="Import"){let c=oa(o[0]);c===void 0?s=!0:r.add(c);return}if(!xs(a)||a.type!=="Identifier"||a.name!=="require")return;let d=oa(o[0]);d===void 0?s=!0:r.add(d)}),{imports:[...r].sort(),ambiguous:s}}catch{return{code:"parse-failed",message:"Source could not be parsed for validation discovery.",path:t}}}function Nc(n){return n.length===0||n.includes("\0")||n.includes("\\")||ry(n)?!1:n.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function FS(n,t){return n.split("/").some(r=>LS.has(r))?!0:t.some(r=>n===r||n.startsWith(`${r}/`))}function BS(n,t){let e=CS(n,t);if(!(e===""||e===".."||e.startsWith(`..${ey}`)||ry(e)))return e.split(ey).join("/")}async function VS(n,t,e){let r=await ny(n),s=[],i=!1;async function a(o){if(i)return;let d=(await SS(o,{withFileTypes:!0})).sort((c,l)=>c.name.localeCompare(l.name,"en"));for(let c of d){if(c.isSymbolicLink())continue;let l=ES(o,c.name),u=BS(r,l);if(!(u===void 0||FS(u,t))){if(c.isDirectory())await a(l);else if(c.isFile()&&iy.has(TS(c.name).toLowerCase())){if(s.length>=e){i=!0;return}s.push(u)}}}}return await a(r),{files:s.sort(),exhausted:i}}function HS(n,t){if(!n.startsWith("./")&&!n.startsWith("../"))return[];let e=ty(t,n),r=[e],s=Oc(e).toLowerCase();if($S.has(s)){let i=e.slice(0,e.length-s.length);for(let a of DS)r.push(`${i}${a}`)}if(s===""){for(let i of Ec)r.push(`${e}${i}`);for(let i of Ec)r.push(ty(e,`index${i}`))}return r.filter(Nc)}function zS(n,t,e){return HS(n,OS(t)).find(r=>e.has(r))}async function US(n){let t=[],e=await VS(n.workspaceRoot,n.ignoredPaths??[],n.limits.maxFiles);e.exhausted&&t.push({code:"budget-exceeded",message:"Source file discovery exceeded its file limit."});let r=new Set(e.files),s=new Map,i=0,a=0,o=!e.exhausted,d=e.exhausted;for(let u of e.files){let p=await Q(n.workspaceRoot,u,n.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(i+=p.bytes.byteLength,i>n.limits.maxTotalBytes){o=!1,d=!0,t.push({code:"budget-exceeded",message:"Source discovery exceeded its total byte limit."});break}let f=jS(new TextDecoder("utf-8",{fatal:!0}).decode(p.bytes),u);if("code"in f){o=!1,t.push(f),s.set(u,{path:u,imports:[],ambiguous:!0});continue}let h=[],m=f.ambiguous;for(let g of f.imports){if(!g.startsWith("./")&&!g.startsWith("../"))continue;let y=zS(g,u,r);if(y===void 0){m=!0,o=!1,t.push({code:"unresolved-local-import",message:`Local import ${JSON.stringify(g)} could not be resolved safely.`,path:u});continue}if(a+=1,a>n.limits.maxImportEdges){o=!1,d=!0,t.push({code:"budget-exceeded",message:"Import graph exceeded its edge limit."});break}h.push(y)}if(s.set(u,{path:u,imports:[...new Set(h)].sort(),ambiguous:m}),m&&(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 s.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:s,reverse:l,edges:Math.min(a,n.limits.maxImportEdges),complete:o,exhausted:d,reasons:t}}function ay(n,t){return t.filter(e=>n===e.testDirectory||n.startsWith(`${e.testDirectory}/`)).sort((e,r)=>r.testDirectory.length-e.testDirectory.length||e.id.localeCompare(r.id))}function qS(n,t,e){let r=new Set,s=[];for(let i of[...n.map(a=>a.path),...t]){let o=ay(i,e)[0];o!==void 0&&!r.has(o.id)&&(r.add(o.id),s.push(o))}return s.sort((i,a)=>i.id.localeCompare(a.id))}function GS(n,t,e){let r=new Set,s=new Set(n),i=[...n].sort(),a=!0;for(let o=0;i.length>0;o+=1){if(o>=e){a=!1;break}let d=[];for(let c of i){t.modules.get(c)?.ambiguous===!0&&(a=!1);for(let u of t.reverse.get(c)??[])MS.test(u)&&r.add(u),s.has(u)||(s.add(u),d.push(u))}i=[...new Set(d)].sort()}return{tests:[...r].sort(),complete:a}}async function da(n,t){for(let e of t){let r=await Q(n,e,1e6);if(r.kind==="read"&&r.relativePath===e)return e}}async function oy(n,t){let e=[];t.some(o=>iy.has(Oc(o).toLowerCase()))&&e.push({kind:"parse",tool:"kwikqa-babel",required:!0});let r=await da(n,["biome.json","biome.jsonc"]),s=await da(n,[".prettierrc",".prettierrc.json","prettier.config.js","prettier.config.cjs","prettier.config.mjs"]);r!==void 0?(e.push({kind:"format",tool:"biome",configPath:r,required:!0}),e.push({kind:"lint",tool:"biome",configPath:r,required:!0})):s!==void 0&&e.push({kind:"format",tool:"prettier",configPath:s,required:!0});let i=await da(n,["tsconfig.json"]);i!==void 0&&e.push({kind:"typecheck",tool:"typescript",configPath:i,required:!0});let a=await da(n,["eslint.config.js","eslint.config.mjs","eslint.config.cjs",".eslintrc.json"]);return r===void 0&&a!==void 0&&e.push({kind:"lint",tool:"eslint",configPath:a,required:!0}),e}function KS(n,t,e){return n.some(r=>r.class==="playwright-config"||r.class==="framework-config")?t.length===1?"project":"suite":e?"affected":t.length===1?"project":"suite"}async function $c(n){let t=await oy(n.workspaceRoot,n.targets.map(u=>u.path));if(n.targets.length===0||!Nc(n.originalTestPath)||n.targets.some(u=>!Nc(u.path))||n.limits.maxFiles<=0||n.limits.maxFileBytes<=0||n.limits.maxTotalBytes<=0||n.limits.maxImportEdges<=0||n.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 ny(n.workspaceRoot).catch(()=>{});if(e===void 0||NS(e,n.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 r=await US(n),s=n.targets.filter(u=>u.class!=="spec");if(s.length===0)return{status:"resolved",scope:"focused",testPaths:[n.originalTestPath],projectIds:ay(n.originalTestPath,n.projects).slice(0,1).map(u=>u.id),staticChecks:t,indexedFiles:r.modules.size,importEdges:r.edges,completeGraph:r.complete,reasons:[]};let i=GS(s.map(u=>u.path),r,n.limits.maxImportDepth),a=r.complete&&i.complete&&!r.exhausted,o=qS(n.targets,i.tests,n.projects),d=KS(n.targets,o,a),c=d==="affected"?[...new Set([n.originalTestPath,...i.tests])].sort():d==="project"?[...new Set([n.originalTestPath,...i.tests])].sort():[n.originalTestPath],l=[...r.reasons];return d==="suite"&&n.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:r.modules.size,importEdges:r.edges,completeGraph:a,reasons:l}}import{spawn as ZS}from"node:child_process";import{createHash as fa,randomUUID as eT}from"node:crypto";import{lstat as ks,mkdir as vs,readdir as tT,readFile as nT,realpath as ha}from"node:fs/promises";import{isAbsolute as wy,join as Qe,relative as ma,resolve as by,sep as ya}from"node:path";import{createHash as WS,randomUUID as la}from"node:crypto";import{constants as dr}from"node:fs";import{chmod as JS,link as XS,lstat as Ct,mkdir as ly,open as ca,readFile as uy,realpath as Et,rename as Lc,rm as dy,unlink as Dc}from"node:fs/promises";import{dirname as Mc,isAbsolute as YS,join as Ut,relative as py,resolve as _c,sep as fy}from"node:path";var QS=/^txn_[a-f0-9]{24}$/;function vn(n,t){let e=py(n,t);return e===""||!YS(e)&&e!==".."&&!e.startsWith(`..${fy}`)}async function cr(n){if(process.platform==="win32")return;let t=await ca(n,"r");try{await t.sync()}finally{await t.close()}}function cy(n){return WS("sha256").update(n).digest("hex")}function hy(){return`txn_${la().replaceAll("-","").slice(0,24)}`}function kn(n){return QS.test(n)}async function ua(n){let t=await Et(n),e=_c(t,".kwikqa","transactions");if(!vn(t,e))throw new Error("Transaction path escapes workspace.");return{root:t,transactionsDirectory:e}}async function He(n,t){let e=await Et(n),r=e;for(let s of t){if(!/^[A-Za-z0-9_.-]+$/.test(s)||s==="."||s==="..")throw new Error("Unsafe transaction directory segment.");let i=Ut(r,s),a=await Ct(i).catch(d=>{if(d.code!=="ENOENT")throw d});if(a===void 0)await ly(i,{mode:448}),await cr(r);else if(!a.isDirectory()||a.isSymbolicLink())throw new Error("Transaction directory contains an unsafe path.");let o=await Et(i);if(!vn(e,o))throw new Error("Transaction directory escapes workspace.");r=o}return r}async function my(n,t,e){if(!/^\.staging-[a-f0-9]{24}$/.test(t)||!kn(e))throw new Error("Transaction publication name is invalid.");let r=await ua(n),s=await Et(r.transactionsDirectory),i=Ut(s,t),a=Ut(s,e),o=await Ct(i);if(!o.isDirectory()||o.isSymbolicLink())throw new Error("Transaction staging directory is unsafe.");if(await Ct(a).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Transaction already exists.");await Lc(i,a),await cr(s)}async function ye(n,t,e){let r=await Et(Mc(n)),s=_c(r,n.slice(Mc(n).length+1));if(!vn(r,s))throw new Error("Write target escapes its directory.");if(!e.replace&&await Ct(s).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Durable record already exists.");let i=Ut(r,`.kwikqa-${la()}.tmp`),a=await ca(i,"wx",e.mode),o=!1;try{await a.writeFile(t),await a.sync(),await a.close(),e.replace?await Lc(i,s):(await XS(i,s),await Dc(i)),o=!0,await cr(r)}finally{await a.close().catch(()=>{}),o||await Dc(i).catch(()=>{})}}async function pa(n,t,e,r){let s=await Et(n),i=_c(s,t);if(!vn(s,i))throw new Error("Target escapes workspace.");let a=await Ct(i);if(!a.isFile()||a.isSymbolicLink())throw new Error("Target is not a regular file.");let o=await Et(Mc(i)),d=await Et(i);if(!vn(s,o)||!vn(s,d))throw new Error("Target escapes workspace.");if(py(s,d).split(fy).join("/")!==t)throw new Error("Target canonical path changed during final authorization.");let l=await ca(d,dr.O_RDONLY|dr.O_NOFOLLOW);try{let m=await l.stat();if(!m.isFile()||m.dev!==a.dev||m.ino!==a.ino)throw new Error("Target changed during final authorization.");let g=await l.readFile();if(cy(g)!==e)throw new Error("Target content changed during final authorization.")}finally{await l.close()}let u=Ut(o,`.kwikqa-target-${la()}.tmp`),p=a.mode&511,f=await ca(u,dr.O_CREAT|dr.O_EXCL|dr.O_WRONLY|dr.O_NOFOLLOW,p),h=!1;try{await f.writeFile(r),await f.sync(),await f.close(),await JS(u,p);let m=await Et(i);if(m!==d||!vn(s,m))throw new Error("Target path changed before replacement.");let g=await uy(m),y=await Ct(m);if(!y.isFile()||y.isSymbolicLink()||y.dev!==a.dev||y.ino!==a.ino||cy(g)!==e)throw new Error("Target changed before replacement.");await Lc(u,m),h=!0,await cr(o)}finally{await f.close().catch(()=>{}),h||await Dc(u).catch(()=>{})}}async function Ye(n,t){let e=await He(n,[".kwikqa","transactions"]),r=Ut(e,".lock"),s=la();await ly(r,{mode:448});let i=await Ct(r);try{await ye(Ut(r,"owner.json"),`${JSON.stringify({...t,nonce:s})}
52
- `,{mode:384,replace:!1})}catch(a){let o=await Ct(r).catch(()=>{});throw o?.dev===i.dev&&o.ino===i.ino&&await dy(r,{recursive:!0,force:!0}).catch(()=>{}),a}return await cr(e),{release:async()=>{let a=await Ct(r).catch(()=>{});if(a===void 0||a.dev!==i.dev||a.ino!==i.ino||a.isSymbolicLink())throw new Error("Workspace lock ownership changed before release.");if(JSON.parse(await uy(Ut(r,"owner.json"),"utf8")).nonce!==s)throw new Error("Workspace lock ownership changed before release.");await dy(r,{recursive:!0,force:!1}),await cr(e)}}}var rT=/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTH)/i,sT=["authorization","cookie","password","passwd","secret","token","api_key","private_key"];function jc(n,t){let e=ma(n,t);return e===""||!wy(e)&&e!==".."&&!e.startsWith(`..${ya}`)}function iT(n){return/^[a-f0-9]{64}$/.test(n)}function aT(n){let t=xn(n.plan),e=t.commands.find(r=>r.commandId===n.commandId);if(!/^txn_[a-f0-9]{24}$/.test(n.transactionId)||t.status!=="resolved"||!iT(t.planHash)||!Ht.test(n.commandId)||e===void 0||e.executable!==process.execPath||!wy(e.workingDirectory)||e.args.some(r=>r.includes("\0"))||!Number.isInteger(e.timeoutMs)||e.timeoutMs<=0||!Number.isInteger(n.limits.maxStreamBytes)||n.limits.maxStreamBytes<=0||n.limits.maxStreamBytes>bn||!Number.isInteger(n.limits.maxTotalStreamBytes)||n.limits.maxTotalStreamBytes<n.limits.maxStreamBytes||!Number.isInteger(n.limits.terminationGraceMs)||n.limits.terminationGraceMs<0)throw new Error("Validation command or execution limits are invalid.");for(let[r,s]of Object.entries(e.environmentDelta))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r)||s.includes("\0"))throw new Error("Validation environment delta is invalid.");return e}async function oT(n,t){let e=await ha(n.workspaceRoot),r=by(e,".kwikqa","transactions",n.transactionId);if(!jc(e,r))throw new Error("Validation transaction escapes workspace.");let s=await ks(r);if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Validation transaction is unsafe.");let i=n.validationRunId??`vld_${eT().replaceAll("-","").slice(0,24)}`;if(!/^vld_[a-f0-9]{24}$/.test(i))throw new Error("Validation run id is invalid.");let a=Qe(r,"validation");await vs(a,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let o=await ks(a);if(!o.isDirectory()||o.isSymbolicLink())throw new Error("Validation directory is unsafe.");let d=Qe(a,i);await vs(d,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let c=await ks(d);if(!c.isDirectory()||c.isSymbolicLink())throw new Error("Validation run directory is unsafe.");let l=Qe(d,"commands");await vs(l,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let u=await ks(l);if(!u.isDirectory()||u.isSymbolicLink())throw new Error("Validation commands directory is unsafe.");let p=Qe(l,t.commandId);return await vs(p,{mode:448}),await vs(Qe(p,"artifacts"),{mode:448}),{root:d,commandDirectory:p,runId:i}}var ga=class{constructor(t,e){this.cap=t;this.consumeGlobal=e}cap;consumeGlobal;#e=fa("sha256");#n=[];#t=0;#r=0;add(t){this.#e.update(t),this.#t+=t.byteLength;let e=Math.max(0,this.cap-this.#r),r=this.consumeGlobal(Math.min(e,t.byteLength));r>0&&(this.#n.push(t.subarray(0,r)),this.#r+=r)}finish(){return{text:Buffer.concat(this.#n).toString("utf8"),observed:this.#t,hash:this.#e.digest("hex"),truncated:this.#r<this.#t}}};function yy(n,t){let e=Buffer.from(n,"utf8");if(e.byteLength<=t)return{text:n,truncated:!1};let r=t;for(;r>0&&(e[r]??0)>=128&&(e[r]??0)<192;)r-=1;return{text:e.subarray(0,r).toString("utf8"),truncated:!0}}function gy(n){return Object.fromEntries(Object.entries(n).sort(([t],[e])=>t.localeCompare(e)).map(([t,e])=>[t,rT.test(t)?"[REDACTED]":e]))}function dT(n){return n.kind==="timeout"||n.kind==="cancelled"?"incomplete":n.kind==="spawn-error"?"unavailable":n.kind==="signal"?"incomplete":n.exitCode===0?"passed":"failed"}function cT(n){return new Promise(t=>setTimeout(t,n))}async function lT(n,t,e,r){let s=await tT(t,{withFileTypes:!0}),i=[],a=0;for(let o of s.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=Qe(t,o.name),c=await ks(d),l=await ha(d);if(!c.isFile()||c.isSymbolicLink()||!jc(t,l)||c.mtimeMs+1<r)throw new Error("Validation artifact is stale or unsafe.");let u=await nT(l);if(a+=u.byteLength,i.push({path:ma(n,l).split(ya).join("/"),sha256:fa("sha256").update(u).digest("hex"),bytes:u.byteLength}),i.length>e.artifactPolicy.maxArtifacts||a>e.artifactPolicy.maxArtifactBytes)throw new Error("Validation artifact policy limit was exceeded.")}if(e.artifactPolicy.reportFile!==void 0&&!i.some(o=>o.path.split("/").at(-1)===e.artifactPolicy.reportFile))throw new Error("Required validation report artifact is missing.");return i}async function Fc(n){let t=aT(n),e=await ha(n.workspaceRoot),r=await ha(t.workingDirectory);if(!jc(e,r))throw new Error("Validation working directory escapes workspace.");let s=n.repositoryRoot??e;for(let K of t.resolutionEvidence){if(K.sha256===void 0)continue;let te=await Q(s,by(e,K.path),16*1024*1024);if(te.kind!=="read"||te.sha256!==K.sha256)throw new Error("Validation resolution evidence changed after approval.")}let i=await oT(n,t),a=n.now??(()=>new Date),o=a(),d=n.limits.maxTotalStreamBytes,c=K=>{let te=Math.min(K,d);return d-=te,te},l=new ga(n.limits.maxStreamBytes,c),u=new ga(n.limits.maxStreamBytes,c),p=Qe(i.commandDirectory,"artifacts"),f={...n.inheritedEnvironment??process.env,...t.environmentDelta,...t.kind.startsWith("playwright-")?{PLAYWRIGHT_JSON_OUTPUT_NAME:Qe(p,t.artifactPolicy.reportFile??gs)}:{},...or(t.kind)&&!t.kind.startsWith("playwright-")?{KWIKQA_REPORT_DIR:p}:{}},h=ZS(t.executable,[...t.args],{cwd:t.workingDirectory,env:f,shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"]});h.stdout.on("data",K=>l.add(K)),h.stderr.on("data",K=>u.add(K));let m,g,y=K=>{m===void 0&&(m=K,h.kill(),g=setTimeout(()=>h.kill("SIGKILL"),n.limits.terminationGraceMs))},w=()=>y("cancelled");n.signal?.addEventListener("abort",w,{once:!0}),n.signal?.aborted&&y("cancelled");let v=setTimeout(()=>y("timeout"),t.timeoutMs),x=await new Promise(K=>{let te=!1;h.once("error",le=>{te||(te=!0,K({kind:"spawn-error",...le.code===void 0?{}:{code:le.code}}))}),h.once("close",(le,X)=>{te||(te=!0,K(m!==void 0?{kind:m}:X!==null?{kind:"signal",signal:X}:{kind:"exit",exitCode:le??1}))})});v!==void 0&&clearTimeout(v),g!==void 0&&clearTimeout(g),n.signal?.removeEventListener("abort",w),await cT(0);let R=n.sensitiveNames??sT,S=l.finish(),N=u.finish(),E=ce(S.text,"report","validation:stdout",R).value,M=yy(E,n.limits.maxStreamBytes),A=ce(N.text,"report","validation:stderr",R).value,C=yy(A,n.limits.maxStreamBytes),P=M.text,I=C.text,$=Qe(i.commandDirectory,"stdout.log"),D=Qe(i.commandDirectory,"stderr.log");await ye($,P,{mode:384,replace:!1}),await ye(D,I,{mode:384,replace:!1});let k=await lT(i.root,p,t,o.getTime()),T=a(),_={schemaVersion:"1.0",validationRunId:i.runId,commandId:t.commandId,commandHash:L(t),planHash:n.plan.planHash,kind:t.kind,timing:t.timing,required:t.required,executable:t.executable,args:t.args,workingDirectory:t.workingDirectory,environmentDelta:gy(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:x,stdout:{path:ma(i.root,$).split(ya).join("/"),observedBytes:S.observed,storedBytes:Buffer.byteLength(P),sha256:S.hash,storedSha256:fa("sha256").update(P).digest("hex"),truncated:S.truncated||M.truncated,redacted:E!==S.text},stderr:{path:ma(i.root,D).split(ya).join("/"),observedBytes:N.observed,storedBytes:Buffer.byteLength(I),sha256:N.hash,storedSha256:fa("sha256").update(I).digest("hex"),truncated:N.truncated||C.truncated,redacted:A!==N.text},artifacts:k,status:dT(x)},U={..._,recordHash:L(_)};return await ye(Qe(i.commandDirectory,"command.json"),`${pe({commandId:t.commandId,planHash:n.plan.planHash,executable:t.executable,args:t.args,workingDirectory:t.workingDirectory,environmentDelta:gy(t.environmentDelta)})}
53
- `,{mode:384,replace:!1}),await ye(Qe(i.commandDirectory,"result.json"),`${pe(U)}
54
- `,{mode:384,replace:!1}),{directory:i.root,record:U}}import{realpath as ST}from"node:fs/promises";import{join as TT}from"node:path";import{createHash as uT}from"node:crypto";import{readdir as pT,readFile as wa}from"node:fs/promises";import{join as Nt}from"node:path";var Rs="1.0";function xy(n){let t=JSON.parse(n);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("Journal record is not an object.");return t}function fT(n){if(n.schemaVersion!==Rs||typeof n.transactionId!="string"||!kn(n.transactionId)||typeof n.manifestHash!="string"||!Array.isArray(n.targets)||n.preview===null||typeof n.preview!="object"||n.authorization===null||typeof n.authorization!="object"||n.config===null||typeof n.config!="object"||typeof n.maxTargetBytes!="number"||typeof n.createdAt!="string")throw new Error("Transaction manifest is malformed.");let t=n,{manifestHash:e,...r}=t;if(L(r)!==e)throw new Error("Transaction manifest integrity check failed.");return t}function hT(n){let t=new Set(["prepared","applying","applied","validating","rolling-back","rolled-back","completed","conflicted"]);if(n.schemaVersion!==Rs||typeof n.transactionId!="string"||!kn(n.transactionId)||typeof n.manifestHash!="string"||typeof n.stateHash!="string"||typeof n.phase!="string"||!t.has(n.phase)||!Number.isInteger(n.revision)||n.revision<1||typeof n.updatedAt!="string"||!Array.isArray(n.history))throw new Error("Transaction state is malformed.");let e=n,{stateHash:r,...s}=e;if(L(s)!==r||e.history.length!==e.revision)throw new Error("Transaction state integrity check failed.");for(let[i,a]of e.history.entries())if(a===null||typeof a!="object"||a.sequence!==i+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 mT(n){return L({purpose:"kwikqa-transaction-target",path:n}).slice(0,32)}function vy(n){return uT("sha256").update(n).digest("hex")}async function ky(n){if(!kn(n.transactionId))throw new Error("Transaction id is invalid.");let t=`.staging-${n.transactionId.slice(4)}`,e=await He(n.workspaceRoot,[".kwikqa","transactions",t]);await He(n.workspaceRoot,[".kwikqa","transactions",t,"preimages"]),await He(n.workspaceRoot,[".kwikqa","transactions",t,"results"]);let r=[];for(let c of n.targets){let l=mT(c.path),u=`preimages/${l}.bin`,p=`results/${l}.bin`;await ye(Nt(e,u),c.sourceBytes,{mode:384,replace:!1}),await ye(Nt(e,p),c.resultBytes,{mode:384,replace:!1}),r.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 s={schemaVersion:Rs,transactionId:n.transactionId,preview:n.preview,authorization:n.authorization,config:n.config,maxTargetBytes:n.maxTargetBytes,targets:r,createdAt:n.now},i={...s,manifestHash:L(s)};await ye(Nt(e,"manifest.json"),`${pe(i)}
55
- `,{mode:384,replace:!1});let a={sequence:1,type:"prepared",at:n.now,phase:"prepared"},o={schemaVersion:Rs,transactionId:n.transactionId,manifestHash:i.manifestHash,phase:"prepared",revision:1,updatedAt:n.now,history:[a]},d={...o,stateHash:L(o)};return await ye(Nt(e,"state.json"),`${pe(d)}
56
- `,{mode:384,replace:!1}),await my(n.workspaceRoot,t,n.transactionId),Re(n.workspaceRoot,n.transactionId)}async function Re(n,t){if(!kn(t))throw new Error("Transaction id is invalid.");let e=await ua(n),r=await He(e.root,[".kwikqa","transactions",t]),s=fT(xy(await wa(Nt(r,"manifest.json"),"utf8"))),i=hT(xy(await wa(Nt(r,"state.json"),"utf8")));if(s.transactionId!==t||i.transactionId!==t||i.manifestHash!==s.manifestHash)throw new Error("Transaction identity mismatch.");let a=new Map,o=new Map;for(let d of s.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 wa(Nt(r,d.preimageFile)),l=await wa(Nt(r,d.resultFile));if(c.byteLength!==d.preimageBytes||l.byteLength!==d.resultBytes||vy(c)!==d.sourceSha256||vy(l)!==d.resultSha256)throw new Error("Transaction target bytes are malformed.");a.set(d.path,c),o.set(d.path,l)}return{directory:r,manifest:s,state:i,preimages:a,results:o}}function yT(n,t){return t==="conflicted"?n!=="completed"&&n!=="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:[]}[n].includes(t)}async function Ue(n){let t=await Re(n.transaction.manifest.preview.workspace.workspaceRoot,n.transaction.manifest.transactionId);if(t.state.revision!==n.transaction.state.revision)throw new Error("Transaction state changed concurrently.");if(!yT(t.state.phase,n.phase))throw new Error("Transaction phase transition is not permitted.");let e={sequence:t.state.history.length+1,type:n.type,at:n.now,phase:n.phase,...n.path===void 0?{}:{path:n.path},...n.message===void 0?{}:{message:n.message},...n.planHash===void 0?{}:{planHash:n.planHash},...n.validationRunId===void 0?{}:{validationRunId:n.validationRunId},...n.validationManifestHash===void 0?{}:{validationManifestHash:n.validationManifestHash}},r={schemaVersion:Rs,transactionId:t.manifest.transactionId,manifestHash:t.manifest.manifestHash,phase:n.phase,revision:t.state.revision+1,updatedAt:n.now,history:[...t.state.history,e]},s={...r,stateHash:L(r)};return await ye(Nt(t.directory,"state.json"),`${pe(s)}
57
- `,{mode:384,replace:!0}),Re(t.manifest.preview.workspace.workspaceRoot,t.manifest.transactionId)}async function Is(n){let t=await ua(n);return(await pT(t.transactionsDirectory,{withFileTypes:!0}).catch(r=>{if(r.code==="ENOENT")return[];throw r})).filter(r=>r.isDirectory()&&!r.isSymbolicLink()&&kn(r.name)).map(r=>r.name).sort()}import{createHash as gT}from"node:crypto";import{lstat as Iy,readFile as Ay,realpath as ba}from"node:fs/promises";import{isAbsolute as wT,relative as bT,resolve as Py,sep as xT}from"node:path";var vT=2*1024*1024,va=4*1024*1024;function xa(n,t){let e=bT(n,t);return e===""||!wT(e)&&e!==".."&&!e.startsWith(`..${xT}`)}async function Rn(n,t,e){let r=await ba(n),s=Py(r,t);if(!xa(r,s))throw new Error("Validation evidence path escapes its run.");let i=await Iy(s),a=await ba(s);if(!i.isFile()||i.isSymbolicLink()||!xa(r,a)||i.size>e)throw new Error("Validation evidence file is unsafe or unbounded.");return JSON.parse(await Ay(a,"utf8"))}async function Bc(n,t){if(!Ht.test(t))throw new Error("Validation command id is invalid.");return Sc(await Rn(n,`commands/${t}/result.json`,vT))}async function Ry(n,t,e,r,s){let i=Py(n,t);if(!xa(n,i))return!1;let a=await Iy(i).catch(()=>{}),o=await ba(i).catch(()=>{});if(a===void 0||o===void 0||!a.isFile()||a.isSymbolicLink()||!xa(n,o)||a.size>s||a.size!==e)return!1;let d=await Ay(o).catch(()=>{});return d!==void 0&&d.byteLength===e&&gT("sha256").update(d).digest("hex")===r}async function Vc(n,t,e){let r=await ba(n);for(let s of[t.stdout,t.stderr])if(!await Ry(r,s.path,s.storedBytes,s.storedSha256,bn))return!1;for(let s of t.artifacts)if(!await Ry(r,s.path,s.bytes,s.sha256,e))return!1;return!0}async function Sy(n,t,e){try{let r=await Bc(n,t.commandId);return L(r)===L(t)&&await Vc(n,t,e)}catch{return!1}}import{createHash as kT}from"node:crypto";import{lstat as Ey,readFile as Cy,realpath as ka}from"node:fs/promises";import{isAbsolute as RT,relative as IT,resolve as Ny,sep as AT}from"node:path";function Ra(n,t){let e=IT(n,t);return e===""||!RT(e)&&e!==".."&&!e.startsWith(`..${AT}`)}function PT(n){return n.status==="expected"?"passed":n.status==="skipped"?"skipped":n.attempts.some(t=>t.status==="interrupted")?"interrupted":"failed"}var Ty={passed:0,skipped:1,interrupted:2,failed:3};function Oy(n){let t=new Map;for(let e of n){let r=PT(e),s=t.get(e.logicalTestId);(s===void 0||Ty[r]>Ty[s])&&t.set(e.logicalTestId,r)}return[...t].map(([e,r])=>({logicalTestId:e,status:r})).sort((e,r)=>e.logicalTestId.localeCompare(r.logicalTestId))}async function Hc(n){if(!Number.isInteger(n.maxBytes)||n.maxBytes<=0)throw new Error("Validation report byte limit is invalid.");let t=await ka(n.runDirectory).catch(()=>{});if(t===void 0)return{kind:"incomplete",reason:"Validation run directory is unavailable."};let e=Ny(t,n.artifact.path);if(!Ra(t,e))return{kind:"incomplete",reason:"Validation report path escapes its run directory."};let r=await Ey(e).catch(()=>{}),s=await ka(e).catch(()=>{});if(r===void 0||s===void 0||!r.isFile()||r.isSymbolicLink()||!Ra(t,s)||r.size>n.maxBytes||r.size!==n.artifact.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unsafe."};let i=await Cy(s).catch(()=>{});if(i===void 0||i.byteLength>n.maxBytes||i.byteLength!==n.artifact.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unbounded."};let a=Hn(i,{workspaceRoot:n.workspaceRoot,...n.gitRoot===void 0?{}:{gitRoot:n.gitRoot},reportPath:n.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!==n.artifact.sha256)return{kind:"incomplete",reason:"Validation report content hash does not match its record."};let o=Oy(a.run.logicalTests),d=new Set(o.map(c=>c.logicalTestId));return n.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 Ia=/^(?:cypress|wdio)-[^/]*\.json$/;async function zc(n){if(!Number.isInteger(n.maxBytes)||n.maxBytes<=0)throw new Error("Validation report byte limit is invalid.");let t=await ka(n.runDirectory).catch(()=>{});if(t===void 0)return{kind:"incomplete",reason:"Validation run directory is unavailable."};let e=n.artifacts.filter(d=>Ia.test(d.path.split("/").at(-1)??""));if(e.length===0)return{kind:"incomplete",reason:"The test run wrote no KwikQA report."};let r=[],s=0;for(let d of e){let c=Ny(t,d.path);if(!Ra(t,c))return{kind:"incomplete",reason:"Validation report path escapes its run directory."};let l=await Ey(c).catch(()=>{}),u=await ka(c).catch(()=>{});if(l===void 0||u===void 0||!l.isFile()||l.isSymbolicLink()||!Ra(t,u)||l.size!==d.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unsafe."};if(s+=l.size,s>n.maxBytes)return{kind:"incomplete",reason:"Validation reports exceed their byte limit."};let p=await Cy(u).catch(()=>{});if(p===void 0||p.byteLength!==d.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unbounded."};if(kT("sha256").update(p).digest("hex")!==d.sha256)return{kind:"incomplete",reason:"Validation report content hash does not match its record."};r.push({path:u,bytes:p})}let i=Mi(r,{workspaceRoot:n.workspaceRoot,...n.gitRoot===void 0?{}:{gitRoot:n.gitRoot}});if(i.kind!=="parsed")return{kind:"incomplete",reason:`Validation report could not be parsed: ${i.diagnostic.reasonCode}.`};if(i.run.artifact.format!=="kwikqa-json")return{kind:"incomplete",reason:"Validation report was not written by KwikQA's reporter."};if(i.run.usability==="interrupted"||i.run.usability==="zero-tests")return{kind:"incomplete",reason:`Validation report is not analysis-ready: ${i.run.usability}.`};let a=Oy(i.run.logicalTests),o=new Set(a.map(d=>d.logicalTestId));return n.expectedLogicalTestIds.some(d=>!o.has(d))?{kind:"incomplete",reason:"Validation report omits an expected logical test."}:{kind:"observed",reportSha256:i.run.sourceHashes.report,observations:a}}var ET=/^txn_[a-f0-9]{24}$/,CT=/^vld_[a-f0-9]{24}$/,NT=new Set(["rolling-back","rolled-back","conflicted"]);function OT(n){return n.length>0&&Number.isFinite(Date.parse(n))}function $T(n){return n.commands.filter(t=>t.required&&t.timing==="post-patch").sort((t,e)=>t.commandId.localeCompare(e.commandId))}function DT(n,t){let e=new Set(n);return e.size===n.length&&n.length===t.length&&t.every(r=>e.has(r))}function MT(n,t,e){let r=n.manifest.preview.authoritativeValidation,s=new Map(r.requiredCommands.map(i=>[i.commandId,i.commandHash]));return r.planHash===t.planHash&&r.repositoryFingerprint===t.repositoryFingerprint&&L(r.targetHashes)===L(t.targetHashes)&&DT(r.requiredCommandIds,e.map(i=>i.commandId))&&e.every(i=>s.get(i.commandId)===L(i))}async function LT(n,t){for(let e of t.manifest.targets){let r=await Q(n,e.path,Math.max(1,e.resultBytes)).catch(()=>{});if(r?.kind!=="read"||r.relativePath!==e.path||r.sha256!==e.resultSha256)return!1}return!0}function _T(n){return n===void 0?[]:Object.entries(n.logicalTestOutcomes).map(([t,e])=>({logicalTestId:t,status:e})).sort((t,e)=>t.logicalTestId.localeCompare(e.logicalTestId))}async function jT(n,t,e,r,s,i){let a={classification:{commandId:s.commandId,required:!0,timing:"post-patch",status:"incomplete",fresh:!0,expectedLogicalTestIds:s.logicalTestIds,observations:[]}},o=await Bc(e,s.commandId).catch(()=>{});if(o===void 0||o.validationRunId!==n.validationRunId||o.planHash!==r.planHash||o.commandId!==s.commandId||o.commandHash!==L(s)||o.timing!=="post-patch"||!await Vc(e,o,s.artifactPolicy.maxArtifactBytes))return a;let d=[],c=o.status==="blocked"?"incomplete":o.status;if(or(s.kind)&&!s.kind.startsWith("playwright-")&&o.status!=="unavailable"){let l=await zc({workspaceRoot:t,...n.gitRoot===void 0?{}:{gitRoot:n.gitRoot},runDirectory:e,artifacts:o.artifacts,expectedLogicalTestIds:s.logicalTestIds,maxBytes:n.reportMaxBytes});l.kind==="observed"?d=l.observations:c="incomplete"}else if(s.kind.startsWith("playwright-")&&o.status!=="unavailable"){let l=s.artifactPolicy.reportFile??gs,u=o.artifacts.find(p=>p.path.split("/").at(-1)===l);if(u===void 0)c="incomplete";else{let p=await Hc({workspaceRoot:t,...n.gitRoot===void 0?{}:{gitRoot:n.gitRoot},runDirectory:e,artifact:u,expectedLogicalTestIds:s.logicalTestIds,maxBytes:n.reportMaxBytes});p.kind==="observed"?d=p.observations:c="incomplete"}}return{record:o,classification:{commandId:s.commandId,required:!0,timing:"post-patch",status:c,fresh:Date.parse(o.startedAt)>=i&&!o.stdout.truncated&&!o.stderr.truncated,expectedLogicalTestIds:s.logicalTestIds,observations:d}}}async function FT(n,t,e,r){let s=await Re(t,n.transactionId),i=s.manifest.preview.authoritativeValidation,a=s.state.history,o=a.findLastIndex(R=>R.type==="validation-started"),d=a[o],c=$T(e);if(d===void 0||d.validationRunId!==n.validationRunId||d.planHash!==e.planHash||!MT(s,e,c))throw new Error("Validation run does not match the durable transaction approval.");if(i.baselineManifestHash!==r?.baselineHash||r!==void 0&&(r.planHash!==e.planHash||r.repositoryFingerprint!==e.repositoryFingerprint||L(r.targetHashes)!==L(e.targetHashes)))throw new Error("Required validation baseline is missing or mismatched.");let l=await He(t,[".kwikqa","transactions",n.transactionId,"validation",n.validationRunId]),u=await Rn(l,"manifest.json",va).catch(R=>{if(R.code!=="ENOENT")throw R});if(u!==void 0){let R=zt(u);if(R.transactionId!==n.transactionId||R.validationRunId!==n.validationRunId||R.planHash!==e.planHash)throw new Error("Validation run was already finalized for different evidence.");return{directory:l,manifest:R}}let p=[],f=s.state.phase;if(f==="validating")await LT(t,s)||p.push("Applied validation targets changed before the run was finalized.");else if(NT.has(f)&&!a.slice(o+1).some(R=>R.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),m=n.completedAt??new Date().toISOString();if(Date.parse(m)<h)throw new Error("Validation completion precedes command execution.");let g=[],y=[];for(let R of c){let S=await jT(n,t,l,e,R,h);S.record!==void 0&&g.push(S.record),y.push(S.classification)}let w=Ic({targetLogicalTestIds:e.targetLogicalTestIds,baseline:_T(r),commands:y,blockingReasons:p}),v={schemaVersion:ra,validationRunId:n.validationRunId,transactionId:n.transactionId,planHash:e.planHash,repositoryFingerprint:e.repositoryFingerprint,targetHashes:e.targetHashes,requiredCommandIds:c.map(R=>R.commandId),status:w.status,commandRecords:g,classifications:w.classifications,startedAt:d.at,completedAt:m},x=zt({...v,manifestHash:ia(v)});return await ye(TT(l,"manifest.json"),`${pe(x)}
58
- `,{mode:384,replace:!1}),{directory:l,manifest:x}}async function Uc(n){if(!ET.test(n.transactionId)||!CT.test(n.validationRunId)||!Number.isInteger(n.reportMaxBytes)||n.reportMaxBytes<=0||n.completedAt!==void 0&&!OT(n.completedAt))throw new Error("Validation finalization identity, timestamp, or limits are invalid.");let t=xn(n.plan);if(t.status!=="resolved")throw new Error("Unavailable validation plan cannot be finalized.");if(t.transactionId!==void 0&&t.transactionId!==n.transactionId)throw new Error("Validation plan is bound to another transaction.");let e=n.baseline===void 0?void 0:bs(n.baseline),r=await ST(n.workspaceRoot),s=await Ye(r,{operation:"finalize-validation",transactionId:n.transactionId,validationRunId:n.validationRunId});try{return await FT(n,r,t,e)}finally{await s.release().catch(()=>{})}}import{fileURLToPath as ZT}from"node:url";import{execFile as BT}from"node:child_process";import{lstat as Aa,realpath as Ze}from"node:fs/promises";import{createRequire as VT}from"node:module";import{dirname as Ot,isAbsolute as My,join as Gc,relative as Ly,resolve as Kc,sep as _y}from"node:path";import{fileURLToPath as HT}from"node:url";import{promisify as zT}from"node:util";var UT=zT(BT),jy=128*1024,qT=64*1024,GT=/^[a-f0-9]{64}$/,$y={"@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 In(n,t){let e=Ly(n,t);return e===""||!My(e)&&e!==".."&&!e.startsWith(`..${_y}`)}function qc(n,t){return Ly(n,t).split(_y).join("/")}function As(n,t,e){return{code:n,message:t,...e===void 0?{}:{path:e}}}function KT(n,t){let e=new TextDecoder("utf-8",{fatal:!0}).decode(n),r=JSON.parse(e);if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("Package manifest is not an object.");let s=r;if(s.name!==t||typeof s.version!="string"||s.version.trim().length===0)throw new Error("Package identity does not match the requested tool.");return{name:s.name,version:s.version}}async function WT(n,t){let e=await Ze(n),r=My(t)?t:Kc(e,t),s=await Ze(r).catch(()=>r);if(!In(e,s))return;let i=s;for((await Aa(i).catch(()=>{}))?.isFile()&&(i=Ot(i));In(e,i);){let o=Gc(i,"package.json"),d=await Aa(o).catch(()=>{});if(d?.isFile()&&!d.isSymbolicLink())return o;if(i===e)break;i=Ot(i)}}async function JT(n,t){let e=await Ze(n),r=Ot(t);for(;In(e,r);){let s=Gc(r,".pnp.cjs"),i=await Aa(s).catch(()=>{});if(i?.isFile()&&!i.isSymbolicLink())return s;if(r===e)break;r=Ot(r)}}async function Dy(n,t,e){let r=Ot(n);for(;;){let s=Gc(r,"node_modules",...t.split("/"),"package.json");if(await Aa(s).catch(()=>{})!==void 0){let o=await Ze(s),d=await Q(Ot(o),o,jy).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 Ze(Kc(Ot(o),u));return{manifestPath:o,entryPath:p}}let a=Ot(r);if(a===r)throw new Error("Package is not installed.");r=a}}async function XT(n,t){let e=VT(n),r=$y[t].bin,s;try{s=await Ze(e.resolve(`${t}/package.json`))}catch(a){if(r===void 0)throw a;return Dy(n,t,r)}let i;for(let a of $y[t].entryRequests)try{i=await Ze(e.resolve(a));break}catch{}if(i===void 0){if(r!==void 0)return Dy(n,t,r);throw new Error("Package CLI entry could not be resolved.")}return{manifestPath:s,entryPath:i}}async function Wc(n,t){let e=await Ze(t),r=await Q(n,e,16*1024*1024);if(r.kind!=="read")throw new Error("PnP loader is not an authorized repository-local regular file.");return{path:e,relativePath:r.relativePath,sha256:r.sha256}}async function YT(n,t,e,r){let s=HT(new URL("./pnp-resolver.mjs",import.meta.url)),{stdout:i}=await UT(process.execPath,[s,n,t.path,t.sha256,e,r],{encoding:"utf8",maxBuffer:qT,timeout:1e4,windowsHide:!0,env:{PATH:process.env.PATH??""}}),a=JSON.parse(i);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 Wc(n,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 Ze(o.manifestPath),entryPath:await Ze(o.entryPath)}}async function QT(n){let t=await Q(n.root,n.paths.manifestPath,n.maxManifestBytes),e=await Q(n.root,n.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 r=KT(t.bytes,n.packageName),s=Ot(n.paths.manifestPath);if(!In(s,n.paths.entryPath))throw new Error("Package CLI entry escapes its package root.");let i=[],a=[];if(n.loader!==void 0){let o=await Wc(n.root,n.loader.path);if(o.path!==n.loader.path||o.relativePath!==n.loader.relativePath||o.sha256!==n.loader.sha256)throw new Error("PnP loader identity changed before tool authorization completed.");a.push("--require",n.loader.path),i.push({kind:"pnp-loader",path:qc(n.workspace,n.loader.path),sha256:n.loader.sha256,detail:"Repository-local Yarn Plug'n'Play loader."})}return a.push(n.paths.entryPath),{packageName:n.packageName,packageVersion:r.version,packageRoot:s,packageManifest:n.paths.manifestPath,packageManifestSha256:t.sha256,entryPath:n.paths.entryPath,entrySha256:e.sha256,executable:process.execPath,nodeArguments:a,packageManagerLayout:n.layout,resolutionEvidence:[{kind:"package-root",path:s,detail:`Canonical repository-local ${n.packageName} package root.`},{kind:"package-manifest",path:qc(n.workspace,n.paths.manifestPath),sha256:t.sha256,detail:`${r.name}@${r.version}`},{kind:"package-entry",path:qc(n.workspace,n.paths.entryPath),sha256:e.sha256,detail:"JavaScript CLI entry executed directly through the current Node runtime."},...i]}}async function Ps(n){try{let t=await Ze(n.workspaceRoot),e=n.repositoryRoot===void 0?t:await Ze(n.repositoryRoot);if(!In(e,t))return{kind:"unavailable",reasons:[As("entry-outside-workspace","The workspace is outside its containing repository.")]};let r=await WT(e,Kc(t,n.ownerPath));if(r===void 0)return{kind:"unavailable",reasons:[As("ambiguous-package-root","No owning repository package was found.")]};let s=n.maxManifestBytes??jy;if(!Number.isInteger(s)||s<=0)return{kind:"unavailable",reasons:[As("budget-exceeded","Package manifest byte limit is invalid.")]};let i,a="node-modules",o;try{i=await XT(r,n.packageName)}catch{let c=await JT(e,r);if(c===void 0)throw new Error("No repository-local dependency resolution succeeded.");o=await Wc(e,c),a="pnp",i=await YT(e,o,r,n.packageName)}return!In(e,i.manifestPath)||!In(e,i.entryPath)?{kind:"unavailable",reasons:[As("entry-outside-workspace","Resolved package files are outside the repository.")]}:{kind:"resolved",tool:await QT({root:e,workspace:t,packageName:n.packageName,paths:i,maxManifestBytes:s,layout:a,...o===void 0?{}:{loader:o}})}}catch{return{kind:"unavailable",reasons:[As("missing-dependency",`Repository-local ${n.packageName} could not be resolved safely. No installation or global fallback was attempted.`)]}}}function Ss(n){if(n.tool.executable!==process.execPath||n.args.some(s=>s.includes("\0"))||n.workingDirectory.includes("\0")||!Number.isInteger(n.timeoutMs)||n.timeoutMs<=0)throw new Error("Resolved validation command is invalid.");let t=[...n.tool.nodeArguments,...n.args],e=[...n.tool.resolutionEvidence,...n.extraEvidence??[]],r=L({packageManifestSha256:n.tool.packageManifestSha256,entrySha256:n.tool.entrySha256,resolutionEvidence:e,kind:n.kind,timing:n.timing,executable:n.tool.executable,args:t,workingDirectory:n.workingDirectory,environmentDelta:n.environmentDelta,timeoutMs:n.timeoutMs,purpose:n.purpose,logicalTestIds:n.logicalTestIds,projectIds:n.projectIds,artifactPolicy:n.artifactPolicy});if(!GT.test(r))throw new Error("Command identity could not be constructed.");return{commandId:`cmd_${r.slice(0,24)}`,kind:n.kind,timing:n.timing,required:!0,executable:n.tool.executable,args:t,workingDirectory:n.workingDirectory,environmentDelta:n.environmentDelta,timeoutMs:n.timeoutMs,purpose:n.purpose,logicalTestIds:n.logicalTestIds,projectIds:n.projectIds,artifactPolicy:n.artifactPolicy,resolutionEvidence:e}}function Jc(n,t){return L({purpose:"kwikqa-validation-repository-fingerprint",evidence:n,targetHashes:t})}var e0=/^[a-f0-9]{64}$/,Yc=3,t0=/^rps_[a-f0-9]{24}$/,Xc=ZT(new URL("./parse-check.mjs",import.meta.url));function n0(n,t){switch(n.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 r0(n,t){return t==="unavailable"?void 0:`${n}-${t}`}var Fy={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"};function s0(n,t){let e=["test"];if(t==="focused"?e.push(`${n.originalTest.path}:${n.originalTest.line}`,`--repeat-each=${Yc}`):t==="affected"&&e.push(...n.discovery.testPaths),t!=="suite")for(let r of n.discovery.projectIds)r!==""&&e.push(`--project=${r}`);return n.originalTest.configPath!==void 0&&e.push(`--config=${n.originalTest.configPath}`),e.push("--reporter=json",`--output=${n.artifactRoot}`,"--trace=retain-on-failure","--retries=0"),e}function i0(n,t){let e=t.targets.map(r=>r.path);switch(n.tool){case"biome":return n.kind==="format"?["format",...e]:["lint",...e];case"prettier":return["--check",...e];case"typescript":return["--noEmit","--pretty","false",...n.configPath?["--project",n.configPath]:[]];case"eslint":return e;case"kwikqa-babel":return[]}}function Pa(n){return{code:"resolution-failed",message:n}}function Qc(n){if(!Number.isInteger(n.timeoutMs)||n.timeoutMs<=0||n.originalTest.line<=0||n.originalTest.logicalTestId.trim().length===0||n.originalTest.projectId.trim().length===0)throw new Error("Validation preparation input is invalid.");let t=L(n.advisoryPlan),e=[...new Set(n.affectedLogicalTestIds??[])].sort(),r=[...n.discovery.reasons.map(y=>({code:y.code==="budget-exceeded"?"budget-exceeded":"resolution-failed",message:y.message,...y.path===void 0?{}:{path:y.path}}))],s=[],i=[],a=n.framework??"playwright",o=n.tools[a],d=r0(a,n.discovery.scope),c=a==="playwright"?void 0:n.frameworkRun,l=()=>c?.args??s0(n,n.discovery.scope),u=c?.evidence??[],p=c?.workingDirectory??n.workspaceRoot;if(n.discovery.status!=="resolved"||d===void 0||o===void 0||a!=="playwright"&&c===void 0)r.push(Pa(`Repository-local ${Fy[a]} validation could not be resolved.`));else{let y=[n.originalTest.logicalTestId,...(n.companionLogicalTestIds??[]).filter(v=>v!==n.originalTest.logicalTestId)],w=a!=="playwright"&&n.discovery.scope==="focused"?Yc:1;for(let v=1;v<=w;v+=1)s.push(Ss({tool:o,kind:d,timing:"post-patch",args:l(),workingDirectory:p,environmentDelta:{},timeoutMs:n.timeoutMs,purpose:`Run the approved risk-based ${Fy[a]} validation scope${w>1?` (run ${v} of ${w})`:""}.`,logicalTestIds:n.discovery.scope==="focused"?[...new Set(y)].sort():e,projectIds:n.discovery.projectIds,artifactPolicy:{outputDirectory:n.artifactRoot,...a==="playwright"?{reportFile:"report.json"}:{},maxArtifacts:100,maxArtifactBytes:32*1024*1024},extraEvidence:u}));if(n.discovery.scope!=="focused"){(e.length===0||!e.includes(n.originalTest.logicalTestId))&&r.push(Pa("Shared validation scope lacks complete canonical affected-test identities."));let v=Ss({tool:o,kind:d,timing:"baseline",args:l(),workingDirectory:p,environmentDelta:{},timeoutMs:n.timeoutMs,purpose:"Capture required affected-test outcomes before shared-source mutation.",logicalTestIds:e,projectIds:n.discovery.projectIds,artifactPolicy:{outputDirectory:`${n.artifactRoot}-baseline`,...a==="playwright"?{reportFile:"report.json"}:{},maxArtifacts:100,maxArtifactBytes:32*1024*1024},extraEvidence:u});s.push(v);let x=`baseline_${L({commandId:v.commandId}).slice(0,24)}`;i.push({baselineId:x,commandId:v.commandId,logicalTestIds:e,reason:"Shared test support requires a pre-patch affected-test baseline."})}else n.originalTest.environmentEquivalent||r.push(Pa("Original failure evidence is not environment-equivalent to validation."))}for(let y of n.discovery.staticChecks){if(y.tool==="kwikqa-babel"){let v=L({purpose:"kwikqa-parse-check-command",executable:process.execPath,shim:Xc,paths:n.proposal.targets.map(x=>x.path),workingDirectory:n.workspaceRoot});s.push({commandId:`cmd_${v.slice(0,24)}`,kind:"parse",timing:"post-patch",required:!0,executable:process.execPath,args:[Xc,...n.proposal.targets.map(x=>x.path)],workingDirectory:n.workspaceRoot,environmentDelta:{},timeoutMs:n.timeoutMs,purpose:"Parse every changed JavaScript or TypeScript source file.",logicalTestIds:[],projectIds:n.discovery.projectIds,artifactPolicy:{outputDirectory:n.artifactRoot,maxArtifacts:1,maxArtifactBytes:1e6},resolutionEvidence:[{kind:"configuration",path:Xc,detail:"KwikQA-owned Babel parse-only validation shim."}]});continue}let w=n0(y,n.tools);if(w===void 0){r.push(Pa(`Required ${y.tool} check could not be resolved locally.`));continue}s.push(Ss({tool:w,kind:y.kind,timing:"post-patch",args:i0(y,n.proposal),workingDirectory:n.workspaceRoot,environmentDelta:{},timeoutMs:n.timeoutMs,purpose:`Run required ${y.kind} validation.`,logicalTestIds:[],projectIds:n.discovery.projectIds,artifactPolicy:{outputDirectory:n.artifactRoot,maxArtifacts:10,maxArtifactBytes:8*1024*1024}}))}let f=s.flatMap(y=>y.resolutionEvidence),h=n.proposal.targets.map(y=>({path:y.path,sourceSha256:y.sourceSha256,resultSha256:y.resultSha256})),m={schemaVersion:na,policyVersion:sa,status:r.length===0?"resolved":"unavailable",proposalHash:n.proposal.proposalHash,targetLogicalTestIds:[n.originalTest.logicalTestId],targetHashes:h,advisoryPlanHash:t,repositoryFingerprint:Jc(f,h),commands:[...s].sort((y,w)=>y.commandId.localeCompare(w.commandId)),baselineRequirements:[...i].sort((y,w)=>y.baselineId.localeCompare(w.baselineId)),unresolvedReasons:r},g={...m,planHash:aa(m)};return{plan:g,requiredBaselineCommands:g.commands.filter(y=>y.timing==="baseline")}}function Zc(n){if(n.plan.status!=="resolved"||!e0.test(n.plan.planHash)||!t0.test(n.repairSessionId)||n.attemptOrdinal!==1&&n.attemptOrdinal!==2)throw new Error("Only a resolved plan can become application execution authority.");let t=n.plan.baselineRequirements.map(s=>s.baselineId),e;if(t.length>0){if(n.baseline===void 0)throw new Error("Required pre-application baseline is missing.");e=bs(n.baseline);let s=new Map(n.plan.baselineRequirements.map(i=>[i.commandId,i]));if(e.planHash!==n.plan.planHash||e.repositoryFingerprint!==n.plan.repositoryFingerprint||L(e.targetHashes)!==L(n.plan.targetHashes)||e.commandRecords.length!==s.size||e.commandRecords.some(i=>{let a=s.get(i.commandId);return a===void 0||i.planHash!==n.plan.planHash||i.timing!=="baseline"||i.status!=="passed"||i.termination.kind!=="exit"||i.termination.exitCode!==0||i.stdout.truncated||i.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 r=n.plan.commands.filter(s=>s.timing==="post-patch"&&s.required).sort((s,i)=>s.commandId.localeCompare(i.commandId));return{schemaVersion:"1.0",policyVersion:"1.0",planHash:n.plan.planHash,repositoryFingerprint:n.plan.repositoryFingerprint,targetHashes:n.plan.targetHashes,advisoryPlanHash:L(n.advisoryPlan),...e===void 0?{}:{baselineManifestHash:e.baselineHash},requiredBaselineIds:t,requiredCommandIds:r.map(s=>s.commandId),requiredCommands:r.map(s=>({commandId:s.commandId,commandHash:L(s)})),repairSessionId:n.repairSessionId,attemptOrdinal:n.attemptOrdinal}}import{randomUUID as A0}from"node:crypto";import{lstat as Ns,mkdir as cl,readFile as P0,realpath as S0,rm as T0}from"node:fs/promises";import{isAbsolute as E0,join as fr,relative as C0,resolve as N0,sep as O0}from"node:path";import{realpath as ur}from"node:fs/promises";import{realpath as lr}from"node:fs/promises";var et=/^[a-f0-9]{64}$/,a0=/^rps_[a-f0-9]{24}$/;function By(n){let t=n.map(e=>e.trim());return t.every(e=>e.length>0)&&new Set(t).size===n.length}function o0(n){return{kind:"rejected",reasons:n}}function zy(n){return n.length>0&&Number.isFinite(Date.parse(n))}function Sa(n){return Number.isFinite(n)&&n>0}function d0(n){let{proposalHash:t,...e}=n;return et.test(t)&&L(e)===t}function c0(n){let t=[];(!d0(n)||L(n.diff)!==n.diffHash)&&t.push({code:"invalid-proposal",message:"Proposal and diff integrity hashes must match their canonical contents."}),(n.targets.length===0||n.changedFiles!==n.targets.length||n.targets.some(s=>!et.test(s.sourceSha256)||!et.test(s.resultSha256)||s.sourceSha256===s.resultSha256))&&t.push({code:"invalid-proposal",message:"Proposal targets and their source/result hashes must be complete and consistent."});let e=new Set,r=new Map;for(let s of n.targets){let i=s.path.toLocaleLowerCase("en-US"),a=r.get(i);(e.has(s.path)||a!==void 0&&a!==s.path)&&t.push({code:"invalid-proposal",message:"Proposal targets may not duplicate or case-collide.",path:s.path}),e.add(s.path),r.set(i,s.path)}return(n.replacements.length===0||n.replacements.some(s=>!e.has(s.path)))&&t.push({code:"invalid-proposal",message:"Every approved replacement must resolve to an approved proposal target."}),t}function l0(n){let t=c0(n.proposal);(n.context.workspace.workspaceRoot.length===0||n.context.workspace.gitRoot.length===0||n.context.snapshot.workspaceRoot!==n.context.workspace.workspaceRoot||n.context.snapshot.gitRoot!==n.context.workspace.gitRoot)&&t.push({code:"invalid-workspace",message:"Confirmed workspace and git roots must match the repository snapshot identity."}),(!Number.isInteger(n.context.maxTargetBytes)||n.context.maxTargetBytes<=0||n.context.config.schemaVersion.length===0)&&t.push({code:"invalid-configuration",message:"Application configuration and target byte limit must be explicit and bounded."}),(n.interactiveSession.sessionId.trim().length===0||!zy(n.previewedAt))&&t.push({code:"invalid-preview",message:"An interactive session identity and valid preview timestamp are required."});let e=n.costBounds;(!Number.isInteger(e.maxRequestTokens)||!Number.isInteger(e.maxRunTokens)||!Sa(e.maxRequestTokens)||!Sa(e.maxRunTokens)||!Sa(e.maxRequestDollars)||!Sa(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 r=new Set;for(let i of n.payloadManifests){if(!et.test(i.manifestHash)||!et.test(i.payloadHash)||!et.test(i.packetHash)||i.model.trim().length===0||i.provider.trim().length===0||i.promptVersion.trim().length===0||i.outputSchemaVersion.trim().length===0||r.has(i.manifestHash)){t.push({code:"invalid-preview",message:"Model payload manifest references must be sanitized, complete, and unique."});break}r.add(i.manifestHash)}(n.scopes.baseline.some(i=>i.trim().length===0)||n.scopes.validation.some(i=>i.trim().length===0))&&t.push({code:"invalid-preview",message:"Baseline and validation scopes may not contain empty entries."});let s=n.authoritativeValidation;return(s.schemaVersion!=="1.0"||s.policyVersion!=="1.0"||!et.test(s.planHash)||!et.test(s.repositoryFingerprint)||!et.test(s.advisoryPlanHash)||s.targetHashes.length!==n.proposal.targets.length||s.targetHashes.some((i,a)=>{let o=n.proposal.targets[a];return o===void 0||i.path!==o.path||i.sourceSha256!==o.sourceSha256||i.resultSha256!==o.resultSha256})||s.baselineManifestHash!==void 0&&!et.test(s.baselineManifestHash)||!a0.test(s.repairSessionId)||s.attemptOrdinal!==1&&s.attemptOrdinal!==2||!By(s.requiredBaselineIds)||!By(s.requiredCommandIds)||s.requiredCommandIds.length===0||s.requiredCommands.length!==s.requiredCommandIds.length||s.requiredCommands.some((i,a)=>i.commandId!==s.requiredCommandIds[a]||!et.test(i.commandHash))||s.requiredBaselineIds.length>0&&s.baselineManifestHash===void 0)&&t.push({code:"invalid-preview",message:"Authoritative validation approval metadata is incomplete or inconsistent."}),t}function el(n){return L({purpose:"kwikqa-approved-application",...n})}function tl(n){let t=l0(n);if(t.length>0)return o0(t);let e={schemaVersion:"2.0",bindingVersion:"2.0",proposal:n.proposal,workspace:n.context.workspace,checkoutPristine:n.context.snapshot.dirtyPaths.length===0,validationPlan:n.proposal.validationPlan,scopes:n.scopes,authoritativeValidation:n.authoritativeValidation,payloadManifests:n.payloadManifests,costBounds:n.costBounds,previewedAt:n.previewedAt,interactiveSession:n.interactiveSession};return{kind:"preview-ready",preview:{...e,bindingHash:el(e)}}}function Ta(n,t,e,r){return L({purpose:"kwikqa-interactive-application-authorization",previewBindingHash:n.bindingHash,authorizationId:t,authorizedAt:e,interactiveSession:r})}function nl(n,t){let{bindingHash:e,...r}=n;return et.test(e)&&el(r)===e&&t.authorizationId.trim().length>0&&zy(t.authorizedAt)&&t.bindingHash===Ta(n,t.authorizationId,t.authorizedAt,t.interactiveSession)&&t.interactiveSession.sessionId===n.interactiveSession.sessionId}import{realpath as Ea}from"node:fs/promises";import{isAbsolute as y0,relative as g0,sep as w0}from"node:path";import{createHash as u0}from"node:crypto";function p0(n){return u0("sha256").update(n,"utf8").digest("hex")}function rl(n,t,e){let r=[],s=[];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){r.push({code:"invalid-replacement",message:"Replacement fields must be meaningful, cited, and non-no-op.",path:n});continue}if(o.oldText===t){r.push({code:"invalid-replacement",message:"A replacement may not rewrite the complete file.",path:n});continue}let d=t.indexOf(o.oldText);if(d<0||t.indexOf(o.oldText,d+1)>=0){r.push({code:"non-unique-match",message:"Replacement preimage must occur exactly once.",path:n});continue}s.push({start:d,end:d+o.oldText.length,newText:o.newText})}let i=[...s].sort((o,d)=>o.start-d.start);for(let o=1;o<i.length;o+=1){let d=i[o-1],c=i[o];d!==void 0&&c!==void 0&&c.start<d.end&&r.push({code:"overlapping-replacement",message:"Exact replacements overlap in the original source.",path:n})}if(r.length>0)return{kind:"rejected",reasons:r};let a=t;for(let o of[...i].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:p0(a)}}function Uy(n){let t=[],e=[];for(let r of n){let s=rl(r.path,r.source,r.replacements);if(s.kind==="rejected"){t.push(...s.reasons);continue}e.push({...r,result:s.result,resultSha256:s.resultSha256})}return t.length>0?{kind:"rejected",reasons:t}:{kind:"applied",targets:e}}import{isAbsolute as f0}from"node:path";function h0(n){return n.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function qy(n,t){let e=h0(n).replaceAll("**/","\0").replaceAll("**","").replaceAll("*","[^/]*").replaceAll("\0","(?:.*/)?").replaceAll("",".*");return new RegExp(`^${e}$`).test(t)}function Ts(n){return n.length===0||n.includes("\0")||n.includes("\\")||f0(n)||/^[A-Za-z]:/.test(n)?!0:n.split("/").some(t=>t===""||t==="."||t==="..")}function Es(n,t){let e=n.toLowerCase(),r=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(r)?!0:t.generatedPaths.some(s=>qy(s,n))}function Cs(n,t){return t.find(e=>qy(e.pattern,n))}function m0(n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return}}async function Gy(n,t,e,r){let s=[],i=new Map;for(let l of e){if(Ts(l.path)){s.push({code:"unauthorized-target",message:"Target path is not a safe repository-relative path.",path:l.path});continue}let u=i.get(l.path)??[];u.push(l),i.set(l.path,u)}if(s.length>0)return{kind:"rejected",reasons:s};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[...i].sort(([p],[f])=>p.localeCompare(f))){let p=Cs(l,n.editablePaths);if(p===void 0||Es(l,n)){s.push({code:"unauthorized-target",message:"Target is outside the configured test-support repair boundary.",path:l});continue}if(a.has(l.toLocaleLowerCase("en-US"))){s.push({code:"dirty-target-file",message:"Already-dirty target files are read-only.",path:l});continue}let f=await Q(t.workspaceRoot,l,r);if(f.kind!=="read"){s.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){s.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"),m=d.get(h);if(o.has(f.relativePath)||m!==void 0&&m!==f.relativePath){s.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 g=m0(f.bytes);if(g===void 0){s.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)){s.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:g,sourceSha256:f.sha256,replacements:u})}return s.length>0?{kind:"rejected",reasons:s}:{kind:"authorized",targets:c}}function b0(n,t){let e=g0(n,t);return e===""||!y0(e)&&e!==".."&&!e.startsWith(`..${w0}`)}function x0(n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return}}async function Ky(n){if(!Number.isInteger(n.maxTargetBytes)||n.maxTargetBytes<=0||n.maxTargetBytes>1e6)return{kind:"rejected",code:"invalid-limit",message:"Target limit is invalid."};let t,e,r,s;try{[t,e,r,s]=await Promise.all([Ea(n.workspaceRoot),Ea(n.gitRoot),Ea(n.approvedWorkspaceRoot),Ea(n.approvedGitRoot)])}catch{return{kind:"rejected",code:"workspace-mismatch",message:"Workspace roots are unreadable."}}if(t!==r||e!==s||!b0(e,t))return{kind:"rejected",code:"workspace-mismatch",message:"Current and approved canonical workspace identities differ."};let i=new Set(n.dirtyPaths.map(c=>c.replaceAll("\\","/").toLocaleLowerCase("en-US"))),a=new Map;for(let c of n.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 n.proposal.targets){let l=c.path.toLocaleLowerCase("en-US");if(o.has(l)||Ts(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=Cs(c.path,n.config.editablePaths);if(u===void 0||u.class!==c.class||Es(c.path,n.config))return{kind:"rejected",code:"unauthorized-target",message:"Target is outside the approved repair boundary.",path:c.path};if(i.has(l))return{kind:"rejected",code:"dirty-target-file",message:"An approved target is currently dirty.",path:c.path};let p=await Q(t,c.path,n.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=x0(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)??[],m=rl(c.path,f,h);if(m.kind!=="applied"||m.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:m.result,resultBytes:new TextEncoder().encode(m.result),resultSha256:m.resultSha256,replacements:h})}return{kind:"verified",workspaceRoot:t,gitRoot:e,targets:d,nonPristine:n.dirtyPaths.length>0}}var v0=new Set(["completed","rolled-back","conflicted"]);function An(n,t,e){return{code:n,message:t,...e===void 0?{}:{path:e}}}function Se(n){return{schemaVersion:"2.0",transactionId:n.manifest.transactionId,authorizationId:n.manifest.authorization.authorizationId,approvalBindingHash:n.manifest.preview.bindingHash,proposalHash:n.manifest.preview.proposal.proposalHash,diffHash:n.manifest.preview.proposal.diffHash,workspace:n.manifest.preview.workspace,phase:n.state.phase,revision:n.state.revision,targets:n.manifest.targets.map(t=>({path:t.path,sourceSha256:t.sourceSha256,resultSha256:t.resultSha256,preimageBytes:t.preimageBytes,resultBytes:t.resultBytes})),validationPlan:n.manifest.preview.validationPlan,authoritativeValidation:n.manifest.preview.authoritativeValidation,createdAt:n.manifest.createdAt,updatedAt:n.state.updatedAt}}async function k0(n){return(await Promise.all((await Is(n)).map(e=>Re(n,e)))).filter(e=>!v0.has(e.state.phase))}async function Wy(n,t,e,r){let s=await Q(n,t,e);return s.kind==="read"&&s.relativePath===t&&s.sha256===r}async function sl(n){return R0(n,{})}async function R0(n,t){if(!nl(n.preview,n.authorization))return{kind:"rejected",reasons:[An("authorization-mismatch","Authorization does not match this exact preview.")]};let e=n.now??new Date().toISOString(),r;try{let[s,i,a,o,d,c]=await Promise.all([lr(n.context.workspace.workspaceRoot),lr(n.context.snapshot.workspaceRoot),lr(n.preview.workspace.workspaceRoot),lr(n.context.workspace.gitRoot),lr(n.context.snapshot.gitRoot),lr(n.preview.workspace.gitRoot)]);if(s!==i||s!==a||o!==d||o!==c)return{kind:"rejected",reasons:[An("invalid-workspace","Application workspace identity changed.")]};let l=a;r=await Ye(l,{operation:"apply",authorizationId:n.authorization.authorizationId,at:e});let u=await k0(l);if(u.length>0)return{kind:"recovery-required",reasons:[An("transaction-blocked","A nonterminal transaction must be recovered before another application.")],transaction:Se(u[0])};if((await Promise.all((await Is(l)).map(g=>Re(l,g)))).some(g=>g.manifest.authorization.authorizationId===n.authorization.authorizationId))return{kind:"rejected",reasons:[An("authorization-replayed","Authorization has already been consumed.")]};let f=await Ky({workspaceRoot:n.context.snapshot.workspaceRoot,gitRoot:n.context.snapshot.gitRoot,approvedWorkspaceRoot:n.preview.workspace.workspaceRoot,approvedGitRoot:n.preview.workspace.gitRoot,config:n.context.config,dirtyPaths:n.context.snapshot.dirtyPaths,proposal:n.preview.proposal,maxTargetBytes:n.context.maxTargetBytes});if(f.kind!=="verified")return{kind:"rejected",reasons:[An(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=hy(),m=await ky({workspaceRoot:f.workspaceRoot,transactionId:h,preview:n.preview,authorization:n.authorization,config:n.context.config,maxTargetBytes:n.context.maxTargetBytes,targets:f.targets,now:e});await t.failpoint?.("journal-prepared"),m=await Ue({transaction:m,phase:"applying",type:"application-started",now:e}),await t.failpoint?.("phase-applying");for(let g of m.manifest.targets){if(!await Wy(f.workspaceRoot,g.path,n.context.maxTargetBytes,g.sourceSha256))return{kind:"recovery-required",reasons:[An("source-hash-mismatch","Target changed immediately before mutation.",g.path)],transaction:Se(m)};m=await Ue({transaction:m,phase:"applying",type:"target-write-intent",path:g.path,now:e}),await t.failpoint?.(`before-target:${g.path}`);let w=m.results.get(g.path);if(w===void 0)throw new Error("Journal result bytes are unavailable.");if(await pa(f.workspaceRoot,g.path,g.sourceSha256,w),await t.failpoint?.(`after-target:${g.path}`),!await Wy(f.workspaceRoot,g.path,n.context.maxTargetBytes,g.resultSha256))throw new Error("Applied target hash could not be verified.");m=await Ue({transaction:m,phase:"applying",type:"target-write-complete",path:g.path,now:e})}return m=await Ue({transaction:m,phase:"applied",type:"application-complete",now:e}),await t.failpoint?.("phase-applied"),{kind:"applied",transaction:Se(m)}}catch{return{kind:"failed",reasons:[An("application-failed","Application stopped safely; inspect transaction discovery before continuing.")]}}finally{await r?.release().catch(()=>{})}}var Xy=new Set(["completed","rolled-back","conflicted"]);function qt(n,t){return{code:"transaction-conflict",message:n,...t===void 0?{}:{path:t}}}async function al(n,t){let e=n.manifest.targets.find(s=>s.path===t);if(e===void 0)return"conflict";let r=await Q(n.manifest.preview.workspace.workspaceRoot,t,n.manifest.maxTargetBytes);return r.kind!=="read"||r.relativePath!==t?"conflict":r.sha256===e.sourceSha256?"preimage":r.sha256===e.resultSha256?"applied":"conflict"}async function Ca(n,t){let e=await Re(n,t),r=await Promise.all(e.manifest.targets.map(async s=>({path:s.path,classification:await al(e,s.path)})));return{transactionId:t,phase:e.state.phase,targets:r}}async function ol(n){try{let t=await Promise.all((await Is(n)).map(r=>Ca(n,r))),e=t.filter(r=>!Xy.has(r.phase));return e.some(r=>r.targets.some(s=>s.classification==="conflict"))?{kind:"conflicted",transactions:e}:e.length===0?{kind:"clear",transactions:t}:{kind:"recovery-required",transactions:e}}catch{return{kind:"failed",reasons:[qt("Transaction discovery failed closed because a journal is unreadable.")]}}}async function il(n,t,e){return n.state.phase==="conflicted"?n:Ue({transaction:n,phase:"conflicted",type:"conflict-detected",message:e,now:t})}async function Jy(n){let t=await Promise.all(n.manifest.targets.map(async e=>[e.path,await al(n,e.path)]));return new Map(t)}async function I0(n,t,e,r,s){let i;try{let[a,o,d,c]=await Promise.all([ur(n.workspace.workspaceRoot),ur(n.snapshot.workspaceRoot),ur(n.workspace.gitRoot),ur(n.snapshot.gitRoot)]);if(a!==o||d!==c)return{kind:"rejected",reasons:[qt("Recovery workspace identity differs.")]};i=await Ye(a,{operation:e,transactionId:t,at:r});let l=await Re(a,t);if(await ur(l.manifest.preview.workspace.workspaceRoot)!==a||await ur(l.manifest.preview.workspace.gitRoot)!==d)return{kind:"rejected",reasons:[qt("Recovery workspace identity differs.")]};if(Xy.has(l.state.phase))return e==="rollback"&&l.state.phase==="rolled-back"?{kind:"rolled-back",transaction:Se(l)}:{kind:"rejected",reasons:[qt("Terminal transaction cannot perform this recovery operation.")],transaction:Se(l)};let u=await Jy(l),p=[...u].find(([,m])=>m==="conflict");if(p!==void 0)return l=await il(l,r,"Current target bytes match neither recorded preimage nor applied image."),{kind:"conflicted",reasons:[qt("Developer or unknown target bytes prohibit automatic recovery.",p[0])],transaction:Se(l)};e==="rollback"&&(l=await Ue({transaction:l,phase:"rolling-back",type:"rollback-started",now:r}),await s?.("phase-rolling-back"));for(let m of l.manifest.targets){let g=u.get(m.path);if(!(e==="resume"&&g==="preimage"||e==="rollback"&&g==="applied"))continue;let w=e==="resume"?"resume":"rollback";if(await s?.(`before-${w}-target:${m.path}`),await al(l,m.path)!==g)return l=await il(l,r,"Target changed after recovery classification."),{kind:"conflicted",reasons:[qt("Target changed immediately before recovery mutation.",m.path)],transaction:Se(l)};let x=e==="resume"?l.results.get(m.path):l.preimages.get(m.path);if(x===void 0)throw new Error("Recovery bytes are unavailable.");await pa(a,m.path,e==="resume"?m.sourceSha256:m.resultSha256,x),await s?.(`after-${w}-target:${m.path}`),l=await Ue({transaction:l,phase:e==="resume"?"applying":"rolling-back",type:`${e}-target-complete`,path:m.path,now:r})}let f=await Jy(l),h=e==="resume"?"applied":"preimage";return[...f.values()].some(m=>m!==h)?(l=await il(l,r,"Recovery result hashes did not verify."),{kind:"conflicted",reasons:[qt("Recovery completed with an unknown target state.")],transaction:Se(l)}):(l=await Ue({transaction:l,phase:e==="resume"?"applied":"rolled-back",type:e==="resume"?"resume-complete":"rollback-complete",now:r}),{kind:e==="resume"?"resumed":"rolled-back",transaction:Se(l)})}catch{return{kind:"failed",reasons:[qt("Recovery stopped safely; rediscover transaction state.")]}}finally{await i?.release().catch(()=>{})}}async function dl(n,t,e=new Date().toISOString()){return I0(n,t,"rollback",e)}var Yy=/^rps_[a-f0-9]{24}$/,Na=/^[a-f0-9]{64}$/,$0=new Set(["rolling-back","rolled-back","conflicted"]);function D0(n,t){let e=C0(n,t);return e===""||!E0(e)&&e!==".."&&!e.startsWith(`..${O0}`)}function pr(n){return n.length>0&&Number.isFinite(Date.parse(n))}function Qy(n){if(n.ordinal!==1&&n.ordinal!==2||!Na.test(n.proposalHash)||!/^txn_[a-f0-9]{24}$/.test(n.transactionId)||n.validationManifestHash!==void 0&&!Na.test(n.validationManifestHash)||!pr(n.recordedAt))throw new Error("Repair attempt record is malformed.")}function M0(n){let{sessionHash:t,...e}=n;if(n.schemaVersion!=="1.0"||!Yy.test(n.repairSessionId)||n.originalRunId.trim().length===0||!Na.test(n.originalPacketHash)||n.maxAttempts!==2||!pr(n.createdAt)||!pr(n.updatedAt)||!Number.isInteger(n.revision)||n.revision<1||n.attempts.length>2||L(e)!==t)throw new Error("Repair session integrity check failed.");n.attempts.forEach(Qy);for(let[r,s]of n.attempts.entries())if(s.ordinal!==r+1)throw new Error("Repair attempt order is malformed.");return n}async function Oa(n){let t=await S0(n),e=N0(t,".kwikqa");if(!D0(t,e))throw new Error("Repair session directory escapes workspace.");await cl(e,{mode:448}).catch(a=>{if(a.code!=="EEXIST")throw a});let r=await Ns(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Repair session path is unsafe.");let s=fr(e,"repair-sessions");await cl(s,{mode:448}).catch(a=>{if(a.code!=="EEXIST")throw a});let i=await Ns(s);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Repair session path is unsafe.");return s}function $a(n){return{...n,sessionHash:L(n)}}function ll(n){return{schemaVersion:n.schemaVersion,repairSessionId:n.repairSessionId,originalRunId:n.originalRunId,originalPacketHash:n.originalPacketHash,maxAttempts:n.maxAttempts,attempts:n.attempts,state:n.state,createdAt:n.createdAt,updatedAt:n.updatedAt,revision:n.revision}}async function ul(n){if(n.originalRunId.trim().length===0||!Na.test(n.originalPacketHash))throw new Error("Original repair evidence identity is invalid.");let t=n.now??new Date().toISOString();if(!pr(t))throw new Error("Repair session timestamp is invalid.");let e=`rps_${A0().replaceAll("-","").slice(0,24)}`,r=$a({schemaVersion:"1.0",repairSessionId:e,originalRunId:n.originalRunId,originalPacketHash:n.originalPacketHash,maxAttempts:2,attempts:[],state:"first-attempt",createdAt:t,updatedAt:t,revision:1}),s=await Oa(n.workspaceRoot);return await ye(fr(s,`${e}.json`),`${pe(r)}
59
- `,{mode:384,replace:!1}),r}async function Gt(n,t){if(!Yy.test(t))throw new Error("Repair session id is invalid.");let e=await Oa(n),r=fr(e,`${t}.json`),s=await Ns(r);if(!s.isFile()||s.isSymbolicLink())throw new Error("Repair session record is unsafe.");let i=JSON.parse(await P0(r,"utf8"));if(i===null||typeof i!="object"||Array.isArray(i))throw new Error("Repair session record is malformed.");return M0(i)}async function pl(n,t){let e=await Oa(n),r=fr(e,`${t}.lock`);await cl(r,{mode:448});let s=await Ns(r);if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Repair session lock is unsafe.");return{release:async()=>{let i=await Ns(r);if(i.dev!==s.dev||i.ino!==s.ino||i.isSymbolicLink())throw new Error("Repair session lock ownership changed.");await T0(r,{recursive:!0,force:!1})}}}async function fl(n,t,e){let r=await Gt(n,t.repairSessionId);if(r.revision!==t.revision||r.sessionHash!==t.sessionHash)throw new Error("Repair session changed concurrently.");let s=await Oa(n);return await ye(fr(s,`${t.repairSessionId}.json`),`${pe(e)}
60
- `,{mode:384,replace:!0}),Gt(n,t.repairSessionId)}async function hl(n,t,e){Qy(e);let r=await pl(n,t);try{let s=await Gt(n,t);if(s.state==="repaired"||s.state==="stopped")throw new Error("Terminal repair session cannot accept another attempt.");if(e.ordinal!==s.attempts.length+1||e.ordinal>s.maxAttempts)throw new Error("Repair session attempt limit or ordering was violated.");if(e.ordinal===1&&s.state!=="first-attempt"||e.ordinal===2&&s.state!=="retry-approval-required")throw new Error("Repair session is not ready for this attempt.");let i=e.recordedAt,a=$a({...ll(s),attempts:[...s.attempts,e],state:e.ordinal===1?"first-attempt":"second-attempt",updatedAt:i,revision:s.revision+1});return await fl(n,s,a)}finally{await r.release()}}function L0(n,t){let e=n.status;if(e==="blocked")throw new Error("A blocked validation run has no attempt outcome.");let r=t.state.history,s=r.findLastIndex(d=>d.type==="validation-started"),i=r[s];if(i===void 0||i.validationRunId!==n.validationRunId||i.planHash!==n.planHash)throw new Error("Validation run was not started for this transaction approval.");let a=r.slice(s+1).find(d=>d.type==="validation-passed"),o=t.state.phase;if(a!==void 0){if(o!=="completed"||e!=="passed"||a.validationRunId!==n.validationRunId||a.planHash!==n.planHash||a.validationManifestHash!==n.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($0.has(o))return e==="passed"?"incomplete":e;throw new Error("Validation outcome does not match the durable transaction state.")}async function Da(n){if(!/^vld_[a-f0-9]{24}$/.test(n.validationRunId))throw new Error("Validation run id is invalid.");let t=n.now??new Date().toISOString();if(!pr(t))throw new Error("Repair session timestamp is invalid.");let e=await pl(n.workspaceRoot,n.repairSessionId),r;try{r=await Ye(n.workspaceRoot,{operation:"record-repair-validation",repairSessionId:n.repairSessionId,validationRunId:n.validationRunId});let s=await Gt(n.workspaceRoot,n.repairSessionId),i=s.attempts.at(-1);if(i===void 0||i.ordinal!==n.ordinal)throw new Error("Repair attempt cannot be finalized from its current state.");let a=await Re(n.workspaceRoot,i.transactionId),o=a.manifest.preview.authoritativeValidation,d=fr(a.directory,"validation",n.validationRunId),c=zt(await Rn(d,"manifest.json",va)),l=new Map(o.requiredCommands.map(m=>[m.commandId,m.commandHash]));if(c.transactionId!==i.transactionId||c.validationRunId!==n.validationRunId||c.planHash!==o.planHash||c.repositoryFingerprint!==o.repositoryFingerprint||L(c.targetHashes)!==L(o.targetHashes)||c.requiredCommandIds.length!==l.size||c.requiredCommandIds.some(m=>!l.has(m))||c.commandRecords.some(m=>l.get(m.commandId)!==m.commandHash)||o.repairSessionId!==s.repairSessionId||o.attemptOrdinal!==i.ordinal||a.manifest.preview.proposal.proposalHash!==i.proposalHash)throw new Error("Validation manifest does not match the repair attempt authority.");for(let m of c.commandRecords)if(!await Sy(d,m,ar))throw new Error("Validation manifest command evidence failed verification.");let u=L0(c,a);if(i.outcome!=="applied"){if(i.validationManifestHash===c.manifestHash&&i.outcome===u)return{session:s};throw new Error("Repair attempt was already finalized with different evidence.")}let p={...i,validationManifestHash:c.manifestHash,outcome:u,recordedAt:t},f=u==="passed"?"repaired":"rollback-required",h=$a({...ll(s),attempts:[...s.attempts.slice(0,-1),p],state:f,updatedAt:t,revision:s.revision+1});return{session:await fl(n.workspaceRoot,s,h)}}finally{await r?.release(),await e.release()}}async function ml(n){if(!/^txn_[a-f0-9]{24}$/.test(n.proof.transactionId)||n.proof.phase!=="rolled-back"||!Number.isInteger(n.proof.transactionRevision)||n.proof.transactionRevision<1)throw new Error("Repair rollback proof is invalid.");let t=n.now??new Date().toISOString();if(!pr(t))throw new Error("Repair session timestamp is invalid.");let e=await pl(n.workspaceRoot,n.repairSessionId),r;try{r=await Ye(n.workspaceRoot,{operation:"confirm-repair-rollback",repairSessionId:n.repairSessionId,transactionId:n.proof.transactionId});let s=await Gt(n.workspaceRoot,n.repairSessionId),i=s.attempts.at(-1);if(s.state!=="rollback-required"||i===void 0||i.ordinal!==n.ordinal||i.transactionId!==n.proof.transactionId||i.validationManifestHash===void 0||i.outcome==="passed"||i.outcome==="applied")throw new Error("Repair session does not match the rolled-back attempt.");let a=await Re(n.workspaceRoot,i.transactionId),o=a.manifest.preview.authoritativeValidation;if(a.state.phase!=="rolled-back"||a.state.revision!==n.proof.transactionRevision||o.repairSessionId!==s.repairSessionId||o.attemptOrdinal!==i.ordinal||a.manifest.preview.proposal.proposalHash!==i.proposalHash)throw new Error("Repair rollback proof does not match the durable transaction.");let d=await Ca(n.workspaceRoot,i.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=n.ordinal===1?"retry-approval-required":"stopped",l=$a({...ll(s),state:c,updatedAt:t,revision:s.revision+1}),u=await fl(n.workspaceRoot,s,l);if(c!=="retry-approval-required")return{session:u};let p={repairSessionId:u.repairSessionId,failedTransactionId:i.transactionId,failedValidationManifestHash:i.validationManifestHash,nextAttemptOrdinal:2};return{session:u,retry:{...p,handoffHash:L(p)}}}finally{await r?.release(),await e.release()}}import{basename as W0,dirname as ng,join as hr,relative as vl,resolve as $t,sep as J0}from"node:path";import{createHash as _0}from"node:crypto";import{lstat as j0,mkdir as F0,readFile as Zy,realpath as yl,rename as B0,writeFile as V0}from"node:fs/promises";import{isAbsolute as H0,join as eg,relative as gl,sep as tg}from"node:path";import{fileURLToPath as z0}from"node:url";var U0=".kwikqa/runtime",q0=["cypress-reporter.cjs","cypress-capture.js","wdio-reporter.mjs","wdio-capture.mjs"];async function G0(n){return Zy(z0(new URL(`./${n}`,import.meta.url)),"utf8")}function K0(n,t){let e=gl(n,t);return e===""||!H0(e)&&e!==".."&&!e.startsWith(`..${tg}`)}async function Ma(n,t){let e=await yl(n),r=e;for(let s of t.split("/").filter(i=>i!=="")){if(s==="."||s==="..")throw new Error("Unsafe KwikQA directory.");r=eg(r,s);let i=await j0(r).catch(()=>{});if(i===void 0)await F0(r);else if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${gl(e,r)} must be a real directory inside the workspace.`)}if(!K0(e,await yl(r)))throw new Error("KwikQA directory escapes workspace.");return r}async function wl(n,t){let e=`${n}.${process.pid}.tmp`;await V0(e,t,{mode:420}),await B0(e,n)}function bl(n){return _0("sha256").update(n,"utf8").digest("hex")}async function La(n){let t=await yl(n),e=await Ma(t,U0),r={};for(let s of q0){let i=await G0(s),a=eg(e,s);await Zy(a,"utf8").catch(()=>{})!==i&&await wl(a,i),r[s]={path:a,relativePath:gl(t,a).split(tg).join("/"),sha256:bl(i)}}return r}function kl(n){return n.split(J0).join("/")}function Os(n,t){let e=kl(vl(n,t));return e.startsWith(".")?e:`./${e}`}async function xl(n,t,e){return await wl(t,e),{path:t,relativePath:kl(vl(n,t)),sha256:bl(e)}}async function _a(n){let t=n.workspaceRoot,e=n.configFile===void 0?t:ng($t(t,n.configFile)),r=["video=false","screenshotOnRunFailure=true",`screenshotsFolder=${$t(t,n.screenshotsDirectory)}`,...n.noRetries?["retries=0"]:[]],s=[];if(n.capture!==void 0){let a=await Ma(t,n.capture.directory),o=await xl(t,hr(a,"kwikqa-settings.js"),`// Generated by KwikQA for one run.
61
- globalThis.__kwikqaCapture = ${JSON.stringify({directory:kl(vl(e,hr(a,"pages"))),...n.capture.only===void 0?{}:{only:[...n.capture.only].sort()}})};
62
- `),d=[`import ${JSON.stringify(Os(a,o.path))};`,`import ${JSON.stringify(Os(a,n.runtime["cypress-capture.js"].path))};`,...n.capture.supportFile===null||n.capture.supportFile===void 0?[]:[`import ${JSON.stringify(Os(a,$t(t,n.capture.supportFile)))};`]],c=await xl(t,hr(a,"kwikqa-support.js"),`// Generated by KwikQA: its failure capture, then the project's support file.
63
- ${d.join(`
64
- `)}
65
- `);s.push(o,c),r.push(`supportFile=${c.path}`)}return{args:["run","--project",e,...n.configFile===void 0?[]:["--config-file",W0(n.configFile)],...n.specs.length===0?[]:["--spec",n.specs.map(a=>$t(t,a)).join(",")],"--reporter",n.runtime["cypress-reporter.cjs"].path,"--reporter-options",[`screenshotsFolder=${$t(t,n.screenshotsDirectory)}`,...n.capture===void 0?[]:[`captureDir=${hr($t(t,n.capture.directory),"pages")}`]].join(","),"--config",r.join(",")],generated:s}}function rg(n){return n.filter(t=>t!=="").slice(-2).join(" ")}async function ja(n){let t=n.workspaceRoot,e=await Ma(t,n.directory),r=$t(t,n.configFile),s=/\.([cm]?ts)$/.exec(n.configFile)?.[1]??"mjs",i={rootDir:ng(r),noRetries:n.noRetries,...n.grep===void 0?{}:{grep:n.grep},...n.reportDirectory===void 0?{}:{reportDir:$t(t,n.reportDirectory)},...n.capture?{captureDir:hr(e,"pages")}:{}},a=["// Generated by KwikQA: the project's WebdriverIO config, with KwikQA's reporter added.",`import { config as base } from ${JSON.stringify(Os(e,r))};`,`import { withKwikqa } from ${JSON.stringify(Os(e,n.runtime["wdio-capture.mjs"].path))};`,"",`export const config = withKwikqa(base, ${JSON.stringify(i,null,2)});`,""].join(`
66
- `),o=await xl(t,hr(e,`wdio.kwikqa.conf.${s}`),a);return{args:["run",o.path,...n.specs.flatMap(c=>["--spec",$t(t,c)])],generated:[o]}}var ag=".kwikqa/capture",Z0=10*6e4,eE={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};function Rl(n){let t=Y0(n.workspaceRoot,n.tool.entryPath).replaceAll("\\","/"),e=n.workspaceRoot,r=n.args.map(s=>{let i=s===e?".":s.split(`${e}/`).join("").split(`${e}\\`).join("").replaceAll("\\","/");return/[\s"']/.test(i)?JSON.stringify(i):i});return`node ${t} ${r.join(" ")}`}async function og(n){let t=n.targets[0];if(t===void 0)return{kind:"unavailable",message:"No failing tests to capture."};let e=We(n.run);if(e===void 0)return{kind:"unavailable",message:ot(n.run)};let r=eE[e],s=await Ps({workspaceRoot:n.workspaceRoot,...n.repositoryRoot===void 0?{}:{repositoryRoot:n.repositoryRoot},ownerPath:mr(n.workspaceRoot,t.file),packageName:r});if(s.kind!=="resolved")return{kind:"unavailable",message:s.reasons[0]?.message??`The project's ${r} could not be resolved; nothing was installed.`};let i=`${ag}/${n.captureId}`,a={framework:e,tool:s.tool,workspaceRoot:n.workspaceRoot,directory:i,targets:n.targets};if(e==="playwright"){let f=[...new Set(n.targets.map(y=>`${y.file}:${y.line}`))],h=[...new Set(n.targets.map(y=>y.project).filter(y=>y!==void 0))],m=mr(n.workspaceRoot,i,"report.json"),g=["test",...f,...h.map(y=>`--project=${y}`),...n.run.configFile===void 0?[]:[`--config=${n.run.configFile}`],"--trace=retain-on-failure","--retries=0","--reporter=json",`--output=${i}/results`];return{kind:"ready",plan:{...a,args:g,workingDirectory:n.workspaceRoot,environment:{PLAYWRIGHT_JSON_OUTPUT_NAME:m,PLAYWRIGHT_HTML_OPEN:"never"},reportPath:m,...n.run.configFile===void 0?{}:{configPath:n.run.configFile}}}}let o=[...new Set(n.targets.map(f=>f.file))],d=n.run.configFile??await ci(n.workspaceRoot,e,t.file),c=mr(n.workspaceRoot,i,"reports"),l=await La(n.workspaceRoot);await ig(mr(n.workspaceRoot,i),{recursive:!0});let u=d===void 0?n.workspaceRoot:X0(Q0(n.workspaceRoot,d));if(e==="cypress"){let f=await _a({workspaceRoot:n.workspaceRoot,runtime:l,...d===void 0?{}:{configFile:d},specs:o,screenshotsDirectory:`${i}/screenshots`,noRetries:!0,capture:{directory:i,supportFile:await li(n.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 ja({workspaceRoot:n.workspaceRoot,runtime:l,configFile:d,specs:o,directory:i,noRetries:!0,reportDirectory:`${i}/reports`,capture:!0});return{kind:"ready",plan:{...a,args:p.args,workingDirectory:u,environment:{KWIKQA_REPORT_DIR:c},reportPath:c,configPath:d}}}async function dg(n,t){let e=mr(n.workspaceRoot,n.directory);if(n.framework==="playwright")await sg(e,{recursive:!0,force:!0}),await ig(e,{recursive:!0});else for(let u of["reports","pages","screenshots"])await sg(mr(e,u),{recursive:!0,force:!0});let r=await ea(n.tool.executable,[...n.tool.nodeArguments,...n.args],{cwd:n.workingDirectory,env:Zi(t.env,n.environment),timeoutMs:t.timeoutMs??Z0}),s=await at(n.reportPath,{workspaceRoot:n.workspaceRoot}),i=di[n.framework];if(s.kind!=="parsed"){let u=r.output.trim().split(`
67
- `).slice(-5).join(`
68
- `);return{kind:"failed",message:r.timedOut?`The capture run timed out before ${i} wrote its report.`:`${i} wrote no report.${u===""?"":`
69
- ${u}`}`,reproduced:0,passed:0}}let a=new Set(n.targets.map(u=>u.logicalTestId)),o=s.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:n.reportPath,reproduced:c,passed:l,failedAgain:d,message:c===0?`None of the ${n.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 tE=/\b(?:getBy\w+|locator|frameLocator)\((?:[^()]|\([^()]*\))*\)/;function nE(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rE(n,t){if(n===void 0)return;let r=new RegExp(`${nE(t)}:(\\d+):\\d+`).exec(n.replaceAll("\\","/"));return r?.[1]===void 0?void 0:Number(r[1])}function cg(n,t){if(n===void 0)return!1;let e=n.replaceAll("\\","/");return e===t||e.endsWith(`/${t}`)}function Fa(n){let t=new Map(n.projects.map(r=>[r.projectId,r.name])),e=[];for(let r of n.logicalTests){let s=ir(r),i=s.at(-1);if(i===void 0)continue;let a=r.location.file,o=i.errors.map(u=>`${u.message??""}
70
- ${u.stack??""}`),d=(cg(i.errorLocation?.file,a)?i.errorLocation?.line:void 0)??i.errors.map(u=>cg(u.location?.file,a)?u.location?.line:rE(u.stack,a)).find(u=>u!==void 0),c=o.map(u=>tE.exec(u)?.[0]).find(u=>u!==void 0),l=t.get(r.projectId);e.push({logicalTestId:r.logicalTestId,title:r.title,file:a,line:r.location.line??1,...l===void 0||l===""?{}:{project:l},...d===void 0?{}:{failingLine:d},...c===void 0?{}:{locator:c},hasTrace:s.some(u=>u.attachments.some(p=>p.name==="trace")),hasPageSnapshot:s.some(u=>u.attachments.some(p=>p.name==="error-context"))})}return e}var ug=3;async function Il(n){let t=Fa(n.run),e=await og({run:n.run,workspaceRoot:n.workspaceRoot,...n.repositoryRoot===void 0?{}:{repositoryRoot:n.repositoryRoot},targets:t,captureId:n.captureId});if(e.kind!=="ready")return e;let{plan:r}=e,s,i,a=r.framework;n.probe&&a==="playwright"&&(vc(r.tool.packageVersion)?(s=await Vm(n.workspaceRoot,n.env),s===void 0&&(i="Live probing needs Playwright CLI: add `@playwright/cli` to the project's dev dependencies (nothing was installed).")):i=`Live probing needs Playwright 1.59 or later; this project has ${r.tool.packageVersion}.`);let o=di[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 ${r.tool.packageVersion}:`,` ${Rl(r)}`,...s===void 0?[]:[`Then pause up to ${ug} locator failures at their failing line and ask Playwright for locators, using Playwright CLI ${s.version} (${s.source==="project"?"project dependency":s.entryPath}).`],`Everything is written under ${r.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} ${r.tool.packageVersion} and its own config:`,` ${Rl(r)}`,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 ${r.directory}/. Your tests run on this machine, as they do in \`npx ${a==="cypress"?"cypress run":"wdio run"}\`.`];return{kind:"ready",prepared:{plan:r,...s===void 0?{}:{cli:s},...i===void 0?{}:{probeUnavailable:i},description:l}}}async function Al(n,t){let e=await dg(n.plan,{env:t});if(n.cli===void 0||e.reportPath===void 0||e.reproduced===0)return{outcome:e};let r=await at(e.reportPath,{workspaceRoot:n.plan.workspaceRoot}),i=(r.kind==="parsed"?Fa(r.run):[]).filter(l=>l.locator!==void 0).slice(0,ug);if(i.length===0)return{outcome:e};let a=lg(n.plan.workspaceRoot,n.plan.directory,"probe");await sE(a,{recursive:!0});let o=[];for(let l of i)o.push(await Gm({workspaceRoot:n.plan.workspaceRoot,playwright:n.plan.tool,cli:n.cli,target:l,...n.plan.configPath===void 0?{}:{configPath:n.plan.configPath},scratchDirectory:a,env:t}));let d={schemaVersion:Bm,tool:{name:"@playwright/cli",version:n.cli.version,source:n.cli.source},playwrightVersion:n.plan.tool.packageVersion,results:o},c=lg(n.plan.workspaceRoot,n.plan.directory,"probe.json");return await iE(c,`${JSON.stringify(d,null,2)}
71
- `),{outcome:e,probePath:c,probe:d}}import{lstat as wE,mkdir as bE,open as xE}from"node:fs/promises";import{dirname as bg,resolve as vE}from"node:path";import{createHash as aE}from"node:crypto";var Ba="kwikqa-report",yg="1",Sn={"test-support":"Test code",application:"Application",environment:"Environment",undetermined:"Undetermined",inconclusive:"Inconclusive","not-diagnosed":"Not diagnosed"},oE=12,dE=800,pg=`
7
+ `):s=String.fromCharCode(r),++this.state.curLine,this.state.lineStart=this.state.pos,s}jsxReadString(e){let r="",s=++this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(b.UnterminatedString,this.state.startLoc);let i=this.input.charCodeAt(this.state.pos);if(i===e)break;i===38?(r+=this.input.slice(s,this.state.pos),r+=this.jsxReadEntity(),s=this.state.pos):Yn(i)?(r+=this.input.slice(s,this.state.pos),r+=this.jsxReadNewLine(!1),s=this.state.pos):++this.state.pos}r+=this.input.slice(s,this.state.pos++),this.finishToken(134,r)}jsxReadEntity(){let e=++this.state.pos;if(this.codePointAtPos(this.state.pos)===35){++this.state.pos;let r=10;this.codePointAtPos(this.state.pos)===120&&(r=16,++this.state.pos);let s=this.readInt(r,void 0,!1,"bail");if(s!==null&&this.codePointAtPos(this.state.pos)===59)return++this.state.pos,String.fromCodePoint(s)}else{let r=0,s=!1;for(;r++<10&&this.state.pos<this.length&&!(s=this.codePointAtPos(this.state.pos)===59);)++this.state.pos;if(s){let i=this.input.slice(e,this.state.pos),a=iI[i];if(++this.state.pos,a)return a}}return this.state.pos=e,"&"}jsxReadWord(){let e,r=this.state.pos;do e=this.input.charCodeAt(++this.state.pos);while(gn(e)||e===45);this.finishToken(141,this.input.slice(r,this.state.pos))}jsxParseIdentifier(){let e=this.startNode();return this.match(141)?e.name=this.state.value:Yd(this.state.type)?e.name=Vt(this.state.type):this.unexpected(),this.next(),this.finishNode(e,"JSXIdentifier")}jsxParseNamespacedName(){let e=this.state.startLoc,r=this.jsxParseIdentifier();if(!this.eat(14))return r;let s=this.startNodeAt(e);return s.namespace=r,s.name=this.jsxParseIdentifier(),this.finishNode(s,"JSXNamespacedName")}jsxParseElementName(){let e=this.state.startLoc,r=this.jsxParseNamespacedName();if(r.type==="JSXNamespacedName")return r;for(;this.eat(16);){let s=this.startNodeAt(e);s.object=r,s.property=this.jsxParseIdentifier(),r=this.finishNode(s,"JSXMemberExpression")}return r}jsxParseAttributeValue(){let e;switch(this.state.type){case 5:return e=this.startNode(),this.setContext(se.brace),this.next(),e=this.jsxParseExpressionContainer(e,se.j_oTag),e.expression.type==="JSXEmptyExpression"&&this.raise(mn.AttributeIsEmpty,e),e;case 143:case 134:return this.parseExprAtom();default:throw this.raise(mn.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(se.j_expr),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXSpreadChild")}jsxParseExpressionContainer(e,r){if(this.match(8))e.expression=this.jsxParseEmptyExpression();else{let s=this.parseExpression();e.expression=s}return this.setContext(r),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXExpressionContainer")}jsxParseAttribute(){let e=this.startNode();return this.match(5)?(this.setContext(se.brace),this.next(),this.expect(21),e.argument=this.parseMaybeAssignAllowIn(),this.setContext(se.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 r=this.startNodeAt(e);return this.eat(144)?this.finishNode(r,"JSXOpeningFragment"):(r.name=this.jsxParseElementName(),this.jsxParseOpeningElementAfterName(r))}jsxParseOpeningElementAfterName(e){let r=[];for(;!this.match(56)&&!this.match(144);)r.push(this.jsxParseAttribute());return e.attributes=r,e.selfClosing=this.eat(56),this.expect(144),this.finishNode(e,"JSXOpeningElement")}jsxParseClosingElementAt(e){let r=this.startNodeAt(e);return this.eat(144)?this.finishNode(r,"JSXClosingFragment"):(r.name=this.jsxParseElementName(),this.expect(144),this.finishNode(r,"JSXClosingElement"))}jsxParseElementAt(e){let r=this.startNodeAt(e),s=[],i=this.jsxParseOpeningElementAt(e),a=null;if(!i.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}s.push(this.jsxParseElementAt(e));break;case 142:s.push(this.parseLiteral(this.state.value,"JSXText"));break;case 5:{let o=this.startNode();this.setContext(se.brace),this.next(),this.match(21)?s.push(this.jsxParseSpreadChild(o)):s.push(this.jsxParseExpressionContainer(o,se.j_expr));break}default:this.unexpected()}Bt(i)&&!Bt(a)&&a!==null?this.raise(mn.MissingClosingTagFragment,a):!Bt(i)&&Bt(a)?this.raise(mn.MissingClosingTagElement,a,{openingTagName:Xn(i.name)}):!Bt(i)&&!Bt(a)&&Xn(a.name)!==Xn(i.name)&&this.raise(mn.MissingClosingTagElement,a,{openingTagName:Xn(i.name)})}if(Bt(i)?(r.openingFragment=i,r.closingFragment=a):(r.openingElement=i,r.closingElement=a),r.children=s,this.match(47))throw this.raise(mn.UnwrappedAdjacentJSXElements,this.state.startLoc);return Bt(i)?this.finishNode(r,"JSXFragment"):this.finishNode(r,"JSXElement")}jsxParseElement(){let e=this.state.startLoc;return this.next(),this.jsxParseElementAt(e)}setContext(e){let{context:r}=this.state;r[r.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 r=this.curContext();if(r===se.j_expr){this.jsxReadToken();return}if(r===se.j_oTag||r===se.j_cTag){if(yt(e)){this.jsxReadWord();return}if(e===62){++this.state.pos,this.finishToken(144);return}if((e===34||e===39)&&r===se.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:r,type:s}=this.state;if(s===56&&e===143)r.splice(-2,2,se.j_cTag),this.state.canStartJSXElement=!1;else if(s===143)r.push(se.j_oTag);else if(s===144){let i=r[r.length-1];i===se.j_oTag&&e===56||i===se.j_cTag?(r.pop(),this.state.canStartJSXElement=r[r.length-1]===se.j_expr):(this.setContext(se.j_expr),this.state.canStartJSXElement=!0)}else this.state.canStartJSXElement=DR(s)}},Pd=class extends Qr{constructor(...n){super(...n),this.tsNames=new Map}},Sd=class extends Zr{constructor(...n){super(...n),this.importsStack=[]}createScope(n){return this.importsStack.push(new Set),new Pd(n)}enter(n){n===1024&&this.importsStack.push(new Set),super.enter(n)}exit(){let n=super.exit();return n===1024&&this.importsStack.pop(),n}hasImport(n,e){let r=this.importsStack.length;if(this.importsStack[r-1].has(n))return!0;if(!e&&r>1){for(let s=0;s<r-1;s++)if(this.importsStack[s].has(n))return!0}return!1}declareName(n,e,r){if(e&4096){this.hasImport(n,!0)&&this.parser.raise(b.VarRedeclaration,r,{identifierName:n}),this.importsStack[this.importsStack.length-1].add(n);return}let s=this.currentScope(),i=s.tsNames.get(n)||0;if(e&1024){this.maybeExportDefined(s,n),s.tsNames.set(n,i|16);return}super.declareName(n,e,r),e&2&&(e&1||(this.checkRedeclarationInScope(s,n,e,r),this.maybeExportDefined(s,n)),i=i|1),e&256&&(i=i|2),e&512&&(i=i|4),e&128&&(i=i|8),i&&s.tsNames.set(n,i)}isRedeclaredInScope(n,e,r){let s=n.tsNames.get(e);if((s&2)>0){if(r&256){let i=!!(r&512),a=(s&4)>0;return i!==a}return!0}return r&128&&(s&8)>0?n.names.get(e)&2?!!(r&1):!1:r&2&&(s&1)>0?!0:super.isRedeclaredInScope(n,e,r)}checkLocalExport(n){let{name:e}=n;if(this.hasImport(e))return;let r=this.scopeStack.length;for(let s=r-1;s>=0;s--){let a=this.scopeStack[s].tsNames.get(e);if((a&1)>0||(a&16)>0)return}super.checkLocalExport(n)}},Ed=class{constructor(){this.stacks=[]}enter(n){this.stacks.push(n)}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 $i(t,n){return(t?2:0)|(n?1:0)}var Cd=class{constructor(){this.sawUnambiguousESM=!1,this.ambiguousScriptDifferentAst=!1}sourceToOffsetPos(n){return n+this.startIndex}offsetToSourcePos(n){return n-this.startIndex}hasPlugin(n){if(typeof n=="string")return this.plugins.has(n);{let[e,r]=n;if(!this.hasPlugin(e))return!1;let s=this.plugins.get(e);for(let i of Object.keys(r))if(s?.[i]!==r[i])return!1;return!0}}getPluginOption(n,e){var r;return(r=this.plugins.get(n))==null?void 0:r[e]}};function xh(t,n){t.trailingComments===void 0?t.trailingComments=n:t.trailingComments.unshift(...n)}function cI(t,n){t.leadingComments===void 0?t.leadingComments=n:t.leadingComments.unshift(...n)}function es(t,n){t.innerComments===void 0?t.innerComments=n:t.innerComments.unshift(...n)}function st(t,n,e){let r=null,s=n.length;for(;r===null&&s>0;)r=n[--s];r===null||r.start>e.start?es(t,e.comments):xh(r,e.comments)}var Nd=class extends Cd{addComment(n){this.filename&&(n.loc.filename=this.filename);let{commentsLen:e}=this.state;this.comments.length!==e&&(this.comments.length=e),this.comments.push(n),this.state.commentsLen++}processComment(n){let{commentStack:e}=this.state,r=e.length;if(r===0)return;let s=r-1,i=e[s];i.start===n.end&&(i.leadingNode=n,s--);let{start:a}=n;for(;s>=0;s--){let o=e[s],d=o.end;if(d>a)o.containingNode=n,this.finalizeComment(o),e.splice(s,1);else{d===a&&(o.trailingNode=n);break}}}finalizeComment(n){var e;let{comments:r}=n;if(n.leadingNode!==null||n.trailingNode!==null)n.leadingNode!==null&&xh(n.leadingNode,r),n.trailingNode!==null&&cI(n.trailingNode,r);else{let s=n.containingNode,i=n.start;if(this.input.charCodeAt(this.offsetToSourcePos(i)-1)===44)switch(s.type){case"ObjectExpression":case"ObjectPattern":st(s,s.properties,n);break;case"CallExpression":case"NewExpression":case"OptionalCallExpression":st(s,s.arguments,n);break;case"ImportExpression":st(s,[s.source,(e=s.options)!=null?e:null],n);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":case"ObjectMethod":case"ClassMethod":case"ClassPrivateMethod":case"TSTypeParameterDeclaration":st(s,s.params,n);break;case"ArrayExpression":case"ArrayPattern":st(s,s.elements,n);break;case"ExportNamedDeclaration":case"ImportDeclaration":st(s,s.specifiers,n);break;case"TSEnumDeclaration":st(s,s.members,n);break;case"TSEnumBody":st(s,s.members,n);break;case"TSInterfaceBody":st(s,s.body,n);break;default:{if(s.type==="RecordExpression"){st(s,s.properties,n);break}if(s.type==="TupleExpression"){st(s,s.elements,n);break}es(s,r)}}else es(s,r)}}finalizeRemainingComments(){let{commentStack:n}=this.state;for(let e=n.length-1;e>=0;e--)this.finalizeComment(n[e]);this.state.commentStack=[]}resetPreviousNodeTrailingComments(n){let{commentStack:e}=this.state,{length:r}=e;if(r===0)return;let s=e[r-1];s.leadingNode===n&&(s.leadingNode=null)}takeSurroundingComments(n,e,r){let{commentStack:s}=this.state,i=s.length;if(i===0)return;let a=i-1;for(;a>=0;a--){let o=s[a],d=o.end;if(o.start===r)o.leadingNode=n;else if(d===e)o.trailingNode=n;else if(d<e)break}}},Od=class t{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=[se.brace],this.firstInvalidTemplateEscapePos=null,this.strictErrors=new Map,this.tokensLength=0}get strict(){return(this.flags&1)>0}set strict(n){n?this.flags|=1:this.flags&=-2}init({strictMode:n,sourceType:e,startIndex:r,startLine:s,startColumn:i}){this.strict=n===!1?!1:n===!0?!0:e==="module",this.startIndex=r,this.curLine=s,this.lineStart=-i,this.startLoc=this.endLoc=new gt(s,i,r)}get maybeInArrowParameters(){return(this.flags&2)>0}set maybeInArrowParameters(n){n?this.flags|=2:this.flags&=-3}get inType(){return(this.flags&4)>0}set inType(n){n?this.flags|=4:this.flags&=-5}get noAnonFunctionType(){return(this.flags&8)>0}set noAnonFunctionType(n){n?this.flags|=8:this.flags&=-9}get hasFlowComment(){return(this.flags&16)>0}set hasFlowComment(n){n?this.flags|=16:this.flags&=-17}get isAmbientContext(){return(this.flags&32)>0}set isAmbientContext(n){n?this.flags|=32:this.flags&=-33}get inAbstractClass(){return(this.flags&64)>0}set inAbstractClass(n){n?this.flags|=64:this.flags&=-65}get inDisallowConditionalTypesContext(){return(this.flags&128)>0}set inDisallowConditionalTypesContext(n){n?this.flags|=128:this.flags&=-129}get soloAwait(){return(this.flags&256)>0}set soloAwait(n){n?this.flags|=256:this.flags&=-257}get inFSharpPipelineDirectBody(){return(this.flags&512)>0}set inFSharpPipelineDirectBody(n){n?this.flags|=512:this.flags&=-513}get canStartJSXElement(){return(this.flags&1024)>0}set canStartJSXElement(n){n?this.flags|=1024:this.flags&=-1025}get containsEsc(){return(this.flags&2048)>0}set containsEsc(n){n?this.flags|=2048:this.flags&=-2049}get hasTopLevelAwait(){return(this.flags&4096)>0}set hasTopLevelAwait(n){n?this.flags|=4096:this.flags&=-4097}curPosition(){return new gt(this.curLine,this.pos-this.lineStart,this.pos+this.startIndex)}clone(){let n=new t;return n.flags=this.flags,n.startIndex=this.startIndex,n.curLine=this.curLine,n.lineStart=this.lineStart,n.startLoc=this.startLoc,n.endLoc=this.endLoc,n.errors=this.errors.slice(),n.potentialArrowAt=this.potentialArrowAt,n.noArrowAt=this.noArrowAt.slice(),n.noArrowParamsConversionAt=this.noArrowParamsConversionAt.slice(),n.topicContext=this.topicContext,n.labels=this.labels.slice(),n.commentsLen=this.commentsLen,n.commentStack=this.commentStack.slice(),n.pos=this.pos,n.type=this.type,n.value=this.value,n.start=this.start,n.end=this.end,n.lastTokEndLoc=this.lastTokEndLoc,n.lastTokStartLoc=this.lastTokStartLoc,n.context=this.context.slice(),n.firstInvalidTemplateEscapePos=this.firstInvalidTemplateEscapePos,n.strictErrors=this.strictErrors,n.tokensLength=this.tokensLength,n}},lI=function(n){return n>=48&&n<=57},ih={decBinOct:new Set([46,66,69,79,95,98,101,111]),hex:new Set([46,88,95,120])},Ci={bin:t=>t===48||t===49,oct:t=>t>=48&&t<=55,dec:t=>t>=48&&t<=57,hex:t=>t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102};function ah(t,n,e,r,s,i){let a=e,o=r,d=s,c="",l=null,u=e,{length:p}=n;for(;;){if(e>=p){i.unterminated(a,o,d),c+=n.slice(u,e);break}let f=n.charCodeAt(e);if(uI(t,f,n,e)){c+=n.slice(u,e);break}if(f===92){c+=n.slice(u,e);let h=pI(n,e,r,s,t==="template",i);h.ch===null&&!l?l={pos:e,lineStart:r,curLine:s}:c+=h.ch,{pos:e,lineStart:r,curLine:s}=h,u=e}else f===8232||f===8233?(++e,++s,r=e):f===10||f===13?t==="template"?(c+=n.slice(u,e)+`
8
+ `,++e,f===13&&n.charCodeAt(e)===10&&++e,++s,u=r=e):i.unterminated(a,o,d):++e}return{pos:e,str:c,firstInvalidLoc:l,lineStart:r,curLine:s,containsInvalid:!!l}}function uI(t,n,e,r){return t==="template"?n===96||n===36&&e.charCodeAt(r+1)===123:n===(t==="double"?34:39)}function pI(t,n,e,r,s,i){let a=!s;n++;let o=c=>({pos:n,ch:c,lineStart:e,curLine:r}),d=t.charCodeAt(n++);switch(d){case 110:return o(`
9
+ `);case 114:return o("\r");case 120:{let c;return{code:c,pos:n}=$d(t,n,e,r,2,!1,a,i),o(c===null?null:String.fromCharCode(c))}case 117:{let c;return{code:c,pos:n}=kh(t,n,e,r,a,i),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:t.charCodeAt(n)===10&&++n;case 10:e=n,++r;case 8232:case 8233:return o("");case 56:case 57:if(s)return o(null);i.strictNumericEscape(n-1,e,r);default:if(d>=48&&d<=55){let c=n-1,u=/^[0-7]+/.exec(t.slice(c,n+2))[0],p=parseInt(u,8);p>255&&(u=u.slice(0,-1),p=parseInt(u,8)),n+=u.length-1;let f=t.charCodeAt(n);if(u!=="0"||f===56||f===57){if(s)return o(null);i.strictNumericEscape(c,e,r)}return o(String.fromCharCode(p))}return o(String.fromCharCode(d))}}function $d(t,n,e,r,s,i,a,o){let d=n,c;return{n:c,pos:n}=vh(t,n,e,r,16,s,i,!1,o,!a),c===null&&(a?o.invalidEscapeSequence(d,e,r):n=d-1),{code:c,pos:n}}function vh(t,n,e,r,s,i,a,o,d,c){let l=n,u=s===16?ih.hex:ih.decBinOct,p=s===16?Ci.hex:s===10?Ci.dec:s===8?Ci.oct:Ci.bin,f=!1,h=0;for(let m=0,g=i??1/0;m<g;++m){let y=t.charCodeAt(n),w;if(y===95&&o!=="bail"){let x=t.charCodeAt(n-1),v=t.charCodeAt(n+1);if(o){if(Number.isNaN(v)||!p(v)||u.has(x)||u.has(v)){if(c)return{n:null,pos:n};d.unexpectedNumericSeparator(n,e,r)}}else{if(c)return{n:null,pos:n};d.numericSeparatorInEscapeSequence(n,e,r)}++n;continue}if(y>=97?w=y-97+10:y>=65?w=y-65+10:lI(y)?w=y-48:w=1/0,w>=s){if(w<=9&&c)return{n:null,pos:n};if(w<=9&&d.invalidDigit(n,e,r,s))w=0;else if(a)w=0,f=!0;else break}++n,h=h*s+w}return n===l||i!=null&&n-l!==i||f?{n:null,pos:n}:{n:h,pos:n}}function kh(t,n,e,r,s,i){let a=t.charCodeAt(n),o;if(a===123){if(++n,{code:o,pos:n}=$d(t,n,e,r,t.indexOf("}",n)-n,!0,s,i),++n,o!==null&&o>1114111)if(s)i.invalidCodePoint(n,e,r);else return{code:null,pos:n}}else({code:o,pos:n}=$d(t,n,e,r,4,!1,s,i));return{code:o,pos:n}}function Wr(t,n,e){return new gt(e,t-n,t)}var fI=new Set([103,109,115,105,121,117,100,118]),mt=class{constructor(n){let e=n.startIndex||0;this.type=n.type,this.value=n.value,this.start=e+n.start,this.end=e+n.end,this.loc=new Zn(n.startLoc,n.endLoc)}},Dd=class extends Nd{constructor(n,e){super(),this.isLookahead=void 0,this.tokens=[],this.errorHandlers_readInt={invalidDigit:(r,s,i,a)=>this.optionFlags&2048?(this.raise(b.InvalidDigit,Wr(r,s,i),{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:(r,s,i)=>{this.recordStrictModeErrors(b.StrictNumericEscape,Wr(r,s,i))},unterminated:(r,s,i)=>{throw this.raise(b.UnterminatedString,Wr(r-1,s,i))}}),this.errorHandlers_readStringContents_template=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:this.errorBuilder(b.StrictNumericEscape),unterminated:(r,s,i)=>{throw this.raise(b.UnterminatedTemplate,Wr(r,s,i))}}),this.state=new Od,this.state.init(n),this.input=e,this.length=e.length,this.comments=[],this.isLookahead=!1}pushToken(n){this.tokens.length=this.state.tokensLength,this.tokens.push(n),++this.state.tokensLength}next(){this.checkKeywordEscapes(),this.optionFlags&256&&this.pushToken(new mt(this.state)),this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()}eat(n){return this.match(n)?(this.next(),!0):!1}match(n){return this.state.type===n}createLookaheadState(n){return{pos:n.pos,value:null,type:n.type,start:n.start,end:n.end,context:[this.curContext()],inType:n.inType,startLoc:n.startLoc,lastTokEndLoc:n.lastTokEndLoc,curLine:n.curLine,lineStart:n.lineStart,curPosition:n.curPosition}}lookahead(){let n=this.state;this.state=this.createLookaheadState(n),this.isLookahead=!0,this.nextToken(),this.isLookahead=!1;let e=this.state;return this.state=n,e}nextTokenStart(){return this.nextTokenStartSince(this.state.pos)}nextTokenStartSince(n){return bd.lastIndex=n,bd.test(this.input)?bd.lastIndex:n}lookaheadCharCode(){return this.lookaheadCharCodeSince(this.state.pos)}lookaheadCharCodeSince(n){return this.input.charCodeAt(this.nextTokenStartSince(n))}nextTokenInLineStart(){return this.nextTokenInLineStartSince(this.state.pos)}nextTokenInLineStartSince(n){return xd.lastIndex=n,xd.test(this.input)?xd.lastIndex:n}lookaheadInLineCharCode(){return this.input.charCodeAt(this.nextTokenInLineStart())}codePointAtPos(n){let e=this.input.charCodeAt(n);if((e&64512)===55296&&++n<this.input.length){let r=this.input.charCodeAt(n);(r&64512)===56320&&(e=65536+((e&1023)<<10)+(r&1023))}return e}setStrict(n){this.state.strict=n,n&&(this.state.strictErrors.forEach(([e,r])=>this.raise(e,r)),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(n){let e;this.isLookahead||(e=this.state.curPosition());let r=this.state.pos,s=this.input.indexOf(n,r+2);if(s===-1)throw this.raise(b.UnterminatedComment,this.state.curPosition());for(this.state.pos=s+n.length,Ei.lastIndex=r+2;Ei.test(this.input)&&Ei.lastIndex<=s;)++this.state.curLine,this.state.lineStart=Ei.lastIndex;if(this.isLookahead)return;let i={type:"CommentBlock",value:this.input.slice(r+2,s),start:this.sourceToOffsetPos(r),end:this.sourceToOffsetPos(s+n.length),loc:new Zn(e,this.state.curPosition())};return this.optionFlags&256&&this.pushToken(i),i}skipLineComment(n){let e=this.state.pos,r;this.isLookahead||(r=this.state.curPosition());let s=this.input.charCodeAt(this.state.pos+=n);if(this.state.pos<this.length)for(;!Yn(s)&&++this.state.pos<this.length;)s=this.input.charCodeAt(this.state.pos);if(this.isLookahead)return;let i=this.state.pos,o={type:"CommentLine",value:this.input.slice(e+n,i),start:this.sourceToOffsetPos(e),end:this.sourceToOffsetPos(i),loc:new Zn(r,this.state.curPosition())};return this.optionFlags&256&&this.pushToken(o),o}skipSpace(){let n=this.state.pos,e=this.optionFlags&4096?[]:null;e:for(;this.state.pos<this.length;){let r=this.input.charCodeAt(this.state.pos);switch(r){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 s=this.skipBlockComment("*/");s!==void 0&&(this.addComment(s),e?.push(s));break}case 47:{let s=this.skipLineComment(2);s!==void 0&&(this.addComment(s),e?.push(s));break}default:break e}break;default:if(oI(r))++this.state.pos;else if(r===45&&!this.inModule&&this.optionFlags&8192){let s=this.state.pos;if(this.input.charCodeAt(s+1)===45&&this.input.charCodeAt(s+2)===62&&(n===0||this.state.lineStart>n)){let i=this.skipLineComment(3);i!==void 0&&(this.addComment(i),e?.push(i))}else break e}else if(r===60&&!this.inModule&&this.optionFlags&8192){let s=this.state.pos;if(this.input.charCodeAt(s+1)===33&&this.input.charCodeAt(s+2)===45&&this.input.charCodeAt(s+3)===45){let i=this.skipLineComment(4);i!==void 0&&(this.addComment(i),e?.push(i))}else break e}else break e}}if(e?.length>0){let r=this.state.pos,s={start:this.sourceToOffsetPos(n),end:this.sourceToOffsetPos(r),comments:e,leadingNode:null,trailingNode:null,containingNode:null};this.state.commentStack.push(s)}}finishToken(n,e){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();let r=this.state.type;this.state.type=n,this.state.value=e,this.isLookahead||this.updateContext(r)}replaceToken(n){this.state.type=n,this.updateContext()}readToken_numberSign(){if(this.state.pos===0&&this.readToken_interpreter())return;let n=this.state.pos+1,e=this.codePointAtPos(n);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 yt(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 n=this.input.charCodeAt(this.state.pos+1);if(n>=48&&n<=57){this.readNumber(!0);return}n===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 n=this.input.charCodeAt(this.state.pos+1);if(n!==33)return!1;let e=this.state.pos;for(this.state.pos+=1;!Yn(n)&&++this.state.pos<this.length;)n=this.input.charCodeAt(this.state.pos);let r=this.input.slice(e+2,this.state.pos);return this.finishToken(28,r),!0}readToken_mult_modulo(n){let e=n===42?55:54,r=1,s=this.input.charCodeAt(this.state.pos+1);n===42&&s===42&&(r++,s=this.input.charCodeAt(this.state.pos+2),e=57),s===61&&!this.state.inType&&(r++,e=n===37?33:30),this.finishOp(e,r)}readToken_pipe_amp(n){let e=this.input.charCodeAt(this.state.pos+1);if(e===n){this.input.charCodeAt(this.state.pos+2)===61?this.finishOp(30,3):this.finishOp(n===124?41:42,2);return}if(n===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(n===124?43:45,1)}readToken_caret(){let n=this.input.charCodeAt(this.state.pos+1);n===61&&!this.state.inType?this.finishOp(32,2):n===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(n){let e=this.input.charCodeAt(this.state.pos+1);if(e===n){this.finishOp(34,2);return}e===61?this.finishOp(30,2):this.finishOp(53,1)}readToken_lt(){let{pos:n}=this.state,e=this.input.charCodeAt(n+1);if(e===60){if(this.input.charCodeAt(n+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:n}=this.state,e=this.input.charCodeAt(n+1);if(e===62){let r=this.input.charCodeAt(n+2)===62?3:2;if(this.input.charCodeAt(n+r)===61){this.finishOp(30,r+1);return}this.finishOp(52,r);return}if(e===61){this.finishOp(49,2);return}this.finishOp(48,1)}readToken_eq_excl(n){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(n===61&&e===62){this.state.pos+=2,this.finishToken(19);return}this.finishOp(n===61?29:35,1)}readToken_question(){let n=this.input.charCodeAt(this.state.pos+1),e=this.input.charCodeAt(this.state.pos+2);n===63?e===61?this.finishOp(30,3):this.finishOp(40,2):n===46&&!(e>=48&&e<=57)?(this.state.pos+=2,this.finishToken(18)):(++this.state.pos,this.finishToken(17))}getTokenFromCode(n){switch(n){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(n);return;case 47:this.readToken_slash();return;case 37:case 42:this.readToken_mult_modulo(n);return;case 124:case 38:this.readToken_pipe_amp(n);return;case 94:this.readToken_caret();return;case 43:case 45:this.readToken_plus_min(n);return;case 60:this.readToken_lt();return;case 62:this.readToken_gt();return;case 61:case 33:this.readToken_eq_excl(n);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(yt(n)){this.readWord(n);return}}throw this.raise(b.InvalidOrUnexpectedToken,this.state.curPosition(),{unexpected:String.fromCodePoint(n)})}finishOp(n,e){let r=this.input.slice(this.state.pos,this.state.pos+e);this.state.pos+=e,this.finishToken(n,r)}readRegexp(){let n=this.state.startLoc,e=this.state.start+1,r,s,{pos:i}=this.state;for(;;++i){if(i>=this.length)throw this.raise(b.UnterminatedRegExp,Me(n,1));let c=this.input.charCodeAt(i);if(Yn(c))throw this.raise(b.UnterminatedRegExp,Me(n,1));if(r)r=!1;else{if(c===91)s=!0;else if(c===93&&s)s=!1;else if(c===47&&!s)break;r=c===92}}let a=this.input.slice(e,i);++i;let o="",d=()=>Me(n,i+2-e);for(;i<this.length;){let c=this.codePointAtPos(i),l=String.fromCharCode(c);if(fI.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(gn(c)||c===92)this.raise(b.MalformedRegExpFlags,d());else break;++i,o+=l}this.state.pos=i,this.finishToken(138,{pattern:a,flags:o})}readInt(n,e,r=!1,s=!0){let{n:i,pos:a}=vh(this.input,this.state.pos,this.state.lineStart,this.state.curLine,n,e,r,s,this.errorHandlers_readInt,!1);return this.state.pos=a,i}readRadixNumber(n){let e=this.state.pos,r=this.state.curPosition(),s=!1;this.state.pos+=2;let i=this.readInt(n);i==null&&this.raise(b.InvalidDigit,Me(r,2),{radix:n});let a=this.input.charCodeAt(this.state.pos);if(a===110)++this.state.pos,s=!0;else if(a===109)throw this.raise(b.InvalidDecimal,r);if(yt(this.codePointAtPos(this.state.pos)))throw this.raise(b.NumberIdentifier,this.state.curPosition());if(s){let o=this.input.slice(e,this.state.pos).replace(/[_n]/g,"");this.finishToken(136,o);return}this.finishToken(135,i)}readNumber(n){let e=this.state.pos,r=this.state.curPosition(),s=!1,i=!1,a=!1,o=!1;!n&&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,r),!this.state.strict){let h=f.indexOf("_");h>0&&this.raise(b.ZeroDigitNumericSeparator,Me(r,h))}o=d&&!/[89]/.test(f)}let c=this.input.charCodeAt(this.state.pos);if(c===46&&!o&&(++this.state.pos,this.readInt(10),s=!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,r),s=!0,a=!0,c=this.input.charCodeAt(this.state.pos)),c===110&&((s||d)&&this.raise(b.InvalidBigIntLiteral,r),++this.state.pos,i=!0),c===109){this.expectPlugin("decimal",this.state.curPosition()),(a||d)&&this.raise(b.InvalidDecimal,r),++this.state.pos;var l=!0}if(yt(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(i){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(n){let{code:e,pos:r}=kh(this.input,this.state.pos,this.state.lineStart,this.state.curLine,n,this.errorHandlers_readCodePoint);return this.state.pos=r,e}readString(n){let{str:e,pos:r,curLine:s,lineStart:i}=ah(n===34?"double":"single",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_string);this.state.pos=r+1,this.state.lineStart=i,this.state.curLine=s,this.finishToken(134,e)}readTemplateContinuation(){this.match(8)||this.unexpected(null,8),this.state.pos--,this.readTemplateToken()}readTemplateToken(){let n=this.input[this.state.pos],{str:e,firstInvalidLoc:r,pos:s,curLine:i,lineStart:a}=ah("template",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_template);this.state.pos=s+1,this.state.lineStart=a,this.state.curLine=i,r&&(this.state.firstInvalidTemplateEscapePos=new gt(r.curLine,r.pos-r.lineStart,this.sourceToOffsetPos(r.pos))),this.input.codePointAt(s)===96?this.finishToken(24,r?null:n+e+"`"):(this.state.pos++,this.finishToken(25,r?null:n+e+"${"))}recordStrictModeErrors(n,e){let r=e.index;this.state.strict&&!this.state.strictErrors.has(r)?this.raise(n,e):this.state.strictErrors.set(r,[n,e])}readWord1(n){this.state.containsEsc=!1;let e="",r=this.state.pos,s=this.state.pos;for(n!==void 0&&(this.state.pos+=n<=65535?1:2);this.state.pos<this.length;){let i=this.codePointAtPos(this.state.pos);if(gn(i))this.state.pos+=i<=65535?1:2;else if(i===92){this.state.containsEsc=!0,e+=this.input.slice(s,this.state.pos);let a=this.state.curPosition(),o=this.state.pos===r?yt:gn;if(this.input.charCodeAt(++this.state.pos)!==117){this.raise(b.MissingUnicodeEscape,this.state.curPosition()),s=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)),s=this.state.pos}else break}return e+this.input.slice(s,this.state.pos)}readWord(n){let e=this.readWord1(n),r=qd.get(e);r!==void 0?this.finishToken(r,Vt(r)):this.finishToken(132,e)}checkKeywordEscapes(){let{type:n}=this.state;Yd(n)&&this.state.containsEsc&&this.raise(b.InvalidEscapedReservedWord,this.state.startLoc,{reservedWord:Vt(n)})}raise(n,e,r={}){let s=e instanceof gt?e:e.loc.start,i=n(s,r);if(!(this.optionFlags&2048))throw i;return this.isLookahead||this.state.errors.push(i),i}raiseOverwrite(n,e,r={}){let s=e instanceof gt?e:e.loc.start,i=s.index,a=this.state.errors;for(let o=a.length-1;o>=0;o--){let d=a[o];if(d.loc.index===i)return a[o]=n(s,r);if(d.loc.index<i)break}return this.raise(n,e,r)}updateContext(n){}unexpected(n,e){throw this.raise(b.UnexpectedToken,n??this.state.startLoc,{expected:e?Vt(e):null})}expectPlugin(n,e){if(this.hasPlugin(n))return!0;throw this.raise(b.MissingPlugin,e??this.state.startLoc,{missingPlugin:[n]})}expectOnePlugin(n){if(!n.some(e=>this.hasPlugin(e)))throw this.raise(b.MissingOneOfPlugins,this.state.startLoc,{missingPlugin:n})}errorBuilder(n){return(e,r,s)=>{this.raise(n,Wr(e,r,s))}}},Md=class{constructor(){this.privateNames=new Set,this.loneAccessors=new Map,this.undefinedPrivateNames=new Map}},Ld=class{constructor(n){this.parser=void 0,this.stack=[],this.undefinedPrivateNames=new Map,this.parser=n}current(){return this.stack[this.stack.length-1]}enter(){this.stack.push(new Md)}exit(){let n=this.stack.pop(),e=this.current();for(let[r,s]of Array.from(n.undefinedPrivateNames))e?e.undefinedPrivateNames.has(r)||e.undefinedPrivateNames.set(r,s):this.parser.raise(b.InvalidPrivateFieldResolution,s,{identifierName:r})}declarePrivateName(n,e,r){let{privateNames:s,loneAccessors:i,undefinedPrivateNames:a}=this.current(),o=s.has(n);if(e&3){let d=o&&i.get(n);if(d){let c=d&4,l=e&4,u=d&3,p=e&3;o=u===p||c!==l,o||i.delete(n)}else o||i.set(n,e)}o&&this.parser.raise(b.PrivateNameRedeclaration,r,{identifierName:n}),s.add(n),a.delete(n)}usePrivateName(n,e){let r;for(r of this.stack)if(r.privateNames.has(n))return;r?r.undefinedPrivateNames.set(n,e):this.parser.raise(b.InvalidPrivateFieldResolution,e,{identifierName:n})}},er=class{constructor(n=0){this.type=n}canBeArrowParameterDeclaration(){return this.type===2||this.type===1}isCertainlyParameterDeclaration(){return this.type===3}},Li=class extends er{constructor(n){super(n),this.declarationErrors=new Map}recordDeclarationError(n,e){let r=e.index;this.declarationErrors.set(r,[n,e])}clearDeclarationError(n){this.declarationErrors.delete(n)}iterateErrors(n){this.declarationErrors.forEach(n)}},_d=class{constructor(n){this.parser=void 0,this.stack=[new er],this.parser=n}enter(n){this.stack.push(n)}exit(){this.stack.pop()}recordParameterInitializerError(n,e){let r=e.loc.start,{stack:s}=this,i=s.length-1,a=s[i];for(;!a.isCertainlyParameterDeclaration();){if(a.canBeArrowParameterDeclaration())a.recordDeclarationError(n,r);else return;a=s[--i]}this.parser.raise(n,r)}recordArrowParameterBindingError(n,e){let{stack:r}=this,s=r[r.length-1],i=e.loc.start;if(s.isCertainlyParameterDeclaration())this.parser.raise(n,i);else if(s.canBeArrowParameterDeclaration())s.recordDeclarationError(n,i);else return}recordAsyncArrowParametersError(n){let{stack:e}=this,r=e.length-1,s=e[r];for(;s.canBeArrowParameterDeclaration();)s.type===2&&s.recordDeclarationError(b.AwaitBindingIdentifier,n),s=e[--r]}validateAsPattern(){let{stack:n}=this,e=n[n.length-1];e.canBeArrowParameterDeclaration()&&e.iterateErrors(([r,s])=>{this.parser.raise(r,s);let i=n.length-2,a=n[i];for(;a.canBeArrowParameterDeclaration();)a.clearDeclarationError(s.index),a=n[--i]})}};function hI(){return new er(3)}function mI(){return new Li(1)}function yI(){return new Li(2)}function Rh(){return new er}var jd=class extends Dd{addExtra(n,e,r,s=!0){if(!n)return;let{extra:i}=n;i==null&&(i={},n.extra=i),s?i[e]=r:Object.defineProperty(i,e,{enumerable:s,value:r})}isContextual(n){return this.state.type===n&&!this.state.containsEsc}isUnparsedContextual(n,e){if(this.input.startsWith(e,n)){let r=this.input.charCodeAt(n+e.length);return!(gn(r)||(r&64512)===55296)}return!1}isLookaheadContextual(n){let e=this.nextTokenStart();return this.isUnparsedContextual(e,n)}eatContextual(n){return this.isContextual(n)?(this.next(),!0):!1}expectContextual(n,e){if(!this.eatContextual(n)){if(e!=null)throw this.raise(e,this.state.startLoc);this.unexpected(null,n)}}canInsertSemicolon(){return this.match(140)||this.match(8)||this.hasPrecedingLineBreak()}hasPrecedingLineBreak(){return sh(this.input,this.offsetToSourcePos(this.state.lastTokEndLoc.index),this.state.start)}hasFollowingLineBreak(){return sh(this.input,this.state.end,this.nextTokenStart())}isLineTerminator(){return this.eat(13)||this.canInsertSemicolon()}semicolon(n=!0){(n?this.isLineTerminator():this.eat(13))||this.raise(b.MissingSemicolon,this.state.lastTokEndLoc)}expect(n,e){this.eat(n)||this.unexpected(e,n)}tryParse(n,e=this.state.clone()){let r={node:null};try{let s=n((i=null)=>{throw r.node=i,r});if(this.state.errors.length>e.errors.length){let i=this.state;return this.state=e,this.state.tokensLength=i.tokensLength,{node:s,error:i.errors[e.errors.length],thrown:!1,aborted:!1,failState:i}}return{node:s,error:null,thrown:!1,aborted:!1,failState:null}}catch(s){let i=this.state;if(this.state=e,s instanceof SyntaxError)return{node:null,error:s,thrown:!0,aborted:!1,failState:i};if(s===r)return{node:r.node,error:null,thrown:!1,aborted:!0,failState:i};throw s}}checkExpressionErrors(n,e){if(!n)return!1;let{shorthandAssignLoc:r,doubleProtoLoc:s,privateKeyLoc:i,optionalParametersLoc:a,voidPatternLoc:o}=n,d=!!r||!!s||!!a||!!i||!!o;if(!e)return d;r!=null&&this.raise(b.InvalidCoverInitializedName,r),s!=null&&this.raise(b.DuplicateProto,s),i!=null&&this.raise(b.UnexpectedPrivateField,i),a!=null&&this.unexpected(a),o!=null&&this.raise(b.InvalidCoverDiscardElement,o)}isLiteralPropertyName(){return fh(this.state.type)}isPrivateName(n){return n.type==="PrivateName"}getPrivateNameSV(n){return n.id.name}hasPropertyAsPrivateName(n){return(n.type==="MemberExpression"||n.type==="OptionalMemberExpression")&&this.isPrivateName(n.property)}isObjectProperty(n){return n.type==="ObjectProperty"}isObjectMethod(n){return n.type==="ObjectMethod"}initializeScopes(n=this.options.sourceType==="module"){let e=this.state.labels;this.state.labels=[];let r=this.exportedIdentifiers;this.exportedIdentifiers=new Set;let s=this.inModule;this.inModule=n;let i=this.scope,a=this.getScopeHandler();this.scope=new a(this,n);let o=this.prodParam;this.prodParam=new Ed;let d=this.classScope;this.classScope=new Ld(this);let c=this.expressionScope;return this.expressionScope=new _d(this),()=>{this.state.labels=e,this.exportedIdentifiers=r,this.inModule=s,this.scope=i,this.prodParam=o,this.classScope=d,this.expressionScope=c}}enterInitialScopes(){let n=0;(this.inModule||this.optionFlags&1)&&(n|=2),this.optionFlags&32&&(n|=1);let e=!this.inModule&&this.options.sourceType==="commonjs";(e||this.optionFlags&2)&&(n|=4),this.prodParam.enter(n);let r=e?514:1;this.optionFlags&4&&(r|=512),this.scope.enter(r)}checkDestructuringPrivate(n){let{privateKeyLoc:e}=n;e!==null&&this.expectPlugin("destructuringPrivate",e)}},Qn=class{constructor(){this.shorthandAssignLoc=null,this.doubleProtoLoc=null,this.privateKeyLoc=null,this.optionalParametersLoc=null,this.voidPatternLoc=null}},tr=class{constructor(n,e,r){this.type="",this.start=e,this.end=0,this.loc=new Zn(r),n?.optionFlags&128&&(this.range=[e,0]),n!=null&&n.filename&&(this.loc.filename=n.filename)}},Fd=tr.prototype;Fd.__clone=function(){let t=new tr(void 0,this.start,this.loc.start),n=Object.keys(this);for(let e=0,r=n.length;e<r;e++){let s=n[e];s!=="leadingComments"&&s!=="trailingComments"&&s!=="innerComments"&&(t[s]=this[s])}return t};var Bd=class extends jd{startNode(){let n=this.state.startLoc;return new tr(this,n.index,n)}startNodeAt(n){return new tr(this,n.index,n)}startNodeAtNode(n){return this.startNodeAt(n.loc.start)}finishNode(n,e){return this.finishNodeAt(n,e,this.state.lastTokEndLoc)}finishNodeAt(n,e,r){return n.type=e,n.end=r.index,n.loc.end=r,this.optionFlags&128&&(n.range[1]=r.index),this.optionFlags&4096&&this.processComment(n),n}resetStartLocation(n,e){n.start=e.index,n.loc.start=e,this.optionFlags&128&&(n.range[0]=e.index)}resetEndLocation(n,e=this.state.lastTokEndLoc){n.end=e.index,n.loc.end=e,this.optionFlags&128&&(n.range[1]=e.index)}resetStartLocationFromNode(n,e){this.resetStartLocation(n,e.loc.start)}castNodeTo(n,e){return n.type=e,n}cloneIdentifier(n){let{type:e,start:r,end:s,loc:i,range:a,name:o}=n,d=Object.create(Fd);return d.type=e,d.start=r,d.end=s,d.loc=i,d.range=a,d.name=o,n.extra&&(d.extra=n.extra),d}cloneStringLiteral(n){let{type:e,start:r,end:s,loc:i,range:a,extra:o}=n,d=Object.create(Fd);return d.type=e,d.start=r,d.end=s,d.loc=i,d.range=a,d.extra=o,d.value=n.value,d}},Vd=t=>t.type==="ParenthesizedExpression"?Vd(t.expression):t,zd=class extends Bd{toAssignable(n,e=!1){var r,s;let i;switch((n.type==="ParenthesizedExpression"||(r=n.extra)!=null&&r.parenthesized)&&(i=Vd(n),e?i.type==="Identifier"?this.expressionScope.recordArrowParameterBindingError(b.InvalidParenthesizedAssignment,n):i.type!=="CallExpression"&&i.type!=="MemberExpression"&&!this.isOptionalMemberExpression(i)&&this.raise(b.InvalidParenthesizedAssignment,n):this.raise(b.InvalidParenthesizedAssignment,n)),n.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":break;case"ObjectExpression":this.castNodeTo(n,"ObjectPattern");for(let o=0,d=n.properties.length,c=d-1;o<d;o++){var a;let l=n.properties[o],u=o===c;this.toAssignableObjectExpressionProp(l,u,e),u&&l.type==="RestElement"&&(a=n.extra)!=null&&a.trailingCommaLoc&&this.raise(b.RestTrailingComma,n.extra.trailingCommaLoc)}break;case"ObjectProperty":{let{key:o,value:d}=n;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(n,"ArrayPattern"),this.toAssignableList(n.elements,(s=n.extra)==null?void 0:s.trailingCommaLoc,e);break;case"AssignmentExpression":n.operator!=="="&&this.raise(b.MissingEqInAssignment,n.left.loc.end),this.castNodeTo(n,"AssignmentPattern"),delete n.operator,n.left.type==="VoidPattern"&&this.raise(b.VoidPatternInitializer,n.left),this.toAssignable(n.left,e);break;case"ParenthesizedExpression":this.toAssignable(i,e);break}}toAssignableObjectExpressionProp(n,e,r){if(n.type==="ObjectMethod")this.raise(n.kind==="get"||n.kind==="set"?b.PatternHasAccessor:b.PatternHasMethod,n.key);else if(n.type==="SpreadElement"){this.castNodeTo(n,"RestElement");let s=n.argument;this.checkToRestConversion(s,!1),this.toAssignable(s,r),e||this.raise(b.RestTrailingComma,n)}else this.toAssignable(n,r)}toAssignableList(n,e,r){let s=n.length-1;for(let i=0;i<=s;i++){let a=n[i];a&&(this.toAssignableListItem(n,i,r),a.type==="RestElement"&&(i<s?this.raise(b.RestTrailingComma,a):e&&this.raise(b.RestTrailingComma,e)))}}toAssignableListItem(n,e,r){let s=n[e];if(s.type==="SpreadElement"){this.castNodeTo(s,"RestElement");let i=s.argument;this.checkToRestConversion(i,!0),this.toAssignable(i,r)}else this.toAssignable(s,r)}isAssignable(n,e){switch(n.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":return!0;case"ObjectExpression":{let r=n.properties.length-1;return n.properties.every((s,i)=>s.type!=="ObjectMethod"&&(i===r||s.type!=="SpreadElement")&&this.isAssignable(s))}case"ObjectProperty":return this.isAssignable(n.value);case"SpreadElement":return this.isAssignable(n.argument);case"ArrayExpression":return n.elements.every(r=>r===null||this.isAssignable(r));case"AssignmentExpression":return n.operator==="=";case"ParenthesizedExpression":return this.isAssignable(n.expression);case"MemberExpression":case"OptionalMemberExpression":return!e;default:return!1}}toReferencedList(n,e){return n}toReferencedListDeep(n,e){this.toReferencedList(n,e);for(let r of n)r?.type==="ArrayExpression"&&this.toReferencedListDeep(r.elements)}parseSpread(n){let e=this.startNode();return this.next(),e.argument=this.parseMaybeAssignAllowIn(n,void 0),this.finishNode(e,"SpreadElement")}parseRestBinding(){let n=this.startNode();this.next();let e=this.parseBindingAtom();return e.type==="VoidPattern"&&this.raise(b.UnexpectedVoidPattern,e),n.argument=e,this.finishNode(n,"RestElement")}parseBindingAtom(){switch(this.state.type){case 0:{let n=this.startNode();return this.next(),n.elements=this.parseBindingList(3,93,1),this.finishNode(n,"ArrayPattern")}case 5:return this.parseObjectLike(8,!0);case 88:return this.parseVoidPattern(null)}return this.parseIdentifier()}parseBindingList(n,e,r){let s=r&1,i=[],a=!0;for(;!this.eat(n);)if(a?a=!1:this.expect(12),s&&this.match(12))i.push(null);else{if(this.eat(n))break;if(this.match(21)){let o=this.parseRestBinding();if((this.hasPlugin("flow")||r&2)&&(o=this.parseFunctionParamType(o)),i.push(o),!this.checkCommaAfterRest(e)){this.expect(n);break}}else{let o=[];if(r&2)for(this.match(26)&&this.hasPlugin("decorators")&&this.raise(b.UnsupportedParameterDecorator,this.state.startLoc);this.match(26);)o.push(this.parseDecorator());i.push(this.parseBindingElement(r,o))}}return i}parseBindingRestProperty(n){return this.next(),this.hasPlugin("discardBinding")&&this.match(88)?(n.argument=this.parseVoidPattern(null),this.raise(b.UnexpectedVoidPattern,n.argument)):n.argument=this.parseIdentifier(),this.checkCommaAfterRest(125),this.finishNode(n,"RestElement")}parseBindingProperty(){let{type:n,startLoc:e}=this.state;if(n===21)return this.parseBindingRestProperty(this.startNode());let r=this.startNode();return n===139?(this.expectPlugin("destructuringPrivate",e),this.classScope.usePrivateName(this.state.value,e),r.key=this.parsePrivateName()):this.parsePropertyName(r),r.method=!1,this.parseObjPropValue(r,e,!1,!1,!0,!1)}parseBindingElement(n,e){let r=this.parseMaybeDefault();return(this.hasPlugin("flow")||n&2)&&this.parseFunctionParamType(r),e.length&&(r.decorators=e,this.resetStartLocationFromNode(r,e[0])),this.parseMaybeDefault(r.loc.start,r)}parseFunctionParamType(n){return n}parseMaybeDefault(n,e){if(n??(n=this.state.startLoc),e=e??this.parseBindingAtom(),!this.eat(29))return e;let r=this.startNodeAt(n);return e.type==="VoidPattern"&&this.raise(b.VoidPatternInitializer,e),r.left=e,r.right=this.parseMaybeAssignAllowIn(),this.finishNode(r,"AssignmentPattern")}isValidLVal(n,e,r,s){switch(n){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(n){return n.type==="OptionalMemberExpression"}checkLVal(n,e,r=64,s=!1,i=!1,a=!1,o=!1){var d;let c=n.type;if(this.isObjectMethod(n))return;let l=this.isOptionalMemberExpression(n);if(l||c==="MemberExpression"){l&&(this.expectPlugin("optionalChainingAssign",n.loc.start),e.type!=="AssignmentExpression"&&this.raise(b.InvalidLhsOptionalChaining,n,{ancestor:e})),r!==64&&this.raise(b.InvalidPropertyBindingPattern,n);return}if(c==="Identifier"){this.checkIdentifier(n,r,i);let{name:y}=n;s&&(s.has(y)?this.raise(b.ParamDupe,n):s.add(y));return}else c==="VoidPattern"&&e.type==="CatchClause"&&this.raise(b.VoidPatternCatchClauseParam,n);let u=Vd(n);o||(o=u.type==="CallExpression"&&(u.callee.type==="Import"||u.callee.type==="Super"));let p=this.isValidLVal(c,o,!(a||(d=n.extra)!=null&&d.parenthesized)&&e.type==="AssignmentExpression",r);if(p===!0)return;if(p===!1){let y=r===64?b.InvalidLhs:b.InvalidLhsBinding;this.raise(y,n,{ancestor:e});return}let f,h;typeof p=="string"?(f=p,h=c==="ParenthesizedExpression"):[f,h]=p;let m=c==="ArrayPattern"||c==="ObjectPattern"?{type:c}:e,g=n[f];if(Array.isArray(g))for(let y of g)y&&this.checkLVal(y,m,r,s,i,h,!0);else g&&this.checkLVal(g,m,r,s,i,h,o)}checkIdentifier(n,e,r=!1){this.state.strict&&(r?bh(n.name,this.inModule):wh(n.name))&&(e===64?this.raise(b.StrictEvalArguments,n,{referenceName:n.name}):this.raise(b.StrictEvalArgumentsBinding,n,{bindingName:n.name})),e&8192&&n.name==="let"&&this.raise(b.LetInLexicalBinding,n),e&64||this.declareNameFromIdentifier(n,e)}declareNameFromIdentifier(n,e){this.scope.declareName(n.name,e,n.loc.start)}checkToRestConversion(n,e){switch(n.type){case"ParenthesizedExpression":this.checkToRestConversion(n.expression,e);break;case"Identifier":case"MemberExpression":break;case"ArrayExpression":case"ObjectExpression":if(e)break;default:this.raise(b.InvalidRestAssignmentPattern,n)}}checkCommaAfterRest(n){return this.match(12)?(this.raise(this.lookaheadCharCode()===n?b.RestTrailingComma:b.ElementAfterRest,this.state.startLoc),!0):!1}},vd=/in(?:stanceof)?|as|satisfies/y;function gI(t){if(t==null)throw new Error(`Unexpected ${t} value.`);return t}function oh(t){if(!t)throw new Error("Assert fail")}var F=it`typescript`({AbstractMethodHasImplementation:({methodName:t})=>`Method '${t}' cannot have an implementation because it is marked abstract.`,AbstractPropertyHasInitializer:({propertyName:t})=>`Property '${t}' 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:t})=>`'declare' is not allowed in ${t}ters.`,DeclareClassFieldHasInitializer:"Initializers are not allowed in ambient contexts.",DeclareFunctionHasImplementation:"An implementation cannot be declared in ambient contexts.",DuplicateAccessibilityModifier:({modifier:t})=>`Accessibility modifier already seen: '${t}'.`,DuplicateModifier:({modifier:t})=>`Duplicate modifier: '${t}'.`,EmptyHeritageClauseType:({token:t})=>`'${t}' 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:t})=>`'${t[0]}' modifier cannot be used with '${t[1]}' modifier.`,IndexSignatureHasAbstract:"Index signatures cannot have the 'abstract' modifier.",IndexSignatureHasAccessibility:({modifier:t})=>`Index signatures cannot have an accessibility modifier ('${t}').`,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:t})=>`'${t}' list can only include identifiers or qualified-names with optional type arguments.`,InvalidModifierOnAwaitUsingDeclaration:t=>`'${t}' modifier cannot appear on an await using declaration.`,InvalidModifierOnTypeMember:({modifier:t})=>`'${t}' modifier cannot appear on a type member.`,InvalidModifierOnTypeParameter:({modifier:t})=>`'${t}' modifier cannot appear on a type parameter.`,InvalidModifierOnTypeParameterPositions:({modifier:t})=>`'${t}' modifier can only appear on a type parameter of a class, interface or type alias.`,InvalidModifierOnUsingDeclaration:t=>`'${t}' modifier cannot appear on a using declaration.`,InvalidModifiersOrder:({orderedModifiers:t})=>`'${t[0]}' modifier must precede '${t[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:t})=>`Private elements cannot have an accessibility modifier ('${t}').`,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:t})=>`Single type parameter ${t} should have a trailing comma. Example usage: <${t},>.`,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:t})=>`Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${t}.`,UsingDeclarationInAmbientContext:t=>`'${t}' declarations are not allowed in ambient contexts.`});function wI(t){switch(t){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 dh(t){return t==="private"||t==="public"||t==="protected"}function bI(t){return t==="in"||t==="out"}var xI=t=>class extends t{constructor(...e){super(...e),this.tsParseInOutModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out"],disallowedModifiers:["const","public","private","protected","readonly","declare","abstract","override"],errorTemplate:F.InvalidModifierOnTypeParameter}),this.tsParseConstModifier=this.tsParseModifiers.bind(this,{allowedModifiers:["const"],disallowedModifiers:["in","out"],errorTemplate:F.InvalidModifierOnTypeParameterPositions}),this.tsParseInOutConstModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out","const"],disallowedModifiers:["public","private","protected","readonly","declare","abstract","override"],errorTemplate:F.InvalidModifierOnTypeParameter})}getScopeHandler(){return Sd}tsIsIdentifier(){return ie(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,r,s){if(!ie(this.state.type)&&this.state.type!==58&&this.state.type!==75)return;let i=this.state.value;if(e.includes(i)){if(s&&this.match(106)||r&&this.tsIsStartOfStaticBlocks())return;if(this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this)))return i}}tsParseModifiers({allowedModifiers:e,disallowedModifiers:r,stopOnStartOfClassStaticBlock:s,errorTemplate:i=F.InvalidModifierOnTypeMember},a){let o=(c,l,u,p)=>{l===u&&a[p]&&this.raise(F.InvalidModifiersOrder,c,{orderedModifiers:[u,p]})},d=(c,l,u,p)=>{(a[u]&&l===p||a[p]&&l===u)&&this.raise(F.IncompatibleModifiers,c,{modifiers:[u,p]})};for(;;){let{startLoc:c}=this.state,l=this.tsParseModifier(e.concat(r??[]),s,a.static);if(!l)break;dh(l)?a.accessibility?this.raise(F.DuplicateAccessibilityModifier,c,{modifier:l}):(o(c,l,l,"override"),o(c,l,l,"static"),o(c,l,l,"readonly"),a.accessibility=l):bI(l)?(a[l]&&this.raise(F.DuplicateModifier,c,{modifier:l}),a[l]=!0,o(c,l,"in","out")):(hasOwnProperty.call(a,l)?this.raise(F.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),r!=null&&r.includes(l)&&this.raise(i,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,r){let s=[];for(;!this.tsIsListTerminator(e);)s.push(r());return s}tsParseDelimitedList(e,r,s){return gI(this.tsParseDelimitedListWorker(e,r,!0,s))}tsParseDelimitedListWorker(e,r,s,i){let a=[],o=-1;for(;!this.tsIsListTerminator(e);){o=-1;let d=r();if(d==null)return;if(a.push(d),this.eat(12)){o=this.state.lastTokStartLoc.index;continue}if(this.tsIsListTerminator(e))break;s&&this.expect(12);return}return i&&(i.value=o),a}tsParseBracketedList(e,r,s,i,a){i||(s?this.expect(0):this.expect(47));let o=this.tsParseDelimitedList(e,r,a);return s?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(F.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 r=this.startNode();return this.isContextual(76)?(r.method=!1,r.key=this.parseIdentifier(!0),r.computed=!1,r.shorthand=!1):this.unexpected(null,76),this.expect(14),r.value=this.tsParseImportTypeWithPropertyValue(),e.properties=[this.finishObjectProperty(r)],this.eat(12),this.expect(8),this.finishNode(e,"ObjectExpression")}tsParseImportTypeWithPropertyValue(){let e=this.startNode(),r=[];for(this.expect(5);!this.match(8);){let s=this.state.type;ie(s)||s===134?r.push(super.parsePropertyDefinition(null)):this.unexpected(),this.eat(12)}return e.properties=r,this.next(),this.finishNode(e,"ObjectExpression")}tsParseEntityName(e){let r;if(e&1&&this.match(78))if(e&2)r=this.parseIdentifier(!0);else{let s=this.startNode();this.next(),r=this.finishNode(s,"ThisExpression")}else r=this.parseIdentifier(!!(e&1));for(;this.eat(16);){let s=this.startNodeAtNode(r);s.left=r,s.right=this.parseIdentifier(!!(e&1)),r=this.finishNode(s,"TSQualifiedName")}return r}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 r=this.startNodeAtNode(e);return r.parameterName=e,r.typeAnnotation=this.tsParseTypeAnnotation(!1),r.asserts=!1,this.finishNode(r,"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 r=this.startNode();return e(r),r.name=this.tsParseTypeParameterName(),r.constraint=this.tsEatThenParseType(81),r.default=this.tsEatThenParseType(29),this.finishNode(r,"TSTypeParameter")}tsTryParseTypeParameters(e){if(this.match(47))return this.tsParseTypeParameters(e)}tsParseTypeParameters(e){let r=this.startNode();this.match(47)||this.match(143)?this.next():this.unexpected();let s={value:-1};return r.params=this.tsParseBracketedList("TypeParametersOrArguments",this.tsParseTypeParameter.bind(this,e),!1,!0,s),r.params.length===0&&this.raise(F.EmptyTypeParameters,r),s.value!==-1&&this.addExtra(r,"trailingComma",s.value),this.finishNode(r,"TSTypeParameterDeclaration")}tsFillSignature(e,r){let s=e===19,i="parameters",a="typeAnnotation";r.typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier),this.expect(10),r[i]=this.tsParseBindingListForSignature(),s?r[a]=this.tsParseTypeOrTypePredicateAnnotation(e):this.match(e)&&(r[a]=this.tsParseTypeOrTypePredicateAnnotation(e))}tsParseBindingListForSignature(){let e=super.parseBindingList(11,41,2);for(let r of e){let{type:s}=r;(s==="AssignmentPattern"||s==="TSParameterProperty")&&this.raise(F.UnsupportedSignatureParameterKind,r,{type:s})}return e}tsParseTypeMemberSemicolon(){!this.eat(12)&&!this.isLineTerminator()&&this.expect(13)}tsParseSignatureMember(e,r){return this.tsFillSignature(14,r),this.tsParseTypeMemberSemicolon(),this.finishNode(r,e)}tsIsUnambiguouslyIndexSignature(){return this.next(),ie(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 r=this.parseIdentifier();r.typeAnnotation=this.tsParseTypeAnnotation(),this.resetEndLocation(r),this.expect(3),e.parameters=[r];let s=this.tsTryParseTypeAnnotation();return s&&(e.typeAnnotation=s),this.tsParseTypeMemberSemicolon(),this.finishNode(e,"TSIndexSignature")}tsParsePropertyOrMethodSignature(e,r){if(this.eat(17)&&(e.optional=!0),this.match(10)||this.match(47)){r&&this.raise(F.ReadonlyForMethodSignature,e);let s=e;s.kind&&this.match(47)&&this.raise(F.AccessorCannotHaveTypeParameters,this.state.curPosition()),this.tsFillSignature(14,s),this.tsParseTypeMemberSemicolon();let i="parameters",a="typeAnnotation";if(s.kind==="get")s[i].length>0&&(this.raise(b.BadGetterArity,this.state.curPosition()),this.isThisParam(s[i][0])&&this.raise(F.AccessorCannotDeclareThisParameter,this.state.curPosition()));else if(s.kind==="set"){if(s[i].length!==1)this.raise(b.BadSetterArity,this.state.curPosition());else{let o=s[i][0];this.isThisParam(o)&&this.raise(F.AccessorCannotDeclareThisParameter,this.state.curPosition()),o.type==="Identifier"&&o.optional&&this.raise(F.SetAccessorCannotHaveOptionalParameter,this.state.curPosition()),o.type==="RestElement"&&this.raise(F.SetAccessorCannotHaveRestParameter,this.state.curPosition())}s[a]&&this.raise(F.SetAccessorCannotHaveReturnType,s[a])}else s.kind="method";return this.finishNode(s,"TSMethodSignature")}else{let s=e;r&&(s.readonly=!0);let i=this.tsTryParseTypeAnnotation();return i&&(s.typeAnnotation=i),this.tsParseTypeMemberSemicolon(),this.finishNode(s,"TSPropertySignature")}}tsParseTypeMember(){let e=this.startNode();if(this.match(10)||this.match(47))return this.tsParseSignatureMember("TSCallSignatureDeclaration",e);if(this.match(77)){let s=this.startNode();return this.next(),this.match(10)||this.match(47)?this.tsParseSignatureMember("TSConstructSignatureDeclaration",e):(e.key=this.createIdentifier(s,"new"),this.tsParsePropertyOrMethodSignature(e,!1))}this.tsParseModifiers({allowedModifiers:["readonly"],disallowedModifiers:["declare","abstract","private","protected","public","static","override"]},e);let r=this.tsTryParseIndexSignature(e);return r||(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 r=this.startNode();return r.name=this.tsParseTypeParameterName(),r.constraint=this.tsExpectThenParseType(58),e.typeParameter=this.finishNode(r,"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 r=!1;return e.elementTypes.forEach(s=>{let{type:i}=s;r&&i!=="TSRestType"&&i!=="TSOptionalType"&&!(i==="TSNamedTupleMember"&&s.optional)&&this.raise(F.OptionalTypeBeforeRequired,s),r||(r=i==="TSNamedTupleMember"&&s.optional||i==="TSOptionalType")}),this.finishNode(e,"TSTupleType")}tsParseTupleElementType(){let e=this.state.startLoc,r=this.eat(21),{startLoc:s}=this.state,i,a,o,d,l=at(this.state.type)?this.lookaheadCharCode():null;if(l===58)i=!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?(i=!0,a=this.createIdentifier(this.startNodeAt(s),u),this.expect(17),this.expect(14),d=this.tsParseType()):(i=!1,d=p,this.expect(17))}else d=this.tsParseType(),o=this.eat(17),i=this.eat(14);if(i){let u;a?(u=this.startNodeAt(s),u.optional=o,u.label=a,u.elementType=d,this.eat(17)&&(u.optional=!0,this.raise(F.TupleOptionalAfterType,this.state.lastTokStartLoc))):(u=this.startNodeAt(s),u.optional=o,this.raise(F.InvalidTupleMemberLabel,d),u.label=d,u.elementType=this.tsParseType()),d=this.finishNode(u,"TSNamedTupleMember")}else if(o){let u=this.startNodeAt(s);u.typeAnnotation=d,d=this.finishNode(u,"TSOptionalType")}if(r){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,r){let s=this.startNode();return e==="TSConstructorType"&&(s.abstract=!!r,r&&this.next(),this.next()),this.tsInAllowConditionalTypesContext(()=>this.tsFillSignature(19,s)),this.finishNode(s,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(),r=this.lookahead();return r.type!==135&&r.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(ie(e)||e===88||e===84){let r=e===88?"TSVoidKeyword":e===84?"TSNullKeyword":wI(this.state.value);if(r!==void 0&&this.lookaheadCharCode()!==46){let s=this.startNode();return this.next(),this.finishNode(s,r)}return this.tsParseTypeReference()}}}throw this.unexpected()}tsParseArrayTypeOrHigher(){let{startLoc:e}=this.state,r=this.tsParseNonArrayType();for(;!this.hasPrecedingLineBreak()&&this.eat(0);)if(this.match(3)){let s=this.startNodeAt(e);s.elementType=r,this.expect(3),r=this.finishNode(s,"TSArrayType")}else{let s=this.startNodeAt(e);s.objectType=r,s.indexType=this.tsParseType(),this.expect(3),r=this.finishNode(s,"TSIndexedAccessType")}return r}tsParseTypeOperator(){let e=this.startNode(),r=this.state.value;return this.next(),e.operator=r,e.typeAnnotation=this.tsParseTypeOperatorOrHigher(),r==="readonly"&&this.tsCheckTypeAnnotationForReadOnly(e),this.finishNode(e,"TSTypeOperator")}tsCheckTypeAnnotationForReadOnly(e){switch(e.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(F.UnexpectedReadonly,e)}}tsParseInferType(){let e=this.startNode();this.expectContextual(115);let r=this.startNode();return r.name=this.tsParseTypeParameterName(),r.constraint=this.tsTryParse(()=>this.tsParseConstraintForInferType()),e.typeParameter=this.finishNode(r,"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 BR(this.state.type)&&!this.state.containsEsc?this.tsParseTypeOperator():this.isContextual(115)?this.tsParseInferType():this.tsInAllowConditionalTypesContext(()=>this.tsParseArrayTypeOrHigher())}tsParseUnionOrIntersectionType(e,r,s){let i=this.startNode(),a=this.eat(s),o=[];do o.push(r());while(this.eat(s));return o.length===1&&!a?o[0]:(i.types=o,this.finishNode(i,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(ie(this.state.type)||this.match(78))return this.next(),!0;if(this.match(5)){let{errors:e}=this.state,r=e.length;try{return this.parseObjectLike(8,!0),e.length===r}catch{return!1}}if(this.match(0)){this.next();let{errors:e}=this.state,r=e.length;try{return super.parseBindingList(3,93,1),e.length===r}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 r=this.startNode();this.expect(e);let s=this.startNode(),i=!!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));if(i&&this.match(78)){let d=this.tsParseThisTypeOrThisTypePredicate();return d.type==="TSThisType"?(s.parameterName=d,s.asserts=!0,s.typeAnnotation=null,d=this.finishNode(s,"TSTypePredicate")):(this.resetStartLocationFromNode(d,s),d.asserts=!0),r.typeAnnotation=d,this.finishNode(r,"TSTypeAnnotation")}let a=this.tsIsIdentifier()&&this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));if(!a)return i?(s.parameterName=this.parseIdentifier(),s.asserts=i,s.typeAnnotation=null,r.typeAnnotation=this.finishNode(s,"TSTypePredicate"),this.finishNode(r,"TSTypeAnnotation")):this.tsParseTypeAnnotation(!1,r);let o=this.tsParseTypeAnnotation(!1);return s.parameterName=a,s.typeAnnotation=o,s.asserts=i,r.typeAnnotation=this.finishNode(s,"TSTypePredicate"),this.finishNode(r,"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(),!ie(this.state.type)&&!this.match(78)?!1:(e&&this.raise(b.InvalidEscapedReservedWord,this.state.lastTokStartLoc,{reservedWord:"asserts"}),!0)}tsParseTypeAnnotation(e=!0,r=this.startNode()){return this.tsInType(()=>{e&&this.expect(14),r.typeAnnotation=this.tsParseType()}),this.finishNode(r,"TSTypeAnnotation")}tsParseType(){oh(this.state.inType);let e=this.tsParseNonConditionalType();if(this.state.inDisallowConditionalTypesContext||this.hasPrecedingLineBreak()||!this.eat(81))return e;let r=this.startNodeAtNode(e);return r.checkType=e,r.extendsType=this.tsInDisallowConditionalTypesContext(()=>this.tsParseNonConditionalType()),this.expect(17),r.trueType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.expect(14),r.falseType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.finishNode(r,"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(F.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 r=this.state.startLoc,s=this.tsParseDelimitedList("HeritageClauseElement",()=>{let i=this.startNode();return i.expression=this.tsParseEntityName(3),this.match(47)&&(i.typeParameters=this.tsParseTypeArguments()),this.finishNode(i,"TSExpressionWithTypeArguments")});return s.length||this.raise(F.EmptyHeritageClauseType,r,{token:e}),s}tsParseInterfaceDeclaration(e,r={}){if(this.hasFollowingLineBreak())return null;this.expectContextual(129),r.declare&&(e.declare=!0),ie(this.state.type)?(e.id=this.parseIdentifier(),this.checkIdentifier(e.id,130)):(e.id=null,this.raise(F.MissingInterfaceName,this.state.startLoc)),e.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers),this.eat(81)&&(e.extends=this.tsParseHeritageClause("extends"));let s=this.startNode();return s.body=this.tsInType(this.tsParseObjectTypeMembers.bind(this)),e.body=this.finishNode(s,"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 r=this.startNode();return this.next(),this.finishNode(r,"TSIntrinsicKeyword")}return this.tsParseType()}),this.semicolon(),this.finishNode(e,"TSTypeAliasDeclaration")}tsInTopLevelContext(e){if(this.curContext()!==se.brace){let r=this.state.context;this.state.context=[r[0]];try{return e()}finally{this.state.context=r}}else return e()}tsInType(e){let r=this.state.inType;this.state.inType=!0;try{return e()}finally{this.state.inType=r}}tsInDisallowConditionalTypesContext(e){let r=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!0;try{return e()}finally{this.state.inDisallowConditionalTypesContext=r}}tsInAllowConditionalTypesContext(e){let r=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!1;try{return e()}finally{this.state.inDisallowConditionalTypesContext=r}}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,r={}){return r.const&&(e.const=!0),r.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,r=!1){if(e.id=this.parseIdentifier(),r||this.checkIdentifier(e.id,1024),this.eat(16)){let s=this.startNode();this.tsParseModuleOrNamespaceDeclaration(s,!0),e.body=s}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,r,s){e.isExport=s||!1,e.id=r||this.parseIdentifier(),this.checkIdentifier(e.id,4096),this.expect(29);let i=this.tsParseModuleReference();return e.importKind==="type"&&i.type!=="TSExternalModuleReference"&&this.raise(F.ImportAliasHasImportType,i),e.moduleReference=i,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 r=this.state.clone(),s=e();return this.state=r,s}tsTryParseAndCatch(e){let r=this.tryParse(s=>e()||s());if(!(r.aborted||!r.node))return r.error&&(this.state=r.failState),r.node}tsTryParse(e){let r=this.state.clone(),s=e();if(s!==void 0&&s!==!1)return s;this.state=r}tsTryParseDeclare(e){if(this.isLineTerminator())return;let r=this.state.type;return this.tsInAmbientContext(()=>{switch(r){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(F.InvalidModifierOnUsingDeclaration,this.state.startLoc,"declare"),e.declare=!0,this.parseVarStatement(e,"using",!0);break;case 96:if(this.isAwaitUsing())return this.raise(F.InvalidModifierOnAwaitUsingDeclaration,this.state.startLoc,"declare"),e.declare=!0,this.next(),this.parseVarStatement(e,"await using",!0);break;case 129:{let s=this.tsParseInterfaceDeclaration(e,{declare:!0});if(s)return s}default:if(ie(r))return this.tsParseDeclaration(e,this.state.type,!0,null)}})}tsTryParseExportDeclaration(){return this.tsParseDeclaration(this.startNode(),this.state.type,!0,null)}tsParseDeclaration(e,r,s,i){switch(r){case 124:if(this.tsCheckLineTerminator(s)&&(this.match(80)||ie(this.state.type)))return this.tsParseAbstractDeclaration(e,i);break;case 127:if(this.tsCheckLineTerminator(s)){if(this.match(134))return this.tsParseAmbientExternalModuleDeclaration(e);if(ie(this.state.type))return e.kind="module",this.tsParseModuleOrNamespaceDeclaration(e)}break;case 128:if(this.tsCheckLineTerminator(s)&&ie(this.state.type))return e.kind="namespace",this.tsParseModuleOrNamespaceDeclaration(e);break;case 130:if(this.tsCheckLineTerminator(s)&&ie(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 r=this.state.maybeInArrowParameters;this.state.maybeInArrowParameters=!0;let s=this.tsTryParseAndCatch(()=>{let i=this.startNodeAt(e);return i.typeParameters=this.tsParseTypeParameters(this.tsParseConstModifier),super.parseFunctionParams(i),i.returnType=this.tsTryParseTypeOrTypePredicateAnnotation(),this.expect(19),i});if(this.state.maybeInArrowParameters=r,!!s)return super.parseArrowExpression(s,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(F.EmptyTypeArguments,e):!this.state.inType&&this.curContext()===se.brace&&this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TSTypeParameterInstantiation")}tsIsDeclarationStart(){return VR(this.state.type)}isExportDefaultSpecifier(){return this.tsIsDeclarationStart()?!1:super.isExportDefaultSpecifier()}parseBindingElement(e,r){let s=r.length?r[0].loc.start:this.state.startLoc,i={};this.tsParseModifiers({allowedModifiers:["public","private","protected","override","readonly"]},i);let a=i.accessibility,o=i.override,d=i.readonly;!(e&4)&&(a||d||o)&&this.raise(F.UnexpectedParameterModifier,s);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(s);return r.length&&(u.decorators=r),a&&(u.accessibility=a),d&&(u.readonly=d),o&&(u.override=o),l.type!=="Identifier"&&l.type!=="AssignmentPattern"&&this.raise(F.UnsupportedParameterPropertyKind,u),u.parameter=l,this.finishNode(u,"TSParameterProperty")}return r.length&&(c.decorators=r),l}isSimpleParameter(e){return e.type==="TSParameterProperty"&&super.isSimpleParameter(e.parameter)||super.isSimpleParameter(e)}tsDisallowOptionalPattern(e){for(let r of e.params)r.type!=="Identifier"&&r.optional&&!this.state.isAmbientContext&&this.raise(F.PatternIsOptional,r)}setArrowFunctionParameters(e,r,s){super.setArrowFunctionParameters(e,r,s),this.tsDisallowOptionalPattern(e)}parseFunctionBodyAndFinish(e,r,s=!1){this.match(14)&&(e.returnType=this.tsParseTypeOrTypePredicateAnnotation(14));let i=r==="FunctionDeclaration"?"TSDeclareFunction":r==="ClassMethod"||r==="ClassPrivateMethod"?"TSDeclareMethod":void 0;return i&&!this.match(5)&&this.isLineTerminator()?this.finishNode(e,i):i==="TSDeclareFunction"&&this.state.isAmbientContext&&(this.raise(F.DeclareFunctionHasImplementation,e),e.declare)?super.parseFunctionBodyAndFinish(e,i,s):(this.tsDisallowOptionalPattern(e),super.parseFunctionBodyAndFinish(e,r,s))}registerFunctionStatementId(e){!e.body&&e.id?this.checkIdentifier(e.id,1024):super.registerFunctionStatementId(e)}tsCheckForInvalidTypeCasts(e){e.forEach(r=>{r?.type==="TSTypeCastExpression"&&this.raise(F.UnexpectedTypeAnnotation,r.typeAnnotation)})}toReferencedList(e,r){return this.tsCheckForInvalidTypeCasts(e),e}parseArrayLike(e,r,s){let i=super.parseArrayLike(e,r,s);return i.type==="ArrayExpression"&&this.tsCheckForInvalidTypeCasts(i.elements),i}parseSubscript(e,r,s,i){if(!this.hasPrecedingLineBreak()&&this.match(35)){this.state.canStartJSXElement=!1,this.next();let o=this.startNodeAt(r);return o.expression=e,this.finishNode(o,"TSNonNullExpression")}let a=!1;if(this.match(18)&&this.lookaheadCharCode()===60){if(s)return i.stop=!0,e;i.optionalChainMember=a=!0,this.next()}if(this.match(47)||this.match(51)){let o,d=this.tsTryParseAndCatch(()=>{if(!s&&this.atPossibleAsyncArrow(e)){let p=this.tsTryParseGenericAsyncArrowFunction(r);if(p)return i.stop=!0,p}let c=this.tsParseTypeArgumentsInExpression();if(!c)return;if(a&&!this.match(10)){o=this.state.curPosition();return}if(Mi(this.state.type)){let p=super.parseTaggedTemplateExpression(e,r,i);return p.typeParameters=c,p}if(!s&&this.eat(10)){let p=this.startNodeAt(r);return p.callee=e,p.arguments=this.parseCallExpressionArguments(),this.tsCheckForInvalidTypeCasts(p.arguments),p.typeParameters=c,i.optionalChainMember&&(p.optional=a),this.finishCallExpression(p,i.optionalChainMember)}let l=this.state.type;if(l===48||l===52||l!==10&&l!==93&&l!==120&&Jr(l)&&!this.hasPrecedingLineBreak())return;let u=this.startNodeAt(r);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(F.InvalidPropertyAccessAfterInstantiationExpression,this.state.startLoc),!this.match(16)&&!this.match(18)&&(d.expression=super.stopParseSubscript(e,i))),d}return super.parseSubscript(e,r,s,i)}parseNewCallee(e){var r;super.parseNewCallee(e);let{callee:s}=e;s.type==="TSInstantiationExpression"&&!((r=s.extra)!=null&&r.parenthesized)&&(e.typeParameters=s.typeParameters,e.callee=s.expression)}parseExprOp(e,r,s){let i;if(Oi(58)>s&&!this.hasPrecedingLineBreak()&&(this.isContextual(93)||(i=this.isContextual(120)))){let a=this.startNodeAt(r);return a.expression=e,a.typeAnnotation=this.tsInType(()=>(this.next(),this.match(75)?(i&&this.raise(b.UnexpectedKeyword,this.state.startLoc,{keyword:"const"}),this.tsParseTypeReference()):this.tsParseType())),this.finishNode(a,i?"TSSatisfiesExpression":"TSAsExpression"),this.reScan_lt_gt(),this.parseExprOp(a,r,s)}return super.parseExprOp(e,r,s)}checkReservedWord(e,r,s,i){this.state.isAmbientContext||super.checkReservedWord(e,r,s,i)}checkImportReflection(e){super.checkImportReflection(e),e.module&&e.importKind!=="value"&&this.raise(F.ImportReflectionHasImportType,e.specifiers[0].loc.start)}checkDuplicateExports(){}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return!0;if(this.isContextual(130)){let r=this.lookaheadCharCode();return e?r===123||r===42:r!==61}return!e&&this.isContextual(87)}applyImportPhase(e,r,s,i){super.applyImportPhase(e,r,s,i),r?e.exportKind=s==="type"?"type":"value":e.importKind=s==="type"||s==="typeof"?s:"value"}parseImport(e){if(this.match(134))return e.importKind="value",super.parseImport(e);let r;if(ie(this.state.type)&&this.lookaheadCharCode()===61)return e.importKind="value",this.tsParseImportEqualsDeclaration(e);if(this.isContextual(130)){let s=this.parseMaybeImportPhase(e,!1);if(this.lookaheadCharCode()===61)return this.tsParseImportEqualsDeclaration(e,s);r=super.parseImportSpecifiersAndAfter(e,s)}else r=super.parseImport(e);return r.importKind==="type"&&r.specifiers.length>1&&r.specifiers[0].type==="ImportDefaultSpecifier"&&this.raise(F.TypeImportCannotSpecifyDefaultAndNamed,r),r}parseExport(e,r){if(this.match(83)){let s=e;this.next();let i=null;return this.isContextual(130)&&this.isPotentialImportPhase(!1)?i=this.parseMaybeImportPhase(s,!1):s.importKind="value",this.tsParseImportEqualsDeclaration(s,i,!0)}else if(this.eat(29)){let s=e;return s.expression=super.parseExpression(),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(s,"TSExportAssignment")}else if(this.eatContextual(93)){let s=e;return this.expectContextual(128),s.id=this.parseIdentifier(),this.semicolon(),this.finishNode(s,"TSNamespaceExportDeclaration")}else return super.parseExport(e,r)}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,r,s=!1){let{isAmbientContext:i}=this.state,a=super.parseVarStatement(e,r,s||i);if(!i)return a;if(!e.declare&&(r==="using"||r==="await using"))return this.raiseOverwrite(F.UsingDeclarationInAmbientContext,e,r),a;for(let{id:o,init:d}of a.declarations)d&&(r==="var"||r==="let"||o.typeAnnotation?this.raise(F.InitializerNotAllowedInAmbientContext,d):kI(d,this.hasPlugin("estree"))||this.raise(F.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference,d));return a}parseStatementContent(e,r){if(!this.state.containsEsc)switch(this.state.type){case 75:{if(this.isLookaheadContextual("enum")){let s=this.startNode();return this.expect(75),this.tsParseEnumDeclaration(s,{const:!0})}break}case 124:case 125:{if(this.nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine()){let s=this.state.type,i=this.startNode();this.next();let a=s===125?this.tsTryParseDeclare(i):this.tsParseAbstractDeclaration(i,r);return a?(s===125&&(a.declare=!0),a):(i.expression=this.createIdentifier(this.startNodeAt(i.loc.start),s===125?"declare":"abstract"),this.semicolon(!1),this.finishNode(i,"ExpressionStatement"))}break}case 126:return this.tsParseEnumDeclaration(this.startNode());case 112:{if(this.lookaheadCharCode()===123){let i=this.startNode();return this.tsParseAmbientExternalModuleDeclaration(i)}break}case 129:{let s=this.tsParseInterfaceDeclaration(this.startNode());if(s)return s;break}case 127:{if(this.nextTokenIsIdentifierOrStringLiteralOnSameLine()){let s=this.startNode();return this.next(),this.tsParseDeclaration(s,127,!1,r)}break}case 128:{if(this.nextTokenIsIdentifierOnSameLine()){let s=this.startNode();return this.next(),this.tsParseDeclaration(s,128,!1,r)}break}case 130:{if(this.nextTokenIsIdentifierOnSameLine()){let s=this.startNode();return this.next(),this.tsParseTypeAliasDeclaration(s)}break}}return super.parseStatementContent(e,r)}parseAccessModifier(){return this.tsParseModifier(["public","protected","private"])}tsHasSomeModifiers(e,r){return r.some(s=>dh(s)?e.accessibility===s:!!e[s])}tsIsStartOfStaticBlocks(){return this.isContextual(106)&&this.lookaheadCharCode()===123}parseClassMember(e,r,s){let i=["declare","private","public","protected","override","abstract","readonly","static"];this.tsParseModifiers({allowedModifiers:i,disallowedModifiers:["in","out"],stopOnStartOfClassStaticBlock:!0,errorTemplate:F.InvalidModifierOnTypeParameterPositions},r);let a=()=>{this.tsIsStartOfStaticBlocks()?(this.next(),this.next(),this.tsHasSomeModifiers(r,i)&&this.raise(F.StaticBlockCannotHaveModifier,this.state.curPosition()),super.parseClassStaticBlock(e,r)):this.parseClassMemberWithIsStatic(e,r,s,!!r.static)};r.declare?this.tsInAmbientContext(a):a()}parseClassMemberWithIsStatic(e,r,s,i){let a=this.tsTryParseIndexSignature(r);if(a){e.body.push(a),r.abstract&&this.raise(F.IndexSignatureHasAbstract,r),r.accessibility&&this.raise(F.IndexSignatureHasAccessibility,r,{modifier:r.accessibility}),r.declare&&this.raise(F.IndexSignatureHasDeclare,r),r.override&&this.raise(F.IndexSignatureHasOverride,r);return}!this.state.inAbstractClass&&r.abstract&&this.raise(F.NonAbstractClassHasAbstractMethod,r),r.override&&(s.hadSuperClass||this.raise(F.OverrideNotInSubClass,r)),super.parseClassMemberWithIsStatic(e,r,s,i)}parsePostMemberNameModifiers(e){this.eat(17)&&(e.optional=!0),e.readonly&&this.match(10)&&this.raise(F.ClassMethodHasReadonly,e),e.declare&&this.match(10)&&this.raise(F.ClassMethodHasDeclare,e)}shouldParseExportDeclaration(){return this.tsIsDeclarationStart()?!0:super.shouldParseExportDeclaration()}parseConditional(e,r,s){if(!this.match(17))return e;if(this.state.maybeInArrowParameters){let i=this.lookaheadCharCode();if(i===44||i===61||i===58||i===41)return this.setOptionalParametersError(s),e}return super.parseConditional(e,r,s)}parseParenItem(e,r){let s=super.parseParenItem(e,r);if(this.eat(17)&&(s.optional=!0,this.resetEndLocation(e)),this.match(14)){let i=this.startNodeAt(r);return i.expression=e,i.typeAnnotation=this.tsParseTypeAnnotation(),this.finishNode(i,"TSTypeCastExpression")}return e}parseExportDeclaration(e){if(!this.state.isAmbientContext&&this.isContextual(125))return this.tsInAmbientContext(()=>this.parseExportDeclaration(e));let r=this.state.startLoc,s=this.eatContextual(125);if(s&&(this.isContextual(125)||!this.shouldParseExportDeclaration()))throw this.raise(F.ExpectedAmbientAfterExportDeclare,this.state.startLoc);let a=ie(this.state.type)&&this.tsTryParseExportDeclaration()||super.parseExportDeclaration(e);return a?((a.type==="TSInterfaceDeclaration"||a.type==="TSTypeAliasDeclaration"||s)&&(e.exportKind="type"),s&&a.type!=="TSImportEqualsDeclaration"&&(this.resetStartLocation(a,r),a.declare=!0),a):null}parseClassId(e,r,s,i){if((!r||s)&&this.isContextual(113))return;super.parseClassId(e,r,s,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 r=this.tsTryParseTypeAnnotation();r&&(e.typeAnnotation=r)}parseClassProperty(e){if(this.parseClassPropertyAnnotation(e),this.state.isAmbientContext&&!(e.readonly&&!e.typeAnnotation)&&this.match(29)&&this.raise(F.DeclareClassFieldHasInitializer,this.state.startLoc),e.abstract&&this.match(29)){let{key:r}=e;this.raise(F.AbstractPropertyHasInitializer,this.state.startLoc,{propertyName:r.type==="Identifier"&&!e.computed?r.name:`[${this.input.slice(this.offsetToSourcePos(r.start),this.offsetToSourcePos(r.end))}]`})}return super.parseClassProperty(e)}parseClassPrivateProperty(e){return e.abstract&&this.raise(F.PrivateElementHasAbstract,e),e.accessibility&&this.raise(F.PrivateElementHasAccessibility,e,{modifier:e.accessibility}),this.parseClassPropertyAnnotation(e),super.parseClassPrivateProperty(e)}parseClassAccessorProperty(e){return this.parseClassPropertyAnnotation(e),e.optional&&this.raise(F.AccessorCannotBeOptional,e),super.parseClassAccessorProperty(e)}pushClassMethod(e,r,s,i,a,o){let d=this.tsTryParseTypeParameters(this.tsParseConstModifier);d&&a&&this.raise(F.ConstructorHasTypeParameters,d);let{declare:c=!1,kind:l}=r;c&&(l==="get"||l==="set")&&this.raise(F.DeclareAccessor,r,{kind:l}),d&&(r.typeParameters=d),super.pushClassMethod(e,r,s,i,a,o)}pushClassPrivateMethod(e,r,s,i){let a=this.tsTryParseTypeParameters(this.tsParseConstModifier);a&&(r.typeParameters=a),super.pushClassPrivateMethod(e,r,s,i)}declareClassPrivateMethodInScope(e,r){e.type!=="TSDeclareMethod"&&(e.type==="MethodDefinition"&&e.value.body==null||super.declareClassPrivateMethodInScope(e,r))}parseClassSuper(e){if(super.parseClassSuper(e),e.superClass)if(e.superClass.type==="TSInstantiationExpression"){let r=e.superClass,s=r.expression;this.takeSurroundingComments(s,s.start,s.end);let i=r.typeParameters;this.takeSurroundingComments(i,i.start,i.end),e.superClass=s,e.superTypeParameters=i}else(this.match(47)||this.match(51))&&(e.superTypeParameters=this.tsParseTypeArgumentsInExpression());this.eatContextual(113)&&(e.implements=this.tsParseHeritageClause("implements"))}parseObjPropValue(e,r,s,i,a,o,d){let c=this.tsTryParseTypeParameters(this.tsParseConstModifier);return c&&(e.typeParameters=c),super.parseObjPropValue(e,r,s,i,a,o,d)}parseFunctionParams(e,r){let s=this.tsTryParseTypeParameters(this.tsParseConstModifier);s&&(e.typeParameters=s),super.parseFunctionParams(e,r)}parseVarId(e,r){super.parseVarId(e,r),e.id.type==="Identifier"&&!this.hasPrecedingLineBreak()&&this.eat(35)&&(e.definite=!0);let s=this.tsTryParseTypeAnnotation();s&&(e.id.typeAnnotation=s,this.resetEndLocation(e.id))}parseAsyncArrowFromCallExpression(e,r){return this.match(14)&&(e.returnType=this.tsParseTypeAnnotation()),super.parseAsyncArrowFromCallExpression(e,r)}parseMaybeAssign(e,r){var s,i,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,r),c),!l.error)return l.node;let{context:h}=this.state,m=h[h.length-1];(m===se.j_oTag||m===se.j_expr)&&h.pop()}if(!((s=l)!=null&&s.error)&&!this.match(47))return super.parseMaybeAssign(e,r);(!c||c===this.state)&&(c=this.state.clone());let p,f=this.tryParse(h=>{var m,g;p=this.tsParseTypeParameters(this.tsParseConstModifier);let y=super.parseMaybeAssign(e,r);return(y.type!=="ArrowFunctionExpression"||(m=y.extra)!=null&&m.parenthesized)&&h(),((g=p)==null?void 0:g.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&&(oh(!this.hasPlugin("jsx")),u=this.tryParse(()=>super.parseMaybeAssign(e,r),c),!u.error))return u.node;if((i=l)!=null&&i.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 r;e.params.length===1&&!e.params[0].constraint&&!((r=e.extra)!=null&&r.trailingComma)&&this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(F.ReservedArrowTypeParam,e)}parseMaybeUnary(e,r){return!this.hasPlugin("jsx")&&this.match(47)?this.tsParseTypeAssertion():super.parseMaybeUnary(e,r)}parseArrow(e){if(this.match(14)){let r=this.tryParse(s=>{let i=this.tsParseTypeOrTypePredicateAnnotation(14);return(this.canInsertSemicolon()||!this.match(19))&&s(),i});if(r.aborted)return;r.thrown||(r.error&&(this.state=r.failState),e.returnType=r.node)}return super.parseArrow(e)}parseFunctionParamType(e){this.eat(17)&&(e.optional=!0);let r=this.tsTryParseTypeAnnotation();return r&&(e.typeAnnotation=r),this.resetEndLocation(e),e}isAssignable(e,r){switch(e.type){case"TSTypeCastExpression":return this.isAssignable(e.expression,r);case"TSParameterProperty":return!0;default:return super.isAssignable(e,r)}}toAssignable(e,r=!1){switch(e.type){case"ParenthesizedExpression":this.toAssignableParenthesizedExpression(e,r);break;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":r?this.expressionScope.recordArrowParameterBindingError(F.UnexpectedTypeCastInParameter,e):this.raise(F.UnexpectedTypeCastInParameter,e),this.toAssignable(e.expression,r);break;case"AssignmentExpression":!r&&e.left.type==="TSTypeCastExpression"&&(e.left=this.typeCastToParameter(e.left));default:super.toAssignable(e,r)}}toAssignableParenthesizedExpression(e,r){switch(e.expression.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":case"ParenthesizedExpression":this.toAssignable(e.expression,r);break;default:super.toAssignable(e,r)}}checkToRestConversion(e,r){switch(e.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":this.checkToRestConversion(e.expression,!1);break;default:super.checkToRestConversion(e,r)}}isValidLVal(e,r,s,i){switch(e){case"TSTypeCastExpression":return!0;case"TSParameterProperty":return"parameter";case"TSNonNullExpression":return"expression";case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":return(i!==64||!s)&&["expression",!0];default:return super.isValidLVal(e,r,s,i)}}parseBindingAtom(){return this.state.type===78?this.parseIdentifier(!0):super.parseBindingAtom()}parseMaybeDecoratorArguments(e,r){if(this.match(47)||this.match(51)){let s=this.tsParseTypeArgumentsInExpression();if(this.match(10)){let i=super.parseMaybeDecoratorArguments(e,r);return i.typeParameters=s,i}this.unexpected(null,10)}return super.parseMaybeDecoratorArguments(e,r)}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,r){let s=super.parseMaybeDefault(e,r);return s.type==="AssignmentPattern"&&s.typeAnnotation&&s.right.start<s.typeAnnotation.start&&this.raise(F.TypeAnnotationAfterAssign,s.typeAnnotation),s}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,r,s){let i=e[r];i.type==="TSTypeCastExpression"&&(e[r]=this.typeCastToParameter(i)),super.toAssignableListItem(e,r,s)}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(r=>this.isAssignable(r,!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 r=this.tsTryParseAndCatch(()=>this.tsParseTypeArgumentsInExpression());r&&(e.typeParameters=r)}return super.jsxParseOpeningElementAfterName(e)}getGetterSetterExpectedParamCount(e){let r=super.getGetterSetterExpectedParamCount(e),i=this.getObjectOrClassMethodParams(e)[0];return i&&this.isThisParam(i)?r+1:r}parseCatchClauseParam(){let e=super.parseCatchClauseParam(),r=this.tsTryParseTypeAnnotation();return r&&(e.typeAnnotation=r,this.resetEndLocation(e)),e}tsInAmbientContext(e){let{isAmbientContext:r,strict:s}=this.state;this.state.isAmbientContext=!0,this.state.strict=!1;try{return e()}finally{this.state.isAmbientContext=r,this.state.strict=s}}parseClass(e,r,s){let i=this.state.inAbstractClass;this.state.inAbstractClass=!!e.abstract;try{return super.parseClass(e,r,s)}finally{this.state.inAbstractClass=i}}tsParseAbstractDeclaration(e,r){if(this.match(80))return e.abstract=!0,this.maybeTakeDecorators(r,this.parseClass(e,!0,!1));if(this.isContextual(129))return this.hasFollowingLineBreak()?null:(e.abstract=!0,this.raise(F.NonClassMethodPropertyHasAbstractModifier,e),this.tsParseInterfaceDeclaration(e));throw this.unexpected(null,80)}parseMethod(e,r,s,i,a,o,d){let c=super.parseMethod(e,r,s,i,a,o,d);if((c.abstract||c.type==="TSAbstractMethodDefinition")&&(this.hasPlugin("estree")?c.value:c).body){let{key:p}=c;this.raise(F.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,r,s,i){return!r&&i?(this.parseTypeOnlyImportExportSpecifier(e,!1,s),this.finishNode(e,"ExportSpecifier")):(e.exportKind="value",super.parseExportSpecifier(e,r,s,i))}parseImportSpecifier(e,r,s,i,a){return!r&&i?(this.parseTypeOnlyImportExportSpecifier(e,!0,s),this.finishNode(e,"ImportSpecifier")):(e.importKind="value",super.parseImportSpecifier(e,r,s,i,s?4098:4096))}parseTypeOnlyImportExportSpecifier(e,r,s){let i=r?"imported":"local",a=r?"local":"exported",o=e[i],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();at(this.state.type)?(c=!0,o=f,d=r?this.parseIdentifier():this.parseModuleExportName(),l=!1):(d=h,l=!1)}else at(this.state.type)?(l=!1,d=r?this.parseIdentifier():this.parseModuleExportName()):(c=!0,o=f)}else at(this.state.type)&&(c=!0,r?(o=this.parseIdentifier(!0),this.isContextual(93)||this.checkReservedWord(o.name,o.loc.start,!0,!0)):o=this.parseModuleExportName());c&&s&&this.raise(r?F.TypeModifierIsUsedInTypeImports:F.TypeModifierIsUsedInTypeExports,u),e[i]=o,e[a]=d;let p=r?"importKind":"exportKind";e[p]=c?"type":"value",l&&this.eatContextual(93)&&(e[a]=r?this.parseIdentifier():this.parseModuleExportName()),e[a]||(e[a]=this.cloneIdentifier(e[i])),r&&this.checkIdentifier(e[a],c?4098:4096)}fillOptionalPropertiesForTSESLint(e){var r,s,i,a,o,d,c,l,u,p,f,h,m,g,y,w,x,v,R,P,N,E,M,A,C,T,I,$,D,k,S,_,U,K,te,le,X,Ie,Se,Rt,_t,Dr,Mr,ai,Lr,_r,jr,hp,mp;switch(e.type){case"ImportDeclaration":(r=e.phase)!=null||(e.phase=null);return;case"ExpressionStatement":(s=e.directive)!=null||(e.directive=void 0);return;case"RestElement":e.value=void 0;case"Identifier":case"ArrayPattern":case"AssignmentPattern":case"ObjectPattern":(i=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),(m=e.typeParameters)!=null||(e.typeParameters=void 0);return;case"Property":(g=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":(R=e.declare)!=null||(e.declare=!1),(P=e.definite)!=null||(e.definite=!1),(N=e.readonly)!=null||(e.readonly=!1),(E=e.typeAnnotation)!=null||(e.typeAnnotation=void 0);case"TSAbstractMethodDefinition":case"MethodDefinition":(M=e.accessibility)!=null||(e.accessibility=void 0),(A=e.decorators)!=null||(e.decorators=[]),(C=e.override)!=null||(e.override=!1),(T=e.optional)!=null||(e.optional=!1);return;case"ClassExpression":(I=e.id)!=null||(e.id=null);case"ClassDeclaration":($=e.abstract)!=null||(e.abstract=!1),(D=e.declare)!=null||(e.declare=!1),(k=e.decorators)!=null||(e.decorators=[]),(S=e.implements)!=null||(e.implements=[]),(_=e.superTypeArguments)!=null||(e.superTypeArguments=void 0),(U=e.typeParameters)!=null||(e.typeParameters=void 0);return;case"TSTypeAliasDeclaration":case"VariableDeclaration":(K=e.declare)!=null||(e.declare=!1);return;case"VariableDeclarator":(te=e.definite)!=null||(e.definite=!1);return;case"TSEnumDeclaration":(le=e.const)!=null||(e.const=!1),(X=e.declare)!=null||(e.declare=!1);return;case"TSEnumMember":(Ie=e.computed)!=null||(e.computed=!1);return;case"TSImportType":(Se=e.qualifier)!=null||(e.qualifier=null),(Rt=e.options)!=null||(e.options=null);return;case"TSInterfaceDeclaration":(_t=e.declare)!=null||(e.declare=!1),(Dr=e.extends)!=null||(e.extends=[]);return;case"TSMappedType":(Mr=e.optional)!=null||(e.optional=!1),(ai=e.readonly)!=null||(e.readonly=void 0);return;case"TSModuleDeclaration":(Lr=e.declare)!=null||(e.declare=!1),(_r=e.global)!=null||(e.global=e.kind==="global");return;case"TSTypeParameter":(jr=e.const)!=null||(e.const=!1),(hp=e.in)!=null||(e.in=!1),(mp=e.out)!=null||(e.out=!1);return}}chStartsBindingIdentifierAndNotRelationalOperator(e,r){if(yt(e)){if(vd.lastIndex=r,vd.test(this.input)){let s=this.codePointAtPos(vd.lastIndex);if(!gn(s)&&s!==92)return!1}return!0}else return e===92}nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine(){let e=this.nextTokenInLineStart(),r=this.codePointAtPos(e);return this.chStartsBindingIdentifierAndNotRelationalOperator(r,e)}nextTokenIsIdentifierOrStringLiteralOnSameLine(){let e=this.nextTokenInLineStart(),r=this.codePointAtPos(e);return this.chStartsBindingIdentifier(r,e)||r===34||r===39}};function vI(t){if(t.type!=="MemberExpression")return!1;let{computed:n,property:e}=t;return n&&e.type!=="StringLiteral"&&(e.type!=="TemplateLiteral"||e.expressions.length>0)?!1:Ah(t.object)}function kI(t,n){var e;let{type:r}=t;if((e=t.extra)!=null&&e.parenthesized)return!1;if(n){if(r==="Literal"){let{value:s}=t;if(typeof s=="string"||typeof s=="boolean")return!0}}else if(r==="StringLiteral"||r==="BooleanLiteral")return!0;return!!(Ih(t,n)||RI(t,n)||r==="TemplateLiteral"&&t.expressions.length===0||vI(t))}function Ih(t,n){return n?t.type==="Literal"&&(typeof t.value=="number"||"bigint"in t):t.type==="NumericLiteral"||t.type==="BigIntLiteral"}function RI(t,n){if(t.type==="UnaryExpression"){let{operator:e,argument:r}=t;if(e==="-"&&Ih(r,n))return!0}return!1}function Ah(t){return t.type==="Identifier"?!0:t.type!=="MemberExpression"||t.computed?!1:Ah(t.object)}var ch=it`placeholders`({ClassNameIsRequired:"A class name is required.",UnexpectedSpace:"Unexpected space in placeholder."}),II=t=>class extends t{parsePlaceholder(e){if(this.match(133)){let r=this.startNode();return this.next(),this.assertNoSpace(),r.name=super.parseIdentifier(!0),this.assertNoSpace(),this.expect(133),this.finishPlaceholder(r,e)}}finishPlaceholder(e,r){let s=e;return(!s.expectedNode||!s.type)&&(s=this.finishNode(s,"Placeholder")),s.expectedNode=r,s}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,r,s,i){e!==void 0&&super.checkReservedWord(e,r,s,i)}cloneIdentifier(e){let r=super.cloneIdentifier(e);return r.type==="Placeholder"&&(r.expectedNode=e.expectedNode),r}cloneStringLiteral(e){return e.type==="Placeholder"?this.cloneIdentifier(e):super.cloneStringLiteral(e)}parseBindingAtom(){return this.parsePlaceholder("Pattern")||super.parseBindingAtom()}isValidLVal(e,r,s,i){return e==="Placeholder"||super.isValidLVal(e,r,s,i)}toAssignable(e,r){e&&e.type==="Placeholder"&&e.expectedNode==="Expression"?e.expectedNode="Pattern":super.toAssignable(e,r)}chStartsBindingIdentifier(e,r){if(super.chStartsBindingIdentifier(e,r))return!0;let s=this.nextTokenStart();return this.input.charCodeAt(s)===37&&this.input.charCodeAt(s+1)===37}verifyBreakContinue(e,r){var s;((s=e.label)==null?void 0:s.type)!=="Placeholder"&&super.verifyBreakContinue(e,r)}parseExpressionStatement(e,r){var s;if(r.type!=="Placeholder"||(s=r.extra)!=null&&s.parenthesized)return super.parseExpressionStatement(e,r);if(this.match(14)){let a=e;return a.label=this.finishPlaceholder(r,"Identifier"),this.next(),a.body=super.parseStatementOrSloppyAnnexBFunctionDeclaration(),this.finishNode(a,"LabeledStatement")}this.semicolon();let i=e;return i.name=r.name,this.finishPlaceholder(i,"Statement")}parseBlock(e,r,s){return this.parsePlaceholder("BlockStatement")||super.parseBlock(e,r,s)}parseFunctionId(e){return this.parsePlaceholder("Identifier")||super.parseFunctionId(e)}parseClass(e,r,s){let i=r?"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(s||!r)return e.id=null,e.body=this.finishPlaceholder(o,"ClassBody"),this.finishNode(e,i);throw this.raise(ch.ClassNameIsRequired,this.state.startLoc)}else this.parseClassId(e,r,s);return super.parseClassSuper(e),e.body=this.parsePlaceholder("ClassBody")||super.parseClassBody(!!e.superClass,a),this.finishNode(e,i)}parseExport(e,r){let s=this.parsePlaceholder("Identifier");if(!s)return super.parseExport(e,r);let i=e;if(!this.isContextual(98)&&!this.match(12))return i.specifiers=[],i.source=null,i.declaration=this.finishPlaceholder(s,"Declaration"),this.finishNode(i,"ExportNamedDeclaration");this.expectPlugin("exportDefaultFrom");let a=this.startNode();return a.exported=s,i.specifiers=[this.finishNode(a,"ExportDefaultSpecifier")],super.parseExport(i,r)}isExportDefaultSpecifier(){if(this.match(65)){let e=this.nextTokenStart();if(this.isUnparsedContextual(e,"from")&&this.input.startsWith(Vt(133),this.nextTokenStartSince(e+4)))return!0}return super.isExportDefaultSpecifier()}maybeParseExportDefaultSpecifier(e,r){var s;return(s=e.specifiers)!=null&&s.length?!0:super.maybeParseExportDefaultSpecifier(e,r)}checkExport(e){let{specifiers:r}=e;r!=null&&r.length&&(e.specifiers=r.filter(s=>s.exported.type==="Placeholder")),super.checkExport(e),e.specifiers=r}parseImport(e){let r=this.parsePlaceholder("Identifier");if(!r)return super.parseImport(e);if(e.specifiers=[],!this.isContextual(98)&&!this.match(12))return e.source=this.finishPlaceholder(r,"StringLiteral"),this.semicolon(),this.finishNode(e,"ImportDeclaration");let s=this.startNodeAtNode(r);return s.local=r,e.specifiers.push(this.finishNode(s,"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(ch.UnexpectedSpace,this.state.lastTokEndLoc)}},AI=t=>class extends t{parseV8Intrinsic(){if(this.match(54)){let e=this.state.startLoc,r=this.startNode();if(this.next(),ie(this.state.type)){let s=this.parseIdentifierName(),i=this.createIdentifier(r,s);if(this.castNodeTo(i,"V8IntrinsicIdentifier"),this.match(10))return i}this.unexpected(e)}}parseExprAtom(e){return this.parseV8Intrinsic()||super.parseExprAtom(e)}},lh=["minimal","fsharp","hack","smart"],uh=["^^","@@","^","%","#"];function TI(t){if(t.has("decorators")){if(t.has("decorators-legacy"))throw new Error("Cannot use the decorators and decorators-legacy plugin together");let r=t.get("decorators").decoratorsBeforeExport;if(r!=null&&typeof r!="boolean")throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");let s=t.get("decorators").allowCallParenthesized;if(s!=null&&typeof s!="boolean")throw new Error("'allowCallParenthesized' must be a boolean.")}if(t.has("flow")&&t.has("typescript"))throw new Error("Cannot combine flow and typescript plugins.");if(t.has("placeholders")&&t.has("v8intrinsic"))throw new Error("Cannot combine placeholders and v8intrinsic plugins.");if(t.has("pipelineOperator")){var n;let r=t.get("pipelineOperator").proposal;if(!lh.includes(r)){let s=lh.map(i=>`"${i}"`).join(", ");throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${s}.`)}if(r==="hack"){var e;if(t.has("placeholders"))throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");if(t.has("v8intrinsic"))throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");let s=t.get("pipelineOperator").topicToken;if(!uh.includes(s)){let i=uh.map(a=>`"${a}"`).join(", ");throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${i}.`)}if(s==="#"&&((e=t.get("recordAndTuple"))==null?void 0:e.syntaxType)==="hash")throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple",t.get("recordAndTuple")])}\`.`)}else if(r==="smart"&&((n=t.get("recordAndTuple"))==null?void 0:n.syntaxType)==="hash")throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple",t.get("recordAndTuple")])}\`.`)}if(t.has("moduleAttributes")){if(t.has("deprecatedImportAssert")||t.has("importAssertions"))throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.");if(t.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(t.has("importAssertions")&&t.has("deprecatedImportAssert"))throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins.");if(t.has("deprecatedImportAssert")||t.has("importAttributes")&&t.get("importAttributes").deprecatedAssertSyntax&&t.set("deprecatedImportAssert",{}),t.has("recordAndTuple")){let r=t.get("recordAndTuple").syntaxType;if(r!=null){let s=["hash","bar"];if(!s.includes(r))throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: "+s.map(i=>`'${i}'`).join(", "))}}if(t.has("asyncDoExpressions")&&!t.has("doExpressions")){let r=new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");throw r.missingPlugins="doExpressions",r}if(t.has("optionalChainingAssign")&&t.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(t.has("discardBinding")&&t.get("discardBinding").syntaxType!=="void")throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'.")}var Th={estree:CR,jsx:dI,flow:sI,typescript:xI,v8intrinsic:AI,placeholders:II},PI=Object.keys(Th),Hd=class extends zd{checkProto(n,e,r,s){if(n.type==="SpreadElement"||this.isObjectMethod(n)||n.computed||n.shorthand)return r;let i=n.key;return(i.type==="Identifier"?i.name:i.value)==="__proto__"?e?(this.raise(b.RecordNoProto,i),!0):(r&&(s?s.doubleProtoLoc===null&&(s.doubleProtoLoc=i.loc.start):this.raise(b.DuplicateProto,i)),!0):r}shouldExitDescending(n,e){return n.type==="ArrowFunctionExpression"&&this.offsetToSourcePos(n.start)===e}getExpression(){if(this.enterInitialScopes(),this.nextToken(),this.match(140))throw this.raise(b.ParseExpressionEmptyInput,this.state.startLoc);let n=this.parseExpression();if(!this.match(140))throw this.raise(b.ParseExpressionExpectsEOF,this.state.startLoc,{unexpected:this.input.codePointAt(this.state.start)});return this.finalizeRemainingComments(),n.comments=this.comments,n.errors=this.state.errors,this.optionFlags&256&&(n.tokens=this.tokens),n}parseExpression(n,e){return n?this.disallowInAnd(()=>this.parseExpressionBase(e)):this.allowInAnd(()=>this.parseExpressionBase(e))}parseExpressionBase(n){let e=this.state.startLoc,r=this.parseMaybeAssign(n);if(this.match(12)){let s=this.startNodeAt(e);for(s.expressions=[r];this.eat(12);)s.expressions.push(this.parseMaybeAssign(n));return this.toReferencedList(s.expressions),this.finishNode(s,"SequenceExpression")}return r}parseMaybeAssignDisallowIn(n,e){return this.disallowInAnd(()=>this.parseMaybeAssign(n,e))}parseMaybeAssignAllowIn(n,e){return this.allowInAnd(()=>this.parseMaybeAssign(n,e))}setOptionalParametersError(n){n.optionalParametersLoc=this.state.startLoc}parseMaybeAssign(n,e){let r=this.state.startLoc,s=this.isContextual(108);if(s&&this.prodParam.hasYield){this.next();let d=this.parseYield(r);return e&&(d=e.call(this,d,r)),d}let i;n?i=!1:(n=new Qn,i=!0);let{type:a}=this.state;(a===10||ie(a))&&(this.state.potentialArrowAt=this.state.start);let o=this.parseMaybeConditional(n);if(e&&(o=e.call(this,o,r)),MR(this.state.type)){let d=this.startNodeAt(r),c=this.state.value;if(d.operator=c,this.match(29)){this.toAssignable(o,!0),d.left=o;let l=r.index;n.doubleProtoLoc!=null&&n.doubleProtoLoc.index>=l&&(n.doubleProtoLoc=null),n.shorthandAssignLoc!=null&&n.shorthandAssignLoc.index>=l&&(n.shorthandAssignLoc=null),n.privateKeyLoc!=null&&n.privateKeyLoc.index>=l&&(this.checkDestructuringPrivate(n),n.privateKeyLoc=null),n.voidPatternLoc!=null&&n.voidPatternLoc.index>=l&&(n.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 i&&this.checkExpressionErrors(n,!0);if(s){let{type:d}=this.state;if((this.hasPlugin("v8intrinsic")?Jr(d):Jr(d)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(b.YieldNotInGeneratorFunction,r),this.parseYield(r)}return o}parseMaybeConditional(n){let e=this.state.startLoc,r=this.state.potentialArrowAt,s=this.parseExprOps(n);return this.shouldExitDescending(s,r)?s:this.parseConditional(s,e,n)}parseConditional(n,e,r){if(this.eat(17)){let s=this.startNodeAt(e);return s.test=n,s.consequent=this.parseMaybeAssignAllowIn(),this.expect(14),s.alternate=this.parseMaybeAssign(),this.finishNode(s,"ConditionalExpression")}return n}parseMaybeUnaryOrPrivate(n){return this.match(139)?this.parsePrivateName():this.parseMaybeUnary(n)}parseExprOps(n){let e=this.state.startLoc,r=this.state.potentialArrowAt,s=this.parseMaybeUnaryOrPrivate(n);return this.shouldExitDescending(s,r)?s:this.parseExprOp(s,e,-1)}parseExprOp(n,e,r){if(this.isPrivateName(n)){let i=this.getPrivateNameSV(n);(r>=Oi(58)||!this.prodParam.hasIn||!this.match(58))&&this.raise(b.PrivateInExpectedIn,n,{identifierName:i}),this.classScope.usePrivateName(i,n.loc.start)}let s=this.state.type;if(_R(s)&&(this.prodParam.hasIn||!this.match(58))){let i=Oi(s);if(i>r){if(s===39){if(this.expectPlugin("pipelineOperator"),this.state.inFSharpPipelineDirectBody)return n;this.checkPipelineAtInfixOperator(n,e)}let a=this.startNodeAt(e);a.left=n,a.operator=this.state.value;let o=s===41||s===42,d=s===40;if(d&&(i=Oi(42)),this.next(),s===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(s,i);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,r)}}return n}parseExprOpRightExpr(n,e){let r=this.state.startLoc;switch(n){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(n,e),r)});default:return this.parseExprOpBaseRightExpr(n,e)}}parseExprOpBaseRightExpr(n,e){let r=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnaryOrPrivate(),r,zR(n)?e-1:e)}parseHackPipeBody(){var n;let{startLoc:e}=this.state,r=this.parseMaybeAssign();return kR.has(r.type)&&!((n=r.extra)!=null&&n.parenthesized)&&this.raise(b.PipeUnparenthesizedBody,e,{type:r.type}),this.topicReferenceWasUsedInCurrentContext()||this.raise(b.PipeTopicUnused,e),r}checkExponentialAfterUnary(n){this.match(57)&&this.raise(b.UnexpectedTokenUnaryExponentiation,n.argument)}parseMaybeUnary(n,e){let r=this.state.startLoc,s=this.isContextual(96);if(s&&this.recordAwaitIfAllowed()){this.next();let d=this.parseAwait(r);return e||this.checkExponentialAfterUnary(d),d}let i=this.match(34),a=this.startNode();if(FR(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(n,!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(!i)return e||this.checkExponentialAfterUnary(a),this.finishNode(a,"UnaryExpression")}let o=this.parseUpdate(a,i,n);if(s){let{type:d}=this.state;if((this.hasPlugin("v8intrinsic")?Jr(d):Jr(d)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(b.AwaitNotInAsyncContext,r),this.parseAwait(r)}return o}parseUpdate(n,e,r){if(e){let a=n;return this.checkLVal(a.argument,this.finishNode(a,"UpdateExpression")),n}let s=this.state.startLoc,i=this.parseExprSubscripts(r);if(this.checkExpressionErrors(r,!1))return i;for(;jR(this.state.type)&&!this.canInsertSemicolon();){let a=this.startNodeAt(s);a.operator=this.state.value,a.prefix=!1,a.argument=i,this.next(),this.checkLVal(i,i=this.finishNode(a,"UpdateExpression"))}return i}parseExprSubscripts(n){let e=this.state.startLoc,r=this.state.potentialArrowAt,s=this.parseExprAtom(n);return this.shouldExitDescending(s,r)?s:this.parseSubscripts(s,e)}parseSubscripts(n,e,r){let s={optionalChainMember:!1,maybeAsyncArrow:this.atPossibleAsyncArrow(n),stop:!1};do n=this.parseSubscript(n,e,r,s),s.maybeAsyncArrow=!1;while(!s.stop);return n}parseSubscript(n,e,r,s){let{type:i}=this.state;if(!r&&i===15)return this.parseBind(n,e,s);if(Mi(i))return this.parseTaggedTemplateExpression(n,e,s);let a=!1;if(i===18){if(r&&(this.raise(b.OptionalChainingNoNew,this.state.startLoc),this.lookaheadCharCode()===40))return this.stopParseSubscript(n,s);s.optionalChainMember=a=!0,this.next()}if(!r&&this.match(10))return this.parseCoverCallAndAsyncArrowHead(n,e,s,a);{let o=this.eat(0);return o||a||this.eat(16)?this.parseMember(n,e,s,o,a):this.stopParseSubscript(n,s)}}stopParseSubscript(n,e){return e.stop=!0,n}parseMember(n,e,r,s,i){let a=this.startNodeAt(e);return a.object=n,a.computed=s,s?(a.property=this.parseExpression(),this.expect(3)):this.match(139)?(n.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),r.optionalChainMember?(a.optional=i,this.finishNode(a,"OptionalMemberExpression")):this.finishNode(a,"MemberExpression")}parseBind(n,e,r){let s=this.startNodeAt(e);s.object=n,this.next();let i=this.match(83),a=this.parseNoCallExpr();if(a.type==="Super"||i&&a.type==="ImportExpression"||a.type==="Import")throw this.raise(b.UnsupportedBindRHS,a);return s.callee=a,r.stop=!0,this.parseSubscripts(this.finishNode(s,"BindExpression"),e,!1)}parseCoverCallAndAsyncArrowHead(n,e,r,s){let i=this.state.maybeInArrowParameters,a=null;this.state.maybeInArrowParameters=!0,this.next();let o=this.startNodeAt(e);o.callee=n;let{maybeAsyncArrow:d,optionalChainMember:c}=r;d&&(this.expressionScope.enter(yI()),a=new Qn),c&&(o.optional=s),s?o.arguments=this.parseCallExpressionArguments():o.arguments=this.parseCallExpressionArguments(n.type!=="Super",o,a);let l=this.finishCallExpression(o,c);return d&&this.shouldParseAsyncArrow()&&!s?(r.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=i,l}toReferencedArguments(n,e){this.toReferencedListDeep(n.arguments,e)}parseTaggedTemplateExpression(n,e,r){let s=this.startNodeAt(e);return s.tag=n,s.quasi=this.parseTemplate(!0),r.optionalChainMember&&this.raise(b.OptionalChainingNoTemplate,e),this.finishNode(s,"TaggedTemplateExpression")}atPossibleAsyncArrow(n){return n.type==="Identifier"&&n.name==="async"&&this.state.lastTokEndLoc.index===n.end&&!this.canInsertSemicolon()&&n.end-n.start===5&&this.offsetToSourcePos(n.start)===this.state.potentialArrowAt}finishCallExpression(n,e){if(n.callee.type==="Import")if(n.arguments.length===0||n.arguments.length>2)this.raise(b.ImportCallArity,n);else for(let r of n.arguments)r.type==="SpreadElement"&&this.raise(b.ImportCallSpreadArgument,r);return this.finishNode(n,e?"OptionalCallExpression":"CallExpression")}parseCallExpressionArguments(n,e,r){let s=[],i=!0,a=this.state.inFSharpPipelineDirectBody;for(this.state.inFSharpPipelineDirectBody=!1;!this.eat(11);){if(i)i=!1;else if(this.expect(12),this.match(11)){e&&this.addTrailingCommaExtraToNode(e),this.next();break}s.push(this.parseExprListItem(11,!1,r,n))}return this.state.inFSharpPipelineDirectBody=a,s}shouldParseAsyncArrow(){return this.match(19)&&!this.canInsertSemicolon()}parseAsyncArrowFromCallExpression(n,e){var r;return this.resetPreviousNodeTrailingComments(e),this.expect(19),this.parseArrowExpression(n,e.arguments,!0,(r=e.extra)==null?void 0:r.trailingCommaLoc),e.innerComments&&es(n,e.innerComments),e.callee.trailingComments&&es(n,e.callee.trailingComments),n}parseNoCallExpr(){let n=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),n,!0)}parseExprAtom(n){let e,r=null,{type:s}=this.state;switch(s){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 i=this.state.potentialArrowAt===this.state.start;return this.parseParenAndDistinguishExpression(i)}case 0:return this.parseArrayLike(3,!1,n);case 5:return this.parseObjectLike(8,!1,!1,n);case 68:return this.parseFunctionOrFunctionSent();case 26:r=this.parseDecorators();case 80:return this.parseClass(this.maybeTakeDecorators(r,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 i=e.callee=this.parseNoCallExpr();if(i.type==="MemberExpression")return this.finishNode(e,"BindExpression");throw this.raise(b.UnsupportedBind,i)}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 i=this.getPluginOption("pipelineOperator","proposal");if(i)return this.parseTopicReference(i);throw this.unexpected()}case 47:{let i=this.input.codePointAt(this.nextTokenStart());throw yt(i)||i===62?this.expectOnePlugin(["jsx","flow","typescript"]):this.unexpected()}default:if(s===137)return this.parseDecimalLiteral(this.state.value);if(s===2||s===1)return this.parseArrayLike(this.state.type===2?4:3,!0);if(s===6||s===7)return this.parseObjectLike(this.state.type===6?9:8,!1,!0);if(ie(s)){if(this.isContextual(127)&&this.lookaheadInLineCharCode()===123)return this.parseModuleExpression();let i=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(ie(d))return i&&this.lookaheadCharCode()===61?this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(o)):o;if(d===90)return this.resetPreviousNodeTrailingComments(o),this.parseDo(this.startNodeAtNode(o),!0)}return i&&this.match(19)&&!this.canInsertSemicolon()?(this.next(),this.parseArrowExpression(this.startNodeAtNode(o),[o],!1)):o}else throw this.unexpected()}}parseTopicReferenceThenEqualsSign(n,e){let r=this.getPluginOption("pipelineOperator","proposal");if(r)return this.state.type=n,this.state.value=e,this.state.pos--,this.state.end--,this.state.endLoc=Me(this.state.endLoc,-1),this.parseTopicReference(r);throw this.unexpected()}parseTopicReference(n){let e=this.startNode(),r=this.state.startLoc,s=this.state.type;return this.next(),this.finishTopicReference(e,r,n,s)}finishTopicReference(n,e,r,s){if(this.testTopicReferenceConfiguration(r,e,s))return r==="hack"?(this.topicReferenceIsAllowedInCurrentContext()||this.raise(b.PipeTopicUnbound,e),this.registerTopicReference(),this.finishNode(n,"TopicReference")):(this.topicReferenceIsAllowedInCurrentContext()||this.raise(b.PrimaryTopicNotAllowed,e),this.registerTopicReference(),this.finishNode(n,"PipelinePrimaryTopicReference"));throw this.raise(b.PipeTopicUnconfiguredToken,e,{token:Vt(s)})}testTopicReferenceConfiguration(n,e,r){switch(n){case"hack":return this.hasPlugin(["pipelineOperator",{topicToken:Vt(r)}]);case"smart":return r===27;default:throw this.raise(b.PipeTopicRequiresHackPipes,e)}}parseAsyncArrowUnaryFunction(n){this.prodParam.enter($i(!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(n,e,!0)}parseDo(n,e){this.expectPlugin("doExpressions"),e&&this.expectPlugin("asyncDoExpressions"),n.async=e,this.next();let r=this.state.labels;return this.state.labels=[],e?(this.prodParam.enter(2),n.body=this.parseBlock(),this.prodParam.exit()):n.body=this.parseBlock(),this.state.labels=r,this.finishNode(n,"DoExpression")}parseSuper(){let n=this.startNode();return this.next(),this.match(10)&&!this.scope.allowDirectSuper?this.optionFlags&16||this.raise(b.SuperNotAllowed,n):this.scope.allowSuper||this.optionFlags&16||this.raise(b.UnexpectedSuper,n),!this.match(10)&&!this.match(0)&&!this.match(16)&&this.raise(b.UnsupportedSuper,n),this.finishNode(n,"Super")}parsePrivateName(){let n=this.startNode(),e=this.startNodeAt(Me(this.state.startLoc,1)),r=this.state.value;return this.next(),n.id=this.createIdentifier(e,r),this.finishNode(n,"PrivateName")}parseFunctionOrFunctionSent(){let n=this.startNode();if(this.next(),this.prodParam.hasYield&&this.match(16)){let e=this.createIdentifier(this.startNodeAtNode(n),"function");return this.next(),this.match(103)?this.expectPlugin("functionSent"):this.hasPlugin("functionSent")||this.unexpected(),this.parseMetaProperty(n,e,"sent")}return this.parseFunction(n)}parseMetaProperty(n,e,r){n.meta=e;let s=this.state.containsEsc;return n.property=this.parseIdentifier(!0),(n.property.name!==r||s)&&this.raise(b.UnsupportedMetaProperty,n.property,{target:e.name,onlyValidPropertyName:r}),this.finishNode(n,"MetaProperty")}parseImportMetaPropertyOrPhaseCall(n){if(this.next(),this.isContextual(105)||this.isContextual(97)){let e=this.isContextual(105);return this.expectPlugin(e?"sourcePhaseImports":"deferredImportEvaluation"),this.next(),n.phase=e?"source":"defer",this.parseImportCall(n)}else{let e=this.createIdentifierAt(this.startNodeAtNode(n),"import",this.state.lastTokStartLoc);return this.isContextual(101)&&(this.inModule||this.raise(b.ImportMetaOutsideModule,e),this.sawUnambiguousESM=!0),this.parseMetaProperty(n,e,"meta")}}parseLiteralAtNode(n,e,r){return this.addExtra(r,"rawValue",n),this.addExtra(r,"raw",this.input.slice(this.offsetToSourcePos(r.start),this.state.end)),r.value=n,this.next(),this.finishNode(r,e)}parseLiteral(n,e){let r=this.startNode();return this.parseLiteralAtNode(n,e,r)}parseStringLiteral(n){return this.parseLiteral(n,"StringLiteral")}parseNumericLiteral(n){return this.parseLiteral(n,"NumericLiteral")}parseBigIntLiteral(n){return this.parseLiteral(n,"BigIntLiteral")}parseDecimalLiteral(n){return this.parseLiteral(n,"DecimalLiteral")}parseRegExpLiteral(n){let e=this.startNode();return this.addExtra(e,"raw",this.input.slice(this.offsetToSourcePos(e.start),this.state.end)),e.pattern=n.pattern,e.flags=n.flags,this.next(),this.finishNode(e,"RegExpLiteral")}parseBooleanLiteral(n){let e=this.startNode();return e.value=n,this.next(),this.finishNode(e,"BooleanLiteral")}parseNullLiteral(){let n=this.startNode();return this.next(),this.finishNode(n,"NullLiteral")}parseParenAndDistinguishExpression(n){let e=this.state.startLoc,r;this.next(),this.expressionScope.enter(mI());let s=this.state.maybeInArrowParameters,i=this.state.inFSharpPipelineDirectBody;this.state.maybeInArrowParameters=!0,this.state.inFSharpPipelineDirectBody=!1;let a=this.state.startLoc,o=[],d=new Qn,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=s,this.state.inFSharpPipelineDirectBody=i;let f=this.startNodeAt(e);return n&&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?(r=this.startNodeAt(a),r.expressions=o,this.finishNode(r,"SequenceExpression"),this.resetEndLocation(r,p)):r=o[0],this.wrapParenthesis(e,r))}wrapParenthesis(n,e){if(!(this.optionFlags&1024))return this.addExtra(e,"parenthesized",!0),this.addExtra(e,"parenStart",n.index),this.takeSurroundingComments(e,n.index,this.state.lastTokEndLoc.index),e;let r=this.startNodeAt(n);return r.expression=e,this.finishNode(r,"ParenthesizedExpression")}shouldParseArrow(n){return!this.canInsertSemicolon()}parseArrow(n){if(this.eat(19))return n}parseParenItem(n,e){return n}parseNewOrNewTarget(){let n=this.startNode();if(this.next(),this.match(16)){let e=this.createIdentifier(this.startNodeAtNode(n),"new");this.next();let r=this.parseMetaProperty(n,e,"target");return this.scope.allowNewTarget||this.raise(b.UnexpectedNewTarget,r),r}return this.parseNew(n)}parseNew(n){if(this.parseNewCallee(n),this.eat(10)){let e=this.parseExprList(11);this.toReferencedList(e),n.arguments=e}else n.arguments=[];return this.finishNode(n,"NewExpression")}parseNewCallee(n){let e=this.match(83),r=this.parseNoCallExpr();n.callee=r,(e&&r.type==="ImportExpression"||r.type==="Import")&&this.raise(b.ImportCallNotNewExpression,r),r.type==="Super"&&this.raise(b.SuperCallNotNewExpression,r)}parseTemplateElement(n){let{start:e,startLoc:r,end:s,value:i}=this.state,a=e+1,o=this.startNodeAt(Me(r,1));i===null&&(n||this.raise(b.InvalidEscapeSequenceTemplate,Me(this.state.firstInvalidTemplateEscapePos,1)));let d=this.match(24),c=d?-1:-2,l=s+c;o.value={raw:this.input.slice(a,l).replace(/\r\n?/g,`
10
+ `),cooked:i===null?null:i.slice(1,c)},o.tail=d,this.next();let u=this.finishNode(o,"TemplateElement");return this.resetEndLocation(u,Me(this.state.lastTokEndLoc,c)),u}parseTemplate(n){let e=this.startNode(),r=this.parseTemplateElement(n),s=[r],i=[];for(;!r.tail;)i.push(this.parseTemplateSubstitution()),this.readTemplateContinuation(),s.push(r=this.parseTemplateElement(n));return e.expressions=i,e.quasis=s,this.finishNode(e,"TemplateLiteral")}parseTemplateSubstitution(){return this.parseExpression()}parseObjectLike(n,e,r,s){r&&this.expectPlugin("recordAndTuple");let i=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let a=!1,o=!0,d=this.startNode();for(d.properties=[],this.next();!this.match(n);){if(o)o=!1;else if(this.expect(12),this.match(n)){this.addTrailingCommaExtraToNode(d);break}let l;e?l=this.parseBindingProperty():(l=this.parsePropertyDefinition(s),a=this.checkProto(l,r,a,s)),r&&!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=i;let c="ObjectExpression";return e?c="ObjectPattern":r&&(c="RecordExpression"),this.finishNode(d,c)}addTrailingCommaExtraToNode(n){this.addExtra(n,"trailingComma",this.state.lastTokStartLoc.index),this.addExtra(n,"trailingCommaLoc",this.state.lastTokStartLoc,!1)}maybeAsyncOrAccessorProp(n){return!n.computed&&n.key.type==="Identifier"&&(this.isLiteralPropertyName()||this.match(0)||this.match(55))}parsePropertyDefinition(n){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 r=this.startNode(),s=!1,i=!1,a;if(this.match(21))return e.length&&this.unexpected(),this.parseSpread();e.length&&(r.decorators=e,e=[]),r.method=!1,n&&(a=this.state.startLoc);let o=this.eat(55);this.parsePropertyNamePrefixOperator(r);let d=this.state.containsEsc;if(this.parsePropertyName(r,n),!o&&!d&&this.maybeAsyncOrAccessorProp(r)){let{key:c}=r,l=c.name;l==="async"&&!this.hasPrecedingLineBreak()&&(s=!0,this.resetPreviousNodeTrailingComments(c),o=this.eat(55),this.parsePropertyName(r)),(l==="get"||l==="set")&&(i=!0,this.resetPreviousNodeTrailingComments(c),r.kind=l,this.match(55)&&(o=!0,this.raise(b.AccessorIsGenerator,this.state.curPosition(),{kind:l}),this.next()),this.parsePropertyName(r))}return this.parseObjPropValue(r,a,o,s,!1,i,n)}getGetterSetterExpectedParamCount(n){return n.kind==="get"?0:1}getObjectOrClassMethodParams(n){return n.params}checkGetterSetterParams(n){var e;let r=this.getGetterSetterExpectedParamCount(n),s=this.getObjectOrClassMethodParams(n);s.length!==r&&this.raise(n.kind==="get"?b.BadGetterArity:b.BadSetterArity,n),n.kind==="set"&&((e=s[s.length-1])==null?void 0:e.type)==="RestElement"&&this.raise(b.BadSetterRestParameter,n)}parseObjectMethod(n,e,r,s,i){if(i){let a=this.parseMethod(n,e,!1,!1,!1,"ObjectMethod");return this.checkGetterSetterParams(a),a}if(r||e||this.match(10))return s&&this.unexpected(),n.kind="method",n.method=!0,this.parseMethod(n,e,r,!1,!1,"ObjectMethod")}parseObjectProperty(n,e,r,s){if(n.shorthand=!1,this.eat(14))return n.value=r?this.parseMaybeDefault(this.state.startLoc):this.parseMaybeAssignAllowInOrVoidPattern(8,s),this.finishObjectProperty(n);if(!n.computed&&n.key.type==="Identifier"){if(this.checkReservedWord(n.key.name,n.key.loc.start,!0,!1),r)n.value=this.parseMaybeDefault(e,this.cloneIdentifier(n.key));else if(this.match(29)){let i=this.state.startLoc;s!=null?s.shorthandAssignLoc===null&&(s.shorthandAssignLoc=i):this.raise(b.InvalidCoverInitializedName,i),n.value=this.parseMaybeDefault(e,this.cloneIdentifier(n.key))}else n.value=this.cloneIdentifier(n.key);return n.shorthand=!0,this.finishObjectProperty(n)}}finishObjectProperty(n){return this.finishNode(n,"ObjectProperty")}parseObjPropValue(n,e,r,s,i,a,o){let d=this.parseObjectMethod(n,r,s,i,a)||this.parseObjectProperty(n,e,i,o);return d||this.unexpected(),d}parsePropertyName(n,e){if(this.eat(0))n.computed=!0,n.key=this.parseMaybeAssignAllowIn(),this.expect(3);else{let{type:r,value:s}=this.state,i;if(at(r))i=this.parseIdentifier(!0);else switch(r){case 135:i=this.parseNumericLiteral(s);break;case 134:i=this.parseStringLiteral(s);break;case 136:i=this.parseBigIntLiteral(s);break;case 139:{let a=this.state.startLoc;e!=null?e.privateKeyLoc===null&&(e.privateKeyLoc=a):this.raise(b.UnexpectedPrivateField,a),i=this.parsePrivateName();break}default:if(r===137){i=this.parseDecimalLiteral(s);break}this.unexpected()}n.key=i,r!==139&&(n.computed=!1)}}initFunction(n,e){n.id=null,n.generator=!1,n.async=e}parseMethod(n,e,r,s,i,a,o=!1){this.initFunction(n,r),n.generator=e,this.scope.enter(530|(o?576:0)|(i?32:0)),this.prodParam.enter($i(r,n.generator)),this.parseFunctionParams(n,s);let d=this.parseFunctionBodyAndFinish(n,a,!0);return this.prodParam.exit(),this.scope.exit(),d}parseArrayLike(n,e,r){e&&this.expectPlugin("recordAndTuple");let s=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let i=this.startNode();return this.next(),i.elements=this.parseExprList(n,!e,r,i),this.state.inFSharpPipelineDirectBody=s,this.finishNode(i,e?"TupleExpression":"ArrayExpression")}parseArrowExpression(n,e,r,s){this.scope.enter(518);let i=$i(r,!1);!this.match(5)&&this.prodParam.hasIn&&(i|=8),this.prodParam.enter(i),this.initFunction(n,r);let a=this.state.maybeInArrowParameters;return e&&(this.state.maybeInArrowParameters=!0,this.setArrowFunctionParameters(n,e,s)),this.state.maybeInArrowParameters=!1,this.parseFunctionBody(n,!0),this.prodParam.exit(),this.scope.exit(),this.state.maybeInArrowParameters=a,this.finishNode(n,"ArrowFunctionExpression")}setArrowFunctionParameters(n,e,r){this.toAssignableList(e,r,!1),n.params=e}parseFunctionBodyAndFinish(n,e,r=!1){return this.parseFunctionBody(n,!1,r),this.finishNode(n,e)}parseFunctionBody(n,e,r=!1){let s=e&&!this.match(5);if(this.expressionScope.enter(Rh()),s)n.body=this.parseMaybeAssign(),this.checkParams(n,!1,e,!1);else{let i=this.state.strict,a=this.state.labels;this.state.labels=[],this.prodParam.enter(this.prodParam.currentFlags()|4),n.body=this.parseBlock(!0,!1,o=>{let d=!this.isSimpleParamList(n.params);o&&d&&this.raise(b.IllegalLanguageModeDirective,(n.kind==="method"||n.kind==="constructor")&&n.key?n.key.loc.end:n);let c=!i&&this.state.strict;this.checkParams(n,!this.state.strict&&!e&&!r&&!d,e,c),this.state.strict&&n.id&&this.checkIdentifier(n.id,65,c)}),this.prodParam.exit(),this.state.labels=a}this.expressionScope.exit()}isSimpleParameter(n){return n.type==="Identifier"}isSimpleParamList(n){for(let e=0,r=n.length;e<r;e++)if(!this.isSimpleParameter(n[e]))return!1;return!0}checkParams(n,e,r,s=!0){let i=!e&&new Set,a={type:"FormalParameters"};for(let o of n.params)this.checkLVal(o,a,5,i,s)}parseExprList(n,e,r,s){let i=[],a=!0;for(;!this.eat(n);){if(a)a=!1;else if(this.expect(12),this.match(n)){s&&this.addTrailingCommaExtraToNode(s),this.next();break}i.push(this.parseExprListItem(n,e,r))}return i}parseExprListItem(n,e,r,s){let i;if(this.match(12))e||this.raise(b.UnexpectedToken,this.state.curPosition(),{unexpected:","}),i=null;else if(this.match(21)){let a=this.state.startLoc;i=this.parseParenItem(this.parseSpread(r),a)}else if(this.match(17)){this.expectPlugin("partialApplication"),s||this.raise(b.UnexpectedArgumentPlaceholder,this.state.startLoc);let a=this.startNode();this.next(),i=this.finishNode(a,"ArgumentPlaceholder")}else i=this.parseMaybeAssignAllowInOrVoidPattern(n,r,this.parseParenItem);return i}parseIdentifier(n){let e=this.startNode(),r=this.parseIdentifierName(n);return this.createIdentifier(e,r)}createIdentifier(n,e){return n.name=e,n.loc.identifierName=e,this.finishNode(n,"Identifier")}createIdentifierAt(n,e,r){return n.name=e,n.loc.identifierName=e,this.finishNodeAt(n,"Identifier",r)}parseIdentifierName(n){let e,{startLoc:r,type:s}=this.state;at(s)?e=this.state.value:this.unexpected();let i=$R(s);return n?i&&this.replaceToken(132):this.checkReservedWord(e,r,i,!1),this.next(),e}checkReservedWord(n,e,r,s){if(n.length>10||!QR(n))return;if(r&&JR(n)){this.raise(b.UnexpectedKeyword,e,{keyword:n});return}if((this.state.strict?s?bh:gh:yh)(n,this.inModule)){this.raise(b.UnexpectedReservedWord,e,{reservedWord:n});return}else if(n==="yield"){if(this.prodParam.hasYield){this.raise(b.YieldBindingIdentifier,e);return}}else if(n==="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(n==="arguments"&&this.scope.inClassAndNotInNonArrowFunction){this.raise(b.ArgumentsInClass,e);return}}recordAwaitIfAllowed(){let n=this.prodParam.hasAwait;return n&&!this.scope.inFunction&&(this.state.hasTopLevelAwait=!0),n}parseAwait(n){let e=this.startNodeAt(n);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:n}=this.state;return n===53||n===10||n===0||Mi(n)||n===102&&!this.state.containsEsc||n===138||n===56||this.hasPlugin("v8intrinsic")&&n===54}parseYield(n){let e=this.startNodeAt(n);this.expressionScope.recordParameterInitializerError(b.YieldInParameter,e);let r=!1,s=null;if(!this.hasPrecedingLineBreak())switch(r=this.eat(55),this.state.type){case 13:case 140:case 8:case 11:case 3:case 9:case 14:case 12:if(!r)break;default:s=this.parseMaybeAssign()}return e.delegate=r,e.argument=s,this.finishNode(e,"YieldExpression")}parseImportCall(n){if(this.next(),n.source=this.parseMaybeAssignAllowIn(),n.options=null,this.eat(12)){if(this.match(11))this.addTrailingCommaExtraToNode(n.source);else if(n.options=this.parseMaybeAssignAllowIn(),this.eat(12)&&(this.addTrailingCommaExtraToNode(n.options),!this.match(11))){do this.parseMaybeAssignAllowIn();while(this.eat(12)&&!this.match(11));this.raise(b.ImportCallArity,n)}}return this.expect(11),this.finishNode(n,"ImportExpression")}checkPipelineAtInfixOperator(n,e){this.hasPlugin(["pipelineOperator",{proposal:"smart"}])&&n.type==="SequenceExpression"&&this.raise(b.PipelineHeadSequenceExpression,e)}parseSmartPipelineBodyInStyle(n,e){if(this.isSimpleReference(n)){let r=this.startNodeAt(e);return r.callee=n,this.finishNode(r,"PipelineBareFunction")}else{let r=this.startNodeAt(e);return this.checkSmartPipeTopicBodyEarlyErrors(e),r.expression=n,this.finishNode(r,"PipelineTopicExpression")}}isSimpleReference(n){switch(n.type){case"MemberExpression":return!n.computed&&this.isSimpleReference(n.object);case"Identifier":return!0;default:return!1}}checkSmartPipeTopicBodyEarlyErrors(n){if(this.match(19))throw this.raise(b.PipelineBodyNoArrow,this.state.startLoc);this.topicReferenceWasUsedInCurrentContext()||this.raise(b.PipelineTopicUnused,n)}withTopicBindingContext(n){let e=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:1,maxTopicIndex:null};try{return n()}finally{this.state.topicContext=e}}withSmartMixTopicForbiddingContext(n){if(this.hasPlugin(["pipelineOperator",{proposal:"smart"}])){let e=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null};try{return n()}finally{this.state.topicContext=e}}else return n()}withSoloAwaitPermittingContext(n){let e=this.state.soloAwait;this.state.soloAwait=!0;try{return n()}finally{this.state.soloAwait=e}}allowInAnd(n){let e=this.prodParam.currentFlags();if(8&~e){this.prodParam.enter(e|8);try{return n()}finally{this.prodParam.exit()}}return n()}disallowInAnd(n){let e=this.prodParam.currentFlags();if(8&e){this.prodParam.enter(e&-9);try{return n()}finally{this.prodParam.exit()}}return n()}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(n){let e=this.state.startLoc;this.state.potentialArrowAt=this.state.start;let r=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!0;let s=this.parseExprOp(this.parseMaybeUnaryOrPrivate(),e,n);return this.state.inFSharpPipelineDirectBody=r,s}parseModuleExpression(){this.expectPlugin("moduleBlocks");let n=this.startNode();this.next(),this.match(5)||this.unexpected(null,5);let e=this.startNodeAt(this.state.endLoc);this.next();let r=this.initializeScopes(!0);this.enterInitialScopes();try{n.body=this.parseProgram(e,8,"module")}finally{r()}return this.finishNode(n,"ModuleExpression")}parseVoidPattern(n){this.expectPlugin("discardBinding");let e=this.startNode();return n!=null&&(n.voidPatternLoc=this.state.startLoc),this.next(),this.finishNode(e,"VoidPattern")}parseMaybeAssignAllowInOrVoidPattern(n,e,r){if(e!=null&&this.match(88)){let s=this.lookaheadCharCode();if(s===44||s===(n===3?93:n===8?125:41)||s===61)return this.parseMaybeDefault(this.state.startLoc,this.parseVoidPattern(e))}return this.parseMaybeAssignAllowIn(e,r)}parsePropertyNamePrefixOperator(n){}},kd={kind:1},SI={kind:2},EI=/[\uD800-\uDFFF]/u,Rd=/in(?:stanceof)?/y;function CI(t,n,e){for(let r=0;r<t.length;r++){let s=t[r],{type:i}=s;if(typeof i=="number"){if(i===139){let{loc:a,start:o,value:d,end:c}=s,l=o+1,u=Me(a.start,1);t.splice(r,1,new mt({type:Pt(27),value:"#",start:o,end:l,startLoc:a.start,endLoc:u}),new mt({type:Pt(132),value:d,start:l,end:c,startLoc:u,endLoc:a.end})),r++;continue}if(Mi(i)){let{loc:a,start:o,value:d,end:c}=s,l=o+1,u=Me(a.start,1),p;n.charCodeAt(o-e)===96?p=new mt({type:Pt(22),value:"`",start:o,end:l,startLoc:a.start,endLoc:u}):p=new mt({type:Pt(8),value:"}",start:o,end:l,startLoc:a.start,endLoc:u});let f,h,m,g;i===24?(h=c-1,m=Me(a.end,-1),f=d===null?null:d.slice(1,-1),g=new mt({type:Pt(22),value:"`",start:h,end:c,startLoc:m,endLoc:a.end})):(h=c-2,m=Me(a.end,-2),f=d===null?null:d.slice(1,-2),g=new mt({type:Pt(23),value:"${",start:h,end:c,startLoc:m,endLoc:a.end})),t.splice(r,1,p,new mt({type:Pt(20),value:f,start:l,end:h,startLoc:u,endLoc:m}),g),r+=2;continue}s.type=Pt(i)}}return t}var Ud=class extends Hd{parseTopLevel(n,e){return n.program=this.parseProgram(e,140,this.options.sourceType==="module"?"module":"script"),n.comments=this.comments,this.optionFlags&256&&(n.tokens=CI(this.tokens,this.input,this.startIndex)),this.finishNode(n,"File")}parseProgram(n,e,r){if(n.sourceType=r,n.interpreter=this.parseInterpreterDirective(),this.parseBlockBody(n,!0,!0,e),this.inModule){if(!(this.optionFlags&64)&&this.scope.undefinedExports.size>0)for(let[i,a]of Array.from(this.scope.undefinedExports))this.raise(b.ModuleExportUndefined,a,{localName:i});this.addExtra(n,"topLevelAwait",this.state.hasTopLevelAwait)}let s;return e===140?s=this.finishNode(n,"Program"):s=this.finishNodeAt(n,"Program",Me(this.state.startLoc,-1)),s}stmtToDirective(n){let e=this.castNodeTo(n,"Directive"),r=this.castNodeTo(n.expression,"DirectiveLiteral"),s=r.value,i=this.input.slice(this.offsetToSourcePos(r.start),this.offsetToSourcePos(r.end)),a=r.value=i.slice(1,-1);return this.addExtra(r,"raw",i),this.addExtra(r,"rawValue",a),this.addExtra(r,"expressionValue",s),e.value=r,delete n.expression,e}parseInterpreterDirective(){if(!this.match(28))return null;let n=this.startNode();return n.value=this.state.value,this.next(),this.finishNode(n,"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 n=this.nextTokenInLineStart(),e=this.codePointAtPos(n);if(this.isUnparsedContextual(n,"of")){let r=this.lookaheadCharCodeSince(n+2);if(r!==61&&r!==58&&r!==59)return!1}return!!(this.chStartsBindingIdentifier(e,n)||this.isUnparsedContextual(n,"void"))}nextTokenIsIdentifierOnSameLine(){let n=this.nextTokenInLineStart(),e=this.codePointAtPos(n);return this.chStartsBindingIdentifier(e,n)}isAwaitUsing(){if(!this.isContextual(96))return!1;let n=this.nextTokenInLineStart();if(this.isUnparsedContextual(n,"using")){n=this.nextTokenInLineStartSince(n+5);let e=this.codePointAtPos(n);if(this.chStartsBindingIdentifier(e,n))return!0}return!1}chStartsBindingIdentifier(n,e){if(yt(n)){if(Rd.lastIndex=e,Rd.test(this.input)){let r=this.codePointAtPos(Rd.lastIndex);if(!gn(r)&&r!==92)return!1}return!0}else return n===92}chStartsBindingPattern(n){return n===91||n===123}hasFollowingBindingAtom(){let n=this.nextTokenStart(),e=this.codePointAtPos(n);return this.chStartsBindingPattern(e)||this.chStartsBindingIdentifier(e,n)}hasInLineFollowingBindingIdentifierOrBrace(){let n=this.nextTokenInLineStart(),e=this.codePointAtPos(n);return e===123||this.chStartsBindingIdentifier(e,n)}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(n=!1){let e=0;return this.options.annexB&&!this.state.strict&&(e|=4,n&&(e|=8)),this.parseStatementLike(e)}parseStatement(){return this.parseStatementLike(0)}parseStatementLike(n){let e=null;return this.match(26)&&(e=this.parseDecorators(!0)),this.parseStatementContent(n,e)}parseStatementContent(n,e){let r=this.state.type,s=this.startNode(),i=!!(n&2),a=!!(n&4),o=n&1;switch(r){case 60:return this.parseBreakContinueStatement(s,!0);case 63:return this.parseBreakContinueStatement(s,!1);case 64:return this.parseDebuggerStatement(s);case 90:return this.parseDoWhileStatement(s);case 91:return this.parseForStatement(s);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(s,!1,!i&&a);case 80:return i||this.unexpected(),this.parseClass(this.maybeTakeDecorators(e,s),!0);case 69:return this.parseIfStatement(s);case 70:return this.parseReturnStatement(s);case 71:return this.parseSwitchStatement(s);case 72:return this.parseThrowStatement(s);case 73:return this.parseTryStatement(s);case 96:if(this.isAwaitUsing())return this.allowsUsing()?i?this.recordAwaitIfAllowed()||this.raise(b.AwaitUsingNotInAsyncContext,s):this.raise(b.UnexpectedLexicalDeclaration,s):this.raise(b.UnexpectedUsingDeclaration,s),this.next(),this.parseVarStatement(s,"await using");break;case 107:if(this.state.containsEsc||!this.hasInLineFollowingBindingIdentifierOrBrace())break;return this.allowsUsing()?i||this.raise(b.UnexpectedLexicalDeclaration,this.state.startLoc):this.raise(b.UnexpectedUsingDeclaration,this.state.startLoc),this.parseVarStatement(s,"using");case 100:{if(this.state.containsEsc)break;let l=this.nextTokenStart(),u=this.codePointAtPos(l);if(u!==91&&(!i&&this.hasFollowingLineBreak()||!this.chStartsBindingIdentifier(u,l)&&u!==123))break}case 75:i||this.raise(b.UnexpectedLexicalDeclaration,this.state.startLoc);case 74:{let l=this.state.value;return this.parseVarStatement(s,l)}case 92:return this.parseWhileStatement(s);case 76:return this.parseWithStatement(s);case 5:return this.parseBlock();case 13:return this.parseEmptyStatement(s);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 r===83?l=this.parseImport(s):l=this.parseExport(s,e),this.assertModuleNodeAllowed(l),l}default:if(this.isAsyncFunction())return i||this.raise(b.AsyncFunctionInSingleStatementContext,this.state.startLoc),this.next(),this.parseFunctionStatement(s,!0,!i&&a)}let d=this.state.value,c=this.parseExpression();return ie(r)&&c.type==="Identifier"&&this.eat(14)?this.parseLabeledStatement(s,d,c,n):this.parseExpressionStatement(s,c,e)}assertModuleNodeAllowed(n){!(this.optionFlags&8)&&!this.inModule&&this.raise(b.ImportOutsideModule,n)}decoratorsEnabledBeforeExport(){return this.hasPlugin("decorators-legacy")?!0:this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")!==!1}maybeTakeDecorators(n,e,r){if(n){var s;(s=e.decorators)!=null&&s.length?(typeof this.getPluginOption("decorators","decoratorsBeforeExport")!="boolean"&&this.raise(b.DecoratorsBeforeAfterExport,e.decorators[0]),e.decorators.unshift(...n)):e.decorators=n,this.resetStartLocationFromNode(e,n[0]),r&&this.resetStartLocationFromNode(r,e)}return e}canHaveLeadingDecorator(){return this.match(80)}parseDecorators(n){let e=[];do e.push(this.parseDecorator());while(this.match(26));if(this.match(82))n||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 n=this.startNode();if(this.next(),this.hasPlugin("decorators")){let e=this.state.startLoc,r;if(this.match(10)){let s=this.state.startLoc;this.next(),r=this.parseExpression(),this.expect(11),r=this.wrapParenthesis(s,r);let i=this.state.startLoc;n.expression=this.parseMaybeDecoratorArguments(r,s),this.getPluginOption("decorators","allowCallParenthesized")===!1&&n.expression!==r&&this.raise(b.DecoratorArgumentsOutsideParentheses,i)}else{for(r=this.parseIdentifier(!1);this.eat(16);){let s=this.startNodeAt(e);s.object=r,this.match(139)?(this.classScope.usePrivateName(this.state.value,this.state.startLoc),s.property=this.parsePrivateName()):s.property=this.parseIdentifier(!0),s.computed=!1,r=this.finishNode(s,"MemberExpression")}n.expression=this.parseMaybeDecoratorArguments(r,e)}}else n.expression=this.parseExprSubscripts();return this.finishNode(n,"Decorator")}parseMaybeDecoratorArguments(n,e){if(this.eat(10)){let r=this.startNodeAt(e);return r.callee=n,r.arguments=this.parseCallExpressionArguments(),this.toReferencedList(r.arguments),this.finishNode(r,"CallExpression")}return n}parseBreakContinueStatement(n,e){return this.next(),this.isLineTerminator()?n.label=null:(n.label=this.parseIdentifier(),this.semicolon()),this.verifyBreakContinue(n,e),this.finishNode(n,e?"BreakStatement":"ContinueStatement")}verifyBreakContinue(n,e){let r;for(r=0;r<this.state.labels.length;++r){let s=this.state.labels[r];if((n.label==null||s.name===n.label.name)&&(s.kind!=null&&(e||s.kind===1)||n.label&&e))break}if(r===this.state.labels.length){let s=e?"BreakStatement":"ContinueStatement";this.raise(b.IllegalBreakContinue,n,{type:s})}}parseDebuggerStatement(n){return this.next(),this.semicolon(),this.finishNode(n,"DebuggerStatement")}parseHeaderExpression(){this.expect(10);let n=this.parseExpression();return this.expect(11),n}parseDoWhileStatement(n){return this.next(),this.state.labels.push(kd),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.state.labels.pop(),this.expect(92),n.test=this.parseHeaderExpression(),this.eat(13),this.finishNode(n,"DoWhileStatement")}parseForStatement(n){this.next(),this.state.labels.push(kd);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(n,null);let r=this.isContextual(100);{let d=this.isAwaitUsing(),c=d||this.isForUsing(),l=r&&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(n,f,e):(e!==null&&this.unexpected(e),this.parseFor(n,f))}}let s=this.isContextual(95),i=new Qn,a=this.parseExpression(!0,i),o=this.isContextual(102);if(o&&(r&&this.raise(b.ForOfLet,a),e===null&&s&&a.type==="Identifier"&&this.raise(b.ForOfAsync,a)),o||this.match(58)){this.checkDestructuringPrivate(i),this.toAssignable(a,!0);let d=o?"ForOfStatement":"ForInStatement";return this.checkLVal(a,{type:d}),this.parseForIn(n,a,e)}else this.checkExpressionErrors(i,!0);return e!==null&&this.unexpected(e),this.parseFor(n,a)}parseFunctionStatement(n,e,r){return this.next(),this.parseFunction(n,1|(r?2:0)|(e?8:0))}parseIfStatement(n){return this.next(),n.test=this.parseHeaderExpression(),n.consequent=this.parseStatementOrSloppyAnnexBFunctionDeclaration(),n.alternate=this.eat(66)?this.parseStatementOrSloppyAnnexBFunctionDeclaration():null,this.finishNode(n,"IfStatement")}parseReturnStatement(n){return this.prodParam.hasReturn||this.raise(b.IllegalReturn,this.state.startLoc),this.next(),this.isLineTerminator()?n.argument=null:(n.argument=this.parseExpression(),this.semicolon()),this.finishNode(n,"ReturnStatement")}parseSwitchStatement(n){this.next(),n.discriminant=this.parseHeaderExpression();let e=n.cases=[];this.expect(5),this.state.labels.push(SI),this.scope.enter(256);let r;for(let s;!this.match(8);)if(this.match(61)||this.match(65)){let i=this.match(61);r&&this.finishNode(r,"SwitchCase"),e.push(r=this.startNode()),r.consequent=[],this.next(),i?r.test=this.parseExpression():(s&&this.raise(b.MultipleDefaultsInSwitch,this.state.lastTokStartLoc),s=!0,r.test=null),this.expect(14)}else r?r.consequent.push(this.parseStatementListItem()):this.unexpected();return this.scope.exit(),r&&this.finishNode(r,"SwitchCase"),this.next(),this.state.labels.pop(),this.finishNode(n,"SwitchStatement")}parseThrowStatement(n){return this.next(),this.hasPrecedingLineBreak()&&this.raise(b.NewlineAfterThrow,this.state.lastTokEndLoc),n.argument=this.parseExpression(),this.semicolon(),this.finishNode(n,"ThrowStatement")}parseCatchClauseParam(){let n=this.parseBindingAtom();return this.scope.enter(this.options.annexB&&n.type==="Identifier"?8:0),this.checkLVal(n,{type:"CatchClause"},9),n}parseTryStatement(n){if(this.next(),n.block=this.parseBlock(),n.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(),n.handler=this.finishNode(e,"CatchClause")}return n.finalizer=this.eat(67)?this.parseBlock():null,!n.handler&&!n.finalizer&&this.raise(b.NoCatchOrFinally,n),this.finishNode(n,"TryStatement")}parseVarStatement(n,e,r=!1){return this.next(),this.parseVar(n,!1,e,r),this.semicolon(),this.finishNode(n,"VariableDeclaration")}parseWhileStatement(n){return this.next(),n.test=this.parseHeaderExpression(),this.state.labels.push(kd),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.state.labels.pop(),this.finishNode(n,"WhileStatement")}parseWithStatement(n){return this.state.strict&&this.raise(b.StrictWith,this.state.startLoc),this.next(),n.object=this.parseHeaderExpression(),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.finishNode(n,"WithStatement")}parseEmptyStatement(n){return this.next(),this.finishNode(n,"EmptyStatement")}parseLabeledStatement(n,e,r,s){for(let a of this.state.labels)a.name===e&&this.raise(b.LabelRedeclaration,r,{labelName:e});let i=LR(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===n.start)o.statementStart=this.sourceToOffsetPos(this.state.start),o.kind=i;else break}return this.state.labels.push({name:e,kind:i,statementStart:this.sourceToOffsetPos(this.state.start)}),n.body=s&8?this.parseStatementOrSloppyAnnexBFunctionDeclaration(!0):this.parseStatement(),this.state.labels.pop(),n.label=r,this.finishNode(n,"LabeledStatement")}parseExpressionStatement(n,e,r){return n.expression=e,this.semicolon(),this.finishNode(n,"ExpressionStatement")}parseBlock(n=!1,e=!0,r){let s=this.startNode();return n&&this.state.strictErrors.clear(),this.expect(5),e&&this.scope.enter(0),this.parseBlockBody(s,n,!1,8,r),e&&this.scope.exit(),this.finishNode(s,"BlockStatement")}isValidDirective(n){return n.type==="ExpressionStatement"&&n.expression.type==="StringLiteral"&&!n.expression.extra.parenthesized}parseBlockBody(n,e,r,s,i){let a=n.body=[],o=n.directives=[];this.parseBlockOrModuleBlockBody(a,e?o:void 0,r,s,i)}parseBlockOrModuleBlockBody(n,e,r,s,i){let a=this.state.strict,o=!1,d=!1;for(;!this.match(s);){let c=r?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()}n.push(c)}i?.call(this,o),a||this.setStrict(!1),this.next()}parseFor(n,e){return n.init=e,this.semicolon(!1),n.test=this.match(13)?null:this.parseExpression(),this.semicolon(!1),n.update=this.match(11)?null:this.parseExpression(),this.expect(11),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.scope.exit(),this.state.labels.pop(),this.finishNode(n,"ForStatement")}parseForIn(n,e,r){let s=this.match(58);return this.next(),s?r!==null&&this.unexpected(r):n.await=r!==null,e.type==="VariableDeclaration"&&e.declarations[0].init!=null&&(!s||!this.options.annexB||this.state.strict||e.kind!=="var"||e.declarations[0].id.type!=="Identifier")&&this.raise(b.ForInOfLoopInitializer,e,{type:s?"ForInStatement":"ForOfStatement"}),e.type==="AssignmentPattern"&&this.raise(b.InvalidLhs,e,{ancestor:{type:"ForStatement"}}),n.left=e,n.right=s?this.parseExpression():this.parseMaybeAssignAllowIn(),this.expect(11),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.scope.exit(),this.state.labels.pop(),this.finishNode(n,s?"ForInStatement":"ForOfStatement")}parseVar(n,e,r,s=!1){let i=n.declarations=[];for(n.kind=r;;){let a=this.startNode();if(this.parseVarId(a,r),a.init=this.eat(29)?e?this.parseMaybeAssignDisallowIn():this.parseMaybeAssignAllowIn():null,a.init===null&&!s&&(a.id.type!=="Identifier"&&!(e&&(this.match(58)||this.isContextual(102)))?this.raise(b.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:"destructuring"}):(r==="const"||r==="using"||r==="await using")&&!(this.match(58)||this.isContextual(102))&&this.raise(b.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:r})),i.push(this.finishNode(a,"VariableDeclarator")),!this.eat(12))break}return n}parseVarId(n,e){let r=this.parseBindingAtom();e==="using"||e==="await using"?(r.type==="ArrayPattern"||r.type==="ObjectPattern")&&this.raise(b.UsingDeclarationHasBindingPattern,r.loc.start):r.type==="VoidPattern"&&this.raise(b.UnexpectedVoidPattern,r.loc.start),this.checkLVal(r,{type:"VariableDeclarator"},e==="var"?5:8201),n.id=r}parseAsyncFunctionExpression(n){return this.parseFunction(n,8)}parseFunction(n,e=0){let r=e&2,s=!!(e&1),i=s&&!(e&4),a=!!(e&8);this.initFunction(n,a),this.match(55)&&(r&&this.raise(b.GeneratorInSingleStatementContext,this.state.startLoc),this.next(),n.generator=!0),s&&(n.id=this.parseFunctionId(i));let o=this.state.maybeInArrowParameters;return this.state.maybeInArrowParameters=!1,this.scope.enter(514),this.prodParam.enter($i(a,n.generator)),s||(n.id=this.parseFunctionId()),this.parseFunctionParams(n,!1),this.withSmartMixTopicForbiddingContext(()=>{this.parseFunctionBodyAndFinish(n,s?"FunctionDeclaration":"FunctionExpression")}),this.prodParam.exit(),this.scope.exit(),s&&!r&&this.registerFunctionStatementId(n),this.state.maybeInArrowParameters=o,n}parseFunctionId(n){return n||ie(this.state.type)?this.parseIdentifier():null}parseFunctionParams(n,e){this.expect(10),this.expressionScope.enter(hI()),n.params=this.parseBindingList(11,41,2|(e?4:0)),this.expressionScope.exit()}registerFunctionStatementId(n){n.id&&this.scope.declareName(n.id.name,!this.options.annexB||this.state.strict||n.generator||n.async?this.scope.treatFunctionsAsVar?5:8201:17,n.id.loc.start)}parseClass(n,e,r){this.next();let s=this.state.strict;return this.state.strict=!0,this.parseClassId(n,e,r),this.parseClassSuper(n),n.body=this.parseClassBody(!!n.superClass,s),this.finishNode(n,e?"ClassDeclaration":"ClassExpression")}isClassProperty(){return this.match(29)||this.match(13)||this.match(8)}isClassMethod(){return this.match(10)}nameIsConstructor(n){return n.type==="Identifier"&&n.name==="constructor"||n.type==="StringLiteral"&&n.value==="constructor"}isNonstaticConstructor(n){return!n.computed&&!n.static&&this.nameIsConstructor(n.key)}parseClassBody(n,e){this.classScope.enter();let r={hadConstructor:!1,hadSuperClass:n},s=[],i=this.startNode();if(i.body=[],this.expect(5),this.withSmartMixTopicForbiddingContext(()=>{for(;!this.match(8);){if(this.eat(13)){if(s.length>0)throw this.raise(b.DecoratorSemicolon,this.state.lastTokEndLoc);continue}if(this.match(26)){s.push(this.parseDecorator());continue}let a=this.startNode();s.length&&(a.decorators=s,this.resetStartLocationFromNode(a,s[0]),s=[]),this.parseClassMember(i,a,r),a.kind==="constructor"&&a.decorators&&a.decorators.length>0&&this.raise(b.DecoratorConstructor,a)}}),this.state.strict=e,this.next(),s.length)throw this.raise(b.TrailingDecorator,this.state.startLoc);return this.classScope.exit(),this.finishNode(i,"ClassBody")}parseClassMemberFromModifier(n,e){let r=this.parseIdentifier(!0);if(this.isClassMethod()){let s=e;return s.kind="method",s.computed=!1,s.key=r,s.static=!1,this.pushClassMethod(n,s,!1,!1,!1,!1),!0}else if(this.isClassProperty()){let s=e;return s.computed=!1,s.key=r,s.static=!1,n.body.push(this.parseClassProperty(s)),!0}return this.resetPreviousNodeTrailingComments(r),!1}parseClassMember(n,e,r){let s=this.isContextual(106);if(s){if(this.parseClassMemberFromModifier(n,e))return;if(this.eat(5)){this.parseClassStaticBlock(n,e);return}}this.parseClassMemberWithIsStatic(n,e,r,s)}parseClassMemberWithIsStatic(n,e,r,s){let i=e,a=e,o=e,d=e,c=e,l=i,u=i;if(e.static=s,this.parsePropertyNamePrefixOperator(e),this.eat(55)){l.kind="method";let y=this.match(139);if(this.parseClassElementName(l),this.parsePostMemberNameModifiers(l),y){this.pushClassPrivateMethod(n,a,!0,!1);return}this.isNonstaticConstructor(i)&&this.raise(b.ConstructorIsGenerator,i.key),this.pushClassMethod(n,i,!0,!1,!1,!1);return}let p=!this.state.containsEsc&&ie(this.state.type),f=this.parseClassElementName(e),h=p?f.name:null,m=this.isPrivateName(f),g=this.state.startLoc;if(this.parsePostMemberNameModifiers(u),this.isClassMethod()){if(l.kind="method",m){this.pushClassPrivateMethod(n,a,!1,!1);return}let y=this.isNonstaticConstructor(i),w=!1;y&&(i.kind="constructor",r.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(b.DuplicateConstructor,f),y&&this.hasPlugin("typescript")&&e.override&&this.raise(b.OverrideOnConstructor,f),r.hadConstructor=!0,w=r.hadSuperClass),this.pushClassMethod(n,i,!1,!1,y,w)}else if(this.isClassProperty())m?this.pushClassPrivateProperty(n,d):this.pushClassProperty(n,o);else if(h==="async"&&!this.isLineTerminator()){this.resetPreviousNodeTrailingComments(f);let y=this.eat(55);u.optional&&this.unexpected(g),l.kind="method";let w=this.match(139);this.parseClassElementName(l),this.parsePostMemberNameModifiers(u),w?this.pushClassPrivateMethod(n,a,y,!0):(this.isNonstaticConstructor(i)&&this.raise(b.ConstructorIsAsync,i.key),this.pushClassMethod(n,i,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(i),y?this.pushClassPrivateMethod(n,a,!1,!1):(this.isNonstaticConstructor(i)&&this.raise(b.ConstructorIsAccessor,i.key),this.pushClassMethod(n,i,!1,!1,!1,!1)),this.checkGetterSetterParams(i)}else if(h==="accessor"&&!this.isLineTerminator()){this.expectPlugin("decoratorAutoAccessors"),this.resetPreviousNodeTrailingComments(f);let y=this.match(139);this.parseClassElementName(o),this.pushClassAccessorProperty(n,c,y)}else this.isLineTerminator()?m?this.pushClassPrivateProperty(n,d):this.pushClassProperty(n,o):this.unexpected()}parseClassElementName(n){let{type:e,value:r}=this.state;if((e===132||e===134)&&n.static&&r==="prototype"&&this.raise(b.StaticPrototype,this.state.startLoc),e===139){r==="constructor"&&this.raise(b.ConstructorClassPrivateField,this.state.startLoc);let s=this.parsePrivateName();return n.key=s,s}return this.parsePropertyName(n),n.key}parseClassStaticBlock(n,e){var r;this.scope.enter(720);let s=this.state.labels;this.state.labels=[],this.prodParam.enter(0);let i=e.body=[];this.parseBlockOrModuleBlockBody(i,void 0,!1,8),this.prodParam.exit(),this.scope.exit(),this.state.labels=s,n.body.push(this.finishNode(e,"StaticBlock")),(r=e.decorators)!=null&&r.length&&this.raise(b.DecoratorStaticBlock,e)}pushClassProperty(n,e){!e.computed&&this.nameIsConstructor(e.key)&&this.raise(b.ConstructorClassField,e.key),n.body.push(this.parseClassProperty(e))}pushClassPrivateProperty(n,e){let r=this.parseClassPrivateProperty(e);n.body.push(r),this.classScope.declarePrivateName(this.getPrivateNameSV(r.key),0,r.key.loc.start)}pushClassAccessorProperty(n,e,r){!r&&!e.computed&&this.nameIsConstructor(e.key)&&this.raise(b.ConstructorClassField,e.key);let s=this.parseClassAccessorProperty(e);n.body.push(s),r&&this.classScope.declarePrivateName(this.getPrivateNameSV(s.key),0,s.key.loc.start)}pushClassMethod(n,e,r,s,i,a){n.body.push(this.parseMethod(e,r,s,i,a,"ClassMethod",!0))}pushClassPrivateMethod(n,e,r,s){let i=this.parseMethod(e,r,s,!1,!1,"ClassPrivateMethod",!0);n.body.push(i);let a=i.kind==="get"?i.static?6:2:i.kind==="set"?i.static?5:1:0;this.declareClassPrivateMethodInScope(i,a)}declareClassPrivateMethodInScope(n,e){this.classScope.declarePrivateName(this.getPrivateNameSV(n.key),e,n.key.loc.start)}parsePostMemberNameModifiers(n){}parseClassPrivateProperty(n){return this.parseInitializer(n),this.semicolon(),this.finishNode(n,"ClassPrivateProperty")}parseClassProperty(n){return this.parseInitializer(n),this.semicolon(),this.finishNode(n,"ClassProperty")}parseClassAccessorProperty(n){return this.parseInitializer(n),this.semicolon(),this.finishNode(n,"ClassAccessorProperty")}parseInitializer(n){this.scope.enter(592),this.expressionScope.enter(Rh()),this.prodParam.enter(0),n.value=this.eat(29)?this.parseMaybeAssignAllowIn():null,this.expressionScope.exit(),this.prodParam.exit(),this.scope.exit()}parseClassId(n,e,r,s=8331){if(ie(this.state.type))n.id=this.parseIdentifier(),e&&this.declareNameFromIdentifier(n.id,s);else if(r||!e)n.id=null;else throw this.raise(b.MissingClassName,this.state.startLoc)}parseClassSuper(n){n.superClass=this.eat(81)?this.parseExprSubscripts():null}parseExport(n,e){let r=this.parseMaybeImportPhase(n,!0),s=this.maybeParseExportDefaultSpecifier(n,r),i=!s||this.eat(12),a=i&&this.eatExportStar(n),o=a&&this.maybeParseExportNamespaceSpecifier(n),d=i&&(!o||this.eat(12)),c=s||a;if(a&&!o){if(s&&this.unexpected(),e)throw this.raise(b.UnsupportedDecoratorExport,n);return this.parseExportFrom(n,!0),this.sawUnambiguousESM=!0,this.finishNode(n,"ExportAllDeclaration")}let l=this.maybeParseExportNamedSpecifiers(n);s&&i&&!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,n);this.parseExportFrom(n,c)}else u=this.maybeParseExportDeclaration(n);if(c||l||u){var p;let f=n;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,n);return this.sawUnambiguousESM=!0,this.finishNode(f,"ExportNamedDeclaration")}if(this.eat(65)){let f=n,h=this.parseExportDefaultExpression();if(f.declaration=h,h.type==="ClassDeclaration")this.maybeTakeDecorators(e,h,f);else if(e)throw this.raise(b.UnsupportedDecoratorExport,n);return this.checkExport(f,!0,!0),this.sawUnambiguousESM=!0,this.finishNode(f,"ExportDefaultDeclaration")}throw this.unexpected(null,5)}eatExportStar(n){return this.eat(55)}maybeParseExportDefaultSpecifier(n,e){if(e||this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom",e?.loc.start);let r=e||this.parseIdentifier(!0),s=this.startNodeAtNode(r);return s.exported=r,n.specifiers=[this.finishNode(s,"ExportDefaultSpecifier")],!0}return!1}maybeParseExportNamespaceSpecifier(n){if(this.isContextual(93)){var e,r;(r=(e=n).specifiers)!=null||(e.specifiers=[]);let s=this.startNodeAt(this.state.lastTokStartLoc);return this.next(),s.exported=this.parseModuleExportName(),n.specifiers.push(this.finishNode(s,"ExportNamespaceSpecifier")),!0}return!1}maybeParseExportNamedSpecifiers(n){if(this.match(5)){let e=n;e.specifiers||(e.specifiers=[]);let r=e.exportKind==="type";return e.specifiers.push(...this.parseExportSpecifiers(r)),e.source=null,this.hasPlugin("importAssertions")?e.assertions=[]:e.attributes=[],e.declaration=null,!0}return!1}maybeParseExportDeclaration(n){return this.shouldParseExportDeclaration()?(n.specifiers=[],n.source=null,this.hasPlugin("importAssertions")?n.assertions=[]:n.attributes=[],n.declaration=this.parseExportDeclaration(n),!0):!1}isAsyncFunction(){if(!this.isContextual(95))return!1;let n=this.nextTokenInLineStart();return this.isUnparsedContextual(n,"function")}parseExportDefaultExpression(){let n=this.startNode();if(this.match(68))return this.next(),this.parseFunction(n,5);if(this.isAsyncFunction())return this.next(),this.next(),this.parseFunction(n,13);if(this.match(80))return this.parseClass(n,!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(n){return this.match(80)?this.parseClass(this.startNode(),!0,!1):this.parseStatementListItem()}isExportDefaultSpecifier(){let{type:n}=this.state;if(ie(n)){if(n===95&&!this.state.containsEsc||n===100)return!1;if((n===130||n===129)&&!this.state.containsEsc){let s=this.nextTokenStart(),i=this.input.charCodeAt(s);if(i===123||this.chStartsBindingIdentifier(i,s)&&!this.input.startsWith("from",s))return this.expectOnePlugin(["flow","typescript"]),!1}}else if(!this.match(65))return!1;let e=this.nextTokenStart(),r=this.isUnparsedContextual(e,"from");if(this.input.charCodeAt(e)===44||ie(this.state.type)&&r)return!0;if(this.match(65)&&r){let s=this.input.charCodeAt(this.nextTokenStartSince(e+4));return s===34||s===39}return!1}parseExportFrom(n,e){this.eatContextual(98)?(n.source=this.parseImportSource(),this.checkExport(n),this.maybeParseImportAttributes(n),this.checkJSONModuleImport(n)):e&&this.unexpected(),this.semicolon()}shouldParseExportDeclaration(){let{type:n}=this.state;return n===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):n===74||n===75||n===68||n===80||this.isLet()||this.isAsyncFunction()}checkExport(n,e,r,s){if(e){var i;if(r){if(this.checkDuplicateExports(n,"default"),this.hasPlugin("exportDefaultFrom")){var a;let o=n.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((i=n.specifiers)!=null&&i.length)for(let o of n.specifiers){let{exported:d}=o,c=d.type==="Identifier"?d.name:d.value;if(this.checkDuplicateExports(o,c),!s&&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(n.declaration){let o=n.declaration;if(o.type==="FunctionDeclaration"||o.type==="ClassDeclaration"){let{id:d}=o;if(!d)throw new Error("Assertion failure");this.checkDuplicateExports(n,d.name)}else if(o.type==="VariableDeclaration")for(let d of o.declarations)this.checkDeclaration(d.id)}}}checkDeclaration(n){if(n.type==="Identifier")this.checkDuplicateExports(n,n.name);else if(n.type==="ObjectPattern")for(let e of n.properties)this.checkDeclaration(e);else if(n.type==="ArrayPattern")for(let e of n.elements)e&&this.checkDeclaration(e);else n.type==="ObjectProperty"?this.checkDeclaration(n.value):n.type==="RestElement"?this.checkDeclaration(n.argument):n.type==="AssignmentPattern"&&this.checkDeclaration(n.left)}checkDuplicateExports(n,e){this.exportedIdentifiers.has(e)&&(e==="default"?this.raise(b.DuplicateDefaultExport,n):this.raise(b.DuplicateExport,n,{exportName:e})),this.exportedIdentifiers.add(e)}parseExportSpecifiers(n){let e=[],r=!0;for(this.expect(5);!this.eat(8);){if(r)r=!1;else if(this.expect(12),this.eat(8))break;let s=this.isContextual(130),i=this.match(134),a=this.startNode();a.local=this.parseModuleExportName(),e.push(this.parseExportSpecifier(a,i,n,s))}return e}parseExportSpecifier(n,e,r,s){return this.eatContextual(93)?n.exported=this.parseModuleExportName():e?n.exported=this.cloneStringLiteral(n.local):n.exported||(n.exported=this.cloneIdentifier(n.local)),this.finishNode(n,"ExportSpecifier")}parseModuleExportName(){if(this.match(134)){let n=this.parseStringLiteral(this.state.value),e=EI.exec(n.value);return e&&this.raise(b.ModuleExportNameHasLoneSurrogate,n,{surrogateCharCode:e[0].charCodeAt(0)}),n}return this.parseIdentifier(!0)}isJSONModuleImport(n){return n.assertions!=null?n.assertions.some(({key:e,value:r})=>r.value==="json"&&(e.type==="Identifier"?e.name==="type":e.value==="type")):!1}checkImportReflection(n){let{specifiers:e}=n,r=e.length===1?e[0].type:null;if(n.phase==="source")r!=="ImportDefaultSpecifier"&&this.raise(b.SourcePhaseImportRequiresDefault,e[0].loc.start);else if(n.phase==="defer")r!=="ImportNamespaceSpecifier"&&this.raise(b.DeferImportRequiresNamespace,e[0].loc.start);else if(n.module){var s;r!=="ImportDefaultSpecifier"&&this.raise(b.ImportReflectionNotBinding,e[0].loc.start),((s=n.assertions)==null?void 0:s.length)>0&&this.raise(b.ImportReflectionHasAssertion,e[0].loc.start)}}checkJSONModuleImport(n){if(this.isJSONModuleImport(n)&&n.type!=="ExportAllDeclaration"){let{specifiers:e}=n;if(e!=null){let r=e.find(s=>{let i;if(s.type==="ExportSpecifier"?i=s.local:s.type==="ImportSpecifier"&&(i=s.imported),i!==void 0)return i.type==="Identifier"?i.name!=="default":i.value!=="default"});r!==void 0&&this.raise(b.ImportJSONBindingNotDefault,r.loc.start)}}}isPotentialImportPhase(n){return n?!1:this.isContextual(105)||this.isContextual(97)||this.isContextual(127)}applyImportPhase(n,e,r,s){e||(r==="module"?(this.expectPlugin("importReflection",s),n.module=!0):this.hasPlugin("importReflection")&&(n.module=!1),r==="source"?(this.expectPlugin("sourcePhaseImports",s),n.phase="source"):r==="defer"?(this.expectPlugin("deferredImportEvaluation",s),n.phase="defer"):this.hasPlugin("sourcePhaseImports")&&(n.phase=null))}parseMaybeImportPhase(n,e){if(!this.isPotentialImportPhase(e))return this.applyImportPhase(n,e,null),null;let r=this.startNode(),s=this.parseIdentifierName(!0),{type:i}=this.state;return(at(i)?i!==98||this.lookaheadCharCode()===102:i!==12)?(this.applyImportPhase(n,e,s,r.loc.start),null):(this.applyImportPhase(n,e,null),this.createIdentifier(r,s))}isPrecedingIdImportPhase(n){let{type:e}=this.state;return ie(e)?e!==98||this.lookaheadCharCode()===102:e!==12}parseImport(n){return this.match(134)?this.parseImportSourceAndAttributes(n):this.parseImportSpecifiersAndAfter(n,this.parseMaybeImportPhase(n,!1))}parseImportSpecifiersAndAfter(n,e){n.specifiers=[];let s=!this.maybeParseDefaultImportSpecifier(n,e)||this.eat(12),i=s&&this.maybeParseStarImportSpecifier(n);return s&&!i&&this.parseNamedImportSpecifiers(n),this.expectContextual(98),this.parseImportSourceAndAttributes(n)}parseImportSourceAndAttributes(n){var e;return(e=n.specifiers)!=null||(n.specifiers=[]),n.source=this.parseImportSource(),this.maybeParseImportAttributes(n),this.checkImportReflection(n),this.checkJSONModuleImport(n),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(n,"ImportDeclaration")}parseImportSource(){return this.match(134)||this.unexpected(),this.parseExprAtom()}parseImportSpecifierLocal(n,e,r){e.local=this.parseIdentifier(),n.specifiers.push(this.finishImportSpecifier(e,r))}finishImportSpecifier(n,e,r=8201){return this.checkLVal(n.local,{type:e},r),this.finishNode(n,e)}parseImportAttributes(){this.expect(5);let n=[],e=new Set;do{if(this.match(8))break;let r=this.startNode(),s=this.state.value;if(e.has(s)&&this.raise(b.ModuleAttributesWithDuplicateKeys,this.state.startLoc,{key:s}),e.add(s),this.match(134)?r.key=this.parseStringLiteral(s):r.key=this.parseIdentifier(!0),this.expect(14),!this.match(134))throw this.raise(b.ModuleAttributeInvalidValue,this.state.startLoc);r.value=this.parseStringLiteral(this.state.value),n.push(this.finishNode(r,"ImportAttribute"))}while(this.eat(12));return this.expect(8),n}parseModuleAttributes(){let n=[],e=new Set;do{let r=this.startNode();if(r.key=this.parseIdentifier(!0),r.key.name!=="type"&&this.raise(b.ModuleAttributeDifferentFromType,r.key),e.has(r.key.name)&&this.raise(b.ModuleAttributesWithDuplicateKeys,r.key,{key:r.key.name}),e.add(r.key.name),this.expect(14),!this.match(134))throw this.raise(b.ModuleAttributeInvalidValue,this.state.startLoc);r.value=this.parseStringLiteral(this.state.value),n.push(this.finishNode(r,"ImportAttribute"))}while(this.eat(12));return n}maybeParseImportAttributes(n){let e;var r=!1;if(this.match(76)){if(this.hasPrecedingLineBreak()&&this.lookaheadCharCode()===40)return;this.next(),this.hasPlugin("moduleAttributes")?(e=this.parseModuleAttributes(),this.addExtra(n,"deprecatedWithLegacySyntax",!0)):e=this.parseImportAttributes(),r=!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(n,"deprecatedAssertSyntax",!0),this.next(),e=this.parseImportAttributes()):e=[];!r&&this.hasPlugin("importAssertions")?n.assertions=e:n.attributes=e}maybeParseDefaultImportSpecifier(n,e){if(e){let r=this.startNodeAtNode(e);return r.local=e,n.specifiers.push(this.finishImportSpecifier(r,"ImportDefaultSpecifier")),!0}else if(at(this.state.type))return this.parseImportSpecifierLocal(n,this.startNode(),"ImportDefaultSpecifier"),!0;return!1}maybeParseStarImportSpecifier(n){if(this.match(55)){let e=this.startNode();return this.next(),this.expectContextual(93),this.parseImportSpecifierLocal(n,e,"ImportNamespaceSpecifier"),!0}return!1}parseNamedImportSpecifiers(n){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 r=this.startNode(),s=this.match(134),i=this.isContextual(130);r.imported=this.parseModuleExportName();let a=this.parseImportSpecifier(r,s,n.importKind==="type"||n.importKind==="typeof",i,void 0);n.specifiers.push(a)}}parseImportSpecifier(n,e,r,s,i){if(this.eatContextual(93))n.local=this.parseIdentifier();else{let{imported:a}=n;if(e)throw this.raise(b.ImportBindingIsString,n,{importName:a.value});this.checkReservedWord(a.name,n.loc.start,!0,!0),n.local||(n.local=this.cloneIdentifier(a))}return this.finishImportSpecifier(n,"ImportSpecifier",i)}isThisParam(n){return n.type==="Identifier"&&n.name==="this"}},_i=class extends Ud{constructor(n,e,r){let s=SR(n);super(s,e),this.options=s,this.initializeScopes(),this.plugins=r,this.filename=s.sourceFilename,this.startIndex=s.startIndex;let i=0;s.allowAwaitOutsideFunction&&(i|=1),s.allowReturnOutsideFunction&&(i|=2),s.allowImportExportEverywhere&&(i|=8),s.allowSuperOutsideMethod&&(i|=16),s.allowUndeclaredExports&&(i|=64),s.allowNewTargetOutsideFunction&&(i|=4),s.allowYieldOutsideFunction&&(i|=32),s.ranges&&(i|=128),s.tokens&&(i|=256),s.createImportExpressions&&(i|=512),s.createParenthesizedExpressions&&(i|=1024),s.errorRecovery&&(i|=2048),s.attachComment&&(i|=4096),s.annexB&&(i|=8192),this.optionFlags=i}getScopeHandler(){return Zr}parse(){this.enterInitialScopes();let n=this.startNode(),e=this.startNode();this.nextToken(),n.errors=null;let r=this.parseTopLevel(n,e);return r.errors=this.state.errors,r.comments.length=this.state.commentsLen,r}};function NI(t,n){var e;if(((e=n)==null?void 0:e.sourceType)==="unambiguous"){n=Object.assign({},n);try{n.sourceType="module";let r=Xr(n,t),s=r.parse();if(r.sawUnambiguousESM)return s;if(r.ambiguousScriptDifferentAst)try{return n.sourceType="script",Xr(n,t).parse()}catch{}else s.program.sourceType="script";return s}catch(r){try{return n.sourceType="script",Xr(n,t).parse()}catch{}throw r}}else return Xr(n,t).parse()}function OI(t,n){let e=Xr(n,t);return e.options.strictMode&&(e.state.strict=!0),e.getExpression()}function $I(t){let n={};for(let e of Object.keys(t))n[e]=Pt(t[e]);return n}var DI=$I(OR);function Xr(t,n){let e=_i,r=new Map;if(t!=null&&t.plugins){for(let s of t.plugins){let i,a;typeof s=="string"?i=s:[i,a]=s,r.has(i)||r.set(i,a||{})}TI(r),e=MI(r)}return new e(t,n,r)}var ph=new Map;function MI(t){let n=[];for(let s of PI)t.has(s)&&n.push(s);let e=n.join("|"),r=ph.get(e);if(!r){r=_i;for(let s of n)r=Th[s](r);ph.set(e,r)}return r}ts.parse=NI;ts.parseExpression=OI;ts.tokTypes=DI});import{parseArgs as K2}from"node:util";import{writeFile as Lx}from"node:fs/promises";import{join as _x}from"node:path";function rt(t,n=""){try{let e=new URL(t===void 0||t===""?n:t);return e.protocol==="https:"&&e.username===""&&e.password===""&&e.search===""&&e.hash===""?e.href.replace(/\/+$/,""):void 0}catch{return}}var jx=3e4,Fx="7.1",gp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,vp="KwikQA.Ci",Bx=4,kp=/^\$\([\w.-]+\)$/;function Bo(t){return Object.fromEntries(Object.entries(t).filter(([,n])=>n===void 0||!kp.test(n.trim())))}function Vx(t){if(!(t===void 0||t===""))try{let n=new URL(t);return n.username="",n.password="",rt(n.href)}catch{return}}function wp(t){let n=Number(t);return/^\d+$/.test(t??"")&&Number.isSafeInteger(n)&&n>0?n:void 0}function bp(t){if(!(t===void 0||t===""||t.startsWith("refs/pull/")))return t.replace(/^refs\/(?:heads|tags)\//,"")}function Vo(t){if(t.TF_BUILD!=="True")return;let n=rt(t.SYSTEM_COLLECTIONURI),e=t.SYSTEM_TEAMPROJECT??"",r=wp(t.BUILD_BUILDID),s=t.BUILD_REPOSITORY_PROVIDER??"",i=s==="GitHub"||s==="GitHubEnterprise",a=s==="TfsGit"?"pullrequest":i?"pull":void 0,o=a===void 0?void 0:Vx(t.BUILD_REPOSITORY_URI),d=wp((i?t.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER:void 0)||t.SYSTEM_PULLREQUEST_PULLREQUESTID),c=/^[0-9a-f]{40}$/i.test(t.BUILD_SOURCEVERSION??"")?t.BUILD_SOURCEVERSION:void 0,l=bp(t.SYSTEM_PULLREQUEST_SOURCEBRANCH)??bp(t.BUILD_SOURCEBRANCH),u=(t.SYSTEM_ACCESSTOKEN??"").trim(),p=gp.test(t.SYSTEM_TEAMPROJECTID??"")?t.SYSTEM_TEAMPROJECTID:void 0,f=gp.test(t.BUILD_REPOSITORY_ID??"")?t.BUILD_REPOSITORY_ID:void 0;return{...n===void 0?{}:{collectionUrl:n},...p===void 0?{}:{projectId:p},...f===void 0?{}:{repositoryId:f},provider:s,...t.BUILD_REPOSITORY_NAME?{repository:t.BUILD_REPOSITORY_NAME}:{},...n===void 0||e===""||r===void 0?{}:{runUrl:`${n}/${encodeURIComponent(e)}/_build/results?buildId=${r}`},pipeline:t.SYSTEM_DEFINITIONID||t.BUILD_DEFINITIONNAME||"",job:[t.SYSTEM_STAGENAME,t.SYSTEM_JOBNAME].filter(Boolean).join("."),...l===void 0?{}:{branch:l},...c===void 0?{}:{commit:{sha:c,...o===void 0?{}:{url:`${o}/commit/${c}`}}},...t.AGENT_TEMPDIRECTORY?{tempDirectory:t.AGENT_TEMPDIRECTORY}:{},...u===""||kp.test(u)?{}:{token:u},...d===void 0?{}:{pullRequest:{number:d,...o===void 0?{}:{url:`${o}/${a}/${d}`},fork:t.SYSTEM_PULLREQUEST_ISFORK==="True"}}}}function zx(t){return`kwikqa-ci pipeline=${encodeURIComponent(t.pipeline)} job=${encodeURIComponent(t.job)}`}function Hx(t){return t.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function _o(t){return t.ok&&t.status!==203}async function xp(t){let n=await t.json().catch(()=>{});return typeof n?.message=="string"?n.message.replace(/\s+/g," ").trim().slice(0,200):void 0}async function jo(t){if(t.status===429)return"Azure DevOps's rate limit was reached";if(t.status===401||t.status===203)return"Azure DevOps refused the token";if(t.status===403){let e=await xp(t);return`the build service can't comment on this pull request; give it "Contribute to pull requests" on the repository${e===void 0?"":` (${e})`}`}if(t.status===404)return"Azure DevOps found no such pull request with this token";let n=await xp(t);return`Azure DevOps answered ${t.status}${n===void 0?"":`: ${n}`}`}var Fo=class{constructor(n,e,r){this.send=n;this.base=e;this.token=r}send;base;token;call(n,e,r){return this.send(`${this.base}${e}?api-version=${Fx}`,{method:n,headers:{Accept:"application/json",Authorization:`Bearer ${this.token}`,...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error",signal:AbortSignal.timeout(jx)})}},Vn=class extends Error{};function Ux(t){if(typeof t=="string")return t;let n=typeof t=="object"&&t!==null?t:{};return typeof n.$value=="string"?n.$value:void 0}async function qx(t,n){let e=await t.call("GET","/threads");if(!_o(e))throw new Vn(await jo(e));let r=(await e.json()).value??[];for(let s of r){if(s.isDeleted===!0||Ux(s.properties?.[vp])!==n)continue;let i=s.comments?.find(a=>a.parentCommentId===0&&a.isDeleted!==!0);if(typeof s.id=="number"&&typeof i?.id=="number")return{thread:s.id,comment:i.id}}}async function Gx(t,n,e,r,s){let i=c=>t.print(`No pull-request comment: ${c}.`),a=e.pullRequest;if(a===void 0)return i("this run isn't for a pull request");if(e.provider!=="TfsGit")return i(`the repository is on ${e.provider||"another host"}, and KwikQA comments from Azure Pipelines only on Azure Repos pull requests`);if(a.fork)return i("the pull request comes from a fork, and its build gets no secrets by default");if(e.token===void 0)return i("SYSTEM_ACCESSTOKEN isn't set; add `SYSTEM_ACCESSTOKEN: $(System.AccessToken)` to the step's env");if(e.collectionUrl===void 0||e.projectId===void 0||e.repositoryId===void 0)return i("System.CollectionUri, System.TeamProjectId, or Build.Repository.ID isn't what Azure Pipelines sets");let o=new Fo(n,`${e.collectionUrl}/${e.projectId}/_apis/git/repositories/${e.repositoryId}/pullRequests/${a.number}`,e.token),d=zx(e);try{let c=await qx(o,d);if(c!==void 0){let u=await o.call("PATCH",`/threads/${c.thread}/comments/${c.comment}`,{content:r});if(_o(u))return t.print("Pull-request comment: updated.");if(u.status!==403&&u.status!==404)throw new Vn(await jo(u))}if(c===void 0&&!s)return i("nothing failed, and there is no earlier comment to update");let l=await o.call("POST","/threads",{comments:[{parentCommentId:0,content:r,commentType:1}],status:Bx,properties:{[vp]:{$type:"System.String",$value:d}}});if(!_o(l))throw new Vn(await jo(l));t.print("Pull-request comment: posted.")}catch(c){let l=c instanceof Vn?c.message:`Azure DevOps couldn't be reached (${c instanceof Error?c.message:String(c)})`;t.error(`No pull-request comment: ${l}.`)}}async function zo(t,n,e,r,s){if(e.tempDirectory===void 0)t.print("No build summary: AGENT_TEMPDIRECTORY isn't set.");else{let i=_x(e.tempDirectory,"kwikqa-summary.md");try{await Lx(i,r);let a=`##vso[task.addattachment type=Distributedtask.Core.Summary;name=KwikQA;]${Hx(i)}`;t.command===void 0?t.print(a):t.command(a),t.print("Build summary: written.")}catch(a){t.error(`No build summary: ${a.message}`)}}await Gx(t,n,e,r,s.failures)}import{lstat as lv,mkdir as uv,open as pv}from"node:fs/promises";import{dirname as jp,resolve as fv}from"node:path";import{createHash as Kx,randomUUID as ci}from"node:crypto";import{constants as zn}from"node:fs";import{chmod as Wx,link as Jx,lstat as At,mkdir as Ap,open as di,readFile as Tp,realpath as It,rename as qo,rm as Rp,unlink as Ho}from"node:fs/promises";import{dirname as Uo,isAbsolute as Xx,join as jt,relative as Pp,resolve as Go,sep as Sp}from"node:path";var Yx=/^txn_[a-f0-9]{24}$/;function nn(t,n){let e=Pp(t,n);return e===""||!Xx(e)&&e!==".."&&!e.startsWith(`..${Sp}`)}async function Hn(t){if(process.platform==="win32")return;let n=await di(t,"r");try{await n.sync()}finally{await n.close()}}function Ip(t){return Kx("sha256").update(t).digest("hex")}function Ep(){return`txn_${ci().replaceAll("-","").slice(0,24)}`}function rn(t){return Yx.test(t)}async function li(t){let n=await It(t),e=Go(n,".kwikqa","transactions");if(!nn(n,e))throw new Error("Transaction path escapes workspace.");return{root:n,transactionsDirectory:e}}async function Fe(t,n){let e=await It(t),r=e;for(let s of n){if(!/^[A-Za-z0-9_.-]+$/.test(s)||s==="."||s==="..")throw new Error("Unsafe transaction directory segment.");let i=jt(r,s),a=await At(i).catch(d=>{if(d.code!=="ENOENT")throw d});if(a===void 0)await Ap(i,{mode:448}),await Hn(r);else if(!a.isDirectory()||a.isSymbolicLink())throw new Error("Transaction directory contains an unsafe path.");let o=await It(i);if(!nn(e,o))throw new Error("Transaction directory escapes workspace.");r=o}return r}async function Cp(t,n,e){if(!/^\.staging-[a-f0-9]{24}$/.test(n)||!rn(e))throw new Error("Transaction publication name is invalid.");let r=await li(t),s=await It(r.transactionsDirectory),i=jt(s,n),a=jt(s,e),o=await At(i);if(!o.isDirectory()||o.isSymbolicLink())throw new Error("Transaction staging directory is unsafe.");if(await At(a).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Transaction already exists.");await qo(i,a),await Hn(s)}async function ye(t,n,e){let r=await It(Uo(t)),s=Go(r,t.slice(Uo(t).length+1));if(!nn(r,s))throw new Error("Write target escapes its directory.");if(!e.replace&&await At(s).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Durable record already exists.");let i=jt(r,`.kwikqa-${ci()}.tmp`),a=await di(i,"wx",e.mode),o=!1;try{await a.writeFile(n),await a.sync(),await a.close(),e.replace?await qo(i,s):(await Jx(i,s),await Ho(i)),o=!0,await Hn(r)}finally{await a.close().catch(()=>{}),o||await Ho(i).catch(()=>{})}}async function ui(t,n,e,r){let s=await It(t),i=Go(s,n);if(!nn(s,i))throw new Error("Target escapes workspace.");let a=await At(i);if(!a.isFile()||a.isSymbolicLink())throw new Error("Target is not a regular file.");let o=await It(Uo(i)),d=await It(i);if(!nn(s,o)||!nn(s,d))throw new Error("Target escapes workspace.");if(Pp(s,d).split(Sp).join("/")!==n)throw new Error("Target canonical path changed during final authorization.");let l=await di(d,zn.O_RDONLY|zn.O_NOFOLLOW);try{let m=await l.stat();if(!m.isFile()||m.dev!==a.dev||m.ino!==a.ino)throw new Error("Target changed during final authorization.");let g=await l.readFile();if(Ip(g)!==e)throw new Error("Target content changed during final authorization.")}finally{await l.close()}let u=jt(o,`.kwikqa-target-${ci()}.tmp`),p=a.mode&511,f=await di(u,zn.O_CREAT|zn.O_EXCL|zn.O_WRONLY|zn.O_NOFOLLOW,p),h=!1;try{await f.writeFile(r),await f.sync(),await f.close(),await Wx(u,p);let m=await It(i);if(m!==d||!nn(s,m))throw new Error("Target path changed before replacement.");let g=await Tp(m),y=await At(m);if(!y.isFile()||y.isSymbolicLink()||y.dev!==a.dev||y.ino!==a.ino||Ip(g)!==e)throw new Error("Target changed before replacement.");await qo(u,m),h=!0,await Hn(o)}finally{await f.close().catch(()=>{}),h||await Ho(u).catch(()=>{})}}async function Ge(t,n){let e=await Fe(t,[".kwikqa","transactions"]),r=jt(e,".lock"),s=ci();await Ap(r,{mode:448});let i=await At(r);try{await ye(jt(r,"owner.json"),`${JSON.stringify({...n,nonce:s})}
11
+ `,{mode:384,replace:!1})}catch(a){let o=await At(r).catch(()=>{});throw o?.dev===i.dev&&o.ino===i.ino&&await Rp(r,{recursive:!0,force:!0}).catch(()=>{}),a}return await Hn(e),{release:async()=>{let a=await At(r).catch(()=>{});if(a===void 0||a.dev!==i.dev||a.ino!==i.ino||a.isSymbolicLink())throw new Error("Workspace lock ownership changed before release.");if(JSON.parse(await Tp(jt(r,"owner.json"),"utf8")).nonce!==s)throw new Error("Workspace lock ownership changed before release.");await Rp(r,{recursive:!0,force:!1}),await Hn(e)}}}import{createHash as Qx}from"node:crypto";var pi="kwikqa-report",Mp="1",an={"test-support":"Test code",application:"Application",environment:"Environment",undetermined:"Undetermined",inconclusive:"Inconclusive","not-diagnosed":"Not diagnosed"},Zx=12,ev=800,Np=`
72
12
  :root{color-scheme:light dark;--ink:#0B0F17;--paper:#F4F5F7;--text:#0B0F17;--bg:#FFFFFF;--panel:#F4F5F7;--line:#D9DDE5;--muted:#5B6578;--accent:#0E9F6E;--fail:#D9432F;--warn:#9A6700}
73
13
  @media (prefers-color-scheme:dark){:root{--text:#E8ECF4;--bg:#0B0F17;--panel:#131926;--line:#283044;--muted:#8A93A6;--accent:#34D399;--fail:#FF6B57;--warn:#E3B341}}
74
14
  *{box-sizing:border-box}
@@ -112,7 +52,7 @@ details summary{cursor:pointer;color:var(--muted)}
112
52
  .filters button{padding:5px 12px;border:1px solid var(--line);border-radius:999px;background:var(--panel);color:var(--text);cursor:pointer}
113
53
  .filters button[aria-pressed=false]{opacity:.5;text-decoration:line-through}
114
54
  footer{margin-top:40px;padding-bottom:40px;color:var(--muted);font-size:13px;border-top:1px solid var(--line);padding-top:12px}
115
- `,fg=`
55
+ `,Op=`
116
56
  (() => {
117
57
  const groups = [...document.querySelectorAll("article.group")];
118
58
  const contents = document.getElementById("contents");
@@ -161,60 +101,122 @@ footer{margin-top:40px;padding-bottom:40px;color:var(--muted);font-size:13px;bor
161
101
  bar.append(fold);
162
102
  contents.after(bar);
163
103
  })();
164
- `;function hg(n){return aE("sha256").update(n,"utf8").digest("base64")}function gg(n){return n.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}var j=gg;function mg(n){return n.replace(/[^A-Za-z0-9_-]/g,"-")}function wg(n,t){return`ev-${mg(n.anchor)}-${mg(t)}`}function Sl(n){let t=n.split(`
165
- `);if(t.length<=oE&&n.length<=dE)return`<pre>${j(n)}</pre>`;let e=t.find(s=>s.trim()!=="")??"",r=e.length>120?`${e.slice(0,119)}\u2026`:e;return`<details><summary>${j(r)} (${t.length} lines)</summary><pre>${j(n)}</pre></details>`}function Pl(n){if(n.length===0)return"<p>None.</p>";let t=n.some(r=>r.project!==void 0),e=n.map(r=>`<tr><td>${j(r.title)}</td><td><code>${j(r.location)}</code></td>${t?`<td>${j(r.project??"")}</td>`:""}<td>${j(r.status)}</td><td>${j(r.attempts.join(", "))}</td></tr>`);return`<table><thead><tr><th>Test</th><th>Location</th>${t?"<th>Project</th>":""}<th>Status</th><th>Attempts</th></tr></thead><tbody>${e.join("")}</tbody></table>`}function cE(n,t){let e=new Set(n.evidence.map(r=>r.evidenceId));return t.map(r=>e.has(r)?`<a href="#${wg(n,r)}"><code>${j(r)}</code></a>`:`<code>${j(r)}</code>`).join(", ")}function lE(n,t){let e=(s,i)=>i.length===0?"":`<p><strong>${s}:</strong> ${i.map(a=>j(a)).join("; ")}</p>`,r=(s,i)=>i.length===0?"":`<p><strong>${s}:</strong> ${cE(n,i)}</p>`;return["<li>",`<p class="label">${j(t.statement)}</p>`,`<p class="status">Owner: ${j(t.owner)} \xB7 Evidence: ${j(t.grade)} \xB7 Cause: ${j(t.category)}</p>`,r("Supported by",t.supporting),r("Contradicted by",t.contradicting),e("Missing evidence",t.missing),e("Unresolved assumptions",t.assumptions),`<p><strong>Next:</strong> ${j(t.nextAction)}</p>`,"</li>"].join("")}function uE(n,t){return[`<li id="${wg(n,t.evidenceId)}">`,`<p class="label">${j(t.label)}${t.where===void 0?"":` <code>${j(t.where)}</code>`} <span class="id">${j(t.evidenceId)}</span></p>`,Sl(t.text),"</li>"].join("")}function pE(n){let t=Sn[n.owner],e=n.diagnosis,r=[`<article class="group" id="${j(n.anchor)}" data-owner="${j(n.owner)}" data-owner-label="${j(t)}">`,`<h3>${n.number===void 0?"":`<span class="num">Group ${n.number}</span> `}${j(n.title)}</h3>`,`<ul class="badges"><li class="owner-${j(n.owner)}">Owner: ${j(t)}</li>${n.grade===void 0?"":`<li>Evidence: ${j(n.grade)}</li>`}<li>${j(n.category)}</li></ul>`,`<p class="status">${j(n.status)}</p>`,"<h4>Tests</h4>",Pl(n.tests),n.testsCut===0?"":`<p>And ${n.testsCut} more tests in this group.</p>`];return e!==void 0&&r.push("<h4>Diagnosis</h4>",e.hypotheses.length===0?"<p>No cause is supported by the evidence.</p>":`<ol class="hypotheses">${e.hypotheses.map(s=>lE(n,s)).join("")}</ol>`,e.missing.length===0?"":`<p><strong>Missing evidence:</strong> ${e.missing.map(s=>j(s)).join("; ")}</p>`,`<p><strong>Recommended next action:</strong> ${j(e.nextAction)}</p>`,`<p><strong>Repair eligibility:</strong> ${j(e.repairEligibility)}</p>`),r.push("<h4>Why these tests are grouped</h4>",n.signals.length===0?"":`<ul>${n.signals.map(s=>`<li>${j(s.kind)}: <code>${j(s.value)}</code></li>`).join("")}</ul>`,`<p>${n.commonCause.supported?"A common cause is supported":"A common cause is not established"}: ${j(n.commonCause.rationale)}</p>`,`<h4>Evidence${e===void 0?"":" cited by the diagnosis"}</h4>`,n.evidenceNote===void 0?"":`<p class="note">${j(n.evidenceNote)}</p>`,n.evidence.length===0&&n.evidenceNote===void 0?"<p>None.</p>":n.evidence.length===0?"":`<ol class="evidence">${n.evidence.map(s=>uE(n,s)).join("")}</ol>`,n.evidenceCut===0?"":`<p>And ${n.evidenceCut} more evidence items.</p>`,"</article>"),r.join(`
166
- `)}function fE(n){let t=n.map(e=>`<li data-group="${j(e.anchor)}"><a href="#${j(e.anchor)}">${e.number===void 0?"Not sent":`Group ${e.number}`}</a>: ${j(e.title)}. Owner: ${j(Sn[e.owner])}.</li>`);return`<nav id="contents" aria-label="Failure groups"><h2>Failure groups</h2>${t.length===0?"<p>No failing test produced a failure group.</p>":`<ol>${t.join("")}</ol>`}</nav>`}function hE(n){let t=n.run,e=[["Framework",t.format===void 0?t.framework:`${t.framework} (${t.format})`],...t.report===void 0?[]:[["Report",t.report]],["Run started",t.createdAt],["Duration",t.duration],["Analyzed",n.recordedAt],["Diagnosis",t.diagnosedBy],["Result",`${t.outcome}. ${t.message}`]];return['<section id="run" aria-labelledby="run-heading">','<h2 id="run-heading">Run</h2>',`<ul class="counts">${t.counts.map(r=>`<li><span class="n">${r.value}</span> ${j(r.label)}</li>`).join("")}</ul>`,`<dl class="facts">${e.map(([r,s])=>`<dt>${j(r)}</dt><dd>${j(s)}</dd>`).join("")}</dl>`,n.evidenceNote===void 0?"":`<p class="note">${j(n.evidenceNote)}</p>`,"</section>"].join(`
167
- `)}function Pn(n,t,e){return`<section id="${n}" aria-labelledby="${n}-heading"><h2 id="${n}-heading">${j(t)}</h2>${e}</section>`}function mE(n){let t=n.repair;if(t===void 0)return"";let e=t.groupAnchor===void 0?"":`<p>For <a href="#${j(t.groupAnchor)}">${j(t.groupTitle??t.groupAnchor)}</a>.</p>`;return Pn("repair","Repair",[e,`<p><strong>${j(t.outcome)} (${j(t.reasonCode)})</strong>, from <code>kwikqa ${j(t.command)}</code>: ${j(t.message)}</p>`,`<table><thead><tr><th>Phase</th><th>Status</th></tr></thead><tbody>${t.phases.map(r=>`<tr><td>${j(r.phase)}</td><td>${j(r.status)}</td></tr>`).join("")}</tbody></table>`,t.intent===void 0?"":`<p><strong>Intent:</strong> ${j(t.intent.statement)}</p><p><strong>Preserves:</strong> ${j(t.intent.preserved)}</p>`,t.diff===void 0?"":`<h4>Diff</h4>${Sl(t.diff)}`].join(`
168
- `))}function yE(n){if(n.coverage.length===0)return Pn("coverage","What KwikQA could see","<p>No evidence was built for this run.</p>");let t=n.coverage.map(r=>`<tr><td>${j(r.channel)}</td><td>${j(r.availability)}</td><td>${r.included}</td><td>${r.omitted}</td></tr>`).join(""),e=n.omissions.length===0?"":`<p>Items left out: ${n.omissions.map(r=>`${r.count} ${j(r.reason)}`).join(", ")}.</p>`;return Pn("coverage","What KwikQA could see",["<p>A channel marked <em>unavailable</em> was not captured: it is missing knowledge, not a sign that nothing happened. <em>empty</em> means it was captured and held nothing.</p>",`<table><thead><tr><th>Evidence</th><th>Availability</th><th>Included</th><th>Left out</th></tr></thead><tbody>${t}</tbody></table>`,e,`<p>Redactions applied before anything was shown or sent: ${n.redactions}.</p>`].join(`
169
- `))}function gE(n){if(n.requests.length===0)return Pn("sent","What was sent","<p>Nothing: no model request was made.</p>");let t=n.requests.map(e=>`<tr><td>${j(e.group)}</td><td>${j(e.purpose)}</td><td>${j(e.model)}${e.zeroDataRetention?", zero data retention":""}</td><td><code>${j(e.packetHash)}</code></td><td>${j(e.tokens??"")}</td><td>${j(e.outcome)}</td></tr>`).join("");return Pn("sent","What was sent",`<p>Each request carried only the redacted evidence of one group, as its preview showed.</p><table><thead><tr><th>For</th><th>Request</th><th>Model</th><th>Evidence packet</th><th>Tokens</th><th>Outcome</th></tr></thead><tbody>${t}</tbody></table>`)}function $s(n){let t=["default-src 'none'",`style-src 'sha256-${hg(pg)}'`,`script-src 'sha256-${hg(fg)}'`,"base-uri 'none'","form-action 'none'"].join("; "),e=n.flaky.length===0?"":Pn("flaky","Flaky tests",`<p>These tests failed and then passed. KwikQA reports them and doesn't repair them.</p>${Pl(n.flaky)}`),r=n.notAnalyzed,s=r.unclassified.length===0&&r.runErrors.length===0?"":Pn("not-analyzed","Not analyzed",[r.runErrors.length===0?"":`<h4>Run-level errors</h4><ul>${r.runErrors.map(i=>`<li>${Sl(i)}</li>`).join("")}</ul>`,r.unclassified.length===0?"":`<h4>Failures no rule could classify</h4>${Pl(r.unclassified)}`].join(`
170
- `));return["<!doctype html>",'<html lang="en">',"<head>",'<meta charset="utf-8">','<meta name="viewport" content="width=device-width, initial-scale=1">',`<meta name="${Ba}" content="${yg}">`,`<meta http-equiv="Content-Security-Policy" content="${t}">`,'<meta name="referrer" content="no-referrer">',`<title>${j(n.title)}</title>`,`<style>${pg}</style>`,"</head>","<body>","<header>",'<p class="brand">KwikQA</p>',"<h1>Failure report</h1>",`<p class="lede">${j(n.title.replace(/^KwikQA report: /,""))}. ${j(n.run.diagnosedBy)}</p>`,"</header>","<main>",hE(n),fE(n.groups),`<section id="groups" aria-label="Failure group details">${n.groups.map(pE).join(`
171
- `)}</section>`,e,s,mE(n),yE(n),gE(n),"</main>",`<footer><p>Generated by KwikQA ${j(n.footer.kwikqaVersion)} from record <code>${j(n.footer.recordId)}</code> of run <code>${j(n.footer.runId)}</code>.</p><p>This page holds the same redacted evidence a request preview shows. Anyone who can open it can read it, so share it the way you share CI logs.</p></footer>`,`<script>${fg}</script>`,"</body>","</html>",""].join(`
172
- `)}var Va="kwikqa-report.html",xg=4096;async function kE(n){let t=await xE(n,"r");try{let e=Buffer.alloc(xg),{bytesRead:r}=await t.read(e,0,xg,0);return e.subarray(0,r).toString("utf8")}finally{await t.close()}}async function yr(n,t){let e=vE(n,t??Va),r=await wE(e).catch(s=>{if(s.code!=="ENOENT")throw s});return r===void 0?{kind:"writable",path:e}:r.isFile()?(await kE(e)).includes(`<meta name="${Ba}"`)?{kind:"writable",path:e}:{kind:"refused",path:e,message:`${e} exists and isn't a KwikQA report, so KwikQA won't replace it. Choose another path with --output.`}:{kind:"refused",path:e,message:`${e} exists and isn't a regular file, so KwikQA won't write a report there.`}}async function Tl(n,t){let e=await yr(bg(n),n);return e.kind==="refused"||(await bE(bg(n),{recursive:!0}),await ye(n,t,{mode:420,replace:!0})),e}import{basename as UE}from"node:path";var RE=[[/\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 Ds(n){return n.replace(/\\/g,"/").replace(/^[A-Za-z]:/,"").split("/").filter(r=>r.length>0).slice(-2).join("/")}function Ha(n,t=200){let e=n.replace(/\r\n/g,`
173
- `).replace(/(?:file:\/\/)?(?:[A-Za-z]:)?(?:\/[\w.@+-]+){2,}/g,r=>Ds(r));for(let[r,s]of RE)e=e.replace(r,s);return e=e.replace(/\s+/g," ").trim().toLowerCase(),e.length<=t?e:e.slice(0,t)}function vg(n){return n.replace(/['`]/g,'"').replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/\{\s*/g,"{ ").replace(/\s*\}/g," }").trim()}function Ms(n,t){return`${Ds(n)}:${t}`}var gr=["error-field","stack-frame","step"],El=["error-field","stack-frame"],Cl=["trace-event","console-event"];function Dt(n,t,e){return n.evidence.filter(r=>{if(!t.includes(r.kind))return!1;let s=n.normalized.get(r.evidenceId)??"";return e.some(i=>i.test(s))})}function IE(n,t,e){return n.evidence.filter(r=>t.includes(r.kind)&&e.some(s=>s.test(r.observation)))}var AE=[/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/,/no such element: unable to locate element/,/expected condition failed: waiting for/],PE=[/\bexpect\(/,/\bassertion\b/,/\bexpect \$\$?\(/,/\bexpected .{0,200} to (?:have|be|equal|eq|contain|include|exist|match|deep)\b/,/\bassertionerror: assert\b/,/\bexpected: .{0,200}? but was: /,/\bexpected \[.{0,200}?\] but found \[/],SE=[/expected:.{0,80}received:/s,/received:.{0,80}expected:/s],TE=[/uncaught \w*error/,/\bpageerror\b/,/unhandled (?:promise )?rejection/,/uncaught page error/,/originated from your application code/],EE=[/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/],CE=[/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/],NE=[/cy\.request\(\) failed/,/response we received from your web server was/,/request failed with status code/],OE=[/"(?: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/,/\bfailed on (?:setup|teardown) with\b/,/configinvoker\.invokeconfiguration/,/^container \S+ failed(?:, tests inside it did not run)?:/,/^(?:before|after) hook failed: /],$E=[/^(?:undefined|ambiguous|pending) step: /],Nl=[{ruleId:"action-timeout/timeout-text",category:"action-timeout",description:"Failure text reports an expired action, element wait, or test timeout.",match:n=>Dt(n,gr,AE)},{ruleId:"action-timeout/timed-out-status",category:"action-timeout",description:"The attempt status is timedOut and failure text is present to cite.",match:n=>n.attempt?.status==="timedOut"?n.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:n=>{let t=Dt(n,gr,PE);return t.length>0?t:Dt(n,gr,SE)}},{ruleId:"page-exception/uncaught-error",category:"page-exception",description:"An uncaught page error or unhandled rejection was observed.",match:n=>Dt(n,[...gr,...Cl],TE)},{ruleId:"navigation-failure/net-error",category:"navigation-failure",description:"Navigation reported a network-level or navigation timeout error.",match:n=>Dt(n,[...gr,...Cl],EE)},{ruleId:"http-failure/error-status",category:"http-failure",description:"A recorded request returned a 4xx or 5xx status, or reported a failure.",match:n=>IE(n,["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:n=>Dt(n,El,NE)},{ruleId:"browser-crash/target-closed",category:"browser-crash",description:"The page, context, or browser was closed or crashed during the attempt.",match:n=>Dt(n,[...gr,...Cl],CE)},{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:n=>Dt(n,El,OE)},{ruleId:"unimplemented-step/no-runnable-definition",category:"unimplemented-step",description:"A Cucumber step had no step definition, several, or one marked pending.",match:n=>Dt(n,El,$E)}];var Tn={"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","unimplemented-step":"Unimplemented step","artifact-failure":"Artifact failure",unclassified:"Unclassified failure"},DE=new Set(["failed","timedOut","interrupted"]),kg=160;function Ag(n){let t=n.replace(/\s+/g," ").trim();return t.length<=kg?t:`${t.slice(0,kg)}\u2026`}function ME(n){for(let t of n){if(t.kind!=="trace-event")continue;let r=/^action(?: started| finished)?: ([\w.]+)/.exec(t.observation)?.[1];if(r!==void 0&&r!=="unknown")return r}}function LE(n){for(let t of n){if(t.kind!=="network-event")continue;let e=/^(\w+) (\S+) -> (\d{3})/.exec(t.observation);if(e===null)continue;let[,r,s,i]=e;if(r===void 0||s===void 0||i===void 0)continue;let a=s;try{a=new URL(s).host}catch{}return`${r} ${a} -> ${i}`}}function _E(n,t){if(n?.errorLocation!==void 0)return Ms(n.errorLocation.file,n.errorLocation.line??1);for(let e of t)if(e.locator.type==="source-range")return Ms(e.locator.path,e.locator.startLine);for(let e of t){if(e.kind!=="stack-frame")continue;let r=/([^\s():]+):(\d+):\d+/.exec(e.observation),s=r?.[1],i=r?.[2];if(s!==void 0&&i!==void 0)return Ms(s,Number.parseInt(i,10))}}function Pg(n){let t=e=>n.find(r=>r.kind==="error-field"&&r.locator.type==="report-field"&&r.locator.path.endsWith(e));return t(".message")??t(".value")??n.find(e=>e.kind==="error-field")??n[0]}function jE(n,t,e){let r=Pg(t),s=r===void 0?void 0:Ha(r.observation),i=_E(n,t),a=ME(t),o=LE(t),[d]=n===void 0?[]:ms(n),c=d===void 0?void 0:vg(d),l=i!==void 0&&e!==void 0&&!i.startsWith(`${Ds(e)}:`)?i:void 0;return{...s===void 0||s===""?{}:{errorFingerprint:s},...i===void 0?{}:{sourceLocation:i},...a===void 0?{}:{actionApi:a},...o===void 0?{}:{networkEndpoint:o},...c===void 0||c===""?{}:{targetLocator:c},...l===void 0?{}:{supportLocation:l}}}function za(n,t,e,r,s){let i=[...new Set(r.map(c=>c.evidenceId))].sort(),a=jE(s.attempt,r,s.specFile),o=Pg(r),d=s.attempt?.attemptId??"run";return{symptomId:B("sym",[n,d,t,a.errorFingerprint??""]),category:t,ruleId:e,...s.logicalTestId===void 0?{}:{logicalTestId:s.logicalTestId},...s.attempt===void 0?{}:{attemptId:s.attempt.attemptId},evidenceIds:i,artifactIds:[],summary:`${Tn[t]}: ${Ag(o?.observation??"")}`,signals:a}}function Rg(n){let t=new Map;for(let e of Nl){let r=e.match(n);if(r.length===0)continue;let s=t.get(e.category);s===void 0?t.set(e.category,{ruleId:e.ruleId,cited:[...r]}):s.cited.push(...r)}return t}function Ig(n){return new Map(n.map(t=>[t.evidenceId,Ha(t.observation,400)]))}function qa(n,t){let e=new Map;for(let i of t.evidence){if(i.attemptId===void 0)continue;let a=e.get(i.attemptId);a===void 0?e.set(i.attemptId,[i]):a.push(i)}let r=[],s=[];for(let i of n.logicalTests)for(let a of i.attempts){if(!DE.has(a.status))continue;let o=e.get(a.attemptId)??[],d={attempt:a,evidence:o,normalized:Ig(o)},c=Rg(d);if(c.size===0){if(o.length===0){s.push(a.attemptId);continue}r.push(za(n.runId,"unclassified","unclassified/no-rule-matched",o.filter(l=>l.kind==="error-field").slice(0,3),{logicalTestId:i.logicalTestId,attempt:a,specFile:i.location.file}));continue}for(let[l,{ruleId:u,cited:p}]of c)r.push(za(n.runId,l,u,p,{logicalTestId:i.logicalTestId,attempt:a,specFile:i.location.file}))}if(n.reportErrors.length>0){let i=t.evidence.filter(a=>a.attemptId===void 0&&a.logicalTestId===void 0);if(i.length>0){let a=Rg({evidence:i,normalized:Ig(i)});a.size===0&&r.push(za(n.runId,"unclassified","unclassified/no-rule-matched",i.filter(o=>o.kind==="error-field").slice(0,3),{}));for(let[o,{ruleId:d,cited:c}]of a)r.push(za(n.runId,o,d,c,{}))}}for(let i of t.artifacts)i.availability==="unreadable"&&r.push({symptomId:B("sym",[n.runId,i.artifactId,"artifact-failure"]),category:"artifact-failure",ruleId:"artifact-failure/unreadable-artifact",...i.attemptId===void 0?{}:{attemptId:i.attemptId},evidenceIds:[],artifactIds:[i.artifactId],summary:`${Tn["artifact-failure"]}: ${i.channel} artifact could not be read${i.warnings[0]===void 0?"":` (${Ag(i.warnings[0])})`}`,signals:{}});return{schemaVersion:"1.1",runId:n.runId,packetHash:t.packetHash,symptoms:[...r].sort((i,a)=>i.symptomId.localeCompare(a.symptomId)),unclassifiedAttemptIds:[...s].sort()}}var FE=new Set(["error-fingerprint","network-endpoint","failing-source-location","target-locator","support-location"]);var Kt="<absent>";function Ol(n,t){switch(t){case"symptom-category":return n.category;case"action-api":return n.signals.actionApi??Kt;case"error-fingerprint":return n.signals.errorFingerprint??Kt;case"network-endpoint":return n.signals.networkEndpoint??Kt;case"failing-source-location":return n.signals.sourceLocation??Kt;case"target-locator":return n.signals.targetLocator??Kt;case"support-location":return n.signals.supportLocation??Kt}}function BE(n,t){if(t.length<2)return{supported:!1,rationale:"A single logical test provides no shared behavior for a common cause."};let e=n.filter(r=>FE.has(r.kind)&&r.value!==Kt);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(r=>`${r.kind}=${r.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 Sg=["target-locator","support-location","network-endpoint"],Tg=["symptom-category","error-fingerprint"];function $l(n){let t=new Map;for(let s of n.symptoms){if(s.logicalTestId===void 0)continue;let i=t.get(s.logicalTestId);i===void 0?t.set(s.logicalTestId,[s]):i.push(s)}let e=new Map;for(let s of t.values()){let i=[...s].sort((l,u)=>l.symptomId.localeCompare(u.symptomId)),a;for(let l of Sg){let u=i.find(p=>Ol(p,l)!==Kt);if(u!==void 0){a=[{kind:l,value:Ol(u,l)}];break}}let o=i[0];if(a===void 0&&o!==void 0&&(a=Tg.map(l=>({kind:l,value:Ol(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:[...s]}):c.members.push(...s)}let r=[...e.values()].map(({signals:s,members:i})=>{let a=[...new Set(i.map(d=>d.logicalTestId).filter(d=>d!==void 0))].sort(),o=BE(s,a);return{clusterId:B("clu",[n.runId,...s.map(d=>`${d.kind}=${d.value}`)]),logicalTestIds:a,symptomIds:i.map(d=>d.symptomId).sort(),signals:s,commonCauseSupported:o.supported,commonCauseRationale:o.rationale}});return{schemaVersion:"1.1",runId:n.runId,clusters:r.sort((s,i)=>s.clusterId.localeCompare(i.clusterId)),signalKinds:[...Sg,...Tg]}}function he(n,t,e,r,s={}){return{graderId:n,code:t,severity:e,message:r,...s.hypothesisId===void 0?{}:{hypothesisId:s.hypothesisId},...s.reference===void 0?{}:{reference:s.reference}}}function Wt(n,t,e){return{graderId:n,passed:!e.some(r=>r.severity==="violation"),checked:t,findings:e}}var Ls={insufficient:0,weak:1,moderate:2,strong:3},Dl={graderId:"abstention",description:"Diagnosis status matches evidence strength, and insufficient evidence abstains.",grade:n=>{let t=[],{diagnosis:e}=n,s=[...e.hypotheses].sort((o,d)=>o.rank-d.rank)[0],i=s===void 0?-1:Ls[s.evidenceGrade],a=1;return s===void 0||i===Ls.insufficient?e.status!=="inconclusive"&&t.push(he("abstention","failed-to-abstain","violation",`Evidence cannot rank a cause, but the diagnosis claims ${e.status}.`)):e.status==="conclusive"&&i<Ls.strong?t.push(he("abstention","conclusive-without-strong-evidence","violation",`Diagnosis claims conclusive on ${s.evidenceGrade} evidence.`,{hypothesisId:s.hypothesisId})):e.status==="probable"&&i<Ls.moderate&&t.push(he("abstention","probable-without-moderate-evidence","violation",`Diagnosis claims probable on ${s.evidenceGrade} evidence.`,{hypothesisId:s.hypothesisId})),a+=1,e.status==="inconclusive"&&e.repairEligibility==="eligible"&&t.push(he("abstention","repair-eligible-while-inconclusive","violation","Repair was marked eligible while the diagnosis is inconclusive.")),a+=1,e.status==="inconclusive"&&i>=Ls.strong&&t.push(he("abstention","abstained-with-strong-evidence","warning","Diagnosis abstained although the leading hypothesis carries strong evidence.",{...s===void 0?{}:{hypothesisId:s.hypothesisId}})),a+=1,e.status==="inconclusive"&&e.missingEvidence.length===0&&t.push(he("abstention","abstained-without-naming-gaps","warning","Diagnosis abstained without naming the evidence that was missing.")),Wt("abstention",a,t)}};var Ml={graderId:"citation-validity",description:"Every cited evidence, artifact, and symptom id exists in the graded packet.",grade:n=>{let t=[],e=0;n.diagnosis.packetHash!==n.packetHash&&t.push(he("citation-validity","packet-hash-mismatch","violation","The diagnosis was produced from a different evidence packet than the one being graded.",{reference:n.diagnosis.packetHash}));let r=i=>n.evidenceIds.has(i)||n.artifactIds.has(i),s=[["ownershipEvidenceIds",n.diagnosis.ownershipEvidenceIds,void 0],...n.diagnosis.hypotheses.flatMap(i=>[["supportingEvidenceIds",i.supportingEvidenceIds,i.hypothesisId],["contradictingEvidenceIds",i.contradictingEvidenceIds,i.hypothesisId]])];for(let[i,a,o]of s)for(let d of a)e+=1,!r(d)&&t.push(he("citation-validity","unknown-evidence-id","violation",`${i} cites ${d}, which the evidence packet does not contain.`,{...o===void 0?{}:{hypothesisId:o},reference:d}));for(let i of n.diagnosis.symptomIds)e+=1,!n.symptomIds.has(i)&&t.push(he("citation-validity","unknown-symptom-id","violation",`The diagnosis cites symptom ${i}, which this run did not produce.`,{reference:i}));return Wt("citation-validity",e,t)}};var VE=new Set(["strong","moderate"]),Ll={graderId:"ownership",description:"A named owner rests on cited positive evidence, and eligibility proves it.",grade:n=>{let t=[],{diagnosis:e}=n,r=0;for(let s of e.hypotheses)r+=1,s.probableOwner!=="undetermined"&&s.supportingEvidenceIds.length===0&&t.push(he("ownership","ownership-from-absence","violation",`Hypothesis assigns the ${s.probableOwner} owner without citing any supporting evidence.`,{hypothesisId:s.hypothesisId}));if(e.repairEligibility==="eligible"){r+=1,e.ownershipEvidenceIds.length===0&&t.push(he("ownership","eligible-without-ownership-evidence","violation","Repair was marked eligible without identifying the evidence that proves test-side ownership."));let s=[...e.hypotheses].sort((i,a)=>i.rank-a.rank)[0];s===void 0?t.push(he("ownership","eligible-without-hypothesis","violation","Repair was marked eligible without an accepted hypothesis.")):(s.probableOwner!=="test-support"&&t.push(he("ownership","eligible-without-test-ownership","violation",`Repair was marked eligible while the accepted hypothesis assigns the ${s.probableOwner} owner.`,{hypothesisId:s.hypothesisId})),VE.has(s.evidenceGrade)||t.push(he("ownership","eligible-on-insufficient-grade","violation",`Repair was marked eligible on ${s.evidenceGrade} evidence.`,{hypothesisId:s.hypothesisId})))}return Wt("ownership",r,t)}};var HE=/\b(?:evd|art|sym|clu|omi|red)_[a-f0-9]{8,}\b/g,_l={graderId:"unsupported-claims",description:"Claims are backed by citations, and grades match the evidence offered.",grade:n=>{let t=[],e=0;for(let s of n.diagnosis.hypotheses){e+=1;let{hypothesisId:i,supportingEvidenceIds:a,contradictingEvidenceIds:o}=s;s.evidenceGrade!=="insufficient"&&a.length===0&&t.push(he("unsupported-claims","claim-without-evidence","violation",`Hypothesis is graded ${s.evidenceGrade} but cites no supporting evidence.`,{hypothesisId:i})),s.evidenceGrade==="strong"&&(a.length<2&&t.push(he("unsupported-claims","strong-grade-underspecified","violation","A strong grade requires multiple specific observations, but only one was cited.",{hypothesisId:i})),o.length>0&&t.push(he("unsupported-claims","strong-grade-with-contradiction","violation","A strong grade requires no material unresolved contradiction, but contradicting evidence was cited.",{hypothesisId:i})),s.unresolvedAssumptions.length>0&&t.push(he("unsupported-claims","strong-grade-with-unresolved-assumptions","warning","A strong grade carries unresolved assumptions.",{hypothesisId:i})));let d=a.filter(l=>o.includes(l));for(let l of d)t.push(he("unsupported-claims","contradictory-citation","violation",`Evidence ${l} is cited as both supporting and contradicting the same hypothesis.`,{hypothesisId:i,reference:l}));let c=new Set([...a,...o]);for(let l of[s.statement,s.nextAction])for(let u of l.matchAll(HE)){let p=u[0];e+=1,!c.has(p)&&t.push(he("unsupported-claims","uncited-identifier-in-prose","violation",`Prose references ${p}, which this hypothesis does not cite.`,{hypothesisId:i,reference:p}))}}e+=1;let r=n.diagnosis.hypotheses.map(s=>s.rank);return new Set(r).size!==r.length&&t.push(he("unsupported-claims","duplicate-hypothesis-rank","violation","Hypotheses do not carry a distinct rank, so the accepted hypothesis is ambiguous.")),n.diagnosis.hypotheses.length>3&&t.push(he("unsupported-claims","too-many-hypotheses","violation",`A diagnosis returns at most three ranked hypotheses; ${n.diagnosis.hypotheses.length} were supplied.`)),Wt("unsupported-claims",e,t)}};var Cg=[Ml,Ll,Dl,_l];function zE(n){return[...n].sort((t,e)=>{if(t.severity!==e.severity)return t.severity==="violation"?-1:1;let r=t.graderId.localeCompare(e.graderId);if(r!==0)return r;let s=t.code.localeCompare(e.code);return s!==0?s:(t.reference??"").localeCompare(e.reference??"")})}function _s(n,t,e){let r={diagnosis:n,evidenceIds:new Set(t.evidence.map(i=>i.evidenceId)),artifactIds:new Set(t.artifacts.map(i=>i.artifactId)),symptomIds:new Set(e.symptoms.map(i=>i.symptomId)),packetHash:t.packetHash},s=Cg.map(i=>i.grade(r));return{schemaVersion:"1.0",packetHash:t.packetHash,passed:s.every(i=>i.passed),outcomes:s,findings:zE(s.flatMap(i=>i.findings))}}var Ng=50,Og=24,Lg="<absent>",qE={"error-field":"Error","stack-frame":"Stack frame",step:"Step","stdio-chunk":"Output","trace-event":"Browser event","image-metadata":"Screenshot (metadata only)","video-metadata":"Video (metadata only)","dom-subtree":"Page elements","dom-candidates":"Similar elements","accessibility-node":"Accessibility","page-snapshot":"Page snapshot","console-event":"Console","network-event":"Network","source-range":"Source","diff-hunk":"Code change","change-search":"Change search","run-summary":"Run summary","locator-suggestion":"Locator suggestion"},GE={report:"Test report",trace:"Trace or failure capture",stdout:"Standard output",stderr:"Standard error",screenshot:"Screenshots",video:"Video",dom:"Page DOM",accessibility:"Accessibility tree",console:"Browser console",network:"Network",source:"Test source",diff:"Code changes",probe:"Live probe"},KE={unavailable:"not captured",unreadable:"unreadable","unsupported-version":"unsupported version","unauthorized-path":"outside the authorized paths","policy-disabled":"turned off by policy",redacted:"redacted","budget-exceeded":"over the size budget",irrelevant:"not relevant to the failures",unrecognized:"not recognized","parse-failed":"could not be parsed"},WE={"symptom-category":"Symptom","action-api":"Action","error-fingerprint":"Error","network-endpoint":"Request","support-location":"Support code","target-locator":"Locator","failing-source-location":"Failing line"},JE={expected:"passed",unexpected:"failed",flaky:"flaky",skipped:"skipped"};function _g(n,t){return`${n} ${t}${n===1?"":"s"}`}function $g(n,t){let e=n.replace(/\s+/g," ").trim();return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function XE(n){if(n<1e3)return`${Math.round(n)} ms`;let t=n/1e3;return t<60?`${t.toFixed(1)} s`:`${Math.floor(t/60)} min ${Math.round(t%60)} s`}function Dg(n){return n.replace("T"," ").replace(/(?:\.\d+)?Z$/," UTC")}var YE="1970-01-01T00:00:00.000Z";function QE(n){return n.replace(/^sha256:/,"").slice(0,12)}function Fl(n,t){let e=t.location.file,r=t.titlePath.filter(i=>i!==""&&i!==e&&i!==UE(e)),s=n.projects.find(i=>i.projectId===t.projectId)?.name;return{title:r.join(" \u203A ")||t.title,location:t.location.line===void 0?e:`${e}:${t.location.line}`,...s===void 0||s===""||n.projects.length<2?{}:{project:s},status:JE[t.status],attempts:t.attempts.map(i=>i.retry===0?i.status:`${i.status} (retry ${i.retry})`)}}function jg(n,t){let e=new Set(t);return n.logicalTests.filter(r=>e.has(r.logicalTestId)).map(r=>Fl(n,r))}function Jt(n,t){let e=n.signals.find(r=>r.kind===t)?.value;return e===void 0||e===Lg?void 0:e}function ZE(n,t){let e=Jt(n,"symptom-category");return(e!==void 0?[e]:[...new Set((t?.symptoms.symptoms??[]).filter(i=>n.symptomIds.includes(i.symptomId)).map(i=>i.category))]).map(i=>Tn[i]??i).join(", ")||Tn.unclassified}function Fg(n,t){return n.evidence.filter(e=>e.kind==="error-field"&&e.attemptId!==void 0&&t.has(e.attemptId)&&e.locator.type==="report-field"&&/\.(?:message|value)$/.test(e.locator.path))}function eC(n,t){let e=t?.symptoms.symptoms.find(a=>n.symptomIds.includes(a.symptomId));if(t===void 0||e===void 0)return;let r=Fg(t.packet,new Set(e.attemptId===void 0?[]:[e.attemptId])).map(a=>a.observation.split(`
174
- `).find(o=>o.trim()!=="")?.trim()).find(a=>a!==void 0);if(r!==void 0)return r;let s=`${Tn[e.category]}: `,i=e.summary.startsWith(s)?e.summary.slice(s.length):e.summary;return i.trim()===""?void 0:i}function tC(n,t,e){let r=Jt(n,"target-locator"),s=Jt(n,"network-endpoint"),i=Jt(n,"support-location"),a=Jt(n,"failing-source-location"),o=eC(n,e)??Jt(n,"error-fingerprint");return r!==void 0?`Locator ${$g(r,90)}`:s!==void 0?`Request ${s}`:i!==void 0?`Failing in ${i}`:a!==void 0?`Failing at ${a}`:o!==void 0?$g(o,90):t}function nC(n,t){let e=Jt(n,"support-location")??Jt(n,"failing-source-location");if(e!==void 0)return e;let r=new Set(t.map(s=>s.location.replace(/:\d+$/,"")));return r.size===1?[...r][0]:void 0}function rC(n){return[...n.hypotheses].sort((t,e)=>t.rank-e.rank)[0]}function sC(n){let t=n?.diagnosis;if(n===void 0||t===void 0)return{owner:"not-diagnosed"};let e=rC(t);return n.outcome!=="diagnosed"||e===void 0?{owner:"inconclusive"}:{owner:e.probableOwner,grade:e.evidenceGrade}}function iC(n){let t=n.diagnosis;if(t!==void 0)return{status:t.status,hypotheses:[...t.hypotheses].sort((e,r)=>e.rank-r.rank).map(e=>({rank:e.rank,statement:e.statement,owner:e.probableOwner,grade:e.evidenceGrade,category:e.causalCategory,supporting:e.supportingEvidenceIds,contradicting:e.contradictingEvidenceIds,missing:e.missingEvidence,assumptions:e.unresolvedAssumptions,nextAction:e.nextAction})),missing:t.missingEvidence,nextAction:t.recommendedNextAction,repairEligibility:t.repairEligibility,escalated:n.escalated===!0}}function aC(n){let t=n.locator;switch(t.type){case"source-range":{let e=t.endLine===t.startLine?`${t.startLine}`:`${t.startLine}-${t.endLine}`;return`${t.path}:${e}${t.symbol===void 0?"":` (${t.symbol})`}`}case"diff-hunk":return`${t.commit===void 0?"uncommitted":`commit ${t.commit}`}, ${t.path}:${t.newStart}`;default:return}}function oC(n){let t=aC(n);return{evidenceId:n.evidenceId,label:qE[n.kind]??n.kind,...t===void 0?{}:{where:t},text:n.observation}}function Bg(n,t){let e=new Map(n.evidence.map(r=>[r.evidenceId,r]));return[...new Set(t)].flatMap(r=>{let s=e.get(r);return s===void 0?[]:[s]})}function dC(n){return[...[...n.hypotheses].sort((t,e)=>t.rank-e.rank).flatMap(t=>[...t.supportingEvidenceIds,...t.contradictingEvidenceIds]),...n.ownershipEvidenceIds]}function cC(n,t){let e=t.symptoms.symptoms.filter(i=>n.symptomIds.includes(i.symptomId)),r=new Set(e.flatMap(i=>i.attemptId??[])),s=[...Fg(t.packet,r).map(i=>i.evidenceId),...e.flatMap(i=>i.evidenceIds)];return Bg(t.packet,s)}function lC(n,t,e){if(e===void 0)return{evidence:[],evidenceCut:0};let r=t?.diagnosis,s;if(r!==void 0){let i=e.groupPackets[n.clusterId];if(i?.packetHash!==r.packetHash)return{evidence:[],evidenceCut:0,evidenceNote:"This group's evidence has changed since it was diagnosed, so the evidence its diagnosis cites can't be shown."};s=Bg(i,dC(r))}else s=cC(n,e);return{evidence:s.slice(0,Og).map(oC),evidenceCut:Math.max(0,s.length-Og)}}function uC(n,t){return n===void 0?t?"Not diagnosed: this was a local analysis, so no model was asked.":"Not sent: an analysis asks about at most 6 groups, the largest first.":n.outcome==="diagnosed"?n.escalated===!0?"Diagnosed, by the stronger model after the first answer failed its checks.":"Diagnosed.":`${n.outcome} (${n.reasonCode}): ${n.message}`}function jl(n,t,e,r,s,i){let a=ZE(t,r),o=jg(n,t.logicalTestIds),d=sC(e),c=e===void 0?void 0:iC(e),l=tC(t,a,r),u=t.logicalTestIds.length,p=nC(t,o);return{...s===void 0?{}:{number:s},anchor:s===void 0?`group-${t.clusterId}`:`group-${s}`,title:`${l} \xB7 ${_g(u,"test")}`,subject:l,size:u,...p===void 0?{}:{place:p},category:a,signals:t.signals.filter(f=>f.value!==Lg).map(f=>({kind:WE[f.kind]??f.kind,value:f.value})),commonCause:{supported:t.commonCauseSupported,rationale:t.commonCauseRationale},...d,status:uC(e,i),tests:o.slice(0,Ng),testsCut:Math.max(0,o.length-Ng),...c===void 0?{}:{diagnosis:c},...lC(t,e,r)}}function pC(n){return{clusterId:n.clusterId,logicalTestIds:n.logicalTestIds,symptomIds:[],signals:n.signals,commonCauseSupported:!1,commonCauseRationale:"The evidence that grouped these tests could not be rebuilt."}}function Mg(n,t){return t.logicalTestIds.length-n.logicalTestIds.length||n.clusterId.localeCompare(t.clusterId)}function fC(n){let{run:t,record:e,detail:r}=n,s=r?.clusters.clusters??[],i=e.clusters??[];if(i.length===0)return[...s].sort(Mg).map((u,p)=>jl(t,u,void 0,r,p+1,!0));let o=new Map(s.map(u=>[u.clusterId,u])),d=i.map((u,p)=>jl(t,o.get(u.clusterId)??pC(u),u,r,p+1,!1)),c=new Set(i.map(u=>u.clusterId)),l=s.filter(u=>!c.has(u.clusterId)).sort(Mg).map(u=>jl(t,u,void 0,r,void 0,!1));return[...d,...l]}function Vg(n){let t=n.record.clusters??[],e=t.length>0?t.flatMap((s,i)=>s.diagnosisAudit===void 0?[]:[{group:`Group ${i+1}`,audit:s.diagnosisAudit}]):n.record.diagnosisAudit===void 0?[]:[{group:"Run",audit:n.record.diagnosisAudit}],r=n.repair?.repairAudit===void 0?[]:[{group:"Repair",audit:n.repair.repairAudit}];return[...e,...r]}function Hg(n){return`${n.model.modelId} via ${n.reportedProvider??n.model.providerId}`}function hC(n){return Vg(n).map(({group:t,audit:e})=>({group:t,purpose:e.purpose,model:Hg(e),zeroDataRetention:e.model.zeroDataRetention===!0,packetHash:QE(e.packetHash),...e.usage===void 0?{}:{tokens:`${e.usage.promptTokens.toLocaleString("en-US")} in, ${e.usage.completionTokens.toLocaleString("en-US")} out`},outcome:e.outcome.kind}))}function mC(n){let t=Vg(n).filter(({audit:r})=>r.outcome.kind==="diagnosed"||r.outcome.kind==="abstained"),e=[...new Set(t.map(({audit:r})=>Hg(r)))];return e.length>0?`Diagnosed with ${e.join(" and ")}.`:n.record.reasonCode==="remote-diagnosis-not-configured"?"Local analysis: no model was asked.":"No model answered this analysis."}function yC(n){let t=n.repair?.confirmation;if(t===void 0)return[];if(t.status!=="reproduced"&&t.status!=="not-reproduced")return[];let e=new Set(t.failedAgain??[]);return t.logicalTestIds.filter(r=>!e.has(r))}function gC(n){let{run:t}=n,e=t.logicalTests.filter(s=>s.status==="flaky").map(s=>Fl(t,s)),r=jg(t,yC(n)).map(s=>({...s,status:"passed when fix re-ran it"}));return[...e,...r]}function wC(n){let{run:t,detail:e}=n,r=new Set(e?.symptoms.unclassifiedAttemptIds??[]),s=t.logicalTests.filter(o=>o.attempts.some(d=>r.has(d.attemptId))),i=(e?.symptoms.symptoms??[]).filter(o=>o.logicalTestId===void 0).map(o=>o.summary),a=i.length===0&&t.reportErrors.length>0?[`${_g(t.reportErrors.length,"run-level error")} in the test report, not shown here because its evidence could not be built.`]:[];return{unclassified:s.map(o=>Fl(t,o)),runErrors:[...new Set([...i,...a])]}}function bC(n,t){let e=n.repair;if(e===void 0)return;let r=(n.record.clusters??[]).findIndex(a=>a.diagnosis!==void 0&&a.diagnosis.packetHash===e.diagnosis?.packetHash),s=r<0?void 0:t.find(a=>a.number===r+1),i=e.repairProposal;return{...s===void 0?{}:{groupAnchor:s.anchor,groupTitle:s.title},command:e.command,outcome:e.outcome,reasonCode:e.reasonCode,message:e.message,phases:[{phase:"Proposal",status:e.proposal.status},{phase:"Application",status:e.application.status},{phase:"Validation",status:e.validation.status}],...i===void 0?{}:{intent:{statement:i.intent.statement,preserved:i.intent.preservedBehavior},diff:i.diff}}}function Ga(n){let{run:t,record:e,detail:r}=n,s=p=>t.logicalTests.filter(f=>f.status===p).length,i=s("unexpected"),a=s("flaky"),o=gt[t.framework],d=t.artifact.formatVersion===void 0?"":` ${t.artifact.formatVersion}`,c=fC(n),l=new Map;for(let p of r?.packet.omissions??[]){let f=KE[p.reason]??p.reason;l.set(f,(l.get(f)??0)+1)}let u=bC(n,c);return{title:`KwikQA report: ${t.framework==="unknown"?"run from an unidentified framework":`${o} run`}, ${i} failed${a===0?"":`, ${a} flaky`}`,recordedAt:Dg(e.recordedAt),run:{framework:`${o}${d}`,...t.artifact.format===void 0?{}:{format:Bt[t.artifact.format]},counts:[{label:"Tests",value:t.logicalTests.length},{label:"Failed",value:i},{label:"Flaky",value:a},{label:"Passed",value:s("expected")},{label:"Skipped",value:s("skipped")}],duration:XE(t.stats.duration),...e.inputs===void 0?{}:{report:e.inputs.report},createdAt:t.createdAt===YE?"not recorded in the report":Dg(t.createdAt),diagnosedBy:mC(n),outcome:`${e.outcome} (${e.reasonCode})`,message:e.message},groups:c,flaky:gC(n),notAnalyzed:wC(n),coverage:(r?.packet.accounting??[]).map(p=>({channel:GE[p.channel]??p.channel,availability:p.availability,included:p.included,omitted:p.omitted})),omissions:[...l].map(([p,f])=>({reason:p,count:f})).sort((p,f)=>f.count-p.count||p.reason.localeCompare(f.reason)),redactions:r?.packet.totals.redactions??0,requests:hC(n),...u===void 0?{}:{repair:u},...r===void 0?{evidenceNote:"The evidence this analysis read could not be rebuilt, so only its recorded results are shown."}:{},footer:{runId:e.runId,recordId:e.recordId,kwikqaVersion:n.kwikqaVersion}}}var Ka=["on-failure","always"],zg=10,xC=3e4,vC=2e3,kC=6e4;function js(n,t){return`${n} ${t}${n===1?"":"s"}`}function wr(n,t=150){let e=n.replace(new RegExp("\\p{Cc}","gu")," ").replace(/\s+/g," ").trim();return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function Bl(n){let{model:t,run:e}=n,r=t?.run.counts.find(l=>l.label==="Failed")?.value??0,s=t?.run.counts.find(l=>l.label==="Flaky")?.value??0,i=e?.repository===void 0?"":` in ${e.repository}`,a=t===void 0?`KwikQA: no analysis${i}`:r>0?`KwikQA: ${js(r,"test")} failed${i}`:`KwikQA: no failures${i}`,o=[...e?.pullRequest?.url===void 0?e?.commit?.url===void 0?[]:[{label:`Commit ${e.commit.sha.slice(0,7)}`,url:e.commit.url}]:[{label:`Pull request #${e.pullRequest.number}`,url:e.pullRequest.url}],...e?.runUrl===void 0?[]:[{label:"Open the run",url:e.runUrl}]],d=e?.branch===void 0?void 0:`Branch ${wr(e.branch,100)}`,c=[];if(t===void 0)c.push(wr(n.message,300));else{let l=t.run.counts.filter(p=>p.label==="Tests"||p.value>0).map(p=>p.label==="Tests"?js(p.value,"test"):`${p.value} ${p.label.toLowerCase()}`);c.push(`${wr(t.run.framework,60)} run: ${l.join(", ")}.`);for(let p of t.groups.slice(0,zg)){let f=p.place===void 0?"":` in ${wr(p.place,120)}`;c.push(`${p.number===void 0?"\u2013":`${p.number}.`} ${p.category}${f} \xB7 ${js(p.size,"test")} \xB7 ${Sn[p.owner]}`)}let u=t.groups.length-zg;u>0&&c.push(`and ${js(u,"more group")} in the report`),s>0&&c.push(`${js(s,"flaky test")} passed on a retry.`)}return n.notDiagnosed!==void 0&&c.push(`Not diagnosed: ${wr(n.notDiagnosed,300)}`),{headline:a,...d===void 0?{}:{source:d},links:o,lines:c}}function Ug(n){let t=(r,s=!1)=>({type:"text",text:r,...s?{style:{bold:!0}}:{}}),e=[...n.source===void 0?[]:[t(n.source)],...n.links.map(r=>({type:"link",url:r.url,text:r.label}))].flatMap((r,s)=>s===0?[r]:[t(" \xB7 "),r]);return{text:n.headline,blocks:[{type:"rich_text",elements:[{type:"rich_text_section",elements:[t(wr(n.headline,150),!0),...e.length===0?[]:[t(`
175
- `),...e],t(`
104
+ `;function $p(t){return Qx("sha256").update(t,"utf8").digest("base64")}function Lp(t){return t.replace(/[&<>"']/g,n=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[n]??n)}var j=Lp;function Dp(t){return t.replace(/[^A-Za-z0-9_-]/g,"-")}function _p(t,n){return`ev-${Dp(t.anchor)}-${Dp(n)}`}function Wo(t){let n=t.split(`
105
+ `);if(n.length<=Zx&&t.length<=ev)return`<pre>${j(t)}</pre>`;let e=n.find(s=>s.trim()!=="")??"",r=e.length>120?`${e.slice(0,119)}\u2026`:e;return`<details><summary>${j(r)} (${n.length} lines)</summary><pre>${j(t)}</pre></details>`}function Ko(t){if(t.length===0)return"<p>None.</p>";let n=t.some(r=>r.project!==void 0),e=t.map(r=>`<tr><td>${j(r.title)}</td><td><code>${j(r.location)}</code></td>${n?`<td>${j(r.project??"")}</td>`:""}<td>${j(r.status)}</td><td>${j(r.attempts.join(", "))}</td></tr>`);return`<table><thead><tr><th>Test</th><th>Location</th>${n?"<th>Project</th>":""}<th>Status</th><th>Attempts</th></tr></thead><tbody>${e.join("")}</tbody></table>`}function tv(t,n){let e=new Set(t.evidence.map(r=>r.evidenceId));return n.map(r=>e.has(r)?`<a href="#${_p(t,r)}"><code>${j(r)}</code></a>`:`<code>${j(r)}</code>`).join(", ")}function nv(t,n){let e=(s,i)=>i.length===0?"":`<p><strong>${s}:</strong> ${i.map(a=>j(a)).join("; ")}</p>`,r=(s,i)=>i.length===0?"":`<p><strong>${s}:</strong> ${tv(t,i)}</p>`;return["<li>",`<p class="label">${j(n.statement)}</p>`,`<p class="status">Owner: ${j(n.owner)} \xB7 Evidence: ${j(n.grade)} \xB7 Cause: ${j(n.category)}</p>`,r("Supported by",n.supporting),r("Contradicted by",n.contradicting),e("Missing evidence",n.missing),e("Unresolved assumptions",n.assumptions),`<p><strong>Next:</strong> ${j(n.nextAction)}</p>`,"</li>"].join("")}function rv(t,n){return[`<li id="${_p(t,n.evidenceId)}">`,`<p class="label">${j(n.label)}${n.where===void 0?"":` <code>${j(n.where)}</code>`} <span class="id">${j(n.evidenceId)}</span></p>`,Wo(n.text),"</li>"].join("")}function sv(t){let n=an[t.owner],e=t.diagnosis,r=[`<article class="group" id="${j(t.anchor)}" data-owner="${j(t.owner)}" data-owner-label="${j(n)}">`,`<h3>${t.number===void 0?"":`<span class="num">Group ${t.number}</span> `}${j(t.title)}</h3>`,`<ul class="badges"><li class="owner-${j(t.owner)}">Owner: ${j(n)}</li>${t.grade===void 0?"":`<li>Evidence: ${j(t.grade)}</li>`}<li>${j(t.category)}</li></ul>`,`<p class="status">${j(t.status)}</p>`,"<h4>Tests</h4>",Ko(t.tests),t.testsCut===0?"":`<p>And ${t.testsCut} more tests in this group.</p>`];return e!==void 0&&r.push("<h4>Diagnosis</h4>",e.hypotheses.length===0?"<p>No cause is supported by the evidence.</p>":`<ol class="hypotheses">${e.hypotheses.map(s=>nv(t,s)).join("")}</ol>`,e.missing.length===0?"":`<p><strong>Missing evidence:</strong> ${e.missing.map(s=>j(s)).join("; ")}</p>`,`<p><strong>Recommended next action:</strong> ${j(e.nextAction)}</p>`,`<p><strong>Repair eligibility:</strong> ${j(e.repairEligibility)}</p>`),r.push("<h4>Why these tests are grouped</h4>",t.signals.length===0?"":`<ul>${t.signals.map(s=>`<li>${j(s.kind)}: <code>${j(s.value)}</code></li>`).join("")}</ul>`,`<p>${t.commonCause.supported?"A common cause is supported":"A common cause is not established"}: ${j(t.commonCause.rationale)}</p>`,`<h4>Evidence${e===void 0?"":" cited by the diagnosis"}</h4>`,t.evidenceNote===void 0?"":`<p class="note">${j(t.evidenceNote)}</p>`,t.evidence.length===0&&t.evidenceNote===void 0?"<p>None.</p>":t.evidence.length===0?"":`<ol class="evidence">${t.evidence.map(s=>rv(t,s)).join("")}</ol>`,t.evidenceCut===0?"":`<p>And ${t.evidenceCut} more evidence items.</p>`,"</article>"),r.join(`
106
+ `)}function iv(t){let n=t.map(e=>`<li data-group="${j(e.anchor)}"><a href="#${j(e.anchor)}">${e.number===void 0?"Not sent":`Group ${e.number}`}</a>: ${j(e.title)}. Owner: ${j(an[e.owner])}.</li>`);return`<nav id="contents" aria-label="Failure groups"><h2>Failure groups</h2>${n.length===0?"<p>No failing test produced a failure group.</p>":`<ol>${n.join("")}</ol>`}</nav>`}function av(t){let n=t.run,e=[["Framework",n.format===void 0?n.framework:`${n.framework} (${n.format})`],...n.report===void 0?[]:[["Report",n.report]],["Run started",n.createdAt],["Duration",n.duration],["Analyzed",t.recordedAt],["Diagnosis",n.diagnosedBy],["Result",`${n.outcome}. ${n.message}`]];return['<section id="run" aria-labelledby="run-heading">','<h2 id="run-heading">Run</h2>',`<ul class="counts">${n.counts.map(r=>`<li><span class="n">${r.value}</span> ${j(r.label)}</li>`).join("")}</ul>`,`<dl class="facts">${e.map(([r,s])=>`<dt>${j(r)}</dt><dd>${j(s)}</dd>`).join("")}</dl>`,t.evidenceNote===void 0?"":`<p class="note">${j(t.evidenceNote)}</p>`,"</section>"].join(`
107
+ `)}function sn(t,n,e){return`<section id="${t}" aria-labelledby="${t}-heading"><h2 id="${t}-heading">${j(n)}</h2>${e}</section>`}function ov(t){let n=t.repair;if(n===void 0)return"";let e=n.groupAnchor===void 0?"":`<p>For <a href="#${j(n.groupAnchor)}">${j(n.groupTitle??n.groupAnchor)}</a>.</p>`;return sn("repair","Repair",[e,`<p><strong>${j(n.outcome)} (${j(n.reasonCode)})</strong>, from <code>kwikqa ${j(n.command)}</code>: ${j(n.message)}</p>`,`<table><thead><tr><th>Phase</th><th>Status</th></tr></thead><tbody>${n.phases.map(r=>`<tr><td>${j(r.phase)}</td><td>${j(r.status)}</td></tr>`).join("")}</tbody></table>`,n.intent===void 0?"":`<p><strong>Intent:</strong> ${j(n.intent.statement)}</p><p><strong>Preserves:</strong> ${j(n.intent.preserved)}</p>`,n.diff===void 0?"":`<h4>Diff</h4>${Wo(n.diff)}`].join(`
108
+ `))}function dv(t){if(t.coverage.length===0)return sn("coverage","What KwikQA could see","<p>No evidence was built for this run.</p>");let n=t.coverage.map(r=>`<tr><td>${j(r.channel)}</td><td>${j(r.availability)}</td><td>${r.included}</td><td>${r.omitted}</td></tr>`).join(""),e=t.omissions.length===0?"":`<p>Items left out: ${t.omissions.map(r=>`${r.count} ${j(r.reason)}`).join(", ")}.</p>`;return sn("coverage","What KwikQA could see",["<p>A channel marked <em>unavailable</em> was not captured: it is missing knowledge, not a sign that nothing happened. <em>empty</em> means it was captured and held nothing.</p>",`<table><thead><tr><th>Evidence</th><th>Availability</th><th>Included</th><th>Left out</th></tr></thead><tbody>${n}</tbody></table>`,e,`<p>Redactions applied before anything was shown or sent: ${t.redactions}.</p>`].join(`
109
+ `))}function cv(t){if(t.requests.length===0)return sn("sent","What was sent","<p>Nothing: no model request was made.</p>");let n=t.requests.map(e=>`<tr><td>${j(e.group)}</td><td>${j(e.purpose)}</td><td>${j(e.model)}${e.zeroDataRetention?", zero data retention":""}</td><td><code>${j(e.packetHash)}</code></td><td>${j(e.tokens??"")}</td><td>${j(e.outcome)}</td></tr>`).join("");return sn("sent","What was sent",`<p>Each request carried only the redacted evidence of one group, as its preview showed.</p><table><thead><tr><th>For</th><th>Request</th><th>Model</th><th>Evidence packet</th><th>Tokens</th><th>Outcome</th></tr></thead><tbody>${n}</tbody></table>`)}function Fr(t){let n=["default-src 'none'",`style-src 'sha256-${$p(Np)}'`,`script-src 'sha256-${$p(Op)}'`,"base-uri 'none'","form-action 'none'"].join("; "),e=t.flaky.length===0?"":sn("flaky","Flaky tests",`<p>These tests failed and then passed. KwikQA reports them and doesn't repair them.</p>${Ko(t.flaky)}`),r=t.notAnalyzed,s=r.unclassified.length===0&&r.runErrors.length===0?"":sn("not-analyzed","Not analyzed",[r.runErrors.length===0?"":`<h4>Run-level errors</h4><ul>${r.runErrors.map(i=>`<li>${Wo(i)}</li>`).join("")}</ul>`,r.unclassified.length===0?"":`<h4>Failures no rule could classify</h4>${Ko(r.unclassified)}`].join(`
110
+ `));return["<!doctype html>",'<html lang="en">',"<head>",'<meta charset="utf-8">','<meta name="viewport" content="width=device-width, initial-scale=1">',`<meta name="${pi}" content="${Mp}">`,`<meta http-equiv="Content-Security-Policy" content="${n}">`,'<meta name="referrer" content="no-referrer">',`<title>${j(t.title)}</title>`,`<style>${Np}</style>`,"</head>","<body>","<header>",'<p class="brand">KwikQA</p>',"<h1>Failure report</h1>",`<p class="lede">${j(t.title.replace(/^KwikQA report: /,""))}. ${j(t.run.diagnosedBy)}</p>`,"</header>","<main>",av(t),iv(t.groups),`<section id="groups" aria-label="Failure group details">${t.groups.map(sv).join(`
111
+ `)}</section>`,e,s,ov(t),dv(t),cv(t),"</main>",`<footer><p>Generated by KwikQA ${j(t.footer.kwikqaVersion)} from record <code>${j(t.footer.recordId)}</code> of run <code>${j(t.footer.runId)}</code>.</p><p>This page holds the same redacted evidence a request preview shows. Anyone who can open it can read it, so share it the way you share CI logs.</p></footer>`,`<script>${Op}</script>`,"</body>","</html>",""].join(`
112
+ `)}var fi="kwikqa-report.html",Fp=4096;async function hv(t){let n=await pv(t,"r");try{let e=Buffer.alloc(Fp),{bytesRead:r}=await n.read(e,0,Fp,0);return e.subarray(0,r).toString("utf8")}finally{await n.close()}}async function Un(t,n){let e=fv(t,n??fi),r=await lv(e).catch(s=>{if(s.code!=="ENOENT")throw s});return r===void 0?{kind:"writable",path:e}:r.isFile()?(await hv(e)).includes(`<meta name="${pi}"`)?{kind:"writable",path:e}:{kind:"refused",path:e,message:`${e} exists and isn't a KwikQA report, so KwikQA won't replace it. Choose another path with --output.`}:{kind:"refused",path:e,message:`${e} exists and isn't a regular file, so KwikQA won't write a report there.`}}async function Jo(t,n){let e=await Un(jp(t),t);return e.kind==="refused"||(await uv(jp(t),{recursive:!0}),await ye(t,n,{mode:420,replace:!0})),e}import{basename as kS}from"node:path";import{createHash as Bp}from"node:crypto";function mv(t){return`${Buffer.byteLength(t,"utf8")}:${t}`}function Ee(t){return Bp("sha256").update(t).digest("hex")}function B(t,n){let e=n.map(mv).join("|"),r=Bp("sha256").update(e,"utf8").digest("hex");return`${t}_${r.slice(0,24)}`}import{isAbsolute as Vp,relative as yv,sep as zp}from"node:path";var hi=["1.55.0","1.64.1"],ht=["playwright","cypress","webdriverio"],Xo=["vitest","jest","mocha","pytest","junit","testng","cucumber","unknown"];var Yo={playwright:hi,cypress:["16.2.0"],webdriverio:["10.1.0"],vitest:["4.1.11"],jest:["30.5.2"],mocha:["11.8.0"],pytest:["8.4.2"],junit:["6.1.3"],testng:["7.12.0"],cucumber:[],unknown:[]};function Zo(t){return{...t}}function mi(t,n,e){return{errorId:B("err",[n,e]),source:e,...t.message===void 0?{}:{message:t.message},...t.name===void 0?{}:{name:t.name},...t.stack===void 0?{}:{stack:t.stack},...t.snippet===void 0?{}:{snippet:t.snippet},...t.value===void 0?{}:{value:t.value},...t.location===void 0?{}:{location:Zo(t.location)}}}function qp(t){return{type:t.type,...t.description===void 0?{}:{description:t.description},...t.location===void 0?{}:{location:Zo(t.location)}}}function Hp(t){return"text"in t?{kind:"text",text:t.text}:{kind:"base64",base64:t.buffer}}function gv(t,n,e){return{attachmentId:B("att",[n,String(e)]),name:t.name,contentType:t.contentType,sourceIndex:e,...t.path===void 0?{}:{path:t.path},...t.body===void 0?{}:{bodyBase64:t.body}}}function Gp(t,n,e){return{title:t.title,duration:t.duration,...t.error===void 0?{}:{error:mi(t.error,n,`${e}.error`)},steps:t.steps.map((r,s)=>Gp(r,n,`${e}.steps[${s}]`))}}function wv(t){let n=[],e=(r,s,i)=>{r.forEach((a,o)=>{let d=`${i}[${o}]`,c=a.title.length===0?s:[...s,a.title];a.specs.forEach((l,u)=>{l.tests.forEach((p,f)=>{n.push({titlePath:[...c,l.title],spec:l,test:p,sourcePath:`${d}.specs[${u}].tests[${f}]`})})}),e(a.suites,c,`${d}.suites`)})};return e(t.suites,[],"$report.suites"),n}function Qo(t,n){if(!Vp(n))return;let e=yv(t,n);if(!(Vp(e)||e===".."||e.startsWith(`..${zp}`)))return e.split(zp).join("/")}function bv(t,n){return t.config.projects.map(e=>{let r=e.testDir===void 0?void 0:Qo(n,e.testDir);return{projectId:B("prj",[e.id,e.name]),frameworkProjectId:e.id,name:e.name,repeatEach:e.repeatEach,retries:e.retries,...r===void 0?{}:{testDir:r}}}).sort((e,r)=>e.projectId.localeCompare(r.projectId))}function xv(t,n,e,r){let s=B("atm",[n,String(t.retry),"repeat:unknown",String(e)]),i=[];return t.error!==void 0&&i.push(mi(t.error,s,`${r}.error`)),t.errors.forEach((a,o)=>{i.push(mi(a,s,`${r}.errors[${o}]`))}),{attemptId:s,sourceIndex:e,retry:t.retry,repeat:{state:"unknown",reason:"not-serialized-by-playwright-json-reporter"},status:t.status,duration:t.duration,startTime:new Date(t.startTime).toISOString(),workerIndex:t.workerIndex,parallelIndex:t.parallelIndex,errors:i,stdout:t.stdout.map(Hp),stderr:t.stderr.map(Hp),steps:t.steps.map((a,o)=>Gp(a,s,`${r}.steps[${o}]`)),attachments:t.attachments.map((a,o)=>gv(a,s,o)),annotations:t.annotations.map(qp),...t.errorLocation===void 0?{}:{errorLocation:Zo(t.errorLocation)}}}function vv(t,n){return t.length===0?"zero-tests":t.some(e=>e.attempts.some(r=>r.status==="interrupted"))?"interrupted":n.length>0?"report-errors":"analysis-ready"}function Kp(t){let{report:n,reportHash:e,artifact:r,options:s}=t,i=s.workspaceRoot,a=bv(n,i),o=n.config.rootDir===void 0?void 0:Qo(i,n.config.rootDir),d=y=>{let w=y.replaceAll("\\","/");return o===void 0||o===""?w:`${o}/${w}`},c=n.config.configFile===void 0?void 0:Qo(i,n.config.configFile),l=new Map(a.map(y=>[y.frameworkProjectId,y.projectId])),p=wv(n).map(({spec:y,test:w,titlePath:x,sourcePath:v})=>{let R=l.get(w.projectId);if(R===void 0)throw new Error(`Validated test references unknown project ID: ${w.projectId}`);let P=d(y.file),N=B("tst",[i,R,P,...x]);return{logicalTestId:N,projectId:R,title:y.title,titlePath:x,tags:[...y.tags].sort(),location:{file:P,line:y.line,column:y.column},timeout:w.timeout,expectedStatus:w.expectedStatus,status:w.status,annotations:w.annotations.map(qp),attempts:w.results.map((E,M)=>xv(E,N,M,`${v}.results[${M}]`))}});p.sort((y,w)=>y.logicalTestId.localeCompare(w.logicalTestId));let f=n.errors.map((y,w)=>mi(y,r.artifactId,`$report.errors[${w}]`)),h=p.reduce((y,w)=>y+w.attempts.reduce((x,v)=>x+v.attachments.length,0),0),m=new Date(n.stats.startTime).toISOString(),g=B("run",[e,i,s.gitRoot??"","1.7","1"]);return{schemaVersion:"1.7",runId:g,framework:"playwright",createdAt:m,workspace:{root:i,...s.gitRoot===void 0?{}:{gitRoot:s.gitRoot}},sourceHashes:{report:e},artifact:r,usability:vv(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:[...t.warnings].sort(),stats:{...n.stats,startTime:m}}}var Gn=class extends Error{constructor(n){super(n),this.name="ReportValidationError"}};function Ne(t,n){throw new Gn(`${t} must be ${n}`)}function ne(t,n){return typeof t!="object"||t===null||Array.isArray(t)?Ne(n,"an object"):t}function on(t,n){return Array.isArray(t)?t:Ne(n,"an array")}function G(t,n){return typeof t!="string"?Ne(n,"a string"):t}function fe(t,n){return t===void 0?void 0:G(t,n)}function Ke(t,n){return typeof t!="number"||!Number.isFinite(t)?Ne(n,"a finite number"):t}function yi(t,n){let e=Ke(t,n);return Number.isInteger(e)?e:Ne(n,"an integer")}function we(t,n){let e=yi(t,n);return e<0?Ne(n,"a non-negative integer"):e}function ed(t,n){let e=G(t,n);return!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(e)||new Date(e).toISOString()!==e?Ne(n,"an ISO 8601 UTC timestamp with millisecond precision"):e}function Wp(t,n){return typeof t!="boolean"?Ne(n,"a boolean"):t}function ue(t,n,e,r){let s=t[n];return s===void 0?void 0:e(s,`${r}.${n}`)}function Z(t,n,e){return on(t,n).map((r,s)=>e(r,`${n}[${s}]`))}function kv(t){return t.length===0?!0:t.length%4!==0?!1:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}function td(t,n){let e=G(t,n);return kv(e)?e:Ne(n,"canonical base64")}function dn(t,n,e){let r=G(t,n);return e.has(r)?r:Ne(n,`one of ${[...e].join(", ")}`)}function gi(t,n){return n===void 0?{}:{[t]:n}}function nd(t,n){let e=ne(t,n),r=ue(e,"line",we,n),s=ue(e,"column",we,n);return{file:G(e.file,`${n}.file`),...r===void 0?{}:{line:r},...s===void 0?{}:{column:s}}}function wi(t,n){let e=ne(t,n),r=ue(e,"message",G,n),s=ue(e,"name",G,n),i=ue(e,"stack",G,n),a=ue(e,"snippet",G,n),o=ue(e,"value",G,n),d=ue(e,"location",nd,n);return{...r===void 0?{}:{message:r},...s===void 0?{}:{name:s},...i===void 0?{}:{stack:i},...a===void 0?{}:{snippet:a},...o===void 0?{}:{value:o},...d===void 0?{}:{location:d}}}function Xp(t,n){let e=ne(t,n),r=ue(e,"description",G,n),s=ue(e,"location",nd,n);return{type:G(e.type,`${n}.type`),...r===void 0?{}:{description:r},...s===void 0?{}:{location:s}}}function Jp(t,n){let e=ne(t,n),r=typeof e.text=="string",s=typeof e.buffer=="string";return r===s?Ne(n,"exactly one of text or buffer"):r?{text:G(e.text,`${n}.text`)}:{buffer:td(e.buffer,`${n}.buffer`)}}function Rv(t,n){let e=ne(t,n),r=ue(e,"path",G,n),s=ue(e,"body",td,n);return{name:G(e.name,`${n}.name`),contentType:G(e.contentType,`${n}.contentType`),...r===void 0?{}:{path:r},...s===void 0?{}:{body:s}}}function Yp(t,n){let e=ne(t,n),r=ue(e,"error",wi,n);return{title:G(e.title,`${n}.title`),duration:Ke(e.duration,`${n}.duration`),...r===void 0?{}:{error:r},steps:Z(e.steps??[],`${n}.steps`,Yp)}}var Qp=new Set(["passed","failed","timedOut","skipped","interrupted"]),Iv=new Set(["expected","unexpected","flaky","skipped"]);function Av(t,n){let e=ne(t,n),r=ue(e,"error",wi,n),s=ue(e,"errorLocation",nd,n);return{workerIndex:yi(e.workerIndex,`${n}.workerIndex`),parallelIndex:yi(e.parallelIndex,`${n}.parallelIndex`),status:dn(e.status,`${n}.status`,Qp),duration:Ke(e.duration,`${n}.duration`),startTime:ed(e.startTime,`${n}.startTime`),retry:we(e.retry,`${n}.retry`),...r===void 0?{}:{error:r},errors:Z(e.errors??[],`${n}.errors`,wi),stdout:Z(e.stdout??[],`${n}.stdout`,Jp),stderr:Z(e.stderr??[],`${n}.stderr`,Jp),steps:Z(e.steps??[],`${n}.steps`,Yp),attachments:Z(e.attachments??[],`${n}.attachments`,Rv),annotations:Z(e.annotations??[],`${n}.annotations`,Xp),...s===void 0?{}:{errorLocation:s}}}function Tv(t,n){let e=ne(t,n);return{timeout:Ke(e.timeout,`${n}.timeout`),annotations:Z(e.annotations??[],`${n}.annotations`,Xp),expectedStatus:dn(e.expectedStatus,`${n}.expectedStatus`,Qp),projectName:G(e.projectName,`${n}.projectName`),projectId:G(e.projectId,`${n}.projectId`),results:Z(e.results,`${n}.results`,Av),status:dn(e.status,`${n}.status`,Iv)}}function Pv(t,n){let e=ne(t,n);return{title:G(e.title,`${n}.title`),ok:Wp(e.ok,`${n}.ok`),tags:Z(e.tags??[],`${n}.tags`,G),tests:Z(e.tests,`${n}.tests`,Tv),file:G(e.file,`${n}.file`),line:we(e.line,`${n}.line`),column:we(e.column,`${n}.column`)}}function Zp(t,n){let e=ne(t,n),r=ue(e,"file",G,n),s=ue(e,"line",we,n),i=ue(e,"column",we,n);return{title:G(e.title,`${n}.title`),...r===void 0?{}:{file:r},...s===void 0?{}:{line:s},...i===void 0?{}:{column:i},suites:Z(e.suites??[],`${n}.suites`,Zp),specs:Z(e.specs??[],`${n}.specs`,Pv)}}function Sv(t,n){let e=ne(t,n);return{id:G(e.id,`${n}.id`),name:G(e.name,`${n}.name`),repeatEach:we(e.repeatEach,`${n}.repeatEach`),retries:we(e.retries,`${n}.retries`),...gi("testDir",fe(e.testDir,`${n}.testDir`))}}function ef(t){let n=ne(t,"$report"),e=ne(n.config,"$report.config"),r=ne(n.stats,"$report.stats");return{config:{version:G(e.version,"$report.config.version"),projects:Z(e.projects,"$report.config.projects",Sv),...gi("rootDir",fe(e.rootDir,"$report.config.rootDir")),...gi("configFile",fe(e.configFile,"$report.config.configFile"))},suites:Z(n.suites,"$report.suites",Zp),errors:Z(n.errors??[],"$report.errors",wi),stats:{startTime:ed(r.startTime,"$report.stats.startTime"),duration:Ke(r.duration,"$report.stats.duration"),expected:we(r.expected,"$report.stats.expected"),skipped:we(r.skipped,"$report.stats.skipped"),unexpected:we(r.unexpected,"$report.stats.unexpected"),flaky:we(r.flaky,"$report.stats.flaky")}}}var Ev=new TextDecoder("utf-8",{fatal:!0});function cn(t,n,e){return{kind:"unreadable",artifact:{artifactId:B("art",[t??"unavailable",n??"bytes"]),kind:"report",availability:"unreadable",...n===void 0?{}:{path:n},...t===void 0?{}:{sha256:t},warnings:[]},diagnostic:e}}function Cv(t){return new Set(t??hi)}function Kn(t,n){let e=Ee(t);if(t.byteLength===0)return cn(e,n.reportPath,{reasonCode:"empty-input",message:"The Playwright JSON report is empty.",...n.reportPath===void 0?{}:{path:n.reportPath}});let r;try{r=Ev.decode(t)}catch{return cn(e,n.reportPath,{reasonCode:"invalid-utf8",message:"The Playwright JSON report is not valid UTF-8.",...n.reportPath===void 0?{}:{path:n.reportPath}})}let s;try{s=JSON.parse(r)}catch(p){return cn(e,n.reportPath,{reasonCode:"invalid-json",message:p instanceof Error?p.message:"The report is not valid JSON.",...n.reportPath===void 0?{}:{path:n.reportPath}})}let i;try{i=ef(s)}catch(p){return cn(e,n.reportPath,{reasonCode:"invalid-report-shape",message:p instanceof Gn?p.message:"The JSON value is not a supported Playwright report.",...n.reportPath===void 0?{}:{path:n.reportPath}})}let a=new Set;for(let p of i.config.projects){if(a.has(p.id))return cn(e,n.reportPath,{reasonCode:"invalid-report-shape",message:`$report.config.projects contains duplicate project ID: ${p.id}`,...n.reportPath===void 0?{}:{path:n.reportPath}});a.add(p.id)}if(new Set(n.incompatiblePlaywrightVersions??[]).has(i.config.version))return cn(e,n.reportPath,{reasonCode:"incompatible-playwright-version",message:`Playwright ${i.config.version} is configured as incompatible.`,...n.reportPath===void 0?{}:{path:n.reportPath}});let c=Cv(n.testedPlaywrightVersions).has(i.config.version),l=[];c||l.push(`unverified-producer-version:${i.config.version}`),i.config.projects.some(p=>p.repeatEach>1)&&l.push("repeat-index-unavailable");let u={artifactId:B("art",[e]),kind:"report",availability:"present",...n.reportPath===void 0?{}:{path:n.reportPath},sha256:e,format:"playwright-json",formatVersion:i.config.version,versionConfidence:c?"verified":"unverified",warnings:[...l].sort()};try{return{kind:"parsed",run:Kp({report:i,reportHash:e,artifact:u,options:n,warnings:l})}}catch(p){return cn(e,n.reportPath,{reasonCode:"invalid-report-shape",message:p instanceof Error?p.message:"The report could not be normalized.",...n.reportPath===void 0?{}:{path:n.reportPath}})}}import{createHash as YI}from"node:crypto";import{readdir as QI,readFile as ZI,stat as eA}from"node:fs/promises";import{basename as tA,dirname as nA,join as rA}from"node:path";import{resolve as Vv}from"node:path";import{readdir as Nv,stat as Ov}from"node:fs/promises";import{join as tf}from"node:path";var sf=/\.(?:java|kt|groovy|scala)$/,$v=/^at (?:([\w.$-]+)\/\/?)?([\w$]+(?:\.[\w$]+)*)\.([\w$<>-]+)\(([\w$-]+\.(?:java|kt|groovy|scala)):(\d+)\)\s*$/,Dv=/^(?:java|javax|jdk|sun|com\.sun|org\.junit|junit|org\.testng|org\.openqa\.selenium|org\.assertj|org\.hamcrest|org\.opentest4j|org\.apache\.maven|org\.gradle|worker\.org\.gradle|io\.cucumber|kotlin|kotlinx|scala|groovy|org\.codehaus\.groovy|org\.springframework\.test)\./,Mv=["src/test/java","src/main/java","src/it/java","src/test/kotlin","src/main/kotlin","src/test/groovy","src/main/groovy","src/test/scala","src/main/scala"],Lv=["src/test/resources","src/main/resources"];function bi(t){return sf.test(t)}function nf(t){return t.endsWith(".feature")}function ln(t,n="java"){return`${(t.split("$")[0]??t).replaceAll(".","/")}.${n}`}function Jn(t){let n=$v.exec(t.trim());if(n===null)return;let[,e,r,s,i,a]=n;if(r===void 0||s===void 0||i===void 0||a===void 0||e!==void 0&&e!=="app"||Dv.test(`${r}.`))return;let o=i.replace(sf,""),d=r.lastIndexOf(`.${o}`),c=d>=0?r.slice(0,d):r.split(".").slice(0,-1).join(".");return{file:`${c===""?"":`${c.replaceAll(".","/")}/`}${i}`,line:Number.parseInt(a,10),className:r,method:s}}async function rf(t){try{return(await Ov(t)).isFile()}catch{return!1}}async function _v(t){return(await Nv(t,{withFileTypes:!0}).catch(()=>[])).filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&e.name!=="node_modules"&&e.name!=="src"&&e.name!=="target"&&e.name!=="build").map(e=>e.name).sort()}var Wn=class{constructor(n){this.workspaceRoot=n}workspaceRoot;modules;found=new Map;find(n){let e=this.found.get(n);return e===void 0&&(e=this.lookup(n),this.found.set(n,e)),e}async resolve(n){return bi(n)||nf(n)?await this.find(n)??n:n}async lookup(n){if(await rf(tf(this.workspaceRoot,n)))return n;let e=nf(n)?Lv:Mv;this.modules??=_v(this.workspaceRoot);let r=[...e,...(await this.modules).flatMap(s=>e.map(i=>`${s}/${i}`))];for(let s of r){let i=`${s}/${n}`;if(await rf(tf(this.workspaceRoot,i)))return i}}};var jv=/(?:\(|\bat\s+|^)((?:webpack:\/\/[^\s()]*|file:\/\/[^\s()]*|(?:[A-Za-z]:)?[^():\s][^():]*?)):(\d+):(\d+)\)?\s*$/,Fv=/^File "([^"]+\.py)", line (\d+)/,Bv=/^((?:[A-Za-z]:)?[^\s:][^:]*\.py):(\d+):(?:\s|$)/;function of(t){let n=t,e=/^webpack:\/\/[^/]*\/(.*)$/.exec(n);return e!==null&&(n=e[1]??""),n.startsWith("file://")&&(n=decodeURIComponent(n.slice(7)).replaceAll("\\","/"),/^\/[A-Za-z]:\//.test(n)&&(n=n.slice(1))),n.replace(/^(?:\.\/)+/,"")}function af(t){return/^https?:\/\//.test(t)||t.includes("/__cypress/")||t.includes("node_modules/")||t.startsWith("node:")||t.startsWith("internal/")||t.includes("site-packages/")||/\/lib\/python\d/.test(t)||t.startsWith("<")}function df(t){let n=[];for(let e of t.split(/\r?\n/)){let r=e.trim().replace(/^❯\s+/,""),s=Jn(r);if(s!==void 0){n.push({file:s.file,line:s.line,column:1});continue}let i=Fv.exec(r)??Bv.exec(r),a=i===null?jv.exec(r):[i[0],i[1],i[2],"1"];if(a===null)continue;let[,o,d,c]=a;if(o===void 0||d===void 0||c===void 0||af(o))continue;let l=of(o);l===""||af(l)||n.push({file:l,line:Number.parseInt(d,10),column:Number.parseInt(c,10)})}return n}function xe(t,n){if(t===void 0)return;let e=df(t);if(n!==void 0){let r=n.replaceAll("\\","/").replace(/^(?:\.\/)+/,""),s=e.find(i=>{let a=i.file.replaceAll("\\","/");return a===r||a.endsWith(`/${r}`)||r.endsWith(`/${a}`)});if(s!==void 0)return s}return e[0]}var zv="1",Hv="application/vnd.allure.playwright-trace";function sd(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function id(t){return sd(t)&&typeof t.uuid=="string"&&typeof t.status=="string"&&Array.isArray(t.labels)&&(typeof t.historyId=="string"||typeof t.fullName=="string")}function ad(t){return sd(t)&&typeof t.uuid=="string"&&typeof t.status!="string"&&(Array.isArray(t.children)||Array.isArray(t.befores)||Array.isArray(t.afters))}function od(t){return sd(t)&&t.uuid===void 0&&Array.isArray(t.errors)&&Array.isArray(t.attachments)}var Uv={testng:"testng","junit-platform":"junit",junit5:"junit",junit4:"junit",junit:"junit",pytest:"pytest",playwright:"playwright",cypress:"cypress",webdriverio:"webdriverio",jest:"jest",vitest:"vitest",mocha:"mocha"};function Tt(t,n){return t.labels?.find(e=>e.name===n)?.value}var cf={passed:"passed",failed:"failed",broken:"failed",skipped:"skipped"};function xi(t){return t==="junit"||t==="testng"}function Br(t,n){let e=t?.message?.trim()||void 0,r=t?.trace?.trim()||void 0;if(e===void 0&&r===void 0)return;let s=xe(r,n);return{...e===void 0?{}:{message:e},...r===void 0?{}:{stack:r},...s===void 0?{}:{location:s}}}function lf(t){for(let n of(t??"").split(`
113
+ `)){let e=Jn(n);if(e!==void 0)return e}}function dd(t){return typeof t.start=="number"&&typeof t.stop=="number"&&t.stop>=t.start?t.stop-t.start:0}function ff(t){let n=typeof t=="number"?new Date(t):void 0;return n===void 0||Number.isNaN(n.getTime())?{}:{startTime:n.toISOString()}}function cd(t,n){let r=t.status==="failed"||t.status==="broken"?Br(t.statusDetails,n):void 0;return{title:t.name??"",duration:dd(t),...r===void 0?{}:{error:r},steps:(t.steps??[]).map(s=>cd(s,n))}}function hf(t,n){return[...(t.attachments??[]).flatMap(r=>r.source===void 0?[]:[{name:r.name??r.source,contentType:r.type===Hv?"application/zip":r.type??"",path:n===void 0?r.source:Vv(n,r.source)}]),...(t.steps??[]).flatMap(r=>hf(r,n))]}function qv(t){return t.replace(/^\[/,"").replace(/\]$/,"").split("]/[").map(n=>{let e=n.indexOf(":");return{type:n.slice(0,e),value:n.slice(e+1)}})}function Gv(t){let n=Tt(t,"junit.platform.uniqueid")??t.parameters?.find(a=>a.name==="UniqueId")?.value;if(n===void 0)return;let e=qv(n),r=e.findIndex(a=>a.type==="test-template"||a.type==="test-factory");if(r<0)return;let s=e.slice(r+1).map(a=>/^#(\d+)$/.exec(a.value)?.[1]);return s.length===0||s.includes(void 0)?void 0:`${(e[r]?.value??"").replace(/\(([^)]*)\)$/,(a,o)=>`(${o.split(",").map(c=>c.trim().split(/[.$]/).at(-1)??"").filter(c=>c!=="").join(", ")})`)}${s.map(a=>`[${a}]`).join("")}`}function Kv(t){let n=t.split(".").filter(r=>r!==""),e=n.length;for(;e>1&&/^[A-Z]/.test(n[e-1]??"");)e-=1;return{file:`${n.slice(0,e).join("/")}.py`,classes:n.slice(e)}}function Wv(t){let n=t.titlePath??[],e=n.findIndex(r=>r.endsWith(".py"));return e>=0?{file:n.slice(0,e+1).join("/"),classes:n.slice(e+1)}:Kv((t.fullName??"").split("#")[0]??"")}function rd(t,n){return{file:ln(t),titlePath:[...t.split("$").filter(e=>e!==""),n],projectId:""}}function uf(t,n,e){let r=Tt(t,"testClass");if(r!==void 0&&xi(n))return rd(r,e);if(n==="pytest"){let{file:i,classes:a}=Wv(t);return{file:i,titlePath:[...a,e],projectId:""}}if(n==="playwright"){let i=(t.fullName??e).split(" \u203A ");return{file:Tt(t,"suite")??i[0]??"",titlePath:i.length>1?i.slice(1):[e],projectId:Tt(t,"parentSuite")??""}}let s=Tt(t,"suite");return{file:s!==void 0&&/\.[cm]?[jt]sx?$/.test(s)?s:"",titlePath:[t.fullName??e],projectId:""}}function pf(t,n,e,r){return{status:"failed",retry:n,...ff(t.start),duration:dd(t),errors:e===void 0?[]:[e],attachments:[],stdout:[],stderr:[],steps:(t.steps??[]).map(s=>cd(s,r))}}function mf(t){let n=[],e=[],r=[];for(let A of t)id(A.json)?n.push({...A.json,...A.directory===void 0?{}:{directory:A.directory}}):ad(A.json)?e.push(A.json):od(A.json)&&r.push(...A.json.errors);if(n.length===0)throw new Error("The Allure results hold no test result.");let s=new Set(n.map(A=>Uv[Tt(A,"framework")??""]??"unknown")),i=s.size===1?[...s][0]??"unknown":"unknown",a=[];s.size>1&&a.push("allure-mixed-frameworks");let o=new Map;for(let A of n){let C=A.historyId??`uuid:${A.uuid}`,T=o.get(C)??{key:C,results:[]};o.set(C,T),T.results.push(A)}let d=new Map,c=A=>{let C=Tt(A,"testMethod");if(i==="junit")return Gv(A)??C??A.name??"";if(i!=="testng")return A.name??"";let T=C??A.name??"",I=(A.parameters??[]).map(S=>S.value??"");if(I.length===0)return T;let $=`${Tt(A,"testClass")??""}\0${T}`,D=d.get($)??new Map;d.set($,D);let k=D.get(JSON.stringify(I))??D.size;return D.set(JSON.stringify(I),k),`${T}[${k}]`},l=0,u=0,p=new Map,f=[],h=[...o.values()].sort((A,C)=>{let T=I=>Math.min(...I.results.map($=>$.start??0));return T(A)-T(C)||A.key.localeCompare(C.key)});for(let A of h){let C=[...A.results].sort((D,k)=>(D.start??0)-(k.start??0)||D.uuid.localeCompare(k.uuid)),T=C.filter((D,k)=>{let S=D.status==="passed"&&k<C.length-1;return S&&(l+=1),!S}),I=T.at(-1);if(I===void 0)continue;p.set(A.key,I);let $=uf(I,i,c(I));f.push({file:$.file,titlePath:$.titlePath,projectId:$.projectId,attempts:T.map((D,k)=>{let S=k<T.length-1,_=cf[D.status??""];!S&&_===void 0&&(u+=1);let U=S?"failed":_??"skipped",K=U==="passed"?void 0:Br(D.statusDetails,$.file);return{status:U,retry:k,...ff(D.start),duration:dd(D),errors:K===void 0?[]:[K],attachments:hf(D,D.directory),stdout:[],stderr:[],steps:(D.steps??[]).map(te=>cd(te,$.file))}})})}l>0&&a.push(`allure-passed-before-retry-ignored:${l}`),u>0&&a.push(`allure-unknown-status:${u}`);let m=new Map;for(let A of o.values()){let C=p.get(A.key);if(C!==void 0)for(let T of A.results)m.set(T.uuid,C)}let g=new Set;for(let A of e){let C=(A.children??[]).map(I=>m.get(I)).filter(I=>I!==void 0);if(C.some(I=>cf[I.status??""]==="failed"))continue;let T=[...(A.befores??[]).map(I=>({fixture:I,phase:"setup"})),...(A.afters??[]).map(I=>({fixture:I,phase:"teardown"}))].filter(({fixture:I})=>I.status==="failed"||I.status==="broken");for(let{fixture:I,phase:$}of T){let D=xi(i)?lf(I.statusDetails?.trace):void 0,k=I.name??D?.method??"fixture",S=C[0],_=D?.className??(S===void 0?void 0:Tt(S,"testClass")),U=`${k} (${$})`,K=_!==void 0&&xi(i)?rd(_,U):S===void 0?void 0:uf(S,i,U);if(K===void 0)continue;let te=`${_??K.file}\0${k}`;g.has(te)||(g.add(te),f.push({...K,attempts:[pf(I,0,Br(I.statusDetails,K.file),K.file)]}))}}let y=[],w=new Map,x=[...r].sort((A,C)=>(A.timestamp??0)-(C.timestamp??0));for(let A of x){let C=xi(i)?lf(A.trace):void 0;if(C===void 0){let S=Br(A,"");S!==void 0&&y.push(S);continue}let T=`${C.className}\0${C.method}`;if(g.has(T))continue;let I=/\bdid not run\b/.test(A.message??"")?"setup":"teardown",$=rd(C.className,`${C.method} (${I})`),D=w.get(T)??{...$,attempts:[]};w.set(T,D);let k=A.timestamp===void 0?{}:{start:A.timestamp};D.attempts.push(pf(k,D.attempts.length,Br(A,$.file),$.file))}f.push(...w.values());let v=new Map;if(i==="playwright")for(let A of f)for(let C of A.attempts.flatMap(T=>T.errors)){let T=C.location?.file;T!==void 0&&!v.has(A.file)&&T.replaceAll("\\","/").endsWith(`/${A.file}`)&&v.set(A.file,T)}let R=f.map(A=>{let C=v.get(A.file);return C===void 0?A:{...A,file:C}}),P=n.flatMap(A=>typeof A.start=="number"?[A.start]:[]),N=n.flatMap(A=>typeof A.stop=="number"?[A.stop]:[]),E=P.length===0?void 0:new Date(Math.min(...P)).toISOString(),M=[...new Set(R.map(A=>A.projectId))].sort();return{framework:i,format:"allure-json",adapterVersion:zv,...E===void 0?{}:{startTime:E},duration:P.length===0||N.length===0?0:Math.max(...N)-Math.min(...P),projects:(M.length===0?[""]:M).map(A=>({id:A,name:A,retries:0})),tests:R,errors:y,interrupted:!1,warnings:a}}var Jv="1",Xv=["0.2.0","1.0.0"];function yf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ld(t){return yf(t)&&t.reportFormat==="CTRF"&&yf(t.results)&&Array.isArray(t.results.tests)}var Yv=[...ht,...Xo];function Qv(t){let n=t?.trim().toLowerCase()??"";return Yv.includes(n)?n:"unknown"}var Zv={passed:"passed",failed:"failed",skipped:"skipped",pending:"skipped"};function bf(t){if(typeof t!="number")return;let n=new Date(t);return Number.isNaN(n.getTime())?void 0:n.toISOString()}function ek(t,n){let e=t.message?.trim()||void 0,r=t.trace?.trim()||void 0,s=t.snippet?.trimEnd()||void 0;if(e===void 0&&r===void 0)return;let i=xe(r,n);return{...e===void 0?{}:{message:e},...r===void 0?{}:{stack:r},...s===void 0?{}:{snippet:s},...i===void 0?{}:{location:i}}}function tk(t){return(t.attachments??[]).flatMap(n=>n.path===void 0||n.path===""?[]:[{name:n.name??n.path,contentType:n.contentType??"",path:n.path}])}function gf(t,n,e,r,s){let i=bf(t.start),a=t.duration,o=typeof t.start=="number"&&typeof t.stop=="number"?t.stop-t.start:void 0,d=typeof a=="number"&&a>=0?a:o??0,c=n==="passed"?void 0:ek(t,r);return{status:n,retry:e,...i===void 0?{}:{startTime:i},duration:d>=0?d:0,errors:c===void 0?[]:[c],attachments:tk(t),stdout:t.stdout??[],stderr:t.stderr??[],steps:s}}function wf(t,n){if(n===void 0||t==="")return!1;let e=n.replaceAll("\\","/"),r=t.replaceAll("\\","/");return e===r||e.endsWith(`/${r}`)}function nk(t,n){let e=(t.suite??[]).filter(o=>o!==""),r=t.name??"",s=e.findIndex(o=>wf(o,t.filePath)),i=s<0?e:e.slice(s+1),a=s>0?e.slice(0,s).join(" \u203A "):"";if(n==="pytest"&&r.includes("::")){let o=r.split("::");return{titlePath:wf(o[0]??"",t.filePath)?o.slice(1):o,projectId:a}}if(n==="jest"){let o=`${i.join(" ")} `,d=i.length>0&&r.startsWith(o)?r.slice(o.length):r;return{titlePath:[...i,d],projectId:a}}return{titlePath:[...i,r],projectId:a}}function xf(t){if(!ld(t))throw new Error("A CTRF report needs results with a tests array.");let n=t,e=Qv(n.results.tool?.name),r=n.results.tool?.version?.trim()||void 0,s=[],i=n.specVersion??"";Xv.includes(i)||s.push(`unverified-ctrf-spec-version:${i===""?"unrecorded":i}`);let a=0,o=0,d=!1,c=m=>{let g=Zv[m.status??""];return g===void 0&&(a+=1),g??"skipped"},l=n.results.tests.map(m=>{let g=m.filePath??"",y=nk(m,e),w=m.retryAttempts??[];typeof m.retries=="number"&&m.retries>w.length&&(d=!0);let x=(m.steps??[]).map(P=>({title:P.name??"",duration:0,steps:[]})),v=[...w.map((P,N)=>gf(P,c(P),N,g,[])),gf(m,c(m),w.length,g,x)],R=v.at(-1)?.status==="passed"&&v.slice(0,-1).some(P=>P.status==="failed");return typeof m.flaky=="boolean"&&m.flaky!==R&&(o+=1),{file:g,titlePath:y.titlePath,...typeof m.line=="number"&&m.line>0?{line:m.line}:{},projectId:y.projectId,...m.tags===void 0?{}:{tags:m.tags},attempts:v}});a>0&&s.push(`ctrf-other-status:${a}`),o>0&&s.push(`ctrf-flaky-mismatch:${o}`),d&&s.push("final-attempt-only");let{start:u,stop:p}=n.results.summary??{},f=bf(u),h=[...new Set(l.map(m=>m.projectId))].sort();return{framework:e,format:"ctrf-json",adapterVersion:Jv,...r===void 0?{}:{frameworkVersion:r},...f===void 0?{}:{startTime:f},duration:typeof u=="number"&&typeof p=="number"&&p>=u?p-u:0,projects:(h.length===0?[""]:h).map(m=>({id:m,name:m,retries:0})),tests:l,errors:[],interrupted:!1,warnings:s}}var rk="1";function sk(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ud(t){return Array.isArray(t)&&t.length>0&&t.every(n=>sk(n)&&typeof n.uri=="string"&&typeof n.keyword=="string"&&Array.isArray(n.elements))}function ik(t){return t.startsWith("classpath:")?t.slice(10).replace(/^\/+/,""):t}var kf=new Set(["undefined","ambiguous","pending"]),ak=1e6;function vf(t){let n=t.result?.duration;return typeof n=="number"&&n>0?n/ak:0}function ok(t,n){return n!==void 0?`${n} hook`:`${(t.keyword??"").trim()} ${t.name??""}`.trim()}function dk(t,n){if(n!==void 0||t.hidden!==!0)return n;let e=(t.keyword??"").trim();return e==="Before"||e==="After"?e:void 0}function ck(t,n,e,r){let s=t.result?.status??"",i=t.result?.error_message?.trim()||void 0,a=typeof t.line=="number"?{file:r,line:t.line}:void 0;if(kf.has(s))return{message:`${s[0]?.toUpperCase()}${s.slice(1)} step: ${n}`,...i===void 0?{}:{stack:i},...a===void 0?{}:{location:a}};if(s!=="failed"||i===void 0)return;let o=i.split(/\r?\n/),d=o.findIndex(u=>/^\s*at\s/.test(u)),c=(d<0?o:o.slice(0,d)).join(`
114
+ `).trim()||i,l=xe(i,r)??a;return{message:e===void 0?c:`${e} hook failed: ${c}`,stack:i,...l===void 0?{}:{location:l}}}function lk(t){return(t.embeddings??[]).flatMap(n=>n.data===void 0||n.data===""?[]:[{name:n.name??"attachment",contentType:n.mime_type??n.media?.type??"",body:n.data}])}function uk(t,n,e){let r=t.map(({step:c})=>c.result?.status??""),s=r.some(c=>c==="failed"||kf.has(c))?"failed":r.some(c=>c==="passed")?"passed":"skipped",i=[],a=[],o=[];for(let c of t){let{step:l}=c,u=dk(l,c.hook),p=ok(l,u),f=ck(l,p,u,n);f!==void 0&&a.length===0&&a.push(f),i.push({title:p,duration:vf(l),...f===void 0?{}:{error:f},steps:[]}),o.push(...lk(l))}let d=e===void 0||Number.isNaN(new Date(e).getTime())?void 0:new Date(e).toISOString();return{status:s,retry:0,...d===void 0?{}:{startTime:d},duration:t.reduce((c,{step:l})=>c+vf(l),0),errors:a,attachments:o,stdout:[],stderr:[],steps:i}}function pk(...t){return[...new Set(t.flatMap(n=>(n??[]).flatMap(e=>e.name??[])))].sort()}function Rf(t){if(!ud(t))throw new Error("A Cucumber report is an array of features.");let n=[],e=[];for(let s of t){let i=ik(s.uri),a=[],o=[];for(let l of s.elements){if(l.type==="background"){o.push(l);continue}a.push({element:l,background:o}),o=[]}let d=new Map;for(let{element:l}of a){let u=l.name??"";d.set(u,(d.get(u)??0)+1)}let c=new Map;for(let{element:l,background:u}of a){let p=l.name??"",f=(c.get(p)??0)+1;c.set(p,f);let h=[...u.flatMap(m=>(m.before??[]).map(g=>({step:g,hook:"Before"}))),...(l.before??[]).map(m=>({step:m,hook:"Before"})),...u.flatMap(m=>(m.steps??[]).map(g=>({step:g}))),...(l.steps??[]).map(m=>({step:m})),...(l.after??[]).map(m=>({step:m,hook:"After"})),...u.flatMap(m=>(m.after??[]).map(g=>({step:g,hook:"After"})))];l.start_timestamp!==void 0&&e.push(l.start_timestamp),n.push({file:i,titlePath:[s.name??"",p,...(d.get(p)??0)>1?[`Example #${f}`]:[]],...typeof l.line=="number"?{line:l.line}:{},projectId:"",tags:pk(s.tags,l.tags),attempts:[uk(h,i,l.start_timestamp)]})}}let r=e.map(s=>new Date(s)).filter(s=>!Number.isNaN(s.getTime())).map(s=>s.toISOString()).sort()[0];return{framework:"cucumber",format:"cucumber-json",adapterVersion:rk,...r===void 0?{}:{startTime:r},duration:n.reduce((s,i)=>s+(i.attempts[0]?.duration??0),0),projects:[{id:"",name:"",retries:0}],tests:n,errors:[],interrupted:!1,warnings:["final-attempt-only"]}}import{join as fk}from"node:path";var vi="kwikqa-test-report",pd="1.0",hk="1",mk=new Set(["cypress","webdriverio"]),yk=new Set(["passed","failed","timedOut","skipped","interrupted"]);function If(t,n){let e=n.replaceAll("\\","/");return/^(?:[A-Za-z]:\/|\/|file:\/\/)/.test(e)?n:fk(t,e.replace(/^(?:\.\/)+/,""))}function gk(t){let n=t.rootDir;return n===void 0?t:{...t,tests:t.tests.map(e=>({...e,file:If(n,e.file),attempts:e.attempts.map(r=>({...r,attachments:r.attachments.map(s=>s.path===void 0?s:{...s,path:If(n,s.path)})}))}))}}function Af(t){return typeof t=="object"&&t!==null&&t.schema===vi}function wk(t,n){let e=ne(t,n),r=ue(e,"line",we,n),s=ue(e,"column",we,n);return{file:G(e.file,`${n}.file`),...r===void 0?{}:{line:r},...s===void 0?{}:{column:s}}}function Tf(t,n,e){let r=ne(t,n),s=fe(r.message,`${n}.message`),i=fe(r.name,`${n}.name`),a=fe(r.stack,`${n}.stack`),o=fe(r.snippet,`${n}.snippet`),d=fe(r.expected,`${n}.expected`),c=fe(r.actual,`${n}.actual`),u=ue(r,"location",wk,n)??xe(a,e);return{...s===void 0?{}:{message:s},...i===void 0?{}:{name:i},...a===void 0?{}:{stack:a},...o===void 0?{}:{snippet:o},...d===void 0&&c===void 0?{}:{value:`Expected: ${d??"(not recorded)"}
115
+ Received: ${c??"(not recorded)"}`},...u===void 0?{}:{location:u}}}function bk(t,n,e){let r=ne(t,n),s=fe(r.startTime,`${n}.startTime`);return{status:dn(r.status,`${n}.status`,yk),retry:we(r.retry,`${n}.retry`),...s===void 0?{}:{startTime:s},duration:Ke(r.duration??0,`${n}.duration`),errors:Z(r.errors??[],`${n}.errors`,(i,a)=>Tf(i,a,e)),attachments:Z(r.attachments??[],`${n}.attachments`,(i,a)=>{let o=ne(i,a),d=fe(o.path,`${a}.path`);return{name:G(o.name,`${a}.name`),contentType:G(o.contentType,`${a}.contentType`),...d===void 0?{}:{path:d}}}),stdout:Z(r.stdout??[],`${n}.stdout`,G),stderr:Z(r.stderr??[],`${n}.stderr`,G),steps:[]}}function xk(t,n){let e=ne(t,n),r=G(e.file,`${n}.file`),s=Z(e.titlePath,`${n}.titlePath`,G);s.length===0&&Ne(`${n}.titlePath`,"a non-empty array");let i=ue(e,"line",we,n),a=ue(e,"column",we,n),o=ue(e,"timeout",Ke,n);return{file:r,titlePath:s,...i===void 0?{}:{line:i},...a===void 0?{}:{column:a},projectId:G(e.project,`${n}.project`),...o===void 0?{}:{timeout:o},tags:Z(e.tags??[],`${n}.tags`,G),attempts:Z(e.attempts,`${n}.attempts`,(d,c)=>bk(d,c,r))}}function Pf(t){let n=ne(t,"$report");n.schema!==vi&&Ne("$report.schema",vi),String(n.schemaVersion??"").split(".")[0]!==pd.split(".")[0]&&Ne("$report.schemaVersion",`a ${pd.split(".")[0]}.x version`);let r=dn(n.framework,"$report.framework",mk),s=fe(n.frameworkVersion,"$report.frameworkVersion"),i=fe(n.rootDir,"$report.rootDir"),a=fe(n.configFile,"$report.configFile"),o=fe(n.startTime,"$report.startTime"),d=ue(n,"duration",Ke,"$report"),c=Z(n.projects,"$report.projects",(l,u)=>{let p=ne(l,u);return{id:G(p.id,`${u}.id`),name:G(p.name,`${u}.name`),retries:we(p.retries??0,`${u}.retries`)}});return on(n.tests,"$report.tests"),{framework:r,format:"kwikqa-json",adapterVersion:hk,...s===void 0?{}:{frameworkVersion:s},...i===void 0?{}:{rootDir:i},...a===void 0?{}:{configFile:a},...o===void 0?{}:{startTime:o},...d===void 0?{}:{duration:d},projects:c,tests:Z(n.tests,"$report.tests",xk),errors:Z(n.errors??[],"$report.errors",(l,u)=>Tf(l,u,void 0)),interrupted:n.interrupted===!0,warnings:[]}}function Sf(t){let n=t.map(gk),e=n[0];if(e===void 0)throw new Error("No report parts to merge.");let r=e.framework;if(n.some(l=>l.framework!==r))throw new Error("Report parts come from different frameworks.");let s=[...new Set(n.map(l=>l.frameworkVersion).filter(Boolean))],i=new Map;for(let l of n)for(let u of l.projects){let p=i.get(u.id);(p===void 0||u.retries>p.retries)&&i.set(u.id,u)}let a=n.map(l=>l.startTime).filter(l=>l!==void 0).sort(),o=[...new Set(n.map(l=>l.rootDir).filter(Boolean))],d=[...new Set(n.map(l=>l.configFile).filter(Boolean))],c=n.flatMap(l=>l.warnings);return s.length>1&&c.push(`mixed-framework-versions:${s.join(",")}`),o.length>1&&c.push("mixed-report-roots"),{framework:r,format:e.format,adapterVersion:e.adapterVersion,...s.length===1&&s[0]!==void 0?{frameworkVersion:s[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:n.reduce((l,u)=>Math.max(l,u.duration??0),0),projects:[...i.values()],tests:n.flatMap(l=>l.tests),errors:n.flatMap(l=>l.errors),interrupted:n.some(l=>l.interrupted),warnings:c}}import{basename as Ak,dirname as Tk,isAbsolute as Pk,resolve as Sk}from"node:path";var ki=class extends Error{constructor(n){super(n),this.name="XmlError"}},vk=64,kk=5e5,Rk=/^[A-Za-z_:][\w.:-]*/,Ik={lt:"<",gt:">",amp:"&",quot:'"',apos:"'"};function Ef(t){return t.replace(/&(#x[0-9A-Fa-f]+|#\d+|[A-Za-z]+);/g,(n,e)=>{if(e.startsWith("#x")){let s=Number.parseInt(e.slice(2),16);return s<=1114111?String.fromCodePoint(s):n}if(e.startsWith("#")){let s=Number.parseInt(e.slice(1),10);return s<=1114111?String.fromCodePoint(s):n}let r=Ik[e];if(r===void 0)throw new ki(`Unknown XML entity: &${e};`);return r})}function Ri(t){let n=0,e=0,r=t.charCodeAt(0)===65279?t.slice(1):t,s=c=>{throw new ki(`${c} at offset ${n}`)},i=()=>{for(;;){for(;n<r.length&&/\s/.test(r[n]??"");)n+=1;if(r.startsWith("<?",n)){let c=r.indexOf("?>",n);c<0&&s("Unterminated processing instruction"),n=c+2}else if(r.startsWith("<!--",n)){let c=r.indexOf("-->",n);c<0&&s("Unterminated comment"),n=c+3}else if(r.startsWith("<!DOCTYPE",n)||r.startsWith("<!doctype",n))s("Document type declarations are not accepted");else return}},a=()=>{let c=Rk.exec(r.slice(n,n+256));return c===null?s("Expected a name"):(n+=c[0].length,c[0])},o=c=>{c>vk&&s("XML nests too deeply"),e+=1,e>kk&&s("XML has too many nodes"),r[n]!=="<"&&s("Expected an element"),n+=1;let l=a(),u={};for(;;){for(;/\s/.test(r[n]??"");)n+=1;if(r.startsWith("/>",n))return n+=2,{name:l,attributes:u,children:[]};if(r[n]===">"){n+=1;break}let m=a();for(;/\s/.test(r[n]??"");)n+=1;for(r[n]!=="="&&s(`Expected = after attribute ${m}`),n+=1;/\s/.test(r[n]??"");)n+=1;let g=r[n];if(g!=='"'&&g!=="'")return s("Expected a quoted attribute value");let y=r.indexOf(g,n+1);y<0&&s("Unterminated attribute value");let w=r.slice(n+1,y);w.includes("<")&&s("Attribute values must not contain <"),u[m]=Ef(w),n=y+1}let p=[],f="",h=()=>{f.length>0&&(p.push(f),e+=1,f="")};for(;;){if(n>=r.length&&s(`Unterminated element <${l}>`),r.startsWith("</",n)){n+=2;let y=a();for(y!==l&&s(`Expected </${l}> but found </${y}>`);/\s/.test(r[n]??"");)n+=1;return r[n]!==">"&&s("Expected >"),n+=1,h(),{name:l,attributes:u,children:p}}if(r.startsWith("<![CDATA[",n)){let y=r.indexOf("]]>",n);y<0&&s("Unterminated CDATA section"),f+=r.slice(n+9,y),n=y+3;continue}if(r.startsWith("<!--",n)){let y=r.indexOf("-->",n);y<0&&s("Unterminated comment"),n=y+3;continue}if(r.startsWith("<?",n)){let y=r.indexOf("?>",n);y<0&&s("Unterminated processing instruction"),n=y+2;continue}if(r[n]==="<"){h(),p.push(o(c+1));continue}let m=r.indexOf("<",n),g=m<0?r.length:m;f+=Ef(r.slice(n,g)),n=g}};i();let d=o(0);return i(),n<r.length&&s("Unexpected content after the root element"),d}function Y(t,n){return t.children.filter(e=>typeof e!="string"&&(n===void 0||e.name===n))}function Be(t){return t.children.map(n=>typeof n=="string"?n:Be(n)).join("")}var zr="3",Ek=/(?:^|[\\/])cypress[\\/]|\.cy\.[cm]?[jt]sx?$/,Ck=/webpack:\/\/|__cypress|CypressError/;function $f(t){let n=t.slice(0,4096).replace(/^\uFEFF/,"");return/^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<testsuites?\b/.test(n)}function pn(t){if(t.name==="testsuite")return[t];if(t.name!=="testsuites")throw new Error("A JUnit report's root must be testsuites.");let n=[],e=r=>{for(let s of Y(r,"testsuite"))n.push(s),e(s)};return e(t),n}function fd(t){let n=new Map;for(let e of Y(t,"properties"))for(let r of Y(e,"property")){let s=r.attributes.name;s!==void 0&&n.set(s,r.attributes.value??Be(r))}return n}function Nk(t,n){if(t.name!=="testsuites"||t.attributes.id===void 0)return!1;let e=n.flatMap(r=>Y(r,"testcase").map(s=>({suite:r,testcase:s})));return e.length>0&&e.every(({suite:r,testcase:s})=>s.attributes.classname===r.attributes.name)}function Ok(t){let n=Object.entries(t.attributes).find(([s])=>s.endsWith("noNamespaceSchemaLocation"))?.[1];if(t.name!=="testsuite"||n===void 0||!n.includes("surefire"))return;let e=fd(t),r=`${e.get("surefire.test.class.path")??""}:${e.get("java.class.path")??""}`;return/[\\/]testng-[\d.]+\.jar/.test(r)?"surefire-testng":"surefire-junit"}var $k=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/;function Dk(t){let n=t.attributes.name??"",e=Y(t,"properties");return t.name==="testsuite"&&t.attributes.timestamp!==void 0&&t.attributes.hostname!==void 0&&e.length===1&&e.every(r=>Y(r,"property").length===0)&&$k.test(n)&&Y(t,"testcase").every(r=>r.attributes.classname===n)}function hd(t){if(t.some(e=>/\bat org\.testng\./.test(e)))return"testng";let n=e=>/\bat org\.junit\./.test(e)||/<testcase\b[^>]*\bname="[^"]*\(\)"/.test(e);return t.some(n)?"junit":void 0}function Mk(t,n){let e=Ok(t);if(e!==void 0)return e;if(Dk(t))return"gradle";let r=pn(t),s=t.name==="testsuites"?t.attributes.name:void 0;if(r.some(o=>fd(o).has("capabilities")))return"webdriverio";if(s==="vitest tests")return"vitest";if(s==="jest tests")return"jest";if(s==="pytest tests"||r.some(o=>o.attributes.name==="pytest"))return"pytest";let i=r.some(o=>o.attributes.name==="Root Suite"),a=r.some(o=>Ek.test(o.attributes.file??""));return i&&a||Ck.test(n)?"cypress":i?"mocha":Nk(t,r)?"playwright":"unknown"}function fn(t){let n=Number.parseFloat(t??"");return Number.isFinite(n)&&n>=0?Math.round(n*1e3):0}function Lk(t){if(t===void 0)return;let n=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?$/.test(t)?`${t}Z`:t,e=new Date(n);return Number.isNaN(e.getTime())?void 0:e.toISOString()}function md(t){return t.map(n=>Lk(n.attributes.timestamp)).filter(n=>n!==void 0).sort()[0]}function Ii(t,n){return t.name==="testsuites"&&t.attributes.time!==void 0?fn(t.attributes.time):n.reduce((e,r)=>e+fn(r.attributes.time),0)}function Ai(t,n,e={retriedAsSkipped:!0}){let r=Y(t,"failure")[0]??Y(t,"error")[0]??void 0,s=Y(t,"system-err").map(i=>Be(i).trim()).filter(i=>i!=="").join(`
116
+ `);if(r!==void 0){let i=Be(r).trim(),a=i!==""?i:s!==""?s:void 0,o=e.messageFromBody===!0?i.split(`
117
+ `)[0]?.trim():void 0,d=r.attributes.message??(o===""?void 0:o),c=xe(a,n);return{status:"failed",errors:[{...d===void 0?{}:{message:d},...r.attributes.type===void 0?{}:{name:r.attributes.type},...a===void 0?{}:{stack:a},...c===void 0?{}:{location:c}}]}}if(Y(t,"skipped").length>0){if(e.retriedAsSkipped===!0&&s!==""){let i=xe(s,n),a=s.split(`
118
+ `)[0]?.replace(/^\w*Error:\s*/,"");return{status:"failed",errors:[{...a===void 0?{}:{message:a},stack:s,...i===void 0?{}:{location:i}}]}}return{status:"skipped",errors:[]}}return{status:"passed",errors:[]}}function _k(t,n,e){if(e===""||t===e||!t.endsWith(` ${e}`))return[t];let r=t.slice(0,-(e.length+1));return n===""||n==="Root Suite"?[r,e]:r===n?[n,e]:r.endsWith(` ${n}`)?[r.slice(0,-(n.length+1)),n,e]:[r,e]}function hn(t,n,e,r,s={}){return{status:t,retry:e,duration:r,errors:n,attachments:s.attachments??[],stdout:s.stdout??[],stderr:s.stderr??[],steps:[]}}var jk=/^\[\[ATTACHMENT\|(.+)\]\]$/,Fk={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webm":"video/webm",".zip":"application/zip",".md":"text/markdown",".txt":"text/plain",".json":"application/json"};function Bk(t,n){let e=[],r=[];for(let i of Y(t,"system-out")){let a=[];for(let d of Be(i).split(/\r?\n/)){let c=jk.exec(d.trim());if(c?.[1]===void 0){a.push(d);continue}let l=c[1],u=Pk(l)||n===void 0?l:Sk(Tk(n),l),p=Ak(l),f=/\.[^.]+$/.exec(p)?.[0]?.toLowerCase()??"";e.push({name:p==="error-context.md"?"error-context":p,contentType:Fk[f]??"application/octet-stream",path:u})}let o=a.join(`
119
+ `).trim();o!==""&&r.push(o)}let s=Y(t,"system-err").map(i=>Be(i).trim()).filter(i=>i!=="");return{attachments:e,stdout:r,stderr:s}}function Cf(t,n){let e=[],r=pn(t),s="";for(let a of r){a.attributes.file!==void 0&&a.attributes.file!==""&&(s=a.attributes.file);let o=a.attributes.name??"";for(let d of Y(a,"testcase")){let c=d.attributes.name??"",l=d.attributes.classname??c,u=Ai(d,s);e.push({file:s,titlePath:_k(c,o,l),projectId:"",attempts:[hn(u.status,u.errors,0,fn(d.attributes.time))]})}}let i=md(r);return{framework:n,format:"junit-xml",adapterVersion:zr,...i===void 0?{}:{startTime:i},duration:Ii(t,r),projects:[{id:"",name:"",retries:0}],tests:e,errors:[],interrupted:!1,warnings:["final-attempt-only"]}}function Vk(t){let n=[],e=new Set;for(let r of pn(t)){let s=fd(r),i=s.get("file")??r.attributes.file??"",a=(s.get("capabilities")??"").split(".")[0]??"";e.add(a);let o=s.get("suiteName")??r.attributes.name??"",d=new Map,c=[];for(let l of Y(r,"testcase")){let u=l.attributes.name??"",p=Ai(l,i),f=d.get(u);f===void 0&&(f=[],d.set(u,f),c.push(u)),f.push(hn(p.status,p.errors,f.length,fn(l.attributes.time)))}for(let l of c)n.push({file:i,titlePath:o===""?[l]:[o,l],projectId:a,attempts:d.get(l)??[]})}return{framework:"webdriverio",format:"junit-xml",adapterVersion:zr,projects:[...e].map(r=>({id:r,name:r,retries:0})),tests:n,errors:[],interrupted:!1,warnings:[]}}function Vr(t,n,e,r,s={}){let i=pn(t),a=[],o=new Set;for(let c of i)for(let l of Y(c,"testcase")){let{file:u,titlePath:p,projectId:f="",line:h}=r(c,l);o.add(f);let m=Ai(l,u,s);a.push({file:u,titlePath:p,...h===void 0?{}:{line:h},projectId:f,attempts:[hn(m.status,m.errors,0,fn(l.attributes.time),Bk(l,e))]})}let d=md(i);return{framework:n,format:"junit-xml",adapterVersion:zr,...d===void 0?{}:{startTime:d},duration:Ii(t,i),projects:[...o.size===0?new Set([""]):o].map(c=>({id:c,name:c,retries:0})),tests:a,errors:[],interrupted:!1,warnings:[...s.warnings??[]]}}function zk(t){let n=t.attributes.name??"";for(let e of Y(t,"testcase")){let r=Y(e,"failure")[0]??Y(e,"error")[0],s=r===void 0?void 0:xe(Be(r),n)?.file;if(s?.replaceAll("\\","/").endsWith(`/${n}`))return s}return n}function Hk(t,n){let e=new Map(pn(t).map(r=>[r,zk(r)]));return Vr(t,"playwright",n,(r,s)=>({file:e.get(r)??r.attributes.name??"",titlePath:(s.attributes.name??"").split(" \u203A "),projectId:r.attributes.hostname??""}),{warnings:["final-attempt-only"]})}function Uk(t){let n=(t.attributes.classname??"").split(".").filter(a=>a!==""),e=n.length;for(;e>1&&/^[A-Z]/.test(n[e-1]??"");)e-=1;let r=n.slice(e),s=t.attributes.file,i=Number.parseInt(t.attributes.line??"",10);return{file:s??`${n.slice(0,e).join("/")}.py`,titlePath:[...r,t.attributes.name??""],...Number.isInteger(i)&&i>=0?{line:i+1}:{}}}var Df=new Set(["failure","error"]),qk=new Set(["rerunFailure","rerunError"]),Gk=new Set(["flakyFailure","flakyError"]);function un(t,n){return Y(t,n).map(e=>Be(e).trim()).filter(e=>e!=="").join(`
120
+ `)}function Nf(t,n,e,r,s){let i=!Df.has(t.name),a=(i?un(t,"stackTrace"):Be(t).trim())||void 0,o=t.attributes.message,d=xe(a,r);return hn(n,[{...o===void 0?{}:{message:o},...t.attributes.type===void 0?{}:{name:t.attributes.type},...a===void 0?{}:{stack:a},...d===void 0?{}:{location:d}}],e,s,i?{stdout:[un(t,"system-out")].filter(c=>c!==""),stderr:[un(t,"system-err")].filter(c=>c!=="")}:{})}function Mf(t,n){let e=Y(t),r=fn(t.attributes.time),s={stdout:[un(t,"system-out")].filter(o=>o!==""),stderr:[un(t,"system-err")].filter(o=>o!=="")},i=e.find(o=>Df.has(o.name));if(i!==void 0){let o=e.filter(d=>qk.has(d.name));return[i,...o].map((d,c)=>Nf(d,"failed",c,n,r))}let a=e.filter(o=>Gk.has(o.name));return e.some(o=>o.name==="skipped")?[hn("skipped",[],0,r,s)]:[...a.map((o,d)=>Nf(o,"failed",d,n,r)),hn("passed",[],a.length,r,s)]}function Of(t,n){let e=[];for(let r of pn(t))for(let s of Y(r,"testcase")){let i=s.attributes.classname??r.attributes.name??"",a=ln(i),d=[...i.split("$").filter(l=>l!==""),s.attributes.name??""];if(n==="junit"){e.push({file:a,titlePath:d,projectId:"",attempts:Mf(s,a)});continue}let c=Ai(s,a,{});e.push({file:a,titlePath:d,projectId:"",attempts:[hn(c.status,c.errors,0,fn(s.attributes.time),{stdout:[un(s,"system-out")].filter(l=>l!==""),stderr:[un(s,"system-err")].filter(l=>l!=="")})]})}return{framework:n,format:"junit-xml",adapterVersion:zr,duration:Ii(t,pn(t)),projects:[{id:"",name:"",retries:0}],tests:e,errors:[],interrupted:!1,warnings:n==="testng"?["testng-retries-uncorrelated"]:[]}}var Kk=/^([\w$]+\[\d+\])\(.*\)$/s;function Wk(t,n){return n==="testng"?Kk.exec(t)?.[1]??t:t.endsWith("()")?t.slice(0,-2):t}function Jk(t,n){let e=new Map;for(let i of Y(t,"testcase")){let a=i.attributes.classname??t.attributes.name??"",o=i.attributes.name??"",d=`${a}\0${o}`,c=e.get(d)??{className:a,name:o,cases:[]};e.set(d,c),c.cases.push(i)}let r=[...e.values()].map(({className:i,name:a,cases:o})=>{let d=ln(i),c=i.split("$").filter(l=>l!=="");return{file:d,titlePath:[...c,Wk(a,n)],projectId:"",attempts:o.flatMap(l=>Mf(l,d)).map((l,u)=>({...l,retry:u}))}}),s=md([t]);return{framework:n,format:"junit-xml",adapterVersion:zr,...s===void 0?{}:{startTime:s},duration:Ii(t,[t]),projects:[{id:"",name:"",retries:0}],tests:r,errors:[],interrupted:!1,warnings:[]}}function Lf(t,n){let e=Ri(t),r=Mk(e,t),s=(r==="unknown"||r==="mocha")&&n.framework!==void 0?n.framework:r,i=n.reportPath;switch(s){case"surefire-junit":return Of(e,"junit");case"surefire-testng":return Of(e,"testng");case"gradle":return Jk(e,n.jvmFramework??hd([t])??"unknown");case"cypress":return Cf(e,"cypress");case"mocha":return Cf(e,"mocha");case"webdriverio":return Vk(e);case"playwright":return Hk(e,i);case"vitest":return Vr(e,"vitest",i,(a,o)=>({file:o.attributes.file??o.attributes.classname??a.attributes.name??"",titlePath:(o.attributes.name??"").split(" > ")}),{warnings:["final-attempt-only"]});case"jest":{let a=Vr(e,"jest",i,(o,d)=>({file:d.attributes.file??"",titlePath:[(d.attributes.name??"").trim()]}),{messageFromBody:!0,warnings:["final-attempt-only"]});return a.tests.some(o=>o.file==="")?{...a,warnings:[...a.warnings,"test-file-unrecorded"]}:a}case"pytest":return Vr(e,"pytest",i,(a,o)=>Uk(o));case"unknown":return Vr(e,"unknown",i,(a,o)=>{let d=o.attributes.classname??"",c=o.attributes.name??"";return{file:o.attributes.file??a.attributes.file??"",titlePath:d===""||d===c?[c]:[d,c]}},{warnings:["final-attempt-only","junit-producer-unknown"]})}}var Xk="1";function jf(t){let n=t.slice(0,4096).replace(/^\uFEFF/,"");return/^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<testng-results\b/.test(n)}function Ff(t){if(t===void 0)return;let n=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?) ?(UTC|GMT|Z|[+-]\d\d:?\d\d)?$/.exec(t.trim());if(n?.[1]===void 0||n[2]===void 0)return;let e=n[2],r=e==="UTC"||e==="GMT"||e==="Z"?"Z":e.includes(":")?e:`${e.slice(0,3)}:${e.slice(3)}`,s=new Date(`${n[1]}${r}`);return Number.isNaN(s.getTime())?void 0:s.toISOString()}function _f(t){if(t===void 0)return;let n=Be(t).trim();return n===""?void 0:n}function Yk(t,n){let e=Y(t,"exception")[0];if(e===void 0)return[];let r=_f(Y(e,"message")[0]),s=_f(Y(e,"full-stacktrace")[0]),i=xe(s,n);return[{...r===void 0?{}:{message:r},...e.attributes.class===void 0?{}:{name:e.attributes.class},...s===void 0?{}:{stack:s},...i===void 0?{}:{location:i}}]}function Qk(t){return Y(t,"params").flatMap(n=>Y(n,"param").map(e=>Be(Y(e,"value")[0]??e).trim()))}function Zk(t){let e=Y(t,"reporter-output").flatMap(r=>Y(r,"line").map(s=>Be(s).trim())).filter(r=>r!=="").join(`
121
+ `);return e===""?[]:[e]}var eR={PASS:"passed",FAIL:"failed",SKIP:"skipped"};function tR(t,n,e){let{method:r}=t,s=Ff(r.attributes["started-at"]),i=Number.parseInt(r.attributes["duration-ms"]??"",10);return{status:t.retried?"failed":eR[r.attributes.status??""]??"skipped",retry:n,...s===void 0?{}:{startTime:s},duration:Number.isFinite(i)&&i>=0?i:0,errors:Yk(r,e),attachments:[],stdout:Zk(r),stderr:[],steps:[]}}function nR(t,n){let e=t.attributes.name??"",r=ln(e),s=new Map,i=new Map;for(let a of Y(t,"test-method")){let o=a.attributes.name??"",d=a.attributes["is-config"]==="true";if(d&&a.attributes.status!=="FAIL")continue;let c=Qk(a),l=d?`${o} (configuration)`:o;if(!d&&c.length>0){let p=i.get(o)??new Map;i.set(o,p);let f=JSON.stringify(c),h=p.get(f)??p.size;p.set(f,h),l=`${o}[${h}]`}let u=s.get(l)??[];s.set(l,u),u.push({method:a,retried:a.attributes.retried==="true"})}return[...s].map(([a,o])=>{let d=[...o.filter(c=>c.retried),...o.filter(c=>!c.retried)];return{file:r,titlePath:[e,a],projectId:n,attempts:d.map((c,l)=>tR(c,l,r))}})}function Bf(t){let n=Ri(t);if(n.name!=="testng-results")throw new Error("A TestNG report's root must be testng-results.");let e=Y(n,"suite"),r=e.flatMap(c=>Y(c,"test")),s=r.length>1,i=r.flatMap(c=>Y(c,"class").flatMap(l=>nR(l,s?c.attributes.name??"":""))),a=e.map(c=>Ff(c.attributes["started-at"])).filter(c=>c!==void 0).sort()[0],o=e.reduce((c,l)=>{let u=Number.parseInt(l.attributes["duration-ms"]??"",10);return c+(Number.isFinite(u)&&u>=0?u:0)},0),d=s?r.map(c=>c.attributes.name??""):[""];return{framework:"testng",format:"testng-xml",adapterVersion:Xk,...a===void 0?{}:{startTime:a},duration:o,projects:[...new Set(d)].map(c=>({id:c,name:c,retries:0})),tests:i,errors:[],interrupted:!1,warnings:[]}}import{dirname as oR,isAbsolute as dR,join as cR}from"node:path";import{isAbsolute as Pi,relative as rR,sep as Hr}from"node:path";var Ti="1970-01-01T00:00:00.000Z";function Ur(t,n){switch(t){case"playwright":case"vitest":case"jest":case"mocha":case"pytest":case"junit":case"testng":case"cucumber":case"unknown":return n;case"cypress":return[n.filter(e=>e!=="").join(" ")];case"webdriverio":return n.filter(e=>e!=="").slice(-2)}}function Vf(t,n,e,r,s){return B("tst",[n,e,r,...t==="playwright"?[]:[`framework:${t}`],...Ur(t,s)])}function Si(t,n){if(!Pi(n))return;let e=rR(t,n);if(!(Pi(e)||e===".."||e.startsWith(`..${Hr}`)))return e.split(Hr).join("/")}function qr(t){let n=t.trim();return n.startsWith("file://")&&(n=decodeURIComponent(n.slice(7)).replaceAll("\\","/"),/^\/[A-Za-z]:\//.test(n)&&(n=n.slice(1))),n.replaceAll("\\","/")}function zf(t,n,e){let r=qr(e),s=Hr==="\\"?r.replaceAll("/","\\"):r;if(Pi(s)||/^[A-Za-z]:\//.test(r))return Si(t,s)??r;let i=r.replace(/^(?:\.\/)+/,"");if(n===void 0)return i;let a=Si(t,n);return a===void 0||a===""?i:`${a}/${i}`}function gd(t,n,e,r,s){let i=t.location===void 0?void 0:{...t.location,file:zf(r,s,t.location.file)};return{errorId:B("err",[n,e]),source:e,...t.message===void 0?{}:{message:t.message},...t.name===void 0?{}:{name:t.name},...t.stack===void 0?{}:{stack:t.stack},...t.snippet===void 0?{}:{snippet:t.snippet},...t.value===void 0?{}:{value:t.value},...i===void 0?{}:{location:i}}}function Hf(t,n,e,r,s){return{title:t.title,duration:t.duration,...t.error===void 0?{}:{error:gd(t.error,n,`${e}.error`,r,s)},steps:t.steps.map((i,a)=>Hf(i,n,`${e}.steps[${a}]`,r,s))}}function sR(t,n){let e=qr(n),r=Hr==="\\"?e.replaceAll("/","\\"):e;return Pi(r)||t===void 0?r:`${t}${Hr}${r.replace(/^(?:\.[/\\])+/,"")}`}function iR(t){let n=t.filter(r=>r.status!=="skipped");return n.length===0?"skipped":n.at(-1)?.status==="passed"?n.some(r=>r.status!=="passed")?"flaky":"expected":"unexpected"}function aR(t,n,e){return t.length===0?"zero-tests":e||t.some(r=>r.attempts.some(s=>s.status==="interrupted"))?"interrupted":n.length>0?"report-errors":"analysis-ready"}function yd(t){if(t===void 0)return;let n=new Date(t);return Number.isNaN(n.getTime())?void 0:n.toISOString()}function Uf(t){let{report:n,reportHash:e,artifact:r,options:s}=t,i=s.workspaceRoot,a=new Set(t.warnings),o=n.projects.map(w=>{let x=w.testDir===void 0?void 0:Si(i,w.testDir);return{projectId:B("prj",[`framework:${n.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=[];n.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 R=zf(i,n.rootDir,w.file),P=Vf(n.framework,i,v,R,w.titlePath);if(c.has(P)){a.add(`duplicate-test-identity:${R}`);return}c.add(P);let N=`$tests[${x}]`,E=w.attempts.map((A,C)=>{let T=B("atm",[P,String(A.retry),"repeat:unknown",String(C)]),I=`${N}.attempts[${C}]`,$=A.errors.map((k,S)=>gd(k,T,`${I}.errors[${S}]`,i,n.rootDir)),D=$.find(k=>k.location!==void 0)?.location;return{attemptId:T,sourceIndex:C,retry:A.retry,repeat:{state:"unknown",reason:"not-serialized-by-report"},status:A.status,duration:A.duration,startTime:yd(A.startTime)??yd(n.startTime)??Ti,workerIndex:0,parallelIndex:0,errors:$,stdout:A.stdout.map(k=>({kind:"text",text:k})),stderr:A.stderr.map(k=>({kind:"text",text:k})),steps:A.steps.map((k,S)=>Hf(k,T,`${I}.steps[${S}]`,i,n.rootDir)),attachments:A.attachments.map((k,S)=>({attachmentId:B("att",[T,String(S)]),name:k.name,contentType:k.contentType,sourceIndex:S,...k.path===void 0?{}:{path:sR(n.rootDir,k.path)},...k.body===void 0?{}:{bodyBase64:k.body}})),annotations:[],...D===void 0?{}:{errorLocation:D}}}),M=iR(w.attempts);l.push({logicalTestId:P,projectId:v,title:w.titlePath.at(-1)??"",titlePath:w.titlePath,tags:[...w.tags??[]].sort(),location:{file:R,...w.line===void 0?{}:{line:w.line},...w.column===void 0?{}:{column:w.column}},timeout:w.timeout??0,expectedStatus:M==="skipped"?"skipped":"passed",status:M,annotations:[],attempts:E})}),l.sort((w,x)=>w.logicalTestId.localeCompare(x.logicalTestId));let u=n.errors.map((w,x)=>gd(w,r.artifactId,`$errors[${x}]`,i,n.rootDir)),p=l.reduce((w,x)=>w+x.attempts.reduce((v,R)=>v+R.attachments.length,0),0),f=l.flatMap(w=>w.attempts.map(x=>x.startTime)).filter(w=>w!==Ti).sort()[0],h=yd(n.startTime)??f??Ti;h===Ti&&a.add("start-time-unavailable");let m={expected:0,unexpected:0,flaky:0,skipped:0};for(let w of l)m[w.status]+=1;let g=n.configFile===void 0?void 0:Si(i,qr(n.configFile)),y=B("run",[e,i,s.gitRoot??"","1.7",`${n.format}:${n.adapterVersion}`]);return{schemaVersion:"1.7",runId:y,framework:n.framework,createdAt:h,workspace:{root:i,...s.gitRoot===void 0?{}:{gitRoot:s.gitRoot}},sourceHashes:{report:e},artifact:r,usability:aR(l,u,n.interrupted),projects:o,...g===void 0?{}:{configFile:g},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:n.duration??0,...m}}}var lR="1",uR=/\.(?:png|jpe?g|webp|gif|mp4|webm)$/i;function Gf(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let n=t;if(!Array.isArray(n.results)||typeof n.stats!="object")return!1;let e=n.results[0];return e===void 0||typeof e=="object"&&e!==null&&"uuid"in e&&Array.isArray(e.suites)&&Array.isArray(e.tests)}function pR(t,n){let e=[],r=s=>{if(typeof s=="string"){let i;try{i=JSON.parse(s)}catch{i=void 0}if(i!==void 0&&typeof i!="string"){r(i);return}let a=typeof i=="string"?i:s;uR.test(a)&&!/^https?:/i.test(a)&&e.push(a);return}if(Array.isArray(s)){for(let i of s)r(i);return}typeof s=="object"&&s!==null&&r(s.value)};return r(t),e.map(s=>{let i=qr(s);return dR(i)||n===void 0?i:cR(n,i)})}function fR(t){let n=JSON.stringify(t.results??[]).slice(0,2e5);return/webpack:\/\/|__cypress|\bcy\.|Cypress/.test(n)?"cypress":/\bbrowser\.|\$\(|webdriverio|wdio/.test(n)?"webdriverio":"cypress"}function qf(t){return t.pending===!0||t.skipped===!0?"skipped":t.state==="passed"||t.pass===!0?"passed":t.timedOut===!0?"timedOut":t.state==="failed"||t.fail===!0?"failed":"skipped"}function hR(t,n,e){let r=t.err;if(typeof r!="object"||r===null)return[];let s=r,i=fe(s.message,`${n}.err.message`),a=fe(s.estack,`${n}.err.estack`),o=fe(s.diff??void 0,`${n}.err.diff`);if(i===void 0&&a===void 0)return[];let d=xe(a,e);return[{...i===void 0?{}:{message:i},...a===void 0?{}:{stack:a},...o===void 0||o===""?{}:{value:o},...d===void 0?{}:{location:d}}]}function Kf(t,n){let e=ne(t,"$report"),r=on(e.results,"$report.results"),s=ne(e.stats,"$report.stats"),i=n.reportPath===void 0?void 0:oR(n.reportPath),a=n.framework??fR(e),o=[],d=[],c=(u,p,f,h)=>{let m=ne(u,p),g=typeof m.title=="string"?m.title:"",y=(typeof m.file=="string"&&m.file!==""?m.file:void 0)??(typeof m.fullFile=="string"&&m.fullFile!==""?m.fullFile:void 0)??h,w=g===""?f:[...f,g];Z(m.tests??[],`${p}.tests`,(x,v)=>{let R=ne(x,v),P=G(R.title,`${v}.title`),N=hR(R,v,y);if(R.isHook===!0){qf(R)!=="passed"&&d.push(...N);return}let E=pR(R.context,i).map(M=>({name:/\.(?:mp4|webm)$/i.test(M)?"video":"screenshot",contentType:/\.(?:mp4|webm)$/i.test(M)?"video/mp4":/\.png$/i.test(M)?"image/png":"image/jpeg",path:M}));o.push({file:y,titlePath:[...w,P],projectId:"",attempts:[{status:qf(R),retry:0,duration:typeof R.duration=="number"?R.duration:0,errors:N,attachments:E,stdout:[],stderr:[],steps:[]}]})}),Z(m.suites??[],`${p}.suites`,(x,v)=>c(x,v,w,y))};r.forEach((u,p)=>{c(u,`$report.results[${p}]`,[],"")});let l=fe(s.start,"$report.stats.start");return{framework:a,format:"mochawesome-json",adapterVersion:lR,...l===void 0?{}:{startTime:l},...typeof s.duration=="number"?{duration:Ke(s.duration,"$report.stats.duration")}:{},projects:[{id:"",name:"",retries:0}],tests:o,errors:d,interrupted:!1,warnings:["final-attempt-only"]}}var mR="1";function Jf(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let n=t;return Array.isArray(n.suites)&&Array.isArray(n.specs)&&typeof n.capabilities=="object"&&n.capabilities!==null}function Xf(t){if(typeof t!="object"||t===null)return"";let n=t;if(typeof n.browserName=="string")return n.browserName;let e=Object.values(n);return e.length>0&&e.every(r=>typeof r=="object"&&r!==null)?"multiremote":""}function yR(t){switch(t){case"passed":return"passed";case"failed":return"failed";default:return"skipped"}}function Wf(t,n,e){if(typeof t!="object"||t===null)return;let r=ne(t,n),s=fe(r.message,`${n}.message`),i=fe(r.name,`${n}.name`),a=fe(r.stack,`${n}.stack`),o=xe(a,e);return{...s===void 0?{}:{message:s},...i===void 0?{}:{name:i},...a===void 0?{}:{stack:a},...o===void 0?{}:{location:o}}}function Yf(t){let n=ne(t,"$report"),e=Z(n.specs,"$report.specs",G),r=[];e.length!==1&&r.push("ambiguous-spec-file");let s=e[0]??"",i=Xf(n.capabilities),a=n.capabilities,o=typeof a.browserVersion=="string"?a.browserVersion:void 0,d=[];return on(n.suites,"$report.suites").forEach((c,l)=>{let u=`$report.suites[${l}]`,p=ne(c,u),f=typeof p.name=="string"?p.name:"",h=new Map,m=[];Z(p.tests??[],`${u}.tests`,(g,y)=>{let w=ne(g,y),x=G(w.name,`${y}.name`),v=Wf(w.error,`${y}.error`,s),R=h.get(x);R===void 0&&(R=[],h.set(x,R),m.push(x)),R.push({status:yR(w.state),retry:R.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:[]})}),Z(p.hooks??[],`${u}.hooks`,(g,y)=>{let w=ne(g,y);if(w.state!=="failed")return;let x=Wf(w.error,`${y}.error`,s),v=typeof w.title=="string"?w.title:"hook",R=typeof w.associatedTest=="string"&&w.associatedTest!==""?w.associatedTest:v,P={...x??{},message:`${v}: ${x?.message??"failed"}`},N=h.get(R),E=N?.at(-1);if(N!==void 0&&E!==void 0){E.status!=="failed"&&(N[N.length-1]={...E,status:"failed",errors:[P]});return}h.set(R,[{status:"failed",retry:0,...typeof w.start=="string"?{startTime:w.start}:{},duration:typeof w.duration=="number"?w.duration:0,errors:[P],attachments:[],stdout:[],stderr:[],steps:[]}]),m.push(R)});for(let g of m)d.push({file:s,titlePath:f===""?[g]:[f,g],projectId:i,attempts:h.get(g)??[]})}),{framework:"webdriverio",format:"wdio-json",adapterVersion:mR,...typeof n.start=="string"?{startTime:n.start}:{},...typeof n.start=="string"&&typeof n.end=="string"?{duration:Math.max(0,Date.parse(n.end)-Date.parse(n.start))||0}:{},projects:[{id:i,name:i,retries:0}],tests:d,errors:[],interrupted:!1,warnings:[...r,...o===void 0?[]:[`browser-version:${i}@${o}`]]}}var Eh=oi(ns(),1);import{lstat as LI,readFile as _I,realpath as Ph}from"node:fs/promises";import{isAbsolute as Sh,relative as jI,resolve as FI,sep as BI}from"node:path";var VI=2*1024*1024,zI=new Set(["it","test","specify","xit","fit","xtest","xspecify"]),HI=new Set(["describe","context","suite","xdescribe","fdescribe","xcontext"]),UI=new Set(["only","skip","fixme","serial","parallel","fail","slow"]);function rs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.type=="string"}function qI(t){let n=[],e=t;for(;rs(e)&&e.type==="MemberExpression";){let i=e.property;rs(i)&&i.type==="Identifier"&&n.unshift(String(i.name)),e=e.object}if(!rs(e)||e.type!=="Identifier")return;n.unshift(String(e.name));let s=n.filter(i=>!UI.has(i)).at(-1);if(s!==void 0){if(HI.has(s))return"suite";if(zI.has(s))return"test"}}function GI(t){if(rs(t)){if(t.type==="StringLiteral")return String(t.value);if(t.type==="TemplateLiteral"){let n=t.expressions,e=t.quasis;if(n.length===0&&e.length===1)return e[0]?.value.cooked}}}function KI(t,n){if(!/\.[cm]?[jt]sx?$/i.test(n))return[];let e=[],r=/\.([cm]?[jt]sx?)$/i.exec(n)?.[1]?.toLowerCase()??"ts";r.includes("t")&&e.push("typescript"),(r.endsWith("x")||!r.includes("t"))&&e.push("jsx");let s;try{s=(0,Eh.parse)(t,{sourceType:"unambiguous",errorRecovery:!0,plugins:e})}catch{return[]}let i=[],a=(o,d)=>{if(Array.isArray(o)){for(let c of o)a(c,d);return}if(rs(o)){if(o.type==="CallExpression"){let c=qI(o.callee),l=o.arguments,u=GI(l[0]);if(c!==void 0&&u!==void 0){if(c==="test"){let p=o.loc;p!==void 0&&i.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(s,[]),i}function WI(t,n){let e=jI(t,n);return e===""||!Sh(e)&&e!==".."&&!e.startsWith(`..${BI}`)}async function JI(t,n){if(!(Sh(n)||n.split("/").includes("..")))try{let e=await Ph(t),r=await Ph(FI(e,n));if(!WI(e,r))return;let s=await LI(r);return!s.isFile()||s.size>VI?void 0:await _I(r,"utf8")}catch{return}}function XI(t,n,e){let r=Ur(t,n),s=Ur(t,e);return r.length===s.length&&r.every((i,a)=>i===s[a])}async function ec(t){let n=t.logicalTests.filter(s=>s.location.line===void 0);if(n.length===0)return t;let e=new Map;for(let s of new Set(n.map(i=>i.location.file))){let i=await JI(t.workspace.root,s);e.set(s,i===void 0?[]:KI(i,s))}let r=t.logicalTests.map(s=>{if(s.location.line!==void 0)return s;let i=(e.get(s.location.file)??[]).filter(o=>XI(t.framework,o.titlePath,s.titlePath)),a=i.length===1?i[0]:void 0;return a===void 0?s:{...s,location:{...s.location,line:a.line,column:a.column}}});return{...t,logicalTests:r}}var Ch=5e4,Nh=256*1024*1024,sA=["kwikqa-json","playwright-json","mochawesome-json","wdio-json","allure-json","ctrf-json","testng-xml","cucumber-json","junit-xml"],iA=new TextDecoder("utf-8",{fatal:!0});function aA(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let n=t,e=n.config;return typeof e=="object"&&e!==null&&"version"in e&&Array.isArray(n.suites)}function oA(t){if(t.bytes.byteLength===0)return{kind:"unreadable",diagnostic:{reasonCode:"empty-input",message:"The report is empty."}};let n;try{n=iA.decode(t.bytes)}catch{return{kind:"unreadable",diagnostic:{reasonCode:"invalid-utf8",message:"The report is not valid UTF-8."}}}if(jf(n))return{kind:"classified",value:{file:t,format:"testng-xml",text:n}};if($f(n))return{kind:"classified",value:{file:t,format:"junit-xml",text:n}};let e;try{e=JSON.parse(n)}catch(s){return{kind:"unreadable",diagnostic:{reasonCode:"invalid-json",message:s instanceof Error?s.message:"The report is not valid JSON."}}}let r=Af(e)?"kwikqa-json":aA(e)?"playwright-json":Gf(e)?"mochawesome-json":Jf(e)?"wdio-json":id(e)||ad(e)||od(e)?"allure-json":ld(e)?"ctrf-json":ud(e)?"cucumber-json":void 0;return r===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, @wdio/json-reporter, Allure results, CTRF, or Cucumber JSON."}}:{kind:"classified",value:{file:t,format:r,text:n,json:e}}}function dA(t,n,e){switch(t.format){case"kwikqa-json":return Pf(t.json);case"mochawesome-json":return Kf(t.json,{...t.file.path===void 0?{}:{reportPath:t.file.path},...n.framework===void 0?{}:{framework:n.framework}});case"wdio-json":return Yf(t.json);case"ctrf-json":return xf(t.json);case"cucumber-json":return Rf(t.json);case"testng-xml":return Bf(t.text);case"junit-xml":return Lf(t.text,{...n.framework===void 0?{}:{framework:n.framework},...t.file.path===void 0?{}:{reportPath:t.file.path},...e===void 0?{}:{jvmFramework:e}});case"playwright-json":throw new Error("Playwright JSON is read by its own parser.");case"allure-json":throw new Error("Allure results are read as one set.")}}function We(t,n,e){let r=e.reasonCode==="missing-report"?"unavailable":"unreadable";return{kind:"unreadable",artifact:{artifactId:B("art",[t??r,n??"bytes"]),kind:"report",availability:r,...n===void 0?{}:{path:n},...t===void 0?{}:{sha256:t},warnings:[]},diagnostic:{...e,...n===void 0?{}:{path:n}}}}function cA(t){if(t.length===1&&t[0]!==void 0)return Ee(t[0].bytes);let n=t.map(e=>`${tA(e.path??"")}\0${Ee(e.bytes)}`).sort();return YI("sha256").update(n.join(`
122
+ `),"utf8").digest("hex")}function ji(t,n){let e=n.reportPath;if(t.length===0)return We(void 0,e,{reasonCode:"missing-report",message:"No report files were found."});let r=cA(t),s=[],i;for(let y of t){let w=oA(y);w.kind==="classified"?s.push(w.value):i??=w.diagnostic}if(s.length===0)return We(r,e,i??{reasonCode:"unsupported-report-format",message:"No report was found."});let a=sA.find(y=>s.some(w=>w.format===y)),o=s.filter(y=>y.format===a),d=s.length-o.length+(t.length-s.length),c=d>0?[`ignored-report-files:${d}`]:[];if(a==="playwright-json"){let y=o[0];return o.length!==1||y===void 0?We(r,e,{reasonCode:"invalid-report-shape",message:"Found several Playwright JSON reports; point --report at one, or merge them with `npx playwright merge-reports`."}):Kn(y.file.bytes,{...n,...y.file.path===void 0?{}:{reportPath:y.file.path}})}let l=a==="junit-xml"?hd(o.map(y=>y.text)):void 0,u;try{u=a==="allure-json"?mf(o.map(y=>({json:y.json,...y.file.path===void 0?{}:{directory:nA(y.file.path)}}))):Sf(o.map(y=>dA(y,n,l)))}catch(y){return We(r,e,{reasonCode:"invalid-report-shape",message:y instanceof Error?y.message:"The report could not be read."})}let p=new Set(Yo[u.framework]),f=u.frameworkVersion,h=f!==void 0&&p.has(f),m=[...u.warnings,...c,f===void 0?"producer-version-unrecorded":h?void 0:`unverified-producer-version:${f}`].filter(y=>y!==void 0),g={artifactId:B("art",[r]),kind:"report",availability:"present",...e===void 0?{}:{path:e},sha256:r,format:u.format,...f===void 0?{}:{formatVersion:f},versionConfidence:h?"verified":"unverified",warnings:[...new Set(m)].sort()};try{return{kind:"parsed",run:Uf({report:u,reportHash:r,artifact:g,options:n,warnings:m})}}catch(y){return We(r,e,{reasonCode:"invalid-report-shape",message:y instanceof Error?y.message:"The report could not be normalized."})}}async function lA(t){return(await QI(t,{withFileTypes:!0})).filter(e=>e.isFile()&&/\.(?:json|xml|log)$/i.test(e.name)).map(e=>rA(t,e.name)).sort()}async function ot(t,n){let e;try{e=await eA(t)}catch(o){let d=o.code==="ENOENT";return We(void 0,t,{reasonCode:d?"missing-report":"read-failed",message:d?`Test report does not exist: ${t}`:`Could not inspect: ${t}`})}let r;if(e.isDirectory()){try{r=await lA(t)}catch{return We(void 0,t,{reasonCode:"read-failed",message:`Could not list report directory: ${t}`})}if(r.length===0)return We(void 0,t,{reasonCode:"missing-report",message:`No .json or .xml report files in ${t}`});if(r.length>Ch)return We(void 0,t,{reasonCode:"read-failed",message:`${t} holds ${r.length} report files; KwikQA reads at most ${Ch} from one directory.`})}else if(e.isFile())r=[t];else return We(void 0,t,{reasonCode:"not-a-file",message:`Test report path is not a regular file or directory: ${t}`});let s=[],i=0;for(let o of r)try{let d=await ZI(o);if(i+=d.byteLength,i>Nh)return We(void 0,t,{reasonCode:"read-failed",message:`Report files under ${t} exceed ${Nh} bytes.`});s.push({path:o,bytes:d})}catch{return We(void 0,t,{reasonCode:"read-failed",message:`Could not read test report: ${o}`})}let a=ji(s,{...n,reportPath:t});return a.kind!=="parsed"||a.run.artifact.format==="playwright-json"?a:{kind:"parsed",run:await ec(await uA(a.run))}}async function uA(t){if(t.framework!=="junit"&&t.framework!=="testng"&&t.framework!=="cucumber")return t;let n=new Wn(t.workspace.root),e=async a=>{let o=await n.resolve(a.file);return o===a.file?a:{...a,file:o}},r=async a=>a.location===void 0?a:{...a,location:await e(a.location)},s=async a=>({...a,...a.error===void 0?{}:{error:await r(a.error)},steps:await Promise.all(a.steps.map(s))}),i=await Promise.all(t.logicalTests.map(async a=>({...a,location:await e(a.location),attempts:await Promise.all(a.attempts.map(async o=>({...o,errors:await Promise.all(o.errors.map(r)),steps:await Promise.all(o.steps.map(s)),...o.errorLocation===void 0?{}:{errorLocation:await e(o.errorLocation)}})))})));return{...t,logicalTests:i}}var wt={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO",vitest:"Vitest",jest:"Jest",mocha:"Mocha",pytest:"pytest",junit:"JUnit",testng:"TestNG",cucumber:"Cucumber",unknown:"Unidentified framework"},zt={"playwright-json":"JSON report","kwikqa-json":"KwikQA reporter","mochawesome-json":"mochawesome report","wdio-json":"@wdio/json-reporter report","allure-json":"Allure results","ctrf-json":"CTRF report","testng-xml":"TestNG results","cucumber-json":"Cucumber JSON report","junit-xml":"JUnit report"};var Oh={playwright:["playwright-json"],cypress:["kwikqa-json","mochawesome-json","junit-xml"],webdriverio:["kwikqa-json","wdio-json","junit-xml"]};function tc(t){return ht.includes(t)}function Je(t){let{framework:n}=t;if(!tc(n))return;let e=t.artifact.format;return e!==void 0&&Oh[n].includes(e)?n:void 0}function dt(t){let{framework:n}=t;if(n==="unknown")return"KwikQA can't tell which test framework wrote this report, so it diagnoses the run but doesn't capture, repair, or validate it.";if(tc(n)){let e=Oh[n].map(i=>zt[i]).join(", "),r=t.artifact.format===void 0?void 0:zt[t.artifact.format],s=r===void 0?"this format":r.endsWith(" results")?r:`a ${r}`;return`KwikQA repairs ${wt[n]} tests from a ${e}, whose test identities its validation can match; it only diagnoses a run read from ${s}.`}return`KwikQA diagnoses ${wt[n]} runs but doesn't capture, repair, or validate them.`}function Fi(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(Fi).join(",")}]`:`{${Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>`${JSON.stringify(e)}:${Fi(r)}`).join(",")}}`}function ge(t,n,e,r,s){return B("evd",[t,n,e,Fi(r),s])}function ve(t,n,e){return B("art",["m2",t,n,e])}function nr(t){return Ee(Buffer.from(Fi(t),"utf8"))}var nc={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"]},pA=["maxPacketBytes","maxArtifactBytes","maxTraceEntries","maxTraceEvents","maxReportFields","maxStackFrames","maxSteps","maxStdioChunks","maxStdioBytes","maxTraceExpandedBytes","maxConsoleEvents","maxNetworkEvents","maxDomDepth","maxDomNodes","maxDomTextBytes","maxSourceFiles","maxSourceBytes","maxSourceLinesPerFile","maxImportDepth","maxDiffBytes","maxDiffHunks"];function rc(t){if(t===null||typeof t!="object")return"policy must be an object";if(typeof t.policyVersion!="string")return"policyVersion must be a string";if(t.policyVersion.length===0)return"policyVersion must not be empty";if(typeof t.workspaceRoot!="string")return"workspaceRoot must be a string";if(t.workspaceRoot.length===0)return"workspaceRoot must not be empty";if(typeof t.includeNetworkBodies!="boolean")return"includeNetworkBodies must be a boolean";if(!Array.isArray(t.sensitiveNames)||t.sensitiveNames.some(n=>typeof n!="string"||n.length===0))return"sensitiveNames must be an array of non-empty strings";if(t.sensitiveNames.some(n=>n.trim()!==n))return"sensitiveNames must not contain surrounding whitespace";for(let n of pA){let e=t[n];if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)return`${n} must be a positive safe integer`}if(!Number.isSafeInteger(t.maxNetworkBodyBytes)||t.maxNetworkBodyBytes<0||t.includeNetworkBodies&&t.maxNetworkBodyBytes===0)return"maxNetworkBodyBytes must be positive when network bodies are enabled"}var fA={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"},hA={button:"button",submit:"button",reset:"button",checkbox:"checkbox",radio:"radio",range:"slider",text:"textbox",search:"searchbox",email:"textbox",tel:"textbox",url:"textbox",password:"textbox"},mA=new Set(["script","style","head","title","meta","link"]);function Ve(t){let n=t[0];return typeof n=="string"?n.toLowerCase():void 0}function Le(t){let n=t[1];if(typeof n!="object"||n===null||Array.isArray(n))return{};let e={};for(let[r,s]of Object.entries(n))typeof s=="string"&&(e[r.toLowerCase()]=s);return e}function _e(t){let n=typeof t[1]=="object"&&t[1]!==null&&!Array.isArray(t[1]);return t.slice(n?2:1)}function Et(t,n=0){let e=Ve(t);if(e===void 0||mA.has(e)||n>12)return"";let r=[];for(let s of _e(t))typeof s=="string"?r.push(s):Array.isArray(s)&&r.push(Et(s,n+1));return r.join(" ").replace(/\s+/g," ").trim()}function wn(t){let n=Le(t),e=n.role;if(e!==void 0&&e.length>0)return e.toLowerCase();let r=Ve(t);if(r!==void 0)return r==="a"?n.href===void 0?void 0:"link":r==="input"?hA[(n.type??"text").toLowerCase()]:fA[r]}function zi(t){let n=Le(t),e=n["aria-label"]??n.alt??n.title;return e!==void 0&&e.trim().length>0?e.trim():Et(t)}function $h(t){return t.replace(/\s+/g," ").trim()}function Bi(t,n,e){let r=$h(t),s=$h(n);return e?r===s:r.toLowerCase().includes(s.toLowerCase())}var yA=new Set(["input","textarea","select"]);function Mh(t){let n=[];for(let e of _e(t))if(typeof e=="string")n.push(e);else if(Array.isArray(e)){let r=Ve(e);if(r!==void 0&&yA.has(r))continue;n.push(Et(e))}return n.join(" ").replace(/\s+/g," ").trim()}function gA(t,n){let e,r=s=>{if(e===void 0){if(Ve(s)==="label"&&Le(s).for===n){e=Mh(s);return}for(let i of _e(s))Array.isArray(i)&&r(i)}};return r(t),e}function Dh(t,n){let e=Le(t),r=[];for(let i of["aria-label","placeholder","title"]){let a=e[i];a!==void 0&&a.trim().length>0&&r.push(a.trim())}for(let i=n.path.length-1;i>=0;i-=1){let a=_h(n.root,n.path.slice(0,i));if(a===void 0)break;if(Ve(a)==="label"){r.push(Mh(a));break}}let s=e.id;if(s!==void 0){let i=gA(n.root,s);i!==void 0&&r.push(i)}return r}var wA=`"((?:[^"\\\\]|\\\\.)*)"|'((?:[^'\\\\]|\\\\.)*)'`;function bA(t){return t.replace(/\\(.)/g,"$1")}function Vi(t){let n=new RegExp(`^(?:${wA})([is])?$`).exec(t.trim());if(n===null)return;let e=n[1]??n[2];if(e!==void 0)return{value:bA(e),caseSensitive:n[3]!=="i"}}function xA(t){let n=/^\[\s*([\w:-]+)\s*=\s*(.+?)\s*\]$/.exec(t.trim());if(n===null)return;let e=n[1]?.toLowerCase(),r=Vi(n[2]??"");if(!(e===void 0||r===void 0))return{describe:`[${e}]`,matches:s=>{let i=Le(s)[e];return i!==void 0&&Bi(i,r.value,r.caseSensitive)}}}function vA(t,n){if(t==="role"){let e=/^([\w-]+)(?:\[(.*)\])?$/.exec(n.trim()),r=e?.[1]?.toLowerCase();if(r===void 0)return;let s=e?.[2];if(s===void 0||s.trim()==="")return{describe:`role=${r}`,matches:o=>wn(o)===r};let i=/^name\s*=\s*(.+)$/.exec(s.trim()),a=i===null?void 0:Vi(i[1]??"");return a===void 0?void 0:{describe:`role=${r}[name]`,matches:(o,d)=>wn(o)===r&&[zi(o),...Dh(o,d)].some(c=>Bi(c,a.value,a.caseSensitive))}}if(t==="label"){let e=Vi(n);return e===void 0?void 0:{describe:"label",matches:(r,s)=>Dh(r,s).some(i=>Bi(i,e.value,e.caseSensitive))}}if(t==="text"){let e=Vi(n);if(e===void 0)return;let r=s=>Bi(Et(s),e.value,e.caseSensitive);return{describe:"text",matches:s=>r(s)&&!_e(s).some(i=>Array.isArray(i)&&r(i))}}if(t==="testid"||t==="attr")return xA(n)}function kA(t){let n=t.match(/^[A-Za-z][\w-]*|#[\w-]+|\.[\w-]+|\[[^\]]*\]/g);if(n===null||n.join("")!==t)return;let e=[];for(let r of n)if(r.startsWith("#")){let s=r.slice(1);e.push(i=>Le(i).id===s)}else if(r.startsWith(".")){let s=r.slice(1);e.push(i=>(Le(i).class??"").split(/\s+/).includes(s))}else if(r.startsWith("[")){let s=/^\[\s*([\w:-]+)\s*(?:=\s*["']?([^"'\]]*)["']?)?\s*\]$/.exec(r),i=s?.[1]?.toLowerCase();if(i===void 0)return;let a=s?.[2];e.push(o=>{let d=Le(o)[i];return d===void 0?!1:a===void 0||a===""?!0:d===a})}else{let s=r.toLowerCase();e.push(i=>Ve(i)===s)}return{describe:t,matches:r=>e.every(s=>s(r))}}function RA(t){let n=t.trim(),e=/^internal:([\w-]+)=([\s\S]+)$/.exec(n);if(e!==null)return vA(e[1]??"",e[2]??"");let r=/^role=([\w-]+)$/.exec(n);if(r!==null){let s=r[1]?.toLowerCase();return s===void 0?void 0:{describe:n,matches:i=>wn(i)===s}}return kA(n)}function IA(t){let n=[],e="",r;for(let s=0;s<t.length;s+=1){let i=t[s];if(i!==void 0){if(r!==void 0){if(i==="\\"){e+=i+(t[s+1]??""),s+=1;continue}i===r&&(r=void 0),e+=i;continue}if(i==='"'||i==="'"){r=i,e+=i;continue}if(i===">"&&t[s+1]===">"){n.push(e),e="",s+=1;continue}e+=i}}return n.push(e),n.map(s=>s.trim()).filter(s=>s.length>0)}function AA(t){if(/^(?:internal:|role=)/.test(t))return[t];let n=[],e="",r=0,s;for(let i of t){if(s!==void 0){i===s&&(s=void 0),e+=i;continue}if((i==='"'||i==="'")&&(s=i),(i==="["||i==="(")&&(r+=1),(i==="]"||i===")")&&(r=Math.max(0,r-1)),r===0&&(i===" "||i===">")){e.trim()!==""&&n.push(e.trim()),e="";continue}e+=i}return e.trim()!==""&&n.push(e.trim()),n.length===0?[t]:n}function Lh(t,n){let e=[{node:t,path:n}];return _e(t).forEach((r,s)=>{Array.isArray(r)&&e.push(...Lh(r,[...n,s]))}),e}function _h(t,n){let e=t;for(let r of n){let s=_e(e)[r];if(!Array.isArray(s))return;e=s}return e}function ss(t,n){if(!Array.isArray(t))return{kind:"unsupported",reason:"snapshot root is not an element"};let e=IA(n).flatMap(AA);if(e.length===0)return{kind:"unsupported",reason:"empty selector"};let r=[{node:t,path:[]}];for(let s of e){if(s===".."){let o=new Map;for(let d of r){if(d.path.length===0)continue;let c=d.path.slice(0,-1),l=_h(t,c);l!==void 0&&o.set(c.join("."),{node:l,path:c})}r=[...o.values()];continue}let i=RA(s);if(i===void 0)return{kind:"unsupported",reason:s};let a=new Map;for(let o of r)for(let d of Lh(o.node,o.path))i.matches(d.node,{root:t,path:d.path})&&a.set(d.path.join("."),d);if(r=[...a.values()],r.length===0)break}return{kind:"resolved",matches:r}}var TA=/\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001B]*(?:\u0007|\u001B\\))/g;function bt(t){return t.replace(TA,"")}function ce(t,n,e,r){let s=bt(t),i=[];for(let a of[...new Set(r.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(s=s.replace(d,(l,u)=>(c+=1,`${u}[REDACTED]`)),c===0){let l=new RegExp(`(${o}\\s*[:=]\\s*)\\S+`,"gi");s=s.replace(l,(u,p)=>(c+=1,`${p}[REDACTED]`))}c>0&&i.push({redactionId:B("red",[n,e,a]),ruleId:`sensitive-name:${a}`,channel:n,locator:e,action:"mask",count:c})}return{value:s,records:i}}function is(t,n){let e=t.toLowerCase();return n.map(r=>r.toLowerCase()).sort().find(r=>e===r||e.includes(r))}function Hi(t,n,e,r){let s=[],i=new Map;for(let o of t){let d=is(o.name,r);if(d===void 0){s.push(o);continue}i.set(d,(i.get(d)??0)+1)}let a=[...i.entries()].sort(([o],[d])=>o.localeCompare(d)).map(([o,d])=>({redactionId:B("red",[n,e,`header:${o}`]),ruleId:`sensitive-header:${o}`,channel:n,locator:e,action:"remove",count:d}));return{value:s,records:a}}function Ht(t,n,e,r){let s;try{s=new URL(t)}catch{return ce(t,n,e,r)}let i=[];(s.username!==""||s.password!=="")&&(s.username="",s.password="",i.push({redactionId:B("red",[n,e,"url-userinfo"]),ruleId:"url-userinfo",channel:n,locator:e,action:"remove",count:1}));let a=new Map;for(let o of[...s.searchParams.keys()]){let d=is(o,r);d!==void 0&&(s.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)))i.push({redactionId:B("red",[n,e,`query:${o}`]),ruleId:`sensitive-query:${o}`,channel:n,locator:e,action:"mask",count:d});return{value:s.toString(),records:i}}var PA=new Set(["value","data-value","content","__playwright_value_","__playwright_checked_","__playwright_selected_"]),jh=["type","name","id","autocomplete","placeholder","aria-label"];function sc(t,n,e,r){if(t==="")return{value:t,records:[]};let s=n.filter(i=>jh.includes(i.name.toLowerCase())).map(i=>is(i.value,r)).find(i=>i!==void 0);return s===void 0?{value:t,records:[]}:{value:"[REDACTED]",records:[{redactionId:B("red",["dom",e,`text:${s}`]),ruleId:`sensitive-element-text:${s}`,channel:"dom",locator:e,action:"mask",count:1}]}}function ic(t,n,e){let r=t.filter(o=>jh.includes(o.name.toLowerCase())).map(o=>is(o.value,e)).find(o=>o!==void 0),s=[],i=new Map;for(let o of t){let d=is(o.name,e),c=r!==void 0&&PA.has(o.name.toLowerCase())?r:void 0,l=d??c;if(l===void 0||o.value===""){s.push(o);continue}s.push({name:o.name,value:"[REDACTED]"});let u=d===void 0?`sensitive-element:${l}`:`sensitive-field:${l}`;i.set(u,(i.get(u)??0)+1)}let a=[...i.entries()].sort(([o],[d])=>o.localeCompare(d)).map(([o,d])=>({redactionId:B("red",["dom",n,o]),ruleId:o,channel:"dom",locator:n,action:"mask",count:d}));return{value:s,records:a}}function SA(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function V(t){return typeof t=="string"?t:void 0}function Ae(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Fh(t){return typeof t=="boolean"?t:void 0}function me(t){return SA(t)?t:void 0}function Xe(t){return Array.isArray(t)?t:void 0}function ze(t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return}}function Ui(t){let n=[];return t.split(/\r?\n/).forEach((e,r)=>{let s=e.trim();if(s.length!==0)try{n.push({line:r+1,value:JSON.parse(s),parsed:!0})}catch{n.push({line:r+1,value:void 0,parsed:!1})}}),n}function be(t,n){let e;try{e=typeof t=="string"?t:JSON.stringify(t)??""}catch{return"[unserializable]"}let r=bt(e).replace(/\s+/g," ").trim(),s=Buffer.from(r,"utf8");if(s.byteLength<=n)return r;let i=n;for(;i>0&&((s[i]??0)&192)===128;)i-=1;return`${s.subarray(0,i).toString("utf8")}\u2026`}var Vh=new Set(["script","style","noscript","template","head"]),Bh=120,EA=200,CA={__playwright_value_:"value",__playwright_checked_:"checked",__playwright_selected_:"selected"},NA=new Set(["button","link","textbox","searchbox","checkbox","radio","combobox","listbox","option","menuitem","tab","switch","slider","spinbutton","heading","dialog","img","cell","row"]),zh=["data-testid","data-test-id","data-test","data-qa","data-cy"],OA=new Set(["internal","role","testid","data","name","text","label","attr","has","nth","visible","true","false","exact","css","xpath","and","the"]);function $A(t){let n=[];for(let[e,r]of Object.entries(Le(t))){let s=CA[e];if(s!==void 0){n.push({name:s,value:be(r,Bh)});continue}e.startsWith("__playwright")||/^on[a-z]+$/.test(e)||n.push({name:e,value:be(r,Bh)})}return n.sort((e,r)=>e.name.localeCompare(r.name))}function Hh(t,n){let e,r=(s,i)=>{if(e===void 0){if(Le(s).__playwright_target__===n){e={node:s,path:i};return}_e(s).forEach((a,o)=>{Array.isArray(a)&&r(a,[...i,o])})}};return r(t,[]),e}function DA(t){return _e(t).filter(n=>typeof n=="string").join(" ").replace(/\s+/g," ").trim()}function as(t,n,e){let r=[],s=[],i=0,a=0,o=!1,d=(c,l)=>{if(o)return;let u=Ve(c);if(u===void 0||Vh.has(u))return;if(l>e.maxDepth||a>=e.maxNodes){o=!0;return}let p=`${n}/${a}`,f=$A(c),h=ic(f,p,e.sensitiveNames),m=sc(be(DA(c),EA),f,p,e.sensitiveNames);s.push(...h.records,...m.records);let g=h.value.map(x=>` ${x.name}="${x.value}"`).join(""),y=`${" ".repeat(l)}<${u}${g}>${m.value===""?"":` ${m.value}`}`,w=Buffer.byteLength(y,"utf8")+1;if(i+w>e.maxBytes){o=!0;return}r.push(y),i+=w,a+=1;for(let x of _e(c))Array.isArray(x)&&d(x,l+1)};return d(t,0),{text:r.join(`
123
+ `),redactions:s,nodes:a,truncated:o}}function os(t,n=[],e){let r=Le(t),s=wn(t),i=zi(t),a=be(i===""&&e!==void 0?e:i,80),o=[s===void 0?`<${Ve(t)??"?"}>`:s];a!==""&&o.push(JSON.stringify(a));for(let c of[...new Set([...n,...zh,"id","name"])]){let l=r[c];l!==void 0&&l!==""&&o.push(`${c}=${be(l,60)}`)}let d=r.placeholder;return d!==void 0&&d!==""&&o.push(`placeholder=${JSON.stringify(be(d,60))}`),o.join(" ")}function rr(t){let n=t.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(e=>e.length>=3&&!OA.has(e));return[...new Set(n)]}function MA(t){return/(?:^|>>\s*)(?:internal:)?role=([\w-]+)/.exec(t)?.[1]?.toLowerCase()}function LA(t){return[...t.matchAll(/\[\s*([\w:-]+)\s*=/g)].map(n=>n[1]?.toLowerCase()).filter(n=>n!==void 0&&n!=="name")}function qi(t,n,e,r,s,i){let a=rr(n),o=MA(n),d=LA(n),c=new Set(e.map(v=>v.path.join("."))),l=[],u=0,p=new Map,f=v=>{if(Ve(v)==="label"){let R=Le(v).for;R!==void 0&&p.set(R,Et(v))}for(let R of _e(v))Array.isArray(R)&&f(R)};f(t);let h=(v,R,P)=>{let N=Ve(v);if(N===void 0||Vh.has(N))return;let E=Le(v),M=(E.id===void 0?void 0:p.get(E.id))??P,A=wn(v),C=d.some(I=>E[I]!==void 0)||zh.some(I=>E[I]!==void 0);if(A!==void 0&&NA.has(A)||C){let I=os(v,d,M),$=`${I} ${be(Et(v),200)}`.toLowerCase(),D=c.has(R.join(".")),k=(D?100:0)+(o!==void 0&&A===o?2:0)+a.filter(S=>$.includes(S)).length*3;l.push({line:`${D?"match: ":""}${I}`,score:k,order:u++})}let T=N==="label"?Et(v):P;_e(v).forEach((I,$)=>{Array.isArray(I)&&h(I,[...R,$],T)})};h(t,[],void 0);let m=[...l].sort((v,R)=>R.score-v.score||v.order-R.order),g=[],y=[],w=0,x=m.length>s.maxItems;for(let v of m.slice(0,s.maxItems)){let R=ce(v.line,"dom",r,i),P=Buffer.byteLength(R.value,"utf8")+1;if(w+P>s.maxBytes){x=!0;break}y.push(...R.records),g.push(R.value),w+=P}return{text:g.join(`
124
+ `),redactions:y,nodes:g.length,truncated:x}}import{open as BA}from"node:fs/promises";import{realpath as Uh,stat as _A}from"node:fs/promises";import{isAbsolute as Kh,relative as jA,resolve as FA,sep as qh}from"node:path";function Gh(t,n){let e=jA(t,n);if(e==="")return"";if(!(e===".."||e.startsWith(`..${qh}`)||Kh(e)))return e.split(qh).join("/")}async function ds(t,n){if(n.includes("\0"))return{kind:"unauthorized",message:"Path contains a NUL byte."};let e;try{e=await Uh(t)}catch{return{kind:"unreadable",message:"Authorized root could not be resolved."}}let r=Kh(n)?n:FA(e,n);if(Gh(e,r)===void 0)return{kind:"unauthorized",message:"Path escapes the authorized root."};let s;try{s=await Uh(r)}catch(a){return a.code==="ENOENT"?{kind:"unavailable",message:"Authorized artifact does not exist."}:{kind:"unreadable",message:"Authorized artifact could not be resolved."}}let i=Gh(e,s);if(i===void 0)return{kind:"unauthorized",message:"Resolved path escapes the authorized root."};try{if(!(await _A(s)).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:s,relativePath:i}}function ac(t){return t.length===0||t.includes("\0")||t.includes("\\")||t.startsWith("/")||/^[A-Za-z]:/.test(t)?!1:t.split("/").every(e=>e!==".."&&e!==".")}async function Q(t,n,e){let r=await ds(t,n);if(r.kind!=="authorized")return r;let s;try{s=await BA(r.absolutePath,"r");let i=await s.stat();if(i.size>e)return{kind:"over-budget",message:`Artifact exceeds the ${e}-byte limit.`,relativePath:r.relativePath};let a=new Uint8Array(i.size),o=0;for(;o<a.byteLength;){let d=await s.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:r.relativePath}:{kind:"read",bytes:a,sha256:Ee(a),relativePath:r.relativePath}}catch{return{kind:"unreadable",message:"Authorized artifact could not be read.",relativePath:r.relativePath}}finally{await s?.close()}}import{createRequire as VA}from"module";var zA=VA("/"),or,HA,UA;try{or=zA("worker_threads"),HA=or.Worker,UA=or.isMarkedAsUntransferable}catch{}var Oe=Uint8Array,sr=Uint16Array,qA=Int32Array,Wh=new Oe([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]),Jh=new Oe([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]),GA=new Oe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Xh=function(t,n){for(var e=new sr(31),r=0;r<31;++r)e[r]=n+=1<<t[r-1];for(var s=new qA(e[30]),r=1;r<30;++r)for(var i=e[r];i<e[r+1];++i)s[i]=i-e[r]<<5|r;return{b:e,r:s}},or=Xh(Wh,2),Yh=or.b,KA=or.r;Yh[28]=258,KA[258]=28;var Qh=Xh(Jh,0),WA=Qh.b,$M=Qh.r,lc=new sr(32768);for(ae=0;ae<32768;++ae)Ct=(ae&43690)>>1|(ae&21845)<<1,Ct=(Ct&52428)>>2|(Ct&13107)<<2,Ct=(Ct&61680)>>4|(Ct&3855)<<4,lc[ae]=((Ct&65280)>>8|(Ct&255)<<8)>>1;var Ct,ae,ls=(function(t,n,e){for(var r=t.length,s=0,i=new sr(n);s<r;++s)t[s]&&++i[t[s]-1];var a=new sr(n);for(s=1;s<n;++s)a[s]=a[s-1]+i[s-1]<<1;var o;if(e){o=new sr(1<<n);var d=15-n;for(s=0;s<r;++s)if(t[s])for(var c=s<<4|t[s],l=n-t[s],u=a[t[s]-1]++<<l,p=u|(1<<l)-1;u<=p;++u)o[lc[u]>>d]=c}else for(o=new sr(r),s=0;s<r;++s)t[s]&&(o[s]=lc[a[t[s]-1]++]>>15-t[s]);return o}),ps=new Oe(288);for(ae=0;ae<144;++ae)ps[ae]=8;var ae;for(ae=144;ae<256;++ae)ps[ae]=9;var ae;for(ae=256;ae<280;++ae)ps[ae]=7;var ae;for(ae=280;ae<288;++ae)ps[ae]=8;var ae,Zh=new Oe(32);for(ae=0;ae<32;++ae)Zh[ae]=5;var ae;var JA=ls(ps,9,1);var XA=ls(Zh,5,1),oc=function(t){for(var n=t[0],e=1;e<t.length;++e)t[e]>n&&(n=t[e]);return n},ct=function(t,n,e){var r=n/8|0;return(t[r]|t[r+1]<<8)>>(n&7)&e},dc=function(t,n){var e=n/8|0;return(t[e]|t[e+1]<<8|t[e+2]<<16)>>(n&7)},YA=function(t){return(t+7)/8|0},us=function(t,n,e){return(n==null||n<0)&&(n=0),(e==null||e>t.length)&&(e=t.length),new Oe(t.subarray(n,e))};var QA=["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"],Te=function(t,n,e){var r=new Error(n||QA[t]);if(r.code=t,Error.captureStackTrace&&Error.captureStackTrace(r,Te),!e)throw r;return r},ZA=function(t,n,e,r){var s=t.length,i=r?r.length:0;if(!s||n.f&&!n.l)return e||new Oe(0);var a=!e,o=a||n.i!=2,d=n.i;a&&(e=new Oe(s*3));var c=function(Lr){var _r=e.length;if(Lr>_r){var jr=new Oe(Math.max(_r*2,Lr));jr.set(e),e=jr}},l=n.f||0,u=n.p||0,p=n.b||0,f=n.l,h=n.d,m=n.m,g=n.n,y=s*8;do{if(!f){l=ct(t,u,1);var w=ct(t,u+1,3);if(u+=3,w)if(w==1)f=JA,h=XA,m=9,g=5;else if(w==2){var P=ct(t,u,31)+257,N=ct(t,u+10,15)+4,E=P+ct(t,u+5,31)+1;u+=14;for(var M=new Oe(E),A=new Oe(19),C=0;C<N;++C)A[GA[C]]=ct(t,u+C*3,7);u+=N*3;for(var T=oc(A),I=(1<<T)-1,$=ls(A,T,1),C=0;C<E;){var D=$[ct(t,u,I)];u+=D&15;var x=D>>4;if(x<16)M[C++]=x;else{var k=0,S=0;for(x==16?(S=3+ct(t,u,3),u+=2,k=M[C-1]):x==17?(S=3+ct(t,u,7),u+=3):x==18&&(S=11+ct(t,u,127),u+=7);S--;)M[C++]=k}}var _=M.subarray(0,P),U=M.subarray(P);m=oc(_),g=oc(U),f=ls(_,m,1),h=ls(U,g,1)}else Te(1);else{var x=YA(u)+4,v=t[x-4]|t[x-3]<<8,R=x+v;if(R>s){d&&Te(0);break}o&&c(p+v),e.set(t.subarray(x,R),p),n.b=p+=v,n.p=u=R*8,n.f=l;continue}if(u>y){d&&Te(0);break}}o&&c(p+131072);for(var K=(1<<m)-1,te=(1<<g)-1,le=u;;le=u){var k=f[dc(t,u)&K],X=k>>4;if(u+=k&15,u>y){d&&Te(0);break}if(k||Te(2),X<256)e[p++]=X;else if(X==256){le=u,f=null;break}else{var Ie=X-254;if(X>264){var C=X-257,Se=Wh[C];Ie=ct(t,u,(1<<Se)-1)+Yh[C],u+=Se}var Rt=h[dc(t,u)&te],_t=Rt>>4;Rt||Te(3),u+=Rt&15;var U=WA[_t];if(_t>3){var Se=Jh[_t];U+=dc(t,u)&(1<<Se)-1,u+=Se}if(u>y){d&&Te(0);break}o&&c(p+131072);var Dr=p+Ie;if(p<U){var Mr=i-U,ai=Math.min(U,Dr);for(Mr+p<0&&Te(3);p<ai;++p)e[p]=r[Mr+p]}for(;p<Dr;++p)e[p]=e[p-U]}}n.l=f,n.p=le,n.b=p,n.f=l,f&&(l=1,n.m=m,n.d=h,n.n=g)}while(!l);return p!=e.length&&a?us(e,0,p):e.subarray(0,p)};var cs=new Oe(0);var ir=function(t,n){return t[n]|t[n+1]<<8},ar=function(t,n){return(t[n]|t[n+1]<<8|t[n+2]<<16|t[n+3]<<24)>>>0},cc=function(t,n){return ar(t,n)+ar(t,n+4)*4294967296};var eT=(function(){function t(n,e){typeof n=="function"&&(e=n,n={}),this.ondata=e;var r=n&&n.dictionary&&n.dictionary.subarray(-32768);this.s={i:0,b:r?r.length:0},this.o=new Oe(32768),this.p=new Oe(0),r&&this.o.set(r)}return t.prototype.e=function(n){if(this.ondata||Te(5),this.d&&Te(4),!this.p.length)this.p=n;else if(n.length){var e=new Oe(this.p.length+n.length);e.set(this.p),e.set(n,this.p.length),this.p=e}},t.prototype.c=function(n){this.s.i=+(this.d=n||!1);var e=this.s.b,r=ZA(this.p,this.s,this.o);this.ondata(us(r,e,this.s.b),this.d),this.o=us(r,this.s.b-32768),this.s.b=this.o.length,this.p=us(this.p,this.s.p/8|0),this.s.p&=7},t.prototype.push=function(n,e){this.e(n),this.c(e)},t})();var uc=typeof TextDecoder<"u"&&new TextDecoder,tT=0;try{uc.decode(cs,{stream:!0}),tT=1}catch{}var nT=function(t){for(var n="",e=0;;){var r=t[e++],s=(r>127)+(r>223)+(r>239);if(e+s>t.length)return{s:n,r:us(t,e-1)};s?s==3?(r=((r&15)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,n+=String.fromCharCode(55296|r>>10,56320|r&1023)):s&1?n+=String.fromCharCode((r&31)<<6|t[e++]&63):n+=String.fromCharCode((r&15)<<12|(t[e++]&63)<<6|t[e++]&63):n+=String.fromCharCode(r)}};function rT(t,n){if(n){for(var e="",r=0;r<t.length;r+=16384)e+=String.fromCharCode.apply(null,t.subarray(r,r+16384));return e}else{if(uc)return uc.decode(t);var s=nT(t),i=s.s,e=s.r;return e.length&&Te(8),i}}var sT=function(t,n,e,r,s,i,a){var o=s==4294967295,d=i==4294967295,c=a==4294967295,l=n+e,u=o+d+c;if(r&&u){for(;n+4<l;n+=4+ir(t,n+2))if(ir(t,n)==1)return[o?cc(t,n+4+8*d):s,d?cc(t,n+4):i,c?cc(t,n+4+8*(d+o)):a,1];r<2&&Te(13)}return[s,i,a,0]};var iT=(function(){function t(){}return t.prototype.push=function(n,e){this.ondata(null,n,e)},t.compression=0,t})();var em=(function(){function t(){var n=this;this.i=new eT(function(e,r){n.ondata(null,e,r)})}return t.prototype.push=function(n,e){try{this.i.push(n,e)}catch(r){this.ondata(r,null,e)}},t.compression=8,t})();var tm=(function(){function t(n){this.onfile=n,this.k=[],this.o={0:iT},this.p=cs}return t.prototype.push=function(n,e){var r=this;if(this.onfile||Te(5),this.p||Te(4),this.c>0){var s=Math.min(this.c,n.length),i=n.subarray(0,s);if(this.c-=s,this.d?this.d.push(i,!this.c):this.k[0].push(i),n=n.subarray(s),n.length)return this.push(n,e)}else{var a=0,o=0,d=void 0,c=void 0;this.p.length?n.length?(c=new Oe(this.p.length+n.length),c.set(this.p),c.set(n,this.p.length)):c=this.p:c=n;for(var l=c.length,u=this.c,p=u&&this.d,f=function(){var y=ar(c,o);if(y==67324752){a=1,d=o,h.d=null,h.c=0;var w=ir(c,o+6),x=ir(c,o+8),v=w&2048,R=w&8,P=ir(c,o+26),N=ir(c,o+28);if(l>o+30+P+N){var E=[];h.k.unshift(E),a=2;var M=ar(c,o+18),A=ar(c,o+22),C=rT(c.subarray(o+30,o+=30+P),!v),T=sT(c,o,N,2,M,A,0),I=T[0],$=T[1],D=T[3];R&&(I=-1-D),o+=N,h.c=I;var k,S={name:C,compression:x,start:function(){if(S.ondata||Te(5),!I)S.ondata(null,cs,!0);else{var _=r.o[x];_||S.ondata(Te(14,"unknown compression type "+x,1),null,!1),k=I<0?new _(C):new _(C,I,$),k.ondata=function(le,X,Ie){S.ondata(le,X,Ie)};for(var U=0,K=E;U<K.length;U++){var te=K[U];k.push(te,!1)}r.k[0]==E&&r.c?r.d=k:k.push(cs,!0)}},terminate:function(){k&&k.terminate&&k.terminate()}};I>=0&&(S.size=I,S.originalSize=$),h.onfile(S)}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 m=f();if(m==="break")break}if(this.p=cs,u<0){var g=a?c.subarray(0,d-12-(u==-2&&8)-(ar(c,d-16)==134695760&&4)):c.subarray(0,o);p?p.push(g,!!a):this.k[+(a==2)].push(g)}if(a&2)return this.push(c.subarray(o),e);this.p=c.subarray(o)}e&&(this.c&&Te(13),this.p=null)},t.prototype.register=function(n){this.o[n.compression]=n},t})();var nm=65536;function aT(t,n){let e=new Uint8Array(n),r=0;for(let s of t)e.set(s,r),r+=s.length;return e}function Gi(t,n,e){if(t.byteLength===0)return{kind:"unreadable",message:"Archive is empty."};if(t[0]!==80||t[1]!==75)return{kind:"unreadable",message:"Archive does not begin with a ZIP signature."};let r=new Map,s=[],i=0,a=0,o,d=new Set,c=new tm;c.register(em),c.onfile=l=>{let u=l.name,p=typeof l.originalSize=="number"&&l.originalSize>0,f=l.originalSize??0;if(!ac(u)){s.push({entry:u,reason:"unsafe-entry-name",declaredBytes:f});return}if(!e(u))return;if(d.has(u)){s.push({entry:u,reason:"duplicate-selected-name",declaredBytes:f});return}if(i>=n.maxEntries){s.push({entry:u,reason:"entry-budget-exceeded",declaredBytes:f});return}let h=n.maxExpandedBytes-a;if(p&&f>h){s.push({entry:u,reason:"expanded-budget-exceeded",declaredBytes:f});return}i+=1,d.add(u);let m=[],g=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}g+=x.length;let R=p&&g>f;if(R||g>h){y=!0,m.length=0,s.push({entry:u,reason:R?"declared-size-mismatch":"expanded-budget-exceeded",declaredBytes:f});return}if(m.push(x.slice()),v){if(p&&g!==f){m.length=0,y=!0,s.push({entry:u,reason:"declared-size-mismatch",declaredBytes:f});return}a+=g,r.set(u,aT(m,g))}},l.start()};try{for(let l=0;l<t.byteLength;l+=nm){let u=Math.min(l+nm,t.byteLength);if(c.push(t.subarray(l,u),u===t.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:r,skipped:s}}}var rm=256,sm={before:"before",action:"action",input:"action",after:"after"};function pc(t){return Array.isArray(t)&&typeof t[0]=="string"}function oT(t){return Array.isArray(t)&&Array.isArray(t[0])&&typeof t[0][0]=="number"&&typeof t[0][1]=="number"}function im(t){let n=t[1],e=typeof n=="object"&&n!==null&&!Array.isArray(n);return t.slice(e?2:1)}function dT(t){let n=V(t.snapshotName),e=V(t.callId),r=sm[V(t.phase)??""];if(n!==void 0){let s=n.indexOf("@");s>0&&(r??=sm[n.slice(0,s)],e??=n.slice(s+1))}return{...e===void 0?{}:{callId:e},...r===void 0?{}:{phase:r},...n===void 0?{}:{name:n}}}var Ki=class{frames=new Map;literals=new Map;byCall=new Map;add(n,e,r){let s=me(r.snapshot);if(s===void 0||s.html===void 0)return;let i=dT(s),a=V(s.frameId)??V(s.pageId)??"unknown-frame",o=`${n}
125
+ ${a}`,d=this.frames.get(o)??[],c=V(s.frameUrl),l={entry:n,line:e,frameId:a,index:d.length,snapshotId:i.name??(i.callId===void 0?`${n}#line=${e}`:`${i.phase??"snapshot"}@${i.callId}`),...i.callId===void 0?{}:{callId:i.callId},...i.phase===void 0?{}:{phase:i.phase},...c===void 0?{}:{frameUrl:c},isMainFrame:Fh(s.isMainFrame)??!0,html:s.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(n){return this.byCall.get(n)??[]}get size(){let n=0;for(let e of this.frames.values())n+=e.length;return n}literalNodes(n){let e=this.literals.get(n);if(e!==void 0)return e;let r=[],s=(i,a)=>{if(typeof i=="string"){r.push(i);return}if(!(!pc(i)||a>rm)){for(let o of im(i))s(o,a+1);r.push(i)}};return s(n.html,0),this.literals.set(n,r),r}rebuild(n,e){let r=this.frames.get(`${n.entry}
126
+ ${n.frameId}`)??[],s=0,i=!1,a=(d,c,l)=>{if(s>=e||l>rm){i=!0;return}if(typeof d=="string")return s+=1,d;if(oT(d)){let[h,m]=d[0],g=c-h,y=r[g];if(h<1||y===void 0)return;let w=this.literalNodes(y)[m];return w===void 0?void 0:a(w,g,l)}if(!pc(d))return;s+=1;let u=d[1],p=typeof u=="object"&&u!==null&&!Array.isArray(u)?u:{},f=[];for(let h of im(d)){let m=a(h,c,l+1);m!==void 0&&f.push(m)}return[d[0],p,...f]},o=a(n.html,n.index,0);return{...pc(o)?{root:o}:{},truncated:i,nodes:s}}};var bn=["trace","console","network","dom","accessibility"],fc=/(?:^|\/)(?:\d+-)?(?:trace|test)\.trace$/,Wi=/(?:^|\/)(?:\d+-)?trace\.network$/,hc=/(?:^|\/)(?:\d+-)?trace\.stacks$/,xn=512,gc=2e3,lm=200,cT=2,mc=5e4,yc=25,lT=new Set(["screencast-frame","object","resource","input"]),re={failure:5,failedCall:4,significant:3,context:2,ordinary:1,afterFailure:0};function uT(t,n){switch(n){case"console":return t.maxConsoleEvents;case"network":return t.maxNetworkEvents;case"dom":case"accessibility":return t.maxDomNodes;default:return t.maxTraceEvents}}function oe(t,n,e,r,s,i){t.omissions.push({omissionId:B("omi",[t.input.attemptId,n,e,s??"",r]),channel:n,reason:e,message:r,...s===void 0?{}:{locator:s},...i===void 0?{}:{cap:i}})}function Ji(t,n,e,r,s,i,a){let o=t.channels[n].artifact,d=ge(t.runId,o.artifactId,e,r,s);t.evidence.push({evidenceId:d,kind:e,artifactId:o.artifactId,logicalTestId:t.input.logicalTestId,attemptId:t.input.attemptId,locator:r,observation:s,availability:s.length===0?"empty":"present",redactionIds:i.map(c=>c.redactionId)}),t.redactions.push(...i),t.priorities.set(d,a),t.channels[n].included+=1}function fs(t,n,e,r){let s=ce(r,n,e,t.policy.sensitiveNames);return{value:s.value,records:s.records}}function am(t){let n=Xe(t);if(n===void 0)return[];let e=[];for(let r of n){let s=me(r),i=V(s?.name);i!==void 0&&e.push({name:i,value:V(s?.value)??""})}return e}function pT(t){let n=V(t.type);if(n==="console")return{type:V(t.messageType)??"log",text:V(t.text)??be(t.args,gc)};if(n!=="event"||!(V(t.class)==="ConsoleMessage"||V(t.method)==="console"))return;let r=me(t.params);return{type:V(r?.type)??V(r?.messageType)??"log",text:V(r?.text)??be(r,gc)}}function hs(t){let n=me(t.error);return V(n?.message)??V(me(n?.error)?.message)}function um(t){return t===void 0?"unknown":V(t.apiName)??([V(t.class),V(t.method)].filter(Boolean).join(".")||"unknown")}function fT(t){let n=me(t?.params);return V(n?.selector)}function hT(t,n){let e=V(t.type),r=um(e==="after"?n??t:t),s=V(t.title),i=t.params===void 0?"":` params=${be(t.params,xn)}`,a=hs(t),o=a===void 0?"":` error=${be(a,xn)}`;switch(e){case"before":return`action started: ${r}${s===void 0?"":` "${be(s,120)}"`}${i}`;case"after":return`action finished: ${r}${o}`;case"action":return`action: ${r}${i}${o}`;case"log":return`log: ${be(t.message,xn)}`;case"error":return`error: ${be(t.message,xn)}`;case"stdout":case"stderr":return`${e}: ${be(t.text,xn)}`;case"context-options":return`context options: ${be({browserName:V(t.browserName),platform:V(t.platform),playwrightVersion:V(t.playwrightVersion),sdkLanguage:V(t.sdkLanguage)},xn)}`;case"event":return`event: ${r}${i}`;default:return}}function mT(t){return Ae(t.startTime)??Ae(t.endTime)??Ae(t.time)}function yT(t,n,e){let r=ze(e);if(r===void 0){t.channels.trace.failed=!0,oe(t,"trace","unreadable",`${n} is not valid UTF-8.`,n);return}let s=Ui(r);s.length===0&&(t.channels.trace.parsed=!0);let i=new Set;for(let a of s){let o=`${n}#line=${a.line}`;if(!a.parsed){t.channels.trace.failed=!0,oe(t,"trace","parse-failed",`${o} is not valid JSON.`,o);continue}let d=me(a.value),c=V(d?.type);if(d===void 0||c===void 0){t.channels.trace.failed=!0,oe(t,"trace","unrecognized",`${o} is not a typed trace event.`,o);continue}if(t.channels.trace.parsed=!0,c==="frame-snapshot"){t.snapshots.add(n,a.line,d)===void 0&&oe(t,"dom","unrecognized",`${o} does not carry a readable frame snapshot.`,o);continue}if(c==="resource-snapshot"){fm(t,n,a.line,d,new Map);continue}let l=mT(d);if(c==="error"){l!==void 0&&t.errorTimes.push(l);for(let y of Xe(d.stack)??[]){if(t.seeds.length>=lm)break;let w=me(y),x=V(w?.file),v=Ae(w?.line);if(x===void 0||v===void 0)continue;let R=Ae(w?.column);t.seeds.push({file:x,line:v,...R===void 0?{}:{column:R},origin:`${n}#line=${a.line}:error`,logicalTestId:t.input.logicalTestId,attemptId:t.input.attemptId})}}let u=pT(d);if(u!==void 0){let y=fs(t,"console",o,`console.${u.type}: ${be(u.text,gc)}`);t.candidates.push({channel:"console",kind:"console-event",locator:{type:"trace-event",entry:n,line:a.line,eventType:"console",...l===void 0?{}:{timestamp:l}},locatorText:o,observation:y.value,redactions:y.records,order:t.candidates.length,...l===void 0?{}:{time:l},error:u.type==="error"||u.type==="warning"});continue}if(lT.has(c))continue;let p=V(d.callId),f=p===void 0?void 0:`${n}
127
+ ${p}`;if(f!==void 0&&p!==void 0){if(c==="before")t.actions.set(f,{callId:p,entry:n,before:{line:a.line,event:d}});else if(c==="after"){let y=t.actions.get(f)??{callId:p,entry:n};y.after={line:a.line,event:d},t.actions.set(f,y);let w=Ae(d.endTime);hs(d)!==void 0&&w!==void 0&&t.errorTimes.push(w)}}let h=f===void 0?void 0:t.actions.get(f)?.before,m=hT(d,h?.event);if(m===void 0){i.add(c);continue}let g=fs(t,"trace",o,m);t.candidates.push({channel:"trace",kind:"trace-event",locator:{type:"trace-event",entry:n,line:a.line,eventType:c,...p===void 0?{}:{eventId:p},...l===void 0?{}:{timestamp:l}},locatorText:o,observation:g.value,redactions:g.records,order:t.candidates.length,...l===void 0?{}:{time:l},...p===void 0?{}:{callId:p},error:c==="error"||hs(d)!==void 0})}for(let a of[...i].sort())oe(t,"trace","unrecognized",`Trace event type ${a} is not interpreted by this adapter.`,n)}function gT(t){let n=[];for(let e of t.actions.values()){let r=fT(e.before?.event);if(r===void 0||e.before===void 0||V(e.before.event.class)==="Test")continue;let s=e.after!==void 0&&hs(e.after.event)!==void 0,i=e.after===void 0;!s&&!i||n.push({callId:e.callId,entry:e.entry,selector:r,apiName:um(e.before.event),time:Ae(e.before.event.startTime)??0,unfinished:i})}return n.sort((e,r)=>r.time-e.time||e.callId.localeCompare(r.callId))}function wT(t){let n={after:3,action:2,before:1};return[...t].filter(e=>e.isMainFrame||t.length===1).sort((e,r)=>(n[r.phase??"before"]??0)-(n[e.phase??"before"]??0)||r.line-e.line)[0]}function bT(t,n){let e=wT(t.snapshots.forCall(n.callId)),r=`${n.apiName} on ${n.selector}`;if(e===void 0){oe(t,"dom","unavailable",`No DOM snapshot was recorded for the failed ${r}.`,`${n.entry}#${n.callId}`);return}let s=t.snapshots.rebuild(e,mc),i=`${e.entry}#${e.snapshotId}`;if(s.root===void 0){oe(t,"dom","unreadable",`Snapshot ${e.snapshotId} could not be rebuilt.`,i);return}s.truncated&&oe(t,"dom","budget-exceeded",`Snapshot ${e.snapshotId} was rebuilt only up to ${mc} nodes.`,i,mc);let a={maxDepth:t.policy.maxDomDepth,maxNodes:t.policy.maxDomNodes,maxBytes:t.policy.maxDomTextBytes,sensitiveNames:t.policy.sensitiveNames},o=Hh(s.root,n.callId),d=ss(s.root,n.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],m=as(h.node,i,a);Ji(t,"dom","dom-subtree",{type:"dom-node",snapshotId:e.snapshotId,nodePath:h.path},`${u} snapshot of the element targeted by the failed ${r}:
128
+ ${m.text}`,m.redactions,re.failure),m.truncated&&oe(t,"dom","budget-exceeded",`The target subtree in ${e.snapshotId} was cut at ${a.maxDepth} levels, ${a.maxNodes} elements, or ${a.maxBytes} bytes.`,i,a.maxNodes);let g=fs(t,"accessibility",i,os(h.node));Ji(t,"accessibility","accessibility-node",{type:"dom-node",snapshotId:e.snapshotId,nodePath:h.path},`target of the failed ${n.apiName}: ${g.value}`,g.records,re.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=qi(s.root,n.selector,l,i,{maxItems:yc,maxBytes:a.maxBytes},t.policy.sensitiveNames);Ji(t,"dom","dom-candidates",{type:"dom-node",snapshotId:e.snapshotId,nodePath:[]},`In the ${u} snapshot of the failed ${r}, the locator ${p}. Elements most like it, best first:
129
+ ${f.text}`,f.redactions,re.failure),f.truncated&&oe(t,"dom","budget-exceeded",`Only the ${yc} closest candidates in ${e.snapshotId} were listed.`,i,yc)}function xT(t,n){let e=new Set(n.map(i=>i.callId));for(let i of t.actions.values())i.after!==void 0&&hs(i.after.event)!==void 0&&e.add(i.callId);let r=t.errorTimes.length>0?Math.min(...t.errorTimes):n.length>0?Math.min(...n.map(i=>i.time)):void 0,s=i=>i.error?i.channel==="trace"?re.failedCall+.95:re.significant:i.callId!==void 0&&e.has(i.callId)?re.failedCall:r!==void 0&&i.time!==void 0&&i.time>r+1?re.afterFailure:i.channel==="trace"?re.context:re.ordinary;for(let i of["trace","console","network"]){let a=t.candidates.filter(l=>l.channel===i),o=uT(t.policy,i),d=a.map(l=>({candidate:l,priority:s(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);Ji(t,i,l.kind,l.locator,l.observation,l.redactions,u+p)}d.length>o&&oe(t,i,"budget-exceeded",`Kept the ${o} ${i} observations closest to the failure; ${d.length-o} earlier or less relevant ones were not included.`,d[o]?.candidate.locatorText,o)}}function pm(t){let n=me(t.snapshot)??t,e=me(n.response),r=me(e?.content);return V(r?._sha1)??V(r?.sha1)}function fm(t,n,e,r,s){let i=me(r.snapshot)??r,a=me(i.request),o=V(a?.url),d=`${n}#line=${e}`;if(o===void 0){oe(t,"network","unrecognized",`${d} has no request URL.`,d);return}let c=Ht(o,"network",d,t.policy.sensitiveNames),l=Hi(am(a?.headers),"network",`${d}/request-headers`,t.policy.sensitiveNames),u=me(i.response),p=Hi(am(u?.headers),"network",`${d}/response-headers`,t.policy.sensitiveNames),f=V(a?.method)??"GET",h=Ae(u?.status),m=me(u?.content),g=[`${f} ${c.value}`,h===void 0||h<=0?"-> (no response)":`-> ${h} ${V(u?.statusText)??""}`.trim()],y=V(m?.mimeType),w=Ae(m?.size);(y!==void 0||w!==void 0)&&g.push(`(${y??"unknown"}, ${w??"unknown"} bytes)`);let x=V(m?.text)??V(u?.body),v=pm(r);if(x===void 0&&v!==void 0&&t.policy.includeNetworkBodies){let I=s.get(v)??s.get(`resources/${v}`);I===void 0?oe(t,"network","unavailable",`Referenced response resource ${v} was not present in the trace archive.`,d):I.byteLength>t.policy.maxNetworkBodyBytes?oe(t,"network","budget-exceeded",`Referenced response resource ${v} exceeds the network body byte limit.`,d,t.policy.maxNetworkBodyBytes):(x=ze(I),x===void 0&&oe(t,"network","irrelevant",`Referenced response resource ${v} is not textual UTF-8.`,d))}let R=y?.toLowerCase()??"",P=R.startsWith("image/")||R.startsWith("audio/")||R.startsWith("video/")||R.includes("multipart")||R.includes("octet-stream"),N=[];if(t.policy.includeNetworkBodies)if(x!==void 0&&!P){let I=fs(t,"network",`${d}/body`,be(x,t.policy.maxNetworkBodyBytes));N.push(...I.records),g.push(`body=${I.value}`)}else x!==void 0&&P&&oe(t,"network","irrelevant","Response body omitted because it is binary or multipart.",d);else(x!==void 0||m!==void 0)&&oe(t,"network","policy-disabled","Response body withheld because includeNetworkBodies is disabled.",d);let E=Ae(i.time);E!==void 0&&g.push(`time=${E}ms`);let M=V(i._failureText);M!==void 0&&g.push(`failure=${be(M,xn)}`);let A=fs(t,"network",d,g.join(" ")),C=V(i._requestref)??B("req",[f,c.value,String(e)]),T=Ae(i._monotonicTime);t.candidates.push({channel:"network",kind:"network-event",locator:{type:"network-request",requestId:C,eventIndex:e},locatorText:d,observation:A.value,redactions:[...A.records,...N,...c.records,...l.records,...p.records],order:t.candidates.length,...T===void 0?{}:{time:T},error:M!==void 0||h!==void 0&&(h>=400||h<=0)})}function vT(t,n,e){let r=ze(e);if(r===void 0){t.channels.trace.failed=!0,oe(t,"trace","unreadable",`${n} is not valid UTF-8.`,n);return}let s;try{s=JSON.parse(r),t.channels.trace.parsed=!0}catch{t.channels.trace.failed=!0,oe(t,"trace","parse-failed",`${n} is not valid JSON.`,n);return}let i=me(s),a=Xe(i?.files)??[],o=Xe(i?.stacks)??[];for(let d of o){let c=Xe(d),l=V(c?.[0])??"unknown";for(let u of Xe(c?.[1])??[]){if(t.seeds.length>=lm)return;let p=Xe(u),f=Ae(p?.[0]),h=Ae(p?.[1]);if(f===void 0||h===void 0)continue;let m=V(a[f]);if(m===void 0)continue;let g=Ae(p?.[2]);t.seeds.push({file:m,line:h,...g===void 0?{}:{column:g},origin:`${n}:${l}`,logicalTestId:t.input.logicalTestId,attemptId:t.input.attemptId})}}}function om(t,n,e,r){let s={};for(let i of bn)s[i]={artifact:{artifactId:ve(t,i,`${n.attemptId}:${n.attachmentId}`),channel:i,availability:e,...r.path===void 0?{}:{path:r.path},...r.sha256===void 0?{}:{sha256:r.sha256},format:r.format??"playwright-trace-zip",...r.producerVersion===void 0?{}:{producerVersion:r.producerVersion},attemptId:n.attemptId,warnings:r.warnings},included:0,parsed:!1,failed:!1};return s}function dm(t,n,e,r){return{runId:t,policy:n,input:e,channels:r,evidence:[],redactions:[],omissions:[],seeds:[],priorities:new Map,candidates:[],actions:new Map,snapshots:new Ki,errorTimes:[]}}function cm(t,n){return{artifacts:t,evidence:[],redactions:[],omissions:n,seeds:[],priorities:new Map,failedSelectors:[]}}async function hm(t,n,e,r){let s=await Q(r,e.path,n.maxArtifactBytes);if(s.kind!=="read"){let f=s.kind==="unavailable"?"unavailable":"unreadable",h=s.kind==="over-budget"?"budget-exceeded":s.kind==="unauthorized"?"unauthorized-path":s.kind,m=om(t,e,f,{warnings:[s.message]}),g=dm(t,n,e,m);for(let y of bn)oe(g,y,h,s.message,e.path);return cm(bn.map(y=>m[y].artifact),g.omissions)}let a=Gi(s.bytes,{maxEntries:n.maxTraceEntries,maxExpandedBytes:n.maxTraceExpandedBytes},f=>fc.test(f)||Wi.test(f)||hc.test(f)),o=e.info?.producerVersion===void 0,d=om(t,e,"present",{path:s.relativePath,sha256:s.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=dm(t,n,e,d);if(a.kind!=="read"){let f=a.message;for(let h of bn)oe(c,h,"unreadable",f,s.relativePath);return cm(bn.map(h=>({...d[h].artifact,availability:"unreadable",warnings:[f]})),c.omissions)}o&&oe(c,"trace","unrecognized","Trace producer version was not supplied; parsed evidence is not version-qualified.",s.relativePath);let l=new Set;if(n.includeNetworkBodies){for(let[f,h]of a.contents.entries){if(!Wi.test(f))continue;let m=ze(h);if(m!==void 0)for(let g of Ui(m)){let y=me(g.value);if(y===void 0)continue;let w=pm(y);w!==void 0&&(l.add(w),l.add(`resources/${w}`))}}if(l.size>0){let f=Gi(s.bytes,{maxEntries:n.maxTraceEntries,maxExpandedBytes:n.maxTraceExpandedBytes},h=>fc.test(h)||Wi.test(h)||hc.test(h)||l.has(h));f.kind==="read"?a=f:oe(c,"network","unreadable",f.message,s.relativePath)}}for(let f of a.contents.skipped){let h=f.reason==="unsafe-entry-name"?"unauthorized-path":"budget-exceeded";oe(c,"trace",h,`Archive entry ${f.entry} was not read (${f.reason}, ${f.declaredBytes} declared bytes).`,`${s.relativePath}!${f.entry}`)}let u=[...a.contents.entries.keys()].sort();for(let f of u.filter(h=>hc.test(h)))vT(c,f,a.contents.entries.get(f));for(let f of u.filter(h=>fc.test(h)))yT(c,f,a.contents.entries.get(f));for(let f of u.filter(h=>Wi.test(h))){let h=ze(a.contents.entries.get(f));if(h===void 0){c.channels.network.failed=!0,oe(c,"network","unreadable",`${f} is not valid UTF-8.`,f);continue}let m=Ui(h);m.length===0&&(c.channels.network.parsed=!0);for(let g of m){if(!g.parsed){c.channels.network.failed=!0,oe(c,"network","parse-failed",`${f}#line=${g.line} is not valid JSON.`,`${f}#line=${g.line}`);continue}let y=me(g.value);if(y===void 0){c.channels.network.failed=!0,oe(c,"network","unrecognized",`${f}#line=${g.line} is not a network record.`,`${f}#line=${g.line}`);continue}c.channels.network.parsed=!0,fm(c,f,g.line,y,a.contents.entries)}}let p=gT(c);xT(c,p);for(let f of p.slice(0,cT))bT(c,f);if(p.length===0&&c.snapshots.size>0&&oe(c,"dom","irrelevant","No failed action targeted an element, so no DOM snapshot was examined.",s.relativePath),u.length===0)for(let f of bn)d[f].failed=!0,oe(c,f,"unreadable","Archive contained no Playwright trace, network, or stacks entry.",s.relativePath);return{artifacts:bn.map(f=>{let h=d[f],m=h.included>0?"present":h.failed&&!h.parsed?"unreadable":"empty";return{...h.artifact,availability:m}}),evidence:c.evidence,redactions:c.redactions,omissions:c.omissions,seeds:c.seeds,priorities:c.priorities,failedSelectors:p.map(f=>bt(f.selector))}}var kT="application/vnd.kwikqa.capture+json",mm=["trace","console","network","dom","accessibility"],ym=25,RT=2,IT=25,wc=600,AT=new Set(["type","setValue","addValue","keys"]),TT=new Set(["get","find","contains","$","$$","within"]),PT=/pass|secret|token|otp|pin\b|card|cvv|cvc|ssn|credential|auth/i;function bc(t){return t.name==="kwikqa-capture"||t.contentType.toLowerCase().split(";")[0]?.trim()===kT}function Nt(t,n=""){return typeof t=="string"?t:n}function ST(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let n=t;if(n.schema!=="kwikqa-capture"||String(n.schemaVersion??"").split(".")[0]!=="1")return;let e=n.framework==="webdriverio"?"webdriverio":"cypress",r=s=>Array.isArray(n[s])?n[s].filter(i=>typeof i=="object"&&i!==null&&!Array.isArray(i)):[];return{framework:e,url:Nt(n.url),title:Nt(n.title),...Array.isArray(n.dom)?{dom:n.dom}:{},domTruncated:n.domTruncated===!0,commands:r("commands").map(s=>({name:Nt(s.name),...typeof s.displayName=="string"?{displayName:s.displayName}:{},message:Nt(s.message),state:Nt(s.state),...typeof s.error=="string"?{error:s.error}:{},...typeof s.repeated=="number"?{repeated:s.repeated}:{}})),console:r("console").map(s=>({level:Nt(s.level,"log"),text:Nt(s.text)})),network:r("network").map(s=>({message:Nt(s.message),state:Nt(s.state),...typeof s.url=="string"?{url:s.url}:{}}))}}function ET(t){let n=/^([A-Z]+)\s+(\d{3})\s+(\S+)/.exec(t.trim());if(n!==null)return{method:n[1]??"GET",status:Number(n[2]),url:n[3]??""};let e=/^([A-Z]+)\s+(\S+)\s+(\S+)$/.exec(t.trim());return e!==null&&/^https?:|^\//.test(e[3]??"")?{method:e[1]??"GET",url:e[3]??"",failure:e[2]??"failed"}:{method:"",url:t}}function CT(t){for(let n of _e(t))if(Array.isArray(n)&&Ve(n)==="body")return n;return t}function NT(t){let n=/^([a-z][\w-]*)\*?=/i.exec(t);return n!==null&&!t.includes("[")?n[1]??t:t}async function gm(t,n,e,r){let{attachment:s}=e,i=`${e.attemptId}.attachments[${s.sourceIndex}]`,a=Object.fromEntries(mm.map(k=>[k,ve(t,k,`${e.attemptId}:${s.attachmentId}`)])),o=[],d=[],c=[],l=new Map,u=[],p=(k,S,_,U)=>{c.push({omissionId:B("omi",[e.attemptId,k,S,i,_]),channel:k,reason:S,message:_,locator:i,...U===void 0?{}:{cap:U}})},f=(k,S={})=>mm.map(_=>({artifactId:a[_],channel:_,availability:k(_),format:"kwikqa-capture",attemptId:e.attemptId,warnings:[],...S}));if(s.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 Q(r,s.path,n.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:s.path,warnings:[h.message]}),evidence:o,redactions:d,omissions:c,priorities:l,failedSelectors:u}}let m=Ee(h.bytes),g=ze(h.bytes),y;try{y=g===void 0?void 0:ST(JSON.parse(g))}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:m}),evidence:o,redactions:d,omissions:c,priorities:l,failedSelectors:u};let w=(k,S,_,U,K,te)=>{let le=ge(t,a[k],S,_,U);o.push({evidenceId:le,kind:S,artifactId:a[k],logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:_,observation:U,availability:"present",redactionIds:K.map(X=>X.redactionId)}),d.push(...K),l.set(le,te)},x=(k,S,_)=>ce(bt(S),k,_,n.sensitiveNames),v=y.framework==="cypress"?"cy":"browser",R=y.commands.filter(k=>k.name!==""&&k.state!=="pending"),P=R.findIndex(k=>k.state==="failed"),N=P<0?R.length:P+1,E=Math.max(0,N-ym);E>0&&p("trace","budget-exceeded",`Kept the ${N-E} commands up to the failure; ${E} earlier ones were left out.`,ym);let M="";R.slice(E,Math.min(R.length,N+3)).forEach((k,S)=>{let _=E+S,U=k.state==="failed",le=AT.has(k.name)&&(PT.test(M)||n.sensitiveNames.some(_t=>M.toLowerCase().includes(_t.toLowerCase())))?`<${k.message.length} typed characters, not shown>`:k.message;TT.has(k.name)&&k.message!==""&&(M=k.message),U&&M!==""&&u.push(M.split(",")[0]?.trim()??M);let Ie=k.repeated===void 0?"":` (x${k.repeated})`,Se=`${U?"command failed":_>=N?"command after the failure":"command"}: ${v}.${k.displayName??k.name}(${le.slice(0,wc)})${Ie}${k.error===void 0?"":` error=${k.error.slice(0,wc)}`}`,Rt=x("trace",Se,`${i}#commands[${_}]`);w("trace","trace-event",{type:"trace-event",entry:`${s.attachmentId}#commands`,line:_+1,eventType:U?"command-failed":"command"},Rt.value,Rt.records,U?re.failure:_>=N?re.afterFailure:re.context+(_-E)/1e3)}),R.length===0&&p("trace","unavailable","The capture recorded no commands."),y.console.slice(0,n.maxConsoleEvents).forEach((k,S)=>{let _=k.level==="pageerror"?"uncaught page error":`console.${k.level}`,U=x("console",`${_}: ${k.text.slice(0,wc)}`,`${i}#console[${S}]`);w("console","console-event",{type:"trace-event",entry:`${s.attachmentId}#console`,line:S+1,eventType:"console"},U.value,U.records,k.level==="error"||k.level==="pageerror"?re.significant:re.ordinary)}),y.console.length>n.maxConsoleEvents&&p("console","budget-exceeded",`Kept ${n.maxConsoleEvents} of ${y.console.length} console messages.`,n.maxConsoleEvents),y.network.slice(0,n.maxNetworkEvents).forEach((k,S)=>{let _=ET(k.message),U=Ht(k.url??_.url,"network",`${i}#network[${S}]`,n.sensitiveNames),K=_.status!==void 0?`-> ${_.status}`:_.failure!==void 0?`failure=${_.failure}`:`(${k.state})`,te=`${_.method===""?"request":_.method} ${U.value} ${K}`,le=(_.status??0)>=400||_.failure!==void 0;w("network","network-event",{type:"network-request",requestId:`${s.attachmentId}#${S}`,eventIndex:S},te,U.records,le?re.significant:re.ordinary)}),y.network.length>n.maxNetworkEvents&&p("network","budget-exceeded",`Kept ${n.maxNetworkEvents} of ${y.network.length} network responses.`,n.maxNetworkEvents);let A=y.dom,C=`${s.attachmentId}#dom`,T=Ht(y.url,"dom",`${i}#url`,n.sensitiveNames);d.push(...T.records);let I=`the page ${T.value}${y.title===""?"":` ("${y.title.slice(0,120)}")`} when the attempt failed`,$={maxDepth:n.maxDomDepth,maxNodes:n.maxDomNodes,maxBytes:n.maxDomTextBytes,sensitiveNames:n.sensitiveNames};if(A===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(NT).filter(S=>S!=="").slice(0,RT);for(let S of k){let _=ss(A,S),U=_.kind==="resolved"?_.matches:[];if(U.length===1&&U[0]!==void 0){let le=U[0],X=as(le.node,`${i}#dom`,$);w("dom","dom-subtree",{type:"dom-node",snapshotId:C,nodePath:le.path},`In ${I}, the element ${S} selects:
130
+ ${X.text}`,X.redactions,re.failure);let Ie=x("accessibility",os(le.node),`${i}#a11y`);w("accessibility","accessibility-node",{type:"dom-node",snapshotId:C,nodePath:le.path},`element selected by ${S}: ${Ie.value}`,Ie.records,re.failure);continue}let K=_.kind==="unsupported"?`uses a selector form (${_.reason}) the local DOM adapter does not evaluate`:`matched ${U.length} elements`,te=qi(A,S,U,`${i}#dom`,{maxItems:IT,maxBytes:$.maxBytes},n.sensitiveNames);w("dom","dom-candidates",{type:"dom-node",snapshotId:C,nodePath:[]},`In ${I}, the selector ${S} ${K}. Elements most like it, best first:
131
+ ${te.text}`,te.redactions,re.failure)}if(k.length===0){let S=as(CT(A),`${i}#dom`,$);w("dom","dom-subtree",{type:"dom-node",snapshotId:C,nodePath:[]},`Outline of ${I}:
132
+ ${S.text}`,S.redactions,re.significant),S.truncated&&p("dom","budget-exceeded",`The page outline was cut at ${$.maxNodes} elements or ${$.maxBytes} bytes.`,$.maxNodes)}}let D=new Set(o.map(k=>k.artifactId));return{artifacts:f(k=>D.has(a[k])?"present":"empty",{path:h.relativePath,sha256:m}),evidence:o,redactions:d,omissions:c,priorities:l,failedSelectors:u}}import{execFile as FT}from"node:child_process";import{isAbsolute as BT,relative as VT,resolve as Ac,sep as bm}from"node:path";import{promisify as zT}from"node:util";import{execFile as OT}from"node:child_process";import{promisify as $T}from"node:util";import{isAbsolute as DT,relative as xc,resolve as Xi,sep as vc}from"node:path";var MT=$T(OT),LT=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/,_T=1e4;function Yi(t){let n=[],e,r,s=()=>{if(r===void 0||e===void 0)return;let[,i,a,o,d]=r.header;n.push({path:e,oldStart:Number.parseInt(i??"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:r.lines.join(`
133
+ `)}),r=void 0};for(let i of t.split(/\r?\n/)){if(i.startsWith("diff --git ")){s(),e=void 0;continue}if(i.startsWith("+++ ")){s();let o=i.slice(4).trim();e=o==="/dev/null"?void 0:o.replace(/^b\//,"");continue}let a=LT.exec(i);if(a!==null){s(),r={header:a,lines:[i]};continue}r!==void 0&&r.lines.push(i)}return s(),n}function vn(t,n,e,r){return{omissionId:B("omi",["diff",t,e??"",n]),channel:"diff",reason:t,message:n,...e===void 0?{}:{locator:e},...r===void 0?{}:{cap:r}}}async function jT(t,n,e){let r=["-C",t,"--no-optional-locks","-c","core.quotePath=false","diff","--no-color","--no-ext-diff","--no-renames","--unified=3","HEAD","--",...n];try{return{text:(await MT("git",r,{timeout:_T,maxBuffer:e,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}}catch(s){let i=s;if(i.code==="ENOENT")return{error:"git executable was not found."};let a=(i.stderr??i.message??"").trim().split(`
134
+ `)[0]??"";return{error:a===""?"git diff failed.":a}}}async function wm(t,n,e,r){let s=ve(t,"diff",r.gitRoot??n.workspaceRoot),i=(v,R=[])=>({artifactId:s,channel:"diff",availability:v,...r.gitRoot===void 0?{}:{path:r.gitRoot},format:"git-unified-diff",warnings:R});if(!r.authorized)return{artifacts:[i("unavailable")],evidence:[],redactions:[],omissions:[vn("policy-disabled","Current-diff selection was not authorized for this run.")]};if(r.gitRoot===void 0)return{artifacts:[i("unavailable")],evidence:[],redactions:[],omissions:[vn("unavailable","The workspace has no containing git repository root.")]};let a=Xi(r.workspaceRoot??r.gitRoot),o=Xi(r.gitRoot),d=xc(o,a);if(d===".."||d.startsWith(`..${vc}`))return{artifacts:[i("unavailable")],evidence:[],redactions:[],omissions:[vn("unauthorized-path","The authorized workspace is outside the configured git root.",a)]};let c=[...new Set(e.map(v=>{let R=DT(v)?Xi(v):Xi(a,v),P=xc(o,R).split(vc).join("/");return P===""||P.startsWith("../")||P===".."?void 0:P}).filter(v=>v!==void 0))].sort();if(c.length===0)return{artifacts:[i("empty")],evidence:[],redactions:[],omissions:[vn("irrelevant","No evidence-bearing file was eligible for diff selection.")]};let l=Math.max(n.maxDiffBytes*4,1e6),u=await jT(o,c,l);if("error"in u)return{artifacts:[i("unreadable",[u.error])],evidence:[],redactions:[],omissions:[vn("unreadable",u.error,r.gitRoot)]};let p=a===o?"":`${xc(o,a).split(vc).join("/")}/`,f=Yi(u.text).map(v=>({...v,path:p!==""&&v.path.startsWith(p)?v.path.slice(p.length):v.path}));if(f.length===0)return{artifacts:[i("empty")],evidence:[],redactions:[],omissions:[]};let h=[],m=[],g=[],y=0,w=!1,x=!1;for(let v of f){if(h.length>=n.maxDiffHunks){w||(w=!0,g.push(vn("budget-exceeded",`Reached the ${n.maxDiffHunks}-hunk limit; later hunks were not included.`,v.path,n.maxDiffHunks)));break}let R=`${v.path}@${v.newStart}`,P=ce(v.body,"diff",R,n.sensitiveNames),N=Buffer.byteLength(P.value,"utf8");if(y+N>n.maxDiffBytes){x||(x=!0,g.push(vn("budget-exceeded",`Reached the ${n.maxDiffBytes}-byte diff limit; later hunks were not included.`,v.path,n.maxDiffBytes)));break}y+=N,m.push(...P.records);let E={type:"diff-hunk",path:v.path,oldStart:v.oldStart,oldLines:v.oldLines,newStart:v.newStart,newLines:v.newLines};h.push({evidenceId:ge(t,s,"diff-hunk",E,P.value),kind:"diff-hunk",artifactId:s,locator:E,observation:P.value,availability:"present",redactionIds:P.records.map(M=>M.redactionId)})}return{artifacts:[i("present")],evidence:h,redactions:m,omissions:g}}var HT=zT(FT),UT=1e4,qT=4e6,GT=16,Em=3,KT=120,xm=50,vm=20,km=30,kc=12,Rm=24e3,Rc=40,Cm=20,Im=120,Nm=1440*60*1e3,WT=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"]),Om=/\.(?:[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,$m=/(?:^|\/)(?: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$/,JT=/\u001b\[[0-9;]*m/g,Am=/"([^"\n]{3,120})"|'([^'\n]{3,120})'|`([^`\n]{3,120})`/g,XT=/^\s*(?:Expected|Received)(?: string| pattern| value)?:\s*(.+)$/gm,YT=/^(?:[A-Z]+|request) (\S+) (?:-> (\d{3})|failure=)/;function QT(t){let n=t.trim();return/^(["'`])(.*)\1$/.exec(n)?.[2]??n}function Tm(t){let n=t.trim();if(!(n.length<Em||n.length>KT)&&!WT.has(n.toLowerCase())&&!(/^[\d\s.,:%$-]+$/.test(n)&&!/^[$€£]?\d+[.,]\d+$/.test(n))&&!/^(?:\/|[A-Za-z]:\\|file:)|\.(?:spec|test|cy)\.[cm]?[jt]sx?\b|node_modules|:\d+:\d+/.test(n))return n}function Ic(t){let n=[];for(let e of t.matchAll(/\[[\w-]+[~|^$*]?=\s*["']?([^"'\]]+)["']?\]/g))n.push(e[1]??"");for(let e of t.matchAll(/[#.]([A-Za-z][\w-]{2,})/g))n.push(e[1]??"");return n}var ZT=8;function eP(t){let n=t.trim().split(/\s+/);if(n.length<3)return[];let e=[];for(let r=0;r+1<n.length;r+=1){let s=`${n[r]} ${n[r+1]}`;(s.match(new RegExp("\\p{L}","gu"))??[]).length>=ZT&&e.push(s)}return e}function tP(t){let n;try{n=new URL(t,"http://localhost").pathname}catch{return}if(/\.(?:js|css|png|jpe?g|gif|svg|ico|woff2?|map)$/i.test(n))return;let e=[];for(let s of n.split("/").filter(Boolean)){if(/^\d+$|^[0-9a-f-]{16,}$|^[0-9a-f]{8,}$/i.test(s))break;e.push(s)}let r=`/${e.join("/")}`;return e.length===0?void 0:r}function Dm(t,n,e=[]){let r=[],s=[];for(let c of t){for(let l of n(c)){for(let u of l.matchAll(Am)){let p=u[1]??u[2]??u[3]??"";r.push(p,...Ic(p))}/[('"`]/.test(l)||r.push(...Ic(l))}for(let l of c.errors){let u=(l.message??"").replace(JT,"");for(let f of u.matchAll(XT)){let h=QT(f[1]??"");r.push(h),s.push(h)}let p=u.split(`
135
+ `).slice(0,6).join(`
136
+ `);for(let f of p.matchAll(Am)){let h=f[1]??f[2]??f[3]??"",m=/^[[#.]/.test(h)?Ic(h):[];r.push(...m.length>0?m:[h]),m.length===0&&s.push(h)}}}let i=[];for(let c of e){let l=YT.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=tP(l[1]??"");p!==void 0&&p.length>=Em&&i.push(p)}let a=c=>[...new Set(c)].sort((l,u)=>u.length-l.length||l.localeCompare(u)),o=a([...r.map(Tm).filter(c=>c!==void 0),...i]),d=a(s.flatMap(eP).map(Tm).filter(c=>c!==void 0&&!o.includes(c)));return[...o,...d].slice(0,GT)}function nP(t){return t.map(n=>n.replace(/[.[\]{}()\\*+?^$|]/g,"\\$&")).join("|")}async function dr(t,n){try{return{text:(await HT("git",["-C",t,"--no-optional-locks","-c","core.quotePath=false",...n],{timeout:UT,maxBuffer:qT,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}}catch(e){let r=e;if(r.code==="ENOENT")return{error:"git executable was not found."};if(r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{error:"The matching changes are too large to read."};let s=(r.stderr??r.message??"").trim().split(`
137
+ `)[0]??"";return{error:s===""?"git failed.":s}}}async function ms(t,n){let e=await dr(t,n);if("error"in e)return;let r=e.text.trim();return r===""?void 0:r}async function rP(t){let n=await ms(t,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]);if(n!==void 0)return n;for(let e of["main","master","origin/main","origin/master"])if(await ms(t,["rev-parse","--verify","--quiet",`${e}^{commit}`])!==void 0)return e}async function sP(t,n){let e=await ms(t,["rev-parse","--verify","--quiet","HEAD^{commit}"]);if(e===void 0)return;let r=await rP(t),s=r===void 0?void 0:await ms(t,["merge-base","HEAD",r]);if(r!==void 0&&s!==void 0&&s!==e)return{logArgs:[`--max-count=${xm}`,`${s}..HEAD`],description:`the commits on this branch since it left ${r} (at most ${xm})`};let i=Date.parse(n),a=new Date((Number.isNaN(i)?0:i)-km*Nm).toISOString();return{logArgs:[`--max-count=${vm}`,`--since=${a}`,"HEAD"],description:`the last ${vm} commits from the ${km} days before the run`}}function Mm(t,n){let e=Date.parse(n);if(Number.isNaN(e))return"";let r=Math.floor((e-t)/Nm);return r<0?", after the run":r===0?", the day of the run":`, ${r} day${r===1?"":"s"} before the run`}function iP(t,n){let e=t.split(`
138
+ `);if(e.length<=Rc+1)return t;let[r,...s]=e,i=Math.max(0,s.findIndex(n)),a=Math.max(0,Math.min(i-10,s.length-Rc)),o=s.slice(a,a+Rc),d=a,c=s.length-a-o.length;return[r??"",...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(`
139
+ `)}function Lm(t,n,e){let r=Ac(t,e),s=VT(n,r);if(!(s===""||s===".."||s.startsWith(`..${bm}`)||BT(s)))return s.split(bm).join("/")}function Pm(t,n,e,r,s){let i=a=>(a.startsWith("+")||a.startsWith("-"))&&r.some(o=>a.includes(o));return Yi(t).flatMap(a=>{let o=Lm(n,e,a.path);return o===void 0||!Om.test(o)||$m.test(o)?[]:a.body.split(`
140
+ `).slice(1).some(i)?[{...s===void 0?{}:{commit:s.id},heading:s?.heading??"Uncommitted change",path:o,oldStart:a.oldStart,oldLines:a.oldLines,newStart:a.newStart,newLines:a.newLines,body:iP(a.body,i)}]:[]})}async function aP(t,n,e){let r=await dr(t,["log","--no-merges","--no-show-signature","--format=%h%x1f%ct%x1f%s",...n.logArgs,"--"]);if("error"in r)return{listed:[],total:0};let s=r.text.split(`
141
+ `).filter(a=>a.includes(""));return{listed:s.slice(0,Cm).map(a=>{let[o="",d="0",c=""]=a.split(""),l=c.length>Im?`${c.slice(0,Im)}\u2026`:c;return`${o}${Mm(Number(d)*1e3,e)}: ${l}`}),total:s.length}}async function oP(t,n){let e=await dr(t,["diff","--name-only","--no-renames","HEAD","--"]),r=await dr(t,["ls-files","--others","--exclude-standard","--"]),s=[e,r].flatMap(i=>"error"in i?[]:i.text.split(`
142
+ `).filter(a=>a!==""));return[...new Set(s.map(i=>Lm(t,n,i)).filter(i=>i!==void 0&&Om.test(i)&&!$m.test(i)))].sort().slice(0,Cm)}var Sm=["--no-color","--no-ext-diff","--no-renames","--unified=3","--src-prefix=a/","--dst-prefix=b/"];function Qi(t,n,e,r){return{omissionId:B("omi",["changes",t,e??"",n]),channel:"diff",reason:t,message:n,...e===void 0?{}:{locator:e},...r===void 0?{}:{cap:r}}}async function _m(t,n,e,r,s){let i=ve(t,"diff",`changes:${s.gitRoot??s.workspaceRoot}`),a=(T,I=[])=>({artifactId:i,channel:"diff",availability:T,...s.gitRoot===void 0?{}:{path:s.gitRoot},format:"git-change-search",warnings:I}),o=(T,I)=>({artifacts:[a(T==="irrelevant"?"empty":"unavailable")],evidence:[],redactions:[],omissions:[Qi(T,I)]});if(!s.authorized)return o("policy-disabled","Recent changes were not included (--no-changes).");if(s.gitRoot===void 0)return o("unavailable","The workspace is not in a git repository, so no changes were searched.");if(r.length===0)return o("irrelevant","The failures name no locator, value, or request path to look for in recent changes.");let d=Ac(s.gitRoot),c=Ac(s.workspaceRoot),l=nP(r),u=[];await ms(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 dr(d,["diff",...Sm,`-G${l}`,"HEAD","--"]);"error"in h?f.push(h.error):p.push(...Pm(h.text,d,c,r,void 0));let m=await sP(d,n),g=0;if(m!==void 0){let T=await dr(d,["log",...Sm,"--no-merges","--no-show-signature","--format=%x1e%h%x1f%ct%x1f%s",`-G${l}`,...m.logArgs,"--"]);if("error"in T)f.push(T.error);else for(let I of T.text.split("").slice(1)){let $=I.indexOf(`
143
+ `),[D="",k="0",S=""]=($===-1?I:I.slice(0,$)).split(""),_=Pm(I.slice($+1),d,c,r,{id:D,heading:`Commit ${D}${Mm(Number(k)*1e3,n)}: ${S}`});_.length>0&&(g+=1),p.push(..._)}}if(f.length>0&&p.length===0)return{artifacts:[a("unreadable",f)],evidence:[],redactions:[],omissions:f.map(T=>Qi("unreadable",T,s.gitRoot))};let y=[],w=[],x=f.map(T=>Qi("unreadable",T,s.gitRoot)),v=0;for(let T of p){if(y.length>=kc||v>=Rm){let k=p.length-y.length;x.push(Qi("budget-exceeded",`${k} more matching hunk${k===1?" was":"s were"} left out at the ${kc}-hunk, ${Rm}-byte limit for recent changes.`,void 0,kc));break}let I=`${T.commit??"worktree"}:${T.path}@${T.newStart}`,$=ce(`${T.heading}
144
+ ${T.path}
145
+ ${T.body}`,"diff",I,e.sensitiveNames);v+=Buffer.byteLength($.value,"utf8"),w.push(...$.records);let D={type:"diff-hunk",...T.commit===void 0?{}:{commit:T.commit},path:T.path,oldStart:T.oldStart,oldLines:T.oldLines,newStart:T.newStart,newLines:T.newLines};y.push({evidenceId:ge(t,i,"diff-hunk",D,$.value),kind:"diff-hunk",artifactId:i,locator:D,observation:$.value,availability:"present",redactionIds:$.records.map(k=>k.redactionId)})}let R=["uncommitted changes",...m===void 0?[]:[m.description]].join(" and "),P=m===void 0?{listed:[],total:0}:await aP(d,m,n),N=await oP(d,c),E=[...P.listed.length===0?[]:[`${P.total>P.listed.length?`The newest ${P.listed.length} of the ${P.total} commits searched`:"Commits searched, newest first"}: ${P.listed.join("; ")}.`],...N.length===0?[]:[`Source files with uncommitted changes: ${N.join(", ")}.`]],M=y.length,A=ce(`Searched ${R} for changed lines containing any of: ${r.map(T=>JSON.stringify(T)).join(", ")}. ${M===0?"No change mentioned them.":`${M} changed hunk${M===1?"":"s"} matched${g>0?`, from ${g} commit${g===1?"":"s"}`:""}${p.some(T=>T.commit===void 0)?" and uncommitted changes":""}.`}${E.map(T=>` ${T}`).join("")} A matching change shows what changed, not who owns the failure.`,"diff","changes:search",e.sensitiveNames);w.push(...A.records);let C={type:"report-field",path:"changes"};return y.push({evidenceId:ge(t,i,"change-search",C,A.value),kind:"change-search",artifactId:i,locator:C,observation:A.value,availability:"present",redactionIds:A.records.map(T=>T.redactionId)}),{artifacts:[a(M===0?"empty":"present",u)],evidence:y,redactions:w,omissions:x}}var dP=[137,80,78,71,13,10,26,10];function cP(t){return t<192||t>207?!1:t!==196&&t!==200&&t!==204}function lP(t){if(t.byteLength<24||dP.some((e,r)=>t[r]!==e))return;let n=new DataView(t.buffer,t.byteOffset,t.byteLength);if(String.fromCharCode(...t.subarray(12,16))==="IHDR")return{width:n.getUint32(16,!1),height:n.getUint32(20,!1)}}function uP(t){if(t.byteLength<4||t[0]!==255||t[1]!==216)return;let n=new DataView(t.buffer,t.byteOffset,t.byteLength),e=2;for(;e+9<t.byteLength;){if(t[e]!==255){e+=1;continue}let r=t[e+1];if(r===void 0)return;if(r===216||r===1||r>=208&&r<=215){e+=2;continue}let s=n.getUint16(e+2,!1);if(cP(r))return{height:n.getUint16(e+5,!1),width:n.getUint16(e+7,!1)};if(s<2)return;e+=2+s}}function pP(t){if(t.byteLength<30)return;let n=(s,i)=>String.fromCharCode(...t.subarray(s,i));if(n(0,4)!=="RIFF"||n(8,12)!=="WEBP")return;let e=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n(12,16);if(r==="VP8X"){let s=1+(e.getUint16(24,!0)|e.getUint8(26)<<16),i=1+(e.getUint16(27,!0)|e.getUint8(29)<<16);return{width:s,height:i}}if(r==="VP8 ")return{width:e.getUint16(26,!0)&16383,height:e.getUint16(28,!0)&16383};if(r==="VP8L"){let s=e.getUint32(21,!0);return{width:1+(s&16383),height:1+(s>>14&16383)}}}function Fm(t){return lP(t)??uP(t)??pP(t)}function fP(t){let n=t.toLowerCase().split(";")[0]?.trim()??"";if(n.startsWith("image/"))return"screenshot";if(n.startsWith("video/"))return"video"}function jm(t,n,e,r,s){return{omissionId:B("omi",[t.attemptId,n,e,s,r]),channel:n,reason:e,message:r,locator:s}}async function Bm(t,n,e,r){let{attachment:s}=e,i=fP(s.contentType);if(i===void 0)return{artifacts:[],evidence:[],redactions:[],omissions:[]};let a=`${e.attemptId}.attachments[${s.sourceIndex}]`,o=ve(t,i,`${e.attemptId}:${s.attachmentId}`),d={artifactId:o,channel:i,attemptId:e.attemptId,format:s.contentType},c,l,u;if(s.path!==void 0){let x=await Q(r,s.path,n.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(s.bodyBase64!==void 0&&s.bodyBase64.length>0){let x=Buffer.from(s.bodyBase64,"base64");x.byteLength>n.maxArtifactBytes?u={reason:"budget-exceeded",message:`Inline attachment exceeds the ${n.maxArtifactBytes}-byte limit.`}:c=new Uint8Array(x)}else u={reason:"unavailable",message:"Attachment supplied neither a path nor a body."};let p=ce(s.name,i,a,n.sensitiveNames);if(c===void 0){let x=u?.reason??"unavailable";return{artifacts:[{...d,availability:x==="unavailable"?"unavailable":"unreadable",...s.path===void 0?{}:{path:s.path},warnings:u===void 0?[]:[u.message]}],evidence:[],redactions:p.records,omissions:[jm(e,i,x,u?.message??"Attachment is unavailable.",a)]}}let f=Ee(c),h=i==="screenshot"?Fm(c):void 0,m=[`${i} name=${p.value}`,`contentType=${s.contentType}`,`bytes=${c.byteLength}`,...i==="screenshot"?[h===void 0?"dimensions=unknown":`dimensions=${h.width}x${h.height}`]:[],`sha256=${f}`],g={type:"media",attachmentId:s.attachmentId,sha256:f},y=m.join(" "),w=[];return i==="screenshot"&&h===void 0&&w.push(jm(e,i,"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:ge(t,o,i==="screenshot"?"image-metadata":"video-metadata",g,y),kind:i==="screenshot"?"image-metadata":"video-metadata",artifactId:o,logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:g,observation:y,availability:"present",redactionIds:p.records.map(x=>x.redactionId)}],redactions:p.records,omissions:w}}var hP=new Set(["textbox","searchbox","combobox","spinbutton"]),mP=/\s\[(?:ref=[^\]]+|cursor=[^\]]+)\]/g,Vm=/^#{1,3}\s+page snapshot\s*$/i,yP=/^#{1,3}\s+\S/,zm=2;function Hm(t){let n=t.contentType.toLowerCase().split(";")[0]?.trim()??"";return t.name==="error-context"?!0:n==="text/markdown"&&(t.path?.endsWith("error-context.md")??!1)}function gP(t){let n=t.split(/\r?\n/),e=n.some(i=>Vm.test(i.trim())),r=!e,s;for(let i=0;i<n.length;i+=1){let o=(n[i]??"").trim();if(s===void 0){if(Vm.test(o)){r=!0;continue}if(yP.test(o)){if(r&&e)break;continue}r&&/^```ya?ml\s*$/i.test(o)&&(s=i+1);continue}if(o==="```")return{scope:e?"page":"element",lines:n.slice(s,i),startLine:s+1,endLine:i}}}function Tc(t){return t.length-t.trimStart().length}function Pc(t,n,e){let r=[],s=t,i=/^(\s*-\s+)([\w-]+)(\s+"((?:[^"\\]|\\.)*)")(.*?):\s+(.+)$/.exec(s);if(i!==null&&hP.has(i[2]??"")){let d=(i[4]??"").toLowerCase(),c=[...e].map(l=>l.toLowerCase()).sort().find(l=>d.includes(l));c!==void 0&&(s=`${i[1]}${i[2]}${i[3]}${i[5]}: [REDACTED]`,r.push({redactionId:B("red",["accessibility",n,`field:${c}`]),ruleId:`sensitive-field:${c}`,channel:"accessibility",locator:n,action:"mask",count:1}))}let a=/^(\s*-\s+\/url:\s+)(.+)$/.exec(s);if(a!==null){let d=(a[2]??"").replace(/^"(.*)"$/,"$1"),c=Ht(d,"accessibility",n,e);s=`${a[1]}${c.value}`,r.push(...c.records)}let o=ce(s,"accessibility",n,e);return{value:o.value,records:[...r,...o.records]}}function wP(t,n,e){if(t.reduce((u,p)=>u+Buffer.byteLength(p,"utf8")+1,0)<=e)return{lines:t,dropped:0};let s=[...new Set(n.flatMap(u=>rr(u)))],i=new Set,a=u=>{i.add(u);let p=Tc(t[u]??"");for(let f=u-1;f>=0&&p>0;f-=1){let h=Tc(t[f]??"");h<p&&(i.add(f),p=h)}};t.forEach((u,p)=>{let f=u.toLowerCase();if(s.some(h=>f.includes(h)))for(let h=Math.max(0,p-zm);h<=Math.min(t.length-1,p+zm);h+=1)a(h)});let o=[...i].reduce((u,p)=>u+Buffer.byteLength(t[p]??"","utf8")+1,0);for(let u=0;u<t.length&&o<e;u+=1){if(i.has(u))continue;let p=Buffer.byteLength(t[u]??"","utf8")+1;if(o+p>e)break;i.add(u),o+=p}let d=[],c=!1,l=0;for(let u=0;u<t.length;u+=1){if(!i.has(u)){c=!0;continue}let p=t[u]??"",f=Buffer.byteLength(p,"utf8")+1;if(l+f>e){c=!0;break}c&&d.push(`${" ".repeat(Tc(p))}\u2026`),c=!1,d.push(p),l+=f}return c&&d.push("\u2026"),{lines:d,dropped:t.length-d.filter(u=>u.trim()!=="\u2026").length}}async function Um(t,n,e,r){let{attachment:s}=e,i=ve(t,"accessibility",`${e.attemptId}:${s.attachmentId}`),a=`${e.attemptId}.attachments[${s.sourceIndex}]`,o={artifactId:i,channel:"accessibility",availability:"present",format:"playwright-error-context",attemptId:e.attemptId,warnings:[]},d=(R,P,N)=>({omissionId:B("omi",[e.attemptId,"accessibility",R,a,P]),channel:"accessibility",reason:R,message:P,locator:a,...N===void 0?{}:{cap:N}}),c,l;if(s.path!==void 0){let R=await Q(r,s.path,n.maxArtifactBytes);if(R.kind!=="read"){let P=R.kind==="over-budget"?"budget-exceeded":R.kind==="unauthorized"?"unauthorized-path":R.kind;return{artifacts:[{...o,availability:R.kind==="unavailable"?"unavailable":"unreadable",path:s.path,warnings:[R.message]}],evidence:[],redactions:[],omissions:[d(P,R.message)]}}c=R.bytes,l=R.relativePath}else s.bodyBase64!==void 0&&s.bodyBase64.length>0&&(c=new Uint8Array(Buffer.from(s.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=Ee(c),p={...o,sha256:u,...l===void 0?{}:{path:l}},f=ze(c),h=f===void 0?void 0:gP(bt(f));if(h===void 0||h.lines.every(R=>R.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 m=[],g=h.lines.map((R,P)=>{let N=Pc(R.replace(mP,""),`${a}#line=${h.startLine+P}`,n.sensitiveNames);return m.push(...N.records),N.value}),y=wP(g,e.focus,n.maxDomTextBytes),w=[];y.dropped>0&&w.push(d("budget-exceeded",`Kept ${g.length-y.dropped} of ${g.length} page snapshot lines, favouring those that mention the failed locator.`,n.maxDomTextBytes));let x=`${h.scope==="page"?"Accessibility snapshot of the page when the test failed":"Accessibility snapshot of the element the failed assertion checked"}:
146
+ ${y.lines.join(`
147
+ `)}`,v={type:"attachment-text",attachmentId:s.attachmentId,sha256:u,startLine:h.startLine,endLine:h.endLine};return{artifacts:[p],evidence:[{evidenceId:ge(t,i,"page-snapshot",v,x),kind:"page-snapshot",artifactId:i,logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:v,observation:x,availability:"present",redactionIds:m.map(R=>R.redactionId)}],redactions:m,omissions:w}}var bP=256*1024,xP=10,qm=200;async function Gm(t,n,e,r){let s=ve(t.runId,"probe",e),i=(h,m,g=e)=>({omissionId:B("omi",[t.runId,"probe",h,g,m]),channel:"probe",reason:h,message:m,locator:g}),a=await Q(r,e,bP);if(a.kind!=="read")return{artifacts:[{artifactId:s,channel:"probe",availability:"unavailable",warnings:[a.message]}],evidence:[],redactions:[],omissions:[i("unavailable",a.message)]};let o={artifactId:s,channel:"probe",availability:"present",path:a.relativePath,sha256:a.sha256,format:"kwikqa-playwright-cli-probe",warnings:[]},d;try{d=me(JSON.parse(ze(a.bytes)??""))}catch{d=void 0}if(d===void 0||V(d.schemaVersion)!=="1.0")return{artifacts:[{...o,availability:"unreadable"}],evidence:[],redactions:[],omissions:[i("unrecognized","The probe results are not in a recognized format.")]};let c=me(d.tool),l=`Playwright CLI ${V(c?.version)??"unknown"}, Playwright ${V(d.playwrightVersion)??"unknown"}`,u=[],p=[],f=[];return Xe(d.results)?.forEach((h,m)=>{let g=me(h);if(g===void 0)return;let y=V(g.logicalTestId),w=t.logicalTests.find(T=>T.logicalTestId===y)??t.logicalTests.find(T=>T.title===V(g.title)&&T.location.file===V(g.file)&&T.location.line===Ae(g.line)),x=w?.attempts.at(-1),v=`${a.relativePath}#results[${m}]`;for(let T of Xe(g.issues)??[]){let I=V(T);I!==void 0&&f.push(i("unavailable",`Live probe of "${V(g.title)??"a test"}": ${I}`,v))}let R=(Xe(g.candidates)??[]).map(T=>me(T)).filter(T=>T!==void 0).slice(0,xP);if(w===void 0||R.length===0)return;let P=[],N=[];R.forEach((T,I)=>{let $=Pc(`- ${(V(T.element)??"").slice(0,qm)}`,`${v}/candidates[${I}]`,n.sensitiveNames),D=ce((V(T.locator)??"").slice(0,qm),"probe",`${v}/candidates[${I}]/locator`,n.sensitiveNames);p.push(...$.records,...D.records),N.push(...$.records.map(k=>k.redactionId),...D.records.map(k=>k.redactionId)),P.push(`${$.value.replace(/^- /,"")} \u2192 ${D.value}`)});let E=V(g.locator),A=[`Live page paused at ${`${V(g.file)??w.location.file}:${Ae(g.failingLine)??"?"}`}, before the failing step (${l}).${E===void 0?"":` The failed locator was ${E}.`} Locators Playwright generated for the elements most like it:`,...P].join(`
148
+ `),C={type:"report-field",path:`probe.results[${m}]`};u.push({evidenceId:ge(t.runId,s,"locator-suggestion",C,A),kind:"locator-suggestion",artifactId:s,logicalTestId:w.logicalTestId,...x===void 0?{}:{attemptId:x.attemptId},locator:C,observation:A,availability:"present",redactionIds:N})}),{artifacts:[{...o,availability:u.length>0?"present":"empty"}],evidence:u,redactions:p,omissions:f}}var vP=/(?:\(|\bat\s+|^)((?:[A-Za-z]:)?[^():\s][^():]*?):(\d+):(\d+)\)?\s*$/,kP=/^File "([^"]+\.py)", line (\d+)/,RP=/^((?:[A-Za-z]:)?[^\s:][^:]*\.py):(\d+):(?:\s|$)/,IP=/(?:^|[\\/])(?:node_modules|site-packages|\.venv|venv)[\\/]|[\\/]lib[\\/]python\d|^node:|^internal\//;function Sc(t,n,e){let r=[];return t.split(/\r?\n/).forEach((s,i)=>{let a=s.trim().replace(/webpack:\/\/[^/\s()]*\//g,"").replace(/^❯\s+/,""),o=Jn(a);if(o!==void 0){r.push({file:o.file,line:o.line,origin:`${n}#frame=${i+1}`,...e});return}let d=kP.exec(a)??RP.exec(a),c=d===null?vP.exec(a):[d[0],d[1],d[2],"1"];if(c===null)return;let[,l,u,p]=c;l===void 0||u===void 0||p===void 0||IP.test(l)||r.push({file:l.replace(/^file:\/\//,"").replace(/^(?:\.\/)+/,""),line:Number.parseInt(u,10),column:Number.parseInt(p,10),origin:`${n}#frame=${i+1}`,...e})}),r}async function Km(t,n){if(!t.some(s=>bi(s.file)))return t;let e=new Wn(n);return(await Promise.all(t.map(async s=>{if(!bi(s.file))return s;let i=await e.find(s.file);return i===void 0?void 0:{...s,file:i}}))).filter(s=>s!==void 0)}function ys(t,n,e,r,s,i,a){let o=`${r}:${s}`;if(e.reported.has(o))return;e.reported.add(o);let d=`Reached the ${i}-${s} limit; later observations were not included.`;n.push({omissionId:B("omi",[t.runId,r,"budget-exceeded",a,d]),channel:r,reason:"budget-exceeded",message:d,locator:a,cap:i})}function Ec(t,n,e){return t===void 0?[]:[{file:t.file,line:t.line??1,...t.column===void 0?{}:{column:t.column},origin:n,...e}]}function Cc(t,n,e){let r=[...Ec(t.location,`${n}.location`,e)];return t.stack!==void 0&&r.push(...Sc(t.stack,`${n}.stack`,e)),r}function Wm(t,n,e){let r=[];return t.forEach((s,i)=>{let a=`${n}[${i}]`;s.error!==void 0&&r.push(...Cc(s.error,a,e)),r.push(...Wm(s.steps,`${a}.steps`,e))}),r}function AP(t){let n=[];for(let e of t.logicalTests){for(let r of e.attempts){let s={logicalTestId:e.logicalTestId,attemptId:r.attemptId};n.push(...Ec(r.errorLocation,`${r.attemptId}.errorLocation`,s));for(let i of r.errors)n.push(...Cc(i,i.source,s));n.push(...Wm(r.steps,`${r.attemptId}.steps`,s))}n.push(...Ec(e.location,`${e.logicalTestId}.location`,{logicalTestId:e.logicalTestId}))}for(let e of t.reportErrors)n.push(...Cc(e,e.source,{}));return n}function Zi(t,n,e,r,s,i,a,o,d,c,l){if(c.reportFields>=n.maxReportFields){ys(t,d,c,"report","field",n.maxReportFields,s);return}c.reportFields+=1;let u=ce(i,e.channel,s,n.sensitiveNames);o.push(...u.records);let p={type:"report-field",path:s};a.push({evidenceId:ge(t.runId,e.artifactId,r,p,u.value),kind:r,artifactId:e.artifactId,...l,locator:p,observation:u.value,availability:u.value.length===0?"empty":"present",redactionIds:u.records.map(f=>f.redactionId)})}function Nc(t,n,e,r,s,i,a,o,d){let c=[["name",r.name],["message",r.message],["value",r.value],["snippet",r.snippet]];for(let[l,u]of c)u!==void 0&&Zi(t,n,e,"error-field",`${r.source}.${l}`,u,s,i,a,o,d);r.stack!==void 0&&(Zi(t,n,e,"error-field",`${r.source}.stack`,r.stack,s,i,a,o,d),r.stack.split(/\r?\n/).forEach((l,u)=>{if(l.trim().length===0)return;let p=`${r.source}.stack#line=${u+1}`;if(o.stackFrames>=n.maxStackFrames){ys(t,a,o,"report","stack-frame",n.maxStackFrames,p);return}o.stackFrames+=1,Zi(t,n,e,"stack-frame",p,l,s,i,a,o,d)}))}function Jm(t,n,e,r,s,i,a,o,d,c){r.forEach((l,u)=>{let p=`${s}[${u}]`;if(d.steps>=n.maxSteps){ys(t,o,d,"report","step",n.maxSteps,p);return}d.steps+=1,Zi(t,n,e,"step",`${p}.title`,l.title,i,a,o,d,c),l.error!==void 0&&Nc(t,n,e,l.error,i,a,o,d,c),Jm(t,n,e,l.steps,`${p}.steps`,i,a,o,d,c)})}function TP(t){if(t.kind==="text")return t.text;let n=Buffer.from(t.base64,"base64");return`binary stdio: sha256=${Ee(n)} bytes=${n.byteLength}`}function Xm(t,n){let e={artifactId:ve(t.runId,"report",t.artifact.artifactId),channel:"report",availability:t.artifact.availability,...t.artifact.path===void 0?{}:{path:t.artifact.path},...t.artifact.sha256===void 0?{}:{sha256:t.artifact.sha256},...t.artifact.formatVersion===void 0?{}:{producerVersion:t.artifact.formatVersion},warnings:t.artifact.warnings},r=[e],s=[],i=[],a=[],o={reportFields:0,stackFrames:0,steps:0,stdioChunks:0,stdioBytes:0,reported:new Set};t.reportErrors.forEach(d=>{Nc(t,n,e,d,s,i,a,o,{})});for(let d of t.logicalTests)for(let c of d.attempts){let l={logicalTestId:d.logicalTestId,attemptId:c.attemptId};c.errors.forEach(u=>{Nc(t,n,e,u,s,i,a,o,l)}),Jm(t,n,e,c.steps,`${c.attemptId}.steps`,s,i,a,o,l);for(let u of["stdout","stderr"]){let p=c[u],f={artifactId:ve(t.runId,u,c.attemptId),channel:u,availability:p.length===0?"empty":"present",attemptId:c.attemptId,warnings:[]};r.push(f);let h=0;p.forEach((m,g)=>{let y=m.kind==="text"?Buffer.byteLength(m.text,"utf8"):Buffer.from(m.base64,"base64").byteLength,w=`${c.attemptId}.${u}[${g}]`;if(o.stdioChunks>=n.maxStdioChunks){ys(t,a,o,u,"stdio-chunk",n.maxStdioChunks,w),h+=y;return}if(o.stdioBytes+y>n.maxStdioBytes){ys(t,a,o,u,"stdio-byte",n.maxStdioBytes,w),h+=y;return}o.stdioChunks+=1,o.stdioBytes+=y;let x=TP(m),v=ce(x,u,w,n.sensitiveNames);i.push(...v.records);let R={type:"stdio",stream:u,chunk:g,startByte:h,endByte:h+y};h+=y,s.push({evidenceId:ge(t.runId,f.artifactId,"stdio-chunk",R,v.value),kind:"stdio-chunk",artifactId:f.artifactId,...l,locator:R,observation:v.value,availability:x.length===0?"empty":"present",redactionIds:v.records.map(P=>P.redactionId)})})}}return{artifacts:r,evidence:s,redactions:i,omissions:a,seeds:AP(t)}}var ny=oi(ns(),1);import{dirname as PP,extname as ty,join as Ym}from"node:path/posix";var SP=new Set(["test","it","describe","suite","step","beforeEach","afterEach","beforeAll","afterAll"]),Qm=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],EP=new Set([".js",".mjs",".cjs"]),CP=[".ts",".tsx",".mts",".cts"];function NP(t){return t.split("/").includes("node_modules")}function Ye(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.type=="string"}function gs(t,n,e=new Set){if(!e.has(t)){e.add(t),n(t);for(let r of Object.keys(t)){if(r==="loc")continue;let s=t[r];if(Array.isArray(s))for(let i of s)Ye(i)&&gs(i,n,e);else Ye(s)&&gs(s,n,e)}}}function kn(t){if(Ye(t)&&t.type==="Identifier")return typeof t.name=="string"?t.name:void 0}function cr(t){if(Ye(t)){if(t.type==="Identifier"&&typeof t.name=="string")return t.name;if(t.type==="StringLiteral"&&typeof t.value=="string")return t.value}}function ry(t){if(Ye(t)){if(t.type==="Identifier")return typeof t.name=="string"?t.name:void 0;if(t.type==="MemberExpression"){let n=ry(t.object),e=cr(t.property);return n===void 0||e===void 0?void 0:`${n}.${e}`}}}function OP(t){let n=ry(t.callee);if(n===void 0)return;let e=n.split(".").pop()??n;if(!SP.has(e))return;let s=(Array.isArray(t.arguments)?t.arguments:[])[0];if(!(!Ye(s)||s.type!=="StringLiteral"||typeof s.value!="string"))return`${n}("${s.value}")`}function sy(t){switch(t.type){case"FunctionDeclaration":case"ClassDeclaration":case"TSInterfaceDeclaration":case"TSTypeAliasDeclaration":case"TSEnumDeclaration":case"TSModuleDeclaration":return kn(t.id);case"ClassMethod":case"ObjectMethod":case"ClassProperty":case"PropertyDefinition":return cr(t.key);case"VariableDeclarator":return kn(t.id);case"CallExpression":return OP(t);default:return}}function $P(t,n){let e=t.loc;return e==null?!1:e.start.line<=n&&e.end.line>=n}function DP(t,n){let e;return gs(t,r=>{let s=sy(r);if(s===void 0||!$P(r,n))return;let i=r.loc;if(i==null)return;let a={name:s,startLine:i.start.line,endLine:i.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 MP(t){let n=sy(t);return n!==void 0&&t.type!=="CallExpression"?[n]:t.type==="VariableDeclaration"&&Array.isArray(t.declarations)?t.declarations.map(e=>Ye(e)?kn(e.id):void 0).filter(e=>e!==void 0):[]}function LP(t,n){let e=Array.isArray(t.program)?[]:t.program?.body,r=Array.isArray(e)?e:[],s=[];for(let i of r){if(!Ye(i))continue;let a=i.loc;if(a==null)continue;if(i.type==="ExportDefaultDeclaration"&&n.has("default")){s.push({name:"default",startLine:a.start.line,endLine:a.end.line});continue}if(i.type==="ExportNamedDeclaration"&&Array.isArray(i.specifiers))for(let d of i.specifiers){if(!Ye(d))continue;let c=cr(d.exported);c!==void 0&&n.has(c)&&s.push({name:c,startLine:a.start.line,endLine:a.end.line})}let o=i.type==="ExportNamedDeclaration"&&Ye(i.declaration)?i.declaration:i;for(let d of MP(o))n.has(d)&&s.push({name:d,startLine:a.start.line,endLine:a.end.line})}return s}function _P(t){let n=[];return gs(t,e=>{if(e.type!=="ImportDeclaration"&&e.type!=="ExportNamedDeclaration"&&e.type!=="ExportAllDeclaration")return;let r=Ye(e.source)?e.source.value:void 0;if(typeof r!="string")return;let s=[],i;for(let a of Array.isArray(e.specifiers)?e.specifiers:[])if(Ye(a)){if(e.type==="ExportNamedDeclaration"){let o=cr(a.exported),d=cr(a.local);o!==void 0&&d!==void 0&&s.push({imported:d,local:o})}else if(a.type==="ImportDefaultSpecifier"){let o=kn(a.local);o!==void 0&&s.push({imported:"default",local:o})}else if(a.type==="ImportNamespaceSpecifier")i=kn(a.local);else if(a.type==="ImportSpecifier"){let o=cr(a.imported)??kn(a.local),d=kn(a.local);o!==void 0&&d!==void 0&&s.push({imported:o,local:d})}}n.push({specifier:r,bindings:s,...i===void 0?{}:{namespaceLocal:i},exportStar:e.type==="ExportAllDeclaration"})}),n}function Zm(t,n,e){let r=new Set;return gs(t,s=>{let i=s.loc;i==null||i.end.line<n||i.start.line>e||s.type==="Identifier"&&typeof s.name=="string"&&r.add(s.name)}),r}function jP(t){let n=ty(t).toLowerCase();return n===".tsx"?["typescript","jsx"]:[".ts",".mts",".cts"].includes(n)?["typescript"]:["jsx"]}var iy=/\.[cm]?[jt]sx?$/i,FP=10;function BP(t,n){if(!iy.test(n))return{};try{return{ast:(0,ny.parse)(t,{sourceType:"module",allowReturnOutsideFunction:!0,errorRecovery:!1,plugins:jP(n)})}}catch(e){return{error:e instanceof Error?e.message:"Source could not be parsed."}}}function VP(t,n){if(!t.startsWith("./")&&!t.startsWith("../"))return[];let e=Ym(n,t),r=[e],s=ty(e).toLowerCase();if(EP.has(s)){let i=e.slice(0,e.length-s.length);for(let a of CP)r.push(`${i}${a}`)}if(s===""){for(let i of Qm)r.push(`${e}${i}`);for(let i of Qm)r.push(Ym(e,`index${i}`))}return r}function lt(t,n,e,r,s){t.omissions.push({omissionId:B("omi",["source",n,r,e]),channel:"source",reason:n,message:e,locator:r,...s===void 0?{}:{cap:s}})}async function ay(t,n){let e=await ds(t.workspaceRoot,n);if(e.kind!=="authorized"){lt(t,e.kind==="unauthorized"?"unauthorized-path":e.kind,e.message,n);return}if(NP(e.relativePath)){lt(t,"policy-disabled","Dependency source under node_modules is out of scope for evidence.",e.relativePath);return}let r=t.files.get(e.relativePath);if(r!==void 0)return r;if(t.files.size>=t.policy.maxSourceFiles){t.filesReported||(t.filesReported=!0,lt(t,"budget-exceeded",`Reached the ${t.policy.maxSourceFiles}-file source limit; later files were not read.`,e.relativePath,t.policy.maxSourceFiles));return}let s=await Q(t.workspaceRoot,e.relativePath,t.policy.maxArtifactBytes);if(s.kind!=="read"){let c=s.kind==="over-budget"?"budget-exceeded":s.kind==="unauthorized"?"unauthorized-path":s.kind;lt(t,c,s.message,e.relativePath);return}let i=ze(s.bytes);if(i===void 0){lt(t,"unreadable","Source file is not valid UTF-8.",s.relativePath);return}let a=BP(i,s.relativePath);a.error!==void 0&&lt(t,"parse-failed",`Symbol boundaries are unavailable: ${a.error}`,s.relativePath);let o={artifactId:ve(t.runId,"source",s.relativePath),channel:"source",availability:"present",path:s.relativePath,sha256:s.sha256,warnings:a.error===void 0?[]:[a.error]},d={relativePath:s.relativePath,sha256:s.sha256,lines:i.split(/\r?\n/),ast:a.ast,artifact:o};return t.files.set(s.relativePath,d),t.artifacts.push(o),d}function ey(t,n,e,r,s){let i=t.policy.maxSourceLinesPerFile,a=Math.max(1,e.startLine),o=Math.min(n.lines.length,e.endLine);if(o<a)return;o-a+1>i&&(o=a+i-1,lt(t,"budget-exceeded",`Symbol context in ${n.relativePath} was truncated to ${i} lines.`,`${n.relativePath}:${a}`,i));let d=`${n.relativePath}:${a}:${o}:${s.logicalTestId??""}:${s.attemptId??""}:${r}`;if(t.emitted.has(d))return;t.emitted.add(d);let c=n.lines.slice(a-1,o).join(`
149
+ `),l=ce(c,"source",`${n.relativePath}:${a}-${o}`,t.policy.sensitiveNames),u=Buffer.byteLength(l.value,"utf8");if(t.emittedBytes+u>t.policy.maxSourceBytes){t.bytesReported||(t.bytesReported=!0,lt(t,"budget-exceeded",`Reached the ${t.policy.maxSourceBytes}-byte source limit; later ranges were not included.`,n.relativePath,t.policy.maxSourceBytes));return}t.emittedBytes+=u,t.redactions.push(...l.records);let p=n.lines[o-1]??"",f={type:"source-range",path:n.relativePath,sha256:n.sha256,startLine:a,startColumn:1,endLine:o,endColumn:p.length+1,...e.symbol===void 0?{}:{symbol:e.symbol}},h=`${r}
150
+ ${l.value}`;t.evidence.push({evidenceId:ge(t.runId,n.artifact.artifactId,"source-range",f,h),kind:"source-range",artifactId:n.artifact.artifactId,...s,locator:f,observation:h,availability:"present",redactionIds:l.records.map(m=>m.redactionId)})}async function zP(t,n,e){for(let r of VP(n,e)){let s=await ds(t.workspaceRoot,r);if(s.kind==="authorized")return await ay(t,s.relativePath)}lt(t,"unavailable",`Relative import ${n} did not resolve to a readable workspace file.`,e)}async function oy(t,n,e,r){let s={runId:t,policy:n,workspaceRoot:r,files:new Map,artifacts:[],evidence:[],redactions:[],omissions:[],emitted:new Set,traversed:new Set,emittedBytes:0,filesReported:!1,bytesReported:!1},i=new Set,a=[];for(let d of e){let c=`${d.file}:${d.line}:${d.logicalTestId??""}:${d.attemptId??""}:${d.origin}`;if(i.has(c))continue;i.add(c);let l=await ay(s,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:DP(l.ast,d.line),f=iy.test(l.relativePath)?Math.floor(n.maxSourceLinesPerFile/2):FP,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:Zm(l.ast,h.startLine,h.endLine)}),ey(s,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<=n.maxImportDepth;d+=1){let c=[];for(let l of o){let u=l.file;if(u.ast!==void 0)for(let p of _P(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)){lt(s,"policy-disabled",`Namespace import of ${p.specifier} was not expanded; only named symbols are followed.`,u.relativePath);continue}if(p.exportStar){lt(s,"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 zP(s,p.specifier,PP(u.relativePath));if(h===void 0||h.ast===void 0)continue;let m=l.linkage,g=`${h.relativePath}:${[...f].sort().join(",")}:${m.logicalTestId??""}:${m.attemptId??""}`;if(s.traversed.has(g))continue;s.traversed.add(g);let y=LP(h.ast,f),w=new Set;for(let x of y){for(let v of Zm(h.ast,x.startLine,x.endLine))w.add(v);ey(s,h,{startLine:x.startLine,endLine:x.endLine,symbol:x.name},`${h.relativePath} exports ${x.name}, imported by ${u.relativePath} (depth ${d})`,m)}c.some(x=>x.file===h&&x.linkage.attemptId===m.attemptId)||c.push({file:h,linkage:m,referenced:w})}}if(o=c,o.length===0)break}return{artifacts:s.artifacts,evidence:s.evidence,redactions:s.redactions,omissions:s.omissions}}var HP=["report","trace","stdout","stderr","screenshot","video","dom","accessibility","console","network","source","diff","probe"],UP=["trace","console","network","dom","accessibility"],qP=8,GP=12,KP=5,WP=/\b(?:getBy\w+|locator|frameLocator)\((?:[^()]|\([^()]*\))*\)/g,JP=[/Unable to locate element: \{"method":"[^"]+","selector":"((?:[^"\\]|\\.)+)"\}/g,/\b(By\.\w+: [^,\s)]+)/g,/Expected to find element: `([^`]+)`/g,/within the selector: '([^']+)'/g,/expected '<([a-z][\w-]*(?:[#.][\w-]+)*)>'/gi,/\bselector "([^"]+)"/g,/\belement \("([^"]+)"\)/g,/\${1,2}\(`([^`]+)`\)/g];function ws(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function ea(t,n){return[...t].sort((e,r)=>n(e).localeCompare(n(r)))}function XP(t){return t.length===0?"unavailable":t.some(n=>n.availability==="present")?"present":t.some(n=>n.availability==="empty")?"empty":t.some(n=>n.availability==="unreadable")?"unreadable":"unavailable"}function YP(t,n,e,r,s){let i=n.filter(l=>l.channel===t),a=new Set(i.map(l=>l.artifactId)),o=e.filter(l=>a.has(l.artifactId)),d=r.filter(l=>l.channel===t),c=s.filter(l=>l.channel===t);return{channel:t,availability:XP(i),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:ws({artifacts:i,evidence:o,redactions:c,omissions:d})}}function dy(t,n,e){return{omissionId:B("omi",[t,n,"unavailable",e]),channel:n,reason:"unavailable",message:e,locator:t}}function cy(t,n){return n?.[t.attachmentId]!==void 0?!0:t.name==="trace"&&t.contentType==="application/zip"}function lr(t){return t.attempts.filter(n=>n.status==="interrupted"?!0:t.status==="unexpected"?n.status!=="skipped":t.status==="flaky"?n.status!=="passed"&&n.status!=="skipped":!1)}function QP(t){return{...t,logicalTests:t.logicalTests.map(n=>({...n,attempts:lr(n)})).filter(n=>n.attempts.length>0)}}function ZP(t,n){let e={expected:0,unexpected:0,flaky:0,skipped:0};for(let a of t.logicalTests)e[a.status]+=1;let r=n.logicalTests.reduce((a,o)=>a+o.attempts.length,0),s=[...new Set(t.logicalTests.map(a=>a.projectId))].length,i=t.artifact.formatVersion===void 0?"":` ${t.artifact.formatVersion}`;return[`${wt[t.framework]}${i} run of ${t.logicalTests.length} tests in ${s} project${s===1?"":"s"}`,`${e.expected} passed, ${e.unexpected} failed, ${e.flaky} flaky, ${e.skipped} skipped`,`evidence covers the ${r} failing attempt${r===1?"":"s"} of ${n.logicalTests.length} test${n.logicalTests.length===1?"":"s"}; passing tests are only counted.`].join("; ")}function bs(t){let n=t.errors.map(r=>`${r.message??""}
151
+ ${r.stack??""}`),e=n.flatMap(r=>JP.flatMap(s=>[...r.matchAll(s)].map(i=>(i[1]??"").replace(/\\(.)/g,"$1"))));return[...new Set([...n.flatMap(r=>r.match(WP)??[]),...e.filter(r=>r!=="")])]}function eS(t,n,e,r,s){let i=t.attemptId===void 0?0:r.get(t.attemptId)??0;if(s.has(t.evidenceId))return re.afterFailure;switch(t.kind){case"error-field":case"run-summary":case"change-search":return re.failure;case"locator-suggestion":return re.failedCall+.95-Math.min(.5,i/1e3);case"page-snapshot":case"dom-subtree":case"dom-candidates":case"accessibility-node":{let o=t.kind==="accessibility-node"?.5:.9;return i<KP?re.failedCall+o-i/1e3:re.context+o-Math.min(.8,i/1e3)}default:break}let a=n.get(t.evidenceId);if(a!==void 0)return a;switch(t.kind){case"stack-frame":return/node_modules|node:internal/.test(t.observation)?re.ordinary:re.failedCall;case"source-range":{let o=e.get(t.evidenceId)??0;return re.significant-Math.min(.9,o/100)}case"diff-hunk":return re.failedCall+.9;case"step":return re.context;default:return re.ordinary}}async function ta(t,n,e){let r=rc(e);if(r!==void 0)return{kind:"invalid-policy",message:r};if(e.workspaceRoot!==t.workspace.root)return{kind:"invalid-policy",message:"Evidence policy workspaceRoot must match the normalized run workspace root."};let s=n.artifactRoot??t.workspace.root,i=QP(t),a=Xm(i,e),o=[...a.artifacts],d=[...a.evidence],c=[...a.redactions],l=[...a.omissions],u=[...a.seeds],p=new Map,f=a.artifacts.find(E=>E.channel==="report");if(f!==void 0&&t.logicalTests.length>0){let E={type:"report-field",path:"stats"},M=ZP(t,i);d.push({evidenceId:ge(t.runId,f.artifactId,"run-summary",E,M),kind:"run-summary",artifactId:f.artifactId,locator:E,observation:M,availability:"present",redactionIds:[]})}for(let E of i.logicalTests)for(let M of E.attempts){let A=0,C=0,T=0,I=[...bs(M)];for(let $ of M.attachments){if(!cy($,n.tracePaths))continue;let D=n.tracePaths?.[$.attachmentId]??$.path;if(D===void 0){l.push(dy(M.attemptId,"trace","Trace attachment supplied no path; inline trace bodies are not read."));continue}A+=1;let k=await hm(t.runId,e,{attachmentId:$.attachmentId,logicalTestId:E.logicalTestId,attemptId:M.attemptId,path:D,info:{...t.artifact.formatVersion===void 0?{}:{producerVersion:t.artifact.formatVersion},format:"playwright-trace-zip"}},s);o.push(...k.artifacts),d.push(...k.evidence),c.push(...k.redactions),l.push(...k.omissions),u.push(...k.seeds),I.push(...k.failedSelectors);for(let[S,_]of k.priorities)p.set(S,_)}for(let $ of M.attachments){if(!bc($))continue;C+=1;let D=await gm(t.runId,e,{logicalTestId:E.logicalTestId,attemptId:M.attemptId,attachment:$,focus:I},s);o.push(...D.artifacts),d.push(...D.evidence),c.push(...D.redactions),l.push(...D.omissions),I.push(...D.failedSelectors);for(let[k,S]of D.priorities)p.set(k,S)}for(let $ of M.attachments){if(cy($,n.tracePaths)||bc($))continue;if(Hm($)){T+=1;let k=await Um(t.runId,e,{logicalTestId:E.logicalTestId,attemptId:M.attemptId,attachment:$,focus:I},s);o.push(...k.artifacts),d.push(...k.evidence),c.push(...k.redactions),l.push(...k.omissions);continue}let D=await Bm(t.runId,e,{logicalTestId:E.logicalTestId,attemptId:M.attemptId,attachment:$},s);o.push(...D.artifacts),d.push(...D.evidence),c.push(...D.redactions),l.push(...D.omissions)}if(A===0&&C===0){let $=t.framework==="playwright"?"Attempt produced no trace attachment.":"Attempt has no KwikQA failure capture; run `kwikqa analyze --capture` to record the page.";for(let D of UP)D==="accessibility"&&T>0||l.push(dy(M.attemptId,D,$))}}if(n.probePath!==void 0){let E=await Gm(i,e,n.probePath,t.workspace.root);o.push(...E.artifacts),d.push(...E.evidence),c.push(...E.redactions),l.push(...E.omissions)}let h=await oy(t.runId,e,await Km(u,t.workspace.root),t.workspace.root);o.push(...h.artifacts),d.push(...h.evidence),c.push(...h.redactions),l.push(...h.omissions);let m=new Map(h.evidence.map((E,M)=>[E.evidenceId,M])),g=h.artifacts.map(E=>E.path).filter(E=>E!==void 0),y=await wm(t.runId,e,g,{authorized:n.includeCurrentDiff===!0,workspaceRoot:t.workspace.root,...t.workspace.gitRoot===void 0?{}:{gitRoot:t.workspace.gitRoot}});o.push(...y.artifacts),d.push(...y.evidence),c.push(...y.redactions),l.push(...y.omissions);let w=await _m(t.runId,t.createdAt,e,Dm(i.logicalTests.flatMap(E=>E.attempts),bs,d.filter(E=>E.kind==="network-event").map(E=>E.observation)),{authorized:n.includeChangeHistory===!0,workspaceRoot:t.workspace.root,...t.workspace.gitRoot===void 0?{}:{gitRoot:t.workspace.gitRoot}});o.push(...w.artifacts),d.push(...w.evidence),c.push(...w.redactions),l.push(...w.omissions);let x=ea(o,E=>E.artifactId),v=new Map(x.map(E=>[E.artifactId,E.channel])),R=(E,M,A)=>{let C=ea(E,S=>S.evidenceId),T=ea(M,S=>S.redactionId),I=ea(A,S=>S.omissionId),$=HP.map(S=>YP(S,x,C,I,T)),D=S=>{let _={schemaVersion:"1.2",runId:t.runId,framework:t.framework,createdAt:t.createdAt,workspace:t.workspace,sourceHashes:t.sourceHashes,policy:e,artifacts:x,evidence:C,redactions:T,omissions:I,accounting:$,totals:{artifacts:x.length,evidence:C.length,redactions:T.length,omissions:I.length,serializedBytes:S}};return{..._,packetHash:nr(_)}},k=D(0);for(let S=0;S<qP;S+=1){let _=ws(k);if(k.totals.serializedBytes===_)break;k=D(_)}return k},P=R(d,c,l),N=ws(P);if(N>e.maxPacketBytes){let E=new Set(d.flatMap(k=>k.redactionIds)),M=new Map(d.map(k=>[k.evidenceId,k])),A=new Map(i.logicalTests.flatMap(k=>k.attempts).map((k,S)=>[k.attemptId,S])),C=new Set,T=new Set;for(let k of[...d].sort((S,_)=>(A.get(S.attemptId??"")??0)-(A.get(_.attemptId??"")??0)||S.evidenceId.localeCompare(_.evidenceId))){if(k.kind==="error-field"||k.kind==="run-summary"||k.kind==="change-search")continue;let S=`${k.kind}
152
+ ${k.observation}`;T.has(S)?C.add(k.evidenceId):T.add(S)}let I=d.map(k=>({item:k,priority:eS(k,p,m,A,C)})).filter(k=>k.priority<re.failure).sort((k,S)=>k.priority-S.priority||k.item.evidenceId.localeCompare(S.item.evidenceId)),$=new Set,D=0;for(let k=0;k<GP&&N>e.maxPacketBytes;k+=1){let S=N-e.maxPacketBytes*.97;for(;S>0&&D<I.length;){let X=I[D++];if(X===void 0)break;$.add(X.item.evidenceId),S-=ws(X.item)+64}let _=d.filter(X=>!$.has(X.evidenceId)),U=new Set(_.flatMap(X=>X.redactionIds)),K=c.filter(X=>!E.has(X.redactionId)||U.has(X.redactionId)),te=new Map;for(let X of $){let Ie=M.get(X),Se=Ie===void 0?void 0:v.get(Ie.artifactId);Se!==void 0&&te.set(Se,(te.get(Se)??0)+1)}let le=[...te.entries()].map(([X,Ie])=>{let Se=`Dropped ${Ie} lower-priority ${X} observation${Ie===1?"":"s"} to fit the ${e.maxPacketBytes}-byte packet budget; observations closest to the failure were kept.`;return{omissionId:B("omi",[t.runId,X,"budget-exceeded","packet",Se]),channel:X,reason:"budget-exceeded",message:Se,locator:"packet",cap:e.maxPacketBytes}});if(P=R(_,K,[...l,...le]),N=ws(P),D>=I.length)break}}return N>e.maxPacketBytes?{kind:"budget-exceeded",message:`Even the evidence closest to the failure is ${N} bytes, exceeding maxPacketBytes=${e.maxPacketBytes}; raise the explicit policy limit or narrow the authorized inputs.`}:{kind:"built",packet:P}}var tS=[[/\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 xs(t){return t.replace(/\\/g,"/").replace(/^[A-Za-z]:/,"").split("/").filter(r=>r.length>0).slice(-2).join("/")}function na(t,n=200){let e=t.replace(/\r\n/g,`
153
+ `).replace(/(?:file:\/\/)?(?:[A-Za-z]:)?(?:\/[\w.@+-]+){2,}/g,r=>xs(r));for(let[r,s]of tS)e=e.replace(r,s);return e=e.replace(/\s+/g," ").trim().toLowerCase(),e.length<=n?e:e.slice(0,n)}function uy(t){return t.replace(/['`]/g,'"').replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/\{\s*/g,"{ ").replace(/\s*\}/g," }").trim()}function vs(t,n){return`${xs(t)}:${n}`}var ur=["error-field","stack-frame","step"],Oc=["error-field","stack-frame"],$c=["trace-event","console-event"];function Ot(t,n,e){return t.evidence.filter(r=>{if(!n.includes(r.kind))return!1;let s=t.normalized.get(r.evidenceId)??"";return e.some(i=>i.test(s))})}function nS(t,n,e){return t.evidence.filter(r=>n.includes(r.kind)&&e.some(s=>s.test(r.observation)))}var rS=[/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/,/no such element: unable to locate element/,/expected condition failed: waiting for/],sS=[/\bexpect\(/,/\bassertion\b/,/\bexpect \$\$?\(/,/\bexpected .{0,200} to (?:have|be|equal|eq|contain|include|exist|match|deep)\b/,/\bassertionerror: assert\b/,/\bexpected: .{0,200}? but was: /,/\bexpected \[.{0,200}?\] but found \[/],iS=[/expected:.{0,80}received:/s,/received:.{0,80}expected:/s],aS=[/uncaught \w*error/,/\bpageerror\b/,/unhandled (?:promise )?rejection/,/uncaught page error/,/originated from your application code/],oS=[/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/],dS=[/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/],cS=[/cy\.request\(\) failed/,/response we received from your web server was/,/request failed with status code/],lS=[/"(?: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/,/\bfailed on (?:setup|teardown) with\b/,/configinvoker\.invokeconfiguration/,/^container \S+ failed(?:, tests inside it did not run)?:/,/^(?:before|after) hook failed: /],uS=[/^(?:undefined|ambiguous|pending) step: /],Dc=[{ruleId:"action-timeout/timeout-text",category:"action-timeout",description:"Failure text reports an expired action, element wait, or test timeout.",match:t=>Ot(t,ur,rS)},{ruleId:"action-timeout/timed-out-status",category:"action-timeout",description:"The attempt status is timedOut and failure text is present to cite.",match:t=>t.attempt?.status==="timedOut"?t.evidence.filter(n=>n.kind==="error-field"):[]},{ruleId:"assertion-mismatch/expect-failure",category:"assertion-mismatch",description:"Failure text reports an expectation that did not hold.",match:t=>{let n=Ot(t,ur,sS);return n.length>0?n:Ot(t,ur,iS)}},{ruleId:"page-exception/uncaught-error",category:"page-exception",description:"An uncaught page error or unhandled rejection was observed.",match:t=>Ot(t,[...ur,...$c],aS)},{ruleId:"navigation-failure/net-error",category:"navigation-failure",description:"Navigation reported a network-level or navigation timeout error.",match:t=>Ot(t,[...ur,...$c],oS)},{ruleId:"http-failure/error-status",category:"http-failure",description:"A recorded request returned a 4xx or 5xx status, or reported a failure.",match:t=>nS(t,["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:t=>Ot(t,Oc,cS)},{ruleId:"browser-crash/target-closed",category:"browser-crash",description:"The page, context, or browser was closed or crashed during the attempt.",match:t=>Ot(t,[...ur,...$c],dS)},{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:t=>Ot(t,Oc,lS)},{ruleId:"unimplemented-step/no-runnable-definition",category:"unimplemented-step",description:"A Cucumber step had no step definition, several, or one marked pending.",match:t=>Ot(t,Oc,uS)}];var Rn={"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","unimplemented-step":"Unimplemented step","artifact-failure":"Artifact failure",unclassified:"Unclassified failure"},pS=new Set(["failed","timedOut","interrupted"]),py=160;function my(t){let n=t.replace(/\s+/g," ").trim();return n.length<=py?n:`${n.slice(0,py)}\u2026`}function fS(t){for(let n of t){if(n.kind!=="trace-event")continue;let r=/^action(?: started| finished)?: ([\w.]+)/.exec(n.observation)?.[1];if(r!==void 0&&r!=="unknown")return r}}function hS(t){for(let n of t){if(n.kind!=="network-event")continue;let e=/^(\w+) (\S+) -> (\d{3})/.exec(n.observation);if(e===null)continue;let[,r,s,i]=e;if(r===void 0||s===void 0||i===void 0)continue;let a=s;try{a=new URL(s).host}catch{}return`${r} ${a} -> ${i}`}}function mS(t,n){if(t?.errorLocation!==void 0)return vs(t.errorLocation.file,t.errorLocation.line??1);for(let e of n)if(e.locator.type==="source-range")return vs(e.locator.path,e.locator.startLine);for(let e of n){if(e.kind!=="stack-frame")continue;let r=/([^\s():]+):(\d+):\d+/.exec(e.observation),s=r?.[1],i=r?.[2];if(s!==void 0&&i!==void 0)return vs(s,Number.parseInt(i,10))}}function yy(t){let n=e=>t.find(r=>r.kind==="error-field"&&r.locator.type==="report-field"&&r.locator.path.endsWith(e));return n(".message")??n(".value")??t.find(e=>e.kind==="error-field")??t[0]}function yS(t,n,e){let r=yy(n),s=r===void 0?void 0:na(r.observation),i=mS(t,n),a=fS(n),o=hS(n),[d]=t===void 0?[]:bs(t),c=d===void 0?void 0:uy(d),l=i!==void 0&&e!==void 0&&!i.startsWith(`${xs(e)}:`)?i:void 0;return{...s===void 0||s===""?{}:{errorFingerprint:s},...i===void 0?{}:{sourceLocation:i},...a===void 0?{}:{actionApi:a},...o===void 0?{}:{networkEndpoint:o},...c===void 0||c===""?{}:{targetLocator:c},...l===void 0?{}:{supportLocation:l}}}function ra(t,n,e,r,s){let i=[...new Set(r.map(c=>c.evidenceId))].sort(),a=yS(s.attempt,r,s.specFile),o=yy(r),d=s.attempt?.attemptId??"run";return{symptomId:B("sym",[t,d,n,a.errorFingerprint??""]),category:n,ruleId:e,...s.logicalTestId===void 0?{}:{logicalTestId:s.logicalTestId},...s.attempt===void 0?{}:{attemptId:s.attempt.attemptId},evidenceIds:i,artifactIds:[],summary:`${Rn[n]}: ${my(o?.observation??"")}`,signals:a}}function fy(t){let n=new Map;for(let e of Dc){let r=e.match(t);if(r.length===0)continue;let s=n.get(e.category);s===void 0?n.set(e.category,{ruleId:e.ruleId,cited:[...r]}):s.cited.push(...r)}return n}function hy(t){return new Map(t.map(n=>[n.evidenceId,na(n.observation,400)]))}function ia(t,n){let e=new Map;for(let i of n.evidence){if(i.attemptId===void 0)continue;let a=e.get(i.attemptId);a===void 0?e.set(i.attemptId,[i]):a.push(i)}let r=[],s=[];for(let i of t.logicalTests)for(let a of i.attempts){if(!pS.has(a.status))continue;let o=e.get(a.attemptId)??[],d={attempt:a,evidence:o,normalized:hy(o)},c=fy(d);if(c.size===0){if(o.length===0){s.push(a.attemptId);continue}r.push(ra(t.runId,"unclassified","unclassified/no-rule-matched",o.filter(l=>l.kind==="error-field").slice(0,3),{logicalTestId:i.logicalTestId,attempt:a,specFile:i.location.file}));continue}for(let[l,{ruleId:u,cited:p}]of c)r.push(ra(t.runId,l,u,p,{logicalTestId:i.logicalTestId,attempt:a,specFile:i.location.file}))}if(t.reportErrors.length>0){let i=n.evidence.filter(a=>a.attemptId===void 0&&a.logicalTestId===void 0);if(i.length>0){let a=fy({evidence:i,normalized:hy(i)});a.size===0&&r.push(ra(t.runId,"unclassified","unclassified/no-rule-matched",i.filter(o=>o.kind==="error-field").slice(0,3),{}));for(let[o,{ruleId:d,cited:c}]of a)r.push(ra(t.runId,o,d,c,{}))}}for(let i of n.artifacts)i.availability==="unreadable"&&r.push({symptomId:B("sym",[t.runId,i.artifactId,"artifact-failure"]),category:"artifact-failure",ruleId:"artifact-failure/unreadable-artifact",...i.attemptId===void 0?{}:{attemptId:i.attemptId},evidenceIds:[],artifactIds:[i.artifactId],summary:`${Rn["artifact-failure"]}: ${i.channel} artifact could not be read${i.warnings[0]===void 0?"":` (${my(i.warnings[0])})`}`,signals:{}});return{schemaVersion:"1.1",runId:t.runId,packetHash:n.packetHash,symptoms:[...r].sort((i,a)=>i.symptomId.localeCompare(a.symptomId)),unclassifiedAttemptIds:[...s].sort()}}var gS=new Set(["error-fingerprint","network-endpoint","failing-source-location","target-locator","support-location"]);var Ut="<absent>";function Mc(t,n){switch(n){case"symptom-category":return t.category;case"action-api":return t.signals.actionApi??Ut;case"error-fingerprint":return t.signals.errorFingerprint??Ut;case"network-endpoint":return t.signals.networkEndpoint??Ut;case"failing-source-location":return t.signals.sourceLocation??Ut;case"target-locator":return t.signals.targetLocator??Ut;case"support-location":return t.signals.supportLocation??Ut}}function wS(t,n){if(n.length<2)return{supported:!1,rationale:"A single logical test provides no shared behavior for a common cause."};let e=t.filter(r=>gS.has(r.kind)&&r.value!==Ut);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(r=>`${r.kind}=${r.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 gy=["target-locator","support-location","network-endpoint"],wy=["symptom-category","error-fingerprint"];function Lc(t){let n=new Map;for(let s of t.symptoms){if(s.logicalTestId===void 0)continue;let i=n.get(s.logicalTestId);i===void 0?n.set(s.logicalTestId,[s]):i.push(s)}let e=new Map;for(let s of n.values()){let i=[...s].sort((l,u)=>l.symptomId.localeCompare(u.symptomId)),a;for(let l of gy){let u=i.find(p=>Mc(p,l)!==Ut);if(u!==void 0){a=[{kind:l,value:Mc(u,l)}];break}}let o=i[0];if(a===void 0&&o!==void 0&&(a=wy.map(l=>({kind:l,value:Mc(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:[...s]}):c.members.push(...s)}let r=[...e.values()].map(({signals:s,members:i})=>{let a=[...new Set(i.map(d=>d.logicalTestId).filter(d=>d!==void 0))].sort(),o=wS(s,a);return{clusterId:B("clu",[t.runId,...s.map(d=>`${d.kind}=${d.value}`)]),logicalTestIds:a,symptomIds:i.map(d=>d.symptomId).sort(),signals:s,commonCauseSupported:o.supported,commonCauseRationale:o.rationale}});return{schemaVersion:"1.1",runId:t.runId,clusters:r.sort((s,i)=>s.clusterId.localeCompare(i.clusterId)),signalKinds:[...gy,...wy]}}function he(t,n,e,r,s={}){return{graderId:t,code:n,severity:e,message:r,...s.hypothesisId===void 0?{}:{hypothesisId:s.hypothesisId},...s.reference===void 0?{}:{reference:s.reference}}}function qt(t,n,e){return{graderId:t,passed:!e.some(r=>r.severity==="violation"),checked:n,findings:e}}var ks={insufficient:0,weak:1,moderate:2,strong:3},_c={graderId:"abstention",description:"Diagnosis status matches evidence strength, and insufficient evidence abstains.",grade:t=>{let n=[],{diagnosis:e}=t,s=[...e.hypotheses].sort((o,d)=>o.rank-d.rank)[0],i=s===void 0?-1:ks[s.evidenceGrade],a=1;return s===void 0||i===ks.insufficient?e.status!=="inconclusive"&&n.push(he("abstention","failed-to-abstain","violation",`Evidence cannot rank a cause, but the diagnosis claims ${e.status}.`)):e.status==="conclusive"&&i<ks.strong?n.push(he("abstention","conclusive-without-strong-evidence","violation",`Diagnosis claims conclusive on ${s.evidenceGrade} evidence.`,{hypothesisId:s.hypothesisId})):e.status==="probable"&&i<ks.moderate&&n.push(he("abstention","probable-without-moderate-evidence","violation",`Diagnosis claims probable on ${s.evidenceGrade} evidence.`,{hypothesisId:s.hypothesisId})),a+=1,e.status==="inconclusive"&&e.repairEligibility==="eligible"&&n.push(he("abstention","repair-eligible-while-inconclusive","violation","Repair was marked eligible while the diagnosis is inconclusive.")),a+=1,e.status==="inconclusive"&&i>=ks.strong&&n.push(he("abstention","abstained-with-strong-evidence","warning","Diagnosis abstained although the leading hypothesis carries strong evidence.",{...s===void 0?{}:{hypothesisId:s.hypothesisId}})),a+=1,e.status==="inconclusive"&&e.missingEvidence.length===0&&n.push(he("abstention","abstained-without-naming-gaps","warning","Diagnosis abstained without naming the evidence that was missing.")),qt("abstention",a,n)}};var jc={graderId:"citation-validity",description:"Every cited evidence, artifact, and symptom id exists in the graded packet.",grade:t=>{let n=[],e=0;t.diagnosis.packetHash!==t.packetHash&&n.push(he("citation-validity","packet-hash-mismatch","violation","The diagnosis was produced from a different evidence packet than the one being graded.",{reference:t.diagnosis.packetHash}));let r=i=>t.evidenceIds.has(i)||t.artifactIds.has(i),s=[["ownershipEvidenceIds",t.diagnosis.ownershipEvidenceIds,void 0],...t.diagnosis.hypotheses.flatMap(i=>[["supportingEvidenceIds",i.supportingEvidenceIds,i.hypothesisId],["contradictingEvidenceIds",i.contradictingEvidenceIds,i.hypothesisId]])];for(let[i,a,o]of s)for(let d of a)e+=1,!r(d)&&n.push(he("citation-validity","unknown-evidence-id","violation",`${i} cites ${d}, which the evidence packet does not contain.`,{...o===void 0?{}:{hypothesisId:o},reference:d}));for(let i of t.diagnosis.symptomIds)e+=1,!t.symptomIds.has(i)&&n.push(he("citation-validity","unknown-symptom-id","violation",`The diagnosis cites symptom ${i}, which this run did not produce.`,{reference:i}));return qt("citation-validity",e,n)}};var bS=new Set(["strong","moderate"]),Fc={graderId:"ownership",description:"A named owner rests on cited positive evidence, and eligibility proves it.",grade:t=>{let n=[],{diagnosis:e}=t,r=0;for(let s of e.hypotheses)r+=1,s.probableOwner!=="undetermined"&&s.supportingEvidenceIds.length===0&&n.push(he("ownership","ownership-from-absence","violation",`Hypothesis assigns the ${s.probableOwner} owner without citing any supporting evidence.`,{hypothesisId:s.hypothesisId}));if(e.repairEligibility==="eligible"){r+=1,e.ownershipEvidenceIds.length===0&&n.push(he("ownership","eligible-without-ownership-evidence","violation","Repair was marked eligible without identifying the evidence that proves test-side ownership."));let s=[...e.hypotheses].sort((i,a)=>i.rank-a.rank)[0];s===void 0?n.push(he("ownership","eligible-without-hypothesis","violation","Repair was marked eligible without an accepted hypothesis.")):(s.probableOwner!=="test-support"&&n.push(he("ownership","eligible-without-test-ownership","violation",`Repair was marked eligible while the accepted hypothesis assigns the ${s.probableOwner} owner.`,{hypothesisId:s.hypothesisId})),bS.has(s.evidenceGrade)||n.push(he("ownership","eligible-on-insufficient-grade","violation",`Repair was marked eligible on ${s.evidenceGrade} evidence.`,{hypothesisId:s.hypothesisId})))}return qt("ownership",r,n)}};var xS=/\b(?:evd|art|sym|clu|omi|red)_[a-f0-9]{8,}\b/g,Bc={graderId:"unsupported-claims",description:"Claims are backed by citations, and grades match the evidence offered.",grade:t=>{let n=[],e=0;for(let s of t.diagnosis.hypotheses){e+=1;let{hypothesisId:i,supportingEvidenceIds:a,contradictingEvidenceIds:o}=s;s.evidenceGrade!=="insufficient"&&a.length===0&&n.push(he("unsupported-claims","claim-without-evidence","violation",`Hypothesis is graded ${s.evidenceGrade} but cites no supporting evidence.`,{hypothesisId:i})),s.evidenceGrade==="strong"&&(a.length<2&&n.push(he("unsupported-claims","strong-grade-underspecified","violation","A strong grade requires multiple specific observations, but only one was cited.",{hypothesisId:i})),o.length>0&&n.push(he("unsupported-claims","strong-grade-with-contradiction","violation","A strong grade requires no material unresolved contradiction, but contradicting evidence was cited.",{hypothesisId:i})),s.unresolvedAssumptions.length>0&&n.push(he("unsupported-claims","strong-grade-with-unresolved-assumptions","warning","A strong grade carries unresolved assumptions.",{hypothesisId:i})));let d=a.filter(l=>o.includes(l));for(let l of d)n.push(he("unsupported-claims","contradictory-citation","violation",`Evidence ${l} is cited as both supporting and contradicting the same hypothesis.`,{hypothesisId:i,reference:l}));let c=new Set([...a,...o]);for(let l of[s.statement,s.nextAction])for(let u of l.matchAll(xS)){let p=u[0];e+=1,!c.has(p)&&n.push(he("unsupported-claims","uncited-identifier-in-prose","violation",`Prose references ${p}, which this hypothesis does not cite.`,{hypothesisId:i,reference:p}))}}e+=1;let r=t.diagnosis.hypotheses.map(s=>s.rank);return new Set(r).size!==r.length&&n.push(he("unsupported-claims","duplicate-hypothesis-rank","violation","Hypotheses do not carry a distinct rank, so the accepted hypothesis is ambiguous.")),t.diagnosis.hypotheses.length>3&&n.push(he("unsupported-claims","too-many-hypotheses","violation",`A diagnosis returns at most three ranked hypotheses; ${t.diagnosis.hypotheses.length} were supplied.`)),qt("unsupported-claims",e,n)}};var xy=[jc,Fc,_c,Bc];function vS(t){return[...t].sort((n,e)=>{if(n.severity!==e.severity)return n.severity==="violation"?-1:1;let r=n.graderId.localeCompare(e.graderId);if(r!==0)return r;let s=n.code.localeCompare(e.code);return s!==0?s:(n.reference??"").localeCompare(e.reference??"")})}function Rs(t,n,e){let r={diagnosis:t,evidenceIds:new Set(n.evidence.map(i=>i.evidenceId)),artifactIds:new Set(n.artifacts.map(i=>i.artifactId)),symptomIds:new Set(e.symptoms.map(i=>i.symptomId)),packetHash:n.packetHash},s=xy.map(i=>i.grade(r));return{schemaVersion:"1.0",packetHash:n.packetHash,passed:s.every(i=>i.passed),outcomes:s,findings:vS(s.flatMap(i=>i.findings))}}var vy=50,ky=24,Ty="<absent>",RS={"error-field":"Error","stack-frame":"Stack frame",step:"Step","stdio-chunk":"Output","trace-event":"Browser event","image-metadata":"Screenshot (metadata only)","video-metadata":"Video (metadata only)","dom-subtree":"Page elements","dom-candidates":"Similar elements","accessibility-node":"Accessibility","page-snapshot":"Page snapshot","console-event":"Console","network-event":"Network","source-range":"Source","diff-hunk":"Code change","change-search":"Change search","run-summary":"Run summary","locator-suggestion":"Locator suggestion"},IS={report:"Test report",trace:"Trace or failure capture",stdout:"Standard output",stderr:"Standard error",screenshot:"Screenshots",video:"Video",dom:"Page DOM",accessibility:"Accessibility tree",console:"Browser console",network:"Network",source:"Test source",diff:"Code changes",probe:"Live probe"},AS={unavailable:"not captured",unreadable:"unreadable","unsupported-version":"unsupported version","unauthorized-path":"outside the authorized paths","policy-disabled":"turned off by policy",redacted:"redacted","budget-exceeded":"over the size budget",irrelevant:"not relevant to the failures",unrecognized:"not recognized","parse-failed":"could not be parsed"},TS={"symptom-category":"Symptom","action-api":"Action","error-fingerprint":"Error","network-endpoint":"Request","support-location":"Support code","target-locator":"Locator","failing-source-location":"Failing line"},PS={expected:"passed",unexpected:"failed",flaky:"flaky",skipped:"skipped"};function Py(t,n){return`${t} ${n}${t===1?"":"s"}`}function Ry(t,n){let e=t.replace(/\s+/g," ").trim();return e.length<=n?e:`${e.slice(0,n-1)}\u2026`}function SS(t){if(t<1e3)return`${Math.round(t)} ms`;let n=t/1e3;return n<60?`${n.toFixed(1)} s`:`${Math.floor(n/60)} min ${Math.round(n%60)} s`}function Iy(t){return t.replace("T"," ").replace(/(?:\.\d+)?Z$/," UTC")}var ES="1970-01-01T00:00:00.000Z";function CS(t){return t.replace(/^sha256:/,"").slice(0,12)}function zc(t,n){let e=n.location.file,r=n.titlePath.filter(i=>i!==""&&i!==e&&i!==kS(e)),s=t.projects.find(i=>i.projectId===n.projectId)?.name;return{title:r.join(" \u203A ")||n.title,location:n.location.line===void 0?e:`${e}:${n.location.line}`,...s===void 0||s===""||t.projects.length<2?{}:{project:s},status:PS[n.status],attempts:n.attempts.map(i=>i.retry===0?i.status:`${i.status} (retry ${i.retry})`)}}function Sy(t,n){let e=new Set(n);return t.logicalTests.filter(r=>e.has(r.logicalTestId)).map(r=>zc(t,r))}function Gt(t,n){let e=t.signals.find(r=>r.kind===n)?.value;return e===void 0||e===Ty?void 0:e}function NS(t,n){let e=Gt(t,"symptom-category");return(e!==void 0?[e]:[...new Set((n?.symptoms.symptoms??[]).filter(i=>t.symptomIds.includes(i.symptomId)).map(i=>i.category))]).map(i=>Rn[i]??i).join(", ")||Rn.unclassified}function Ey(t,n){return t.evidence.filter(e=>e.kind==="error-field"&&e.attemptId!==void 0&&n.has(e.attemptId)&&e.locator.type==="report-field"&&/\.(?:message|value)$/.test(e.locator.path))}function OS(t,n){let e=n?.symptoms.symptoms.find(a=>t.symptomIds.includes(a.symptomId));if(n===void 0||e===void 0)return;let r=Ey(n.packet,new Set(e.attemptId===void 0?[]:[e.attemptId])).map(a=>a.observation.split(`
154
+ `).find(o=>o.trim()!=="")?.trim()).find(a=>a!==void 0);if(r!==void 0)return r;let s=`${Rn[e.category]}: `,i=e.summary.startsWith(s)?e.summary.slice(s.length):e.summary;return i.trim()===""?void 0:i}function $S(t,n,e){let r=Gt(t,"target-locator"),s=Gt(t,"network-endpoint"),i=Gt(t,"support-location"),a=Gt(t,"failing-source-location"),o=OS(t,e)??Gt(t,"error-fingerprint");return r!==void 0?`Locator ${Ry(r,90)}`:s!==void 0?`Request ${s}`:i!==void 0?`Failing in ${i}`:a!==void 0?`Failing at ${a}`:o!==void 0?Ry(o,90):n}function DS(t,n){let e=Gt(t,"support-location")??Gt(t,"failing-source-location");if(e!==void 0)return e;let r=new Set(n.map(s=>s.location.replace(/:\d+$/,"")));return r.size===1?[...r][0]:void 0}function MS(t){return[...t.hypotheses].sort((n,e)=>n.rank-e.rank)[0]}function LS(t){let n=t?.diagnosis;if(t===void 0||n===void 0)return{owner:"not-diagnosed"};let e=MS(n);return t.outcome!=="diagnosed"||e===void 0?{owner:"inconclusive"}:{owner:e.probableOwner,grade:e.evidenceGrade}}function _S(t){let n=t.diagnosis;if(n!==void 0)return{status:n.status,hypotheses:[...n.hypotheses].sort((e,r)=>e.rank-r.rank).map(e=>({rank:e.rank,statement:e.statement,owner:e.probableOwner,grade:e.evidenceGrade,category:e.causalCategory,supporting:e.supportingEvidenceIds,contradicting:e.contradictingEvidenceIds,missing:e.missingEvidence,assumptions:e.unresolvedAssumptions,nextAction:e.nextAction})),missing:n.missingEvidence,nextAction:n.recommendedNextAction,repairEligibility:n.repairEligibility,escalated:t.escalated===!0}}function jS(t){let n=t.locator;switch(n.type){case"source-range":{let e=n.endLine===n.startLine?`${n.startLine}`:`${n.startLine}-${n.endLine}`;return`${n.path}:${e}${n.symbol===void 0?"":` (${n.symbol})`}`}case"diff-hunk":return`${n.commit===void 0?"uncommitted":`commit ${n.commit}`}, ${n.path}:${n.newStart}`;default:return}}function FS(t){let n=jS(t);return{evidenceId:t.evidenceId,label:RS[t.kind]??t.kind,...n===void 0?{}:{where:n},text:t.observation}}function Cy(t,n){let e=new Map(t.evidence.map(r=>[r.evidenceId,r]));return[...new Set(n)].flatMap(r=>{let s=e.get(r);return s===void 0?[]:[s]})}function BS(t){return[...[...t.hypotheses].sort((n,e)=>n.rank-e.rank).flatMap(n=>[...n.supportingEvidenceIds,...n.contradictingEvidenceIds]),...t.ownershipEvidenceIds]}function VS(t,n){let e=n.symptoms.symptoms.filter(i=>t.symptomIds.includes(i.symptomId)),r=new Set(e.flatMap(i=>i.attemptId??[])),s=[...Ey(n.packet,r).map(i=>i.evidenceId),...e.flatMap(i=>i.evidenceIds)];return Cy(n.packet,s)}function zS(t,n,e){if(e===void 0)return{evidence:[],evidenceCut:0};let r=n?.diagnosis,s;if(r!==void 0){let i=e.groupPackets[t.clusterId];if(i?.packetHash!==r.packetHash)return{evidence:[],evidenceCut:0,evidenceNote:"This group's evidence has changed since it was diagnosed, so the evidence its diagnosis cites can't be shown."};s=Cy(i,BS(r))}else s=VS(t,e);return{evidence:s.slice(0,ky).map(FS),evidenceCut:Math.max(0,s.length-ky)}}function HS(t,n){return t===void 0?n?"Not diagnosed: this was a local analysis, so no model was asked.":"Not sent: an analysis asks about at most 6 groups, the largest first.":t.outcome==="diagnosed"?t.escalated===!0?"Diagnosed, by the stronger model after the first answer failed its checks.":"Diagnosed.":`${t.outcome} (${t.reasonCode}): ${t.message}`}function Vc(t,n,e,r,s,i){let a=NS(n,r),o=Sy(t,n.logicalTestIds),d=LS(e),c=e===void 0?void 0:_S(e),l=$S(n,a,r),u=n.logicalTestIds.length,p=DS(n,o);return{...s===void 0?{}:{number:s},anchor:s===void 0?`group-${n.clusterId}`:`group-${s}`,title:`${l} \xB7 ${Py(u,"test")}`,subject:l,size:u,...p===void 0?{}:{place:p},category:a,signals:n.signals.filter(f=>f.value!==Ty).map(f=>({kind:TS[f.kind]??f.kind,value:f.value})),commonCause:{supported:n.commonCauseSupported,rationale:n.commonCauseRationale},...d,status:HS(e,i),tests:o.slice(0,vy),testsCut:Math.max(0,o.length-vy),...c===void 0?{}:{diagnosis:c},...zS(n,e,r)}}function US(t){return{clusterId:t.clusterId,logicalTestIds:t.logicalTestIds,symptomIds:[],signals:t.signals,commonCauseSupported:!1,commonCauseRationale:"The evidence that grouped these tests could not be rebuilt."}}function Ay(t,n){return n.logicalTestIds.length-t.logicalTestIds.length||t.clusterId.localeCompare(n.clusterId)}function qS(t){let{run:n,record:e,detail:r}=t,s=r?.clusters.clusters??[],i=e.clusters??[];if(i.length===0)return[...s].sort(Ay).map((u,p)=>Vc(n,u,void 0,r,p+1,!0));let o=new Map(s.map(u=>[u.clusterId,u])),d=i.map((u,p)=>Vc(n,o.get(u.clusterId)??US(u),u,r,p+1,!1)),c=new Set(i.map(u=>u.clusterId)),l=s.filter(u=>!c.has(u.clusterId)).sort(Ay).map(u=>Vc(n,u,void 0,r,void 0,!1));return[...d,...l]}function Ny(t){let n=t.record.clusters??[],e=n.length>0?n.flatMap((s,i)=>s.diagnosisAudit===void 0?[]:[{group:`Group ${i+1}`,audit:s.diagnosisAudit}]):t.record.diagnosisAudit===void 0?[]:[{group:"Run",audit:t.record.diagnosisAudit}],r=t.repair?.repairAudit===void 0?[]:[{group:"Repair",audit:t.repair.repairAudit}];return[...e,...r]}function Oy(t){return`${t.model.modelId} via ${t.reportedProvider??t.model.providerId}`}function GS(t){return Ny(t).map(({group:n,audit:e})=>({group:n,purpose:e.purpose,model:Oy(e),zeroDataRetention:e.model.zeroDataRetention===!0,packetHash:CS(e.packetHash),...e.usage===void 0?{}:{tokens:`${e.usage.promptTokens.toLocaleString("en-US")} in, ${e.usage.completionTokens.toLocaleString("en-US")} out`},outcome:e.outcome.kind}))}function KS(t){let n=Ny(t).filter(({audit:r})=>r.outcome.kind==="diagnosed"||r.outcome.kind==="abstained"),e=[...new Set(n.map(({audit:r})=>Oy(r)))];return e.length>0?`Diagnosed with ${e.join(" and ")}.`:t.record.reasonCode==="remote-diagnosis-not-configured"?"Local analysis: no model was asked.":"No model answered this analysis."}function WS(t){let n=t.repair?.confirmation;if(n===void 0)return[];if(n.status!=="reproduced"&&n.status!=="not-reproduced")return[];let e=new Set(n.failedAgain??[]);return n.logicalTestIds.filter(r=>!e.has(r))}function JS(t){let{run:n}=t,e=n.logicalTests.filter(s=>s.status==="flaky").map(s=>zc(n,s)),r=Sy(n,WS(t)).map(s=>({...s,status:"passed when fix re-ran it"}));return[...e,...r]}function XS(t){let{run:n,detail:e}=t,r=new Set(e?.symptoms.unclassifiedAttemptIds??[]),s=n.logicalTests.filter(o=>o.attempts.some(d=>r.has(d.attemptId))),i=(e?.symptoms.symptoms??[]).filter(o=>o.logicalTestId===void 0).map(o=>o.summary),a=i.length===0&&n.reportErrors.length>0?[`${Py(n.reportErrors.length,"run-level error")} in the test report, not shown here because its evidence could not be built.`]:[];return{unclassified:s.map(o=>zc(n,o)),runErrors:[...new Set([...i,...a])]}}function YS(t,n){let e=t.repair;if(e===void 0)return;let r=(t.record.clusters??[]).findIndex(a=>a.diagnosis!==void 0&&a.diagnosis.packetHash===e.diagnosis?.packetHash),s=r<0?void 0:n.find(a=>a.number===r+1),i=e.repairProposal;return{...s===void 0?{}:{groupAnchor:s.anchor,groupTitle:s.title},command:e.command,outcome:e.outcome,reasonCode:e.reasonCode,message:e.message,phases:[{phase:"Proposal",status:e.proposal.status},{phase:"Application",status:e.application.status},{phase:"Validation",status:e.validation.status}],...i===void 0?{}:{intent:{statement:i.intent.statement,preserved:i.intent.preservedBehavior},diff:i.diff}}}function aa(t){let{run:n,record:e,detail:r}=t,s=p=>n.logicalTests.filter(f=>f.status===p).length,i=s("unexpected"),a=s("flaky"),o=wt[n.framework],d=n.artifact.formatVersion===void 0?"":` ${n.artifact.formatVersion}`,c=qS(t),l=new Map;for(let p of r?.packet.omissions??[]){let f=AS[p.reason]??p.reason;l.set(f,(l.get(f)??0)+1)}let u=YS(t,c);return{title:`KwikQA report: ${n.framework==="unknown"?"run from an unidentified framework":`${o} run`}, ${i} failed${a===0?"":`, ${a} flaky`}`,recordedAt:Iy(e.recordedAt),run:{framework:`${o}${d}`,...n.artifact.format===void 0?{}:{format:zt[n.artifact.format]},counts:[{label:"Tests",value:n.logicalTests.length},{label:"Failed",value:i},{label:"Flaky",value:a},{label:"Passed",value:s("expected")},{label:"Skipped",value:s("skipped")}],duration:SS(n.stats.duration),...e.inputs===void 0?{}:{report:e.inputs.report},createdAt:n.createdAt===ES?"not recorded in the report":Iy(n.createdAt),diagnosedBy:KS(t),outcome:`${e.outcome} (${e.reasonCode})`,message:e.message},groups:c,flaky:JS(t),notAnalyzed:XS(t),coverage:(r?.packet.accounting??[]).map(p=>({channel:IS[p.channel]??p.channel,availability:p.availability,included:p.included,omitted:p.omitted})),omissions:[...l].map(([p,f])=>({reason:p,count:f})).sort((p,f)=>f.count-p.count||p.reason.localeCompare(f.reason)),redactions:r?.packet.totals.redactions??0,requests:GS(t),...u===void 0?{}:{repair:u},...r===void 0?{evidenceNote:"The evidence this analysis read could not be rebuilt, so only its recorded results are shown."}:{},footer:{runId:e.runId,recordId:e.recordId,kwikqaVersion:t.kwikqaVersion}}}var oa=["on-failure","always"],$y=10,QS=3e4,ZS=2e3,e0=6e4;function Is(t,n){return`${t} ${n}${t===1?"":"s"}`}function pr(t,n=150){let e=t.replace(new RegExp("\\p{Cc}","gu")," ").replace(/\s+/g," ").trim();return e.length<=n?e:`${e.slice(0,n-1)}\u2026`}function Hc(t){let{model:n,run:e}=t,r=n?.run.counts.find(l=>l.label==="Failed")?.value??0,s=n?.run.counts.find(l=>l.label==="Flaky")?.value??0,i=e?.repository===void 0?"":` in ${e.repository}`,a=n===void 0?`KwikQA: no analysis${i}`:r>0?`KwikQA: ${Is(r,"test")} failed${i}`:`KwikQA: no failures${i}`,o=[...e?.pullRequest?.url===void 0?e?.commit?.url===void 0?[]:[{label:`Commit ${e.commit.sha.slice(0,7)}`,url:e.commit.url}]:[{label:e.pullRequest.name??`Pull request #${e.pullRequest.number}`,url:e.pullRequest.url}],...e?.runUrl===void 0?[]:[{label:"Open the run",url:e.runUrl}]],d=e?.branch===void 0?void 0:`Branch ${pr(e.branch,100)}`,c=[];if(n===void 0)c.push(pr(t.message,300));else{let l=n.run.counts.filter(p=>p.label==="Tests"||p.value>0).map(p=>p.label==="Tests"?Is(p.value,"test"):`${p.value} ${p.label.toLowerCase()}`);c.push(`${pr(n.run.framework,60)} run: ${l.join(", ")}.`);for(let p of n.groups.slice(0,$y)){let f=p.place===void 0?"":` in ${pr(p.place,120)}`;c.push(`${p.number===void 0?"\u2013":`${p.number}.`} ${p.category}${f} \xB7 ${Is(p.size,"test")} \xB7 ${an[p.owner]}`)}let u=n.groups.length-$y;u>0&&c.push(`and ${Is(u,"more group")} in the report`),s>0&&c.push(`${Is(s,"flaky test")} passed on a retry.`)}return t.notDiagnosed!==void 0&&c.push(`Not diagnosed: ${pr(t.notDiagnosed,300)}`),{headline:a,...d===void 0?{}:{source:d},links:o,lines:c}}function Dy(t){let n=(r,s=!1)=>({type:"text",text:r,...s?{style:{bold:!0}}:{}}),e=[...t.source===void 0?[]:[n(t.source)],...t.links.map(r=>({type:"link",url:r.url,text:r.label}))].flatMap((r,s)=>s===0?[r]:[n(" \xB7 "),r]);return{text:t.headline,blocks:[{type:"rich_text",elements:[{type:"rich_text_section",elements:[n(pr(t.headline,150),!0),...e.length===0?[]:[n(`
155
+ `),...e],n(`
176
156
 
177
- ${n.lines.join(`
178
- `).slice(0,3e3)}`)]}]}]}}function qg(n){let t=(e,r={})=>({type:"RichTextBlock",inlines:[{type:"TextRun",text:e,...r}]});return{type:"message",attachments:[{contentType:"application/vnd.microsoft.card.adaptive",contentUrl:null,content:{$schema:"http://adaptivecards.io/schemas/adaptive-card.json",type:"AdaptiveCard",version:"1.4",msteams:{width:"Full"},body:[t(n.headline,{weight:"Bolder",size:"Medium"}),...n.source===void 0?[]:[t(n.source,{isSubtle:!0})],...n.lines.map(e=>t(e))],actions:n.links.map(e=>({type:"Action.OpenUrl",title:e.label,url:e.url}))}}]}}function RC(n){if(!(n===void 0||n.trim()===""))try{let t=new URL(n.trim());return t.protocol==="https:"&&t.username===""&&t.password===""?t:void 0}catch{return}}function IC(n){let t=Number(n?.headers.get("retry-after"));return Number.isFinite(t)&&t>0?Math.min(t*1e3,kC):vC}async function AC(n,t,e,r,s,i){let a="";for(let o=1;o<=2;o+=1){let d;try{d=await t(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),redirect:"error",signal:AbortSignal.timeout(xC)})}catch(c){a=`the webhook couldn't be reached (${c instanceof Error?c.message:String(c)})`}if(d?.ok===!0){n.print(`${r}: posted.`);return}if(d!==void 0&&(a=`the webhook answered ${d.status}`,d.status!==429&&d.status<500))break;o===1&&await e(IC(d))}n.error(`${r}: not posted; ${a}.`)}async function Vl(n,t,e,r,s,i){let a=[{name:"Slack",variable:"KWIKQA_SLACK_WEBHOOK_URL",message:Ug},{name:"Teams",variable:"KWIKQA_TEAMS_WEBHOOK_URL",message:qg}];for(let o of a){let d=r[o.variable];if(d===void 0||d.trim()==="")continue;let c=RC(d);if(c===void 0){n.error(`${o.name}: not posted; ${o.variable} isn't an https URL.`);continue}if(i.when==="on-failure"&&!i.failures){n.print(`${o.name}: nothing failed, so nothing was posted (--notify always posts).`);continue}await AC(n,t,e,o.name,c,o.message(s))}}import{appendFile as PC,readFile as SC}from"node:fs/promises";var TC=30,Gg=100,EC=3e4,CC=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;function Kg(n,t){try{let e=new URL(n===void 0||n===""?t:n);return e.protocol==="https:"&&e.username===""&&e.password===""&&e.search===""&&e.hash===""?e.href.replace(/\/+$/,""):void 0}catch{return}}async function NC(n){if(n===void 0||n==="")return{};try{let t=JSON.parse(await SC(n,"utf8"));return typeof t=="object"&&t!==null?t:{}}catch{return{}}}async function Ul(n){if(n.GITHUB_ACTIONS!=="true")return;let t=CC.test(n.GITHUB_REPOSITORY??"")?n.GITHUB_REPOSITORY:void 0,e=Kg(n.GITHUB_API_URL,"https://api.github.com"),r=Kg(n.GITHUB_SERVER_URL,"https://github.com"),s=/^\d+$/.test(n.GITHUB_RUN_ID??"")?n.GITHUB_RUN_ID:void 0,i=(await NC(n.GITHUB_EVENT_PATH)).pull_request,a=i?.number,o=i?.head?.repo?.full_name,d=i?.base?.repo?.full_name,c=(n.GITHUB_TOKEN??"").trim(),l=r===void 0||t===void 0?void 0:`${r}/${t}`,u=n.GITHUB_HEAD_REF||n.GITHUB_REF_NAME||void 0,p=/^[0-9a-f]{40}$/.test(n.GITHUB_SHA??"")?n.GITHUB_SHA:void 0;return{...e===void 0?{}:{apiUrl:e},...t===void 0?{}:{repository:t},...l===void 0||s===void 0?{}:{runUrl:`${l}/actions/runs/${s}`},workflow:n.GITHUB_WORKFLOW??"",job:n.GITHUB_JOB??"",...u===void 0?{}:{branch:u},...p===void 0?{}:{commit:{sha:p,...l===void 0?{}:{url:`${l}/commit/${p}`}}},...n.GITHUB_STEP_SUMMARY===void 0||n.GITHUB_STEP_SUMMARY===""?{}:{summaryPath:n.GITHUB_STEP_SUMMARY},...c===""?{}:{token:c},...typeof a=="number"&&Number.isSafeInteger(a)&&a>0?{pullRequest:{number:a,...l===void 0?{}:{url:`${l}/pull/${a}`},fork:n.GITHUB_EVENT_NAME!=="pull_request_target"&&(typeof o!="string"||o!==d)}}:{}}}function Wg(n){return`<!-- kwikqa-ci workflow=${encodeURIComponent(n.workflow)} job=${encodeURIComponent(n.job)} -->`}async function Hl(n){if(n.status===429||n.status===403&&(n.headers.get("x-ratelimit-remaining")==="0"||n.headers.has("retry-after")))return"GitHub's rate limit was reached";if(n.status===403)return"the token can't comment on this pull request; give the job `pull-requests: write` permission";if(n.status===401)return"GitHub refused the token";if(n.status===404)return"GitHub found no such pull request with this token";let t=await n.json().catch(()=>{}),e=typeof t?.message=="string"?`: ${t.message.replace(/\s+/g," ").slice(0,200)}`:"";return`GitHub answered ${n.status}${e}`}var zl=class{constructor(t,e,r){this.send=t;this.apiUrl=e;this.token=r}send;apiUrl;token;call(t,e,r){return this.send(`${this.apiUrl}${e}`,{method:t,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28",...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error",signal:AbortSignal.timeout(EC)})}},br=class extends Error{};async function OC(n,t,e){for(let r=1;r<=TC;r+=1){let s=await n.call("GET",`${t}/comments?per_page=${Gg}&page=${r}`);if(!s.ok)throw new br(await Hl(s));let i=await s.json(),a=i.find(o=>typeof o.body=="string"&&o.body.startsWith(e));if(typeof a?.id=="number")return a.id;if(i.length<Gg)return}}async function $C(n,t,e,r,s){let i=u=>n.print(`No pull-request comment: ${u}.`),a=e.pullRequest;if(a===void 0)return i("this run isn't for a pull request");if(a.fork)return i("the pull request comes from a fork, and GitHub gives its workflows a read-only token");if(e.token===void 0)return i("GITHUB_TOKEN isn't set; add `GITHUB_TOKEN: ${{ github.token }}` to the step's env");if(e.apiUrl===void 0||e.repository===void 0)return i("GITHUB_API_URL or GITHUB_REPOSITORY isn't what GitHub Actions sets");let o=new zl(t,e.apiUrl,e.token),d=`/repos/${e.repository}/issues/${a.number}`,c=Wg(e),l={body:`${c}
179
- ${r}`};try{let u=await OC(o,d,c);if(u!==void 0){let f=await o.call("PATCH",`/repos/${e.repository}/issues/comments/${u}`,l);if(f.ok)return n.print("Pull-request comment: updated.");if(f.status!==403&&f.status!==404)throw new br(await Hl(f))}if(u===void 0&&!s)return i("nothing failed, and there is no earlier comment to update");let p=await o.call("POST",`${d}/comments`,l);if(!p.ok)throw new br(await Hl(p));n.print("Pull-request comment: posted.")}catch(u){let p=u instanceof br?u.message:`GitHub couldn't be reached (${u instanceof Error?u.message:String(u)})`;n.error(`No pull-request comment: ${p}.`)}}async function ql(n,t,e,r,s){if(e.summaryPath===void 0)n.print("No job summary: GITHUB_STEP_SUMMARY isn't set.");else try{await PC(e.summaryPath,`${r}
180
- `),n.print("Job summary: written.")}catch(i){n.error(`No job summary: ${i.message}`)}await $C(n,t,e,r,s.failures)}var DC=20,Jg=10,MC=100;function xr(n,t){return`${n} ${t}${n===1?"":"s"}`}function Xg(n,t){let e=n.replace(/[\p{Cc}\u202a-\u202e\u2066-\u2069]/gu," ").replace(/\s+/g," ").trim();return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function Fs(n,t={}){let e=Xg(n,MC)||"(empty)",r=Math.max(0,...(e.match(/`+/g)??[]).map(o=>o.length)),s="`".repeat(r+1),i=e.startsWith("`")||e.endsWith("`")?" ":"",a=t.table===!0?e.replace(/\|/g,"\\|"):e;return`${s}${i}${a}${i}${s}`}function Bs(n){return Xg(n,1e3).replace(/[\\`*_{}[\]()#+!|<>~&]/g,"\\$&")}function LC(n){return`| ${[n.number===void 0?"\u2013":String(n.number),String(n.size),Fs(n.subject,{table:!0}),Sn[n.owner],n.grade===void 0?"\u2013":Bs(n.grade)].join(" | ")} |`}function _C(n,t){return n>0?`### KwikQA: ${xr(n,"test")} failed${t===0?"":`, ${t} flaky`}`:t===0?"### KwikQA: no failures":`### KwikQA: no failures, ${xr(t,"flaky test")}`}function Gl(n){let{model:t}=n;if(t===void 0)return`### KwikQA: no analysis
157
+ ${t.lines.join(`
158
+ `).slice(0,3e3)}`)]}]}]}}function My(t){let n=(e,r={})=>({type:"RichTextBlock",inlines:[{type:"TextRun",text:e,...r}]});return{type:"message",attachments:[{contentType:"application/vnd.microsoft.card.adaptive",contentUrl:null,content:{$schema:"http://adaptivecards.io/schemas/adaptive-card.json",type:"AdaptiveCard",version:"1.4",msteams:{width:"Full"},body:[n(t.headline,{weight:"Bolder",size:"Medium"}),...t.source===void 0?[]:[n(t.source,{isSubtle:!0})],...t.lines.map(e=>n(e))],actions:t.links.map(e=>({type:"Action.OpenUrl",title:e.label,url:e.url}))}}]}}function t0(t){if(!(t===void 0||t.trim()===""))try{let n=new URL(t.trim());return n.protocol==="https:"&&n.username===""&&n.password===""?n:void 0}catch{return}}function n0(t){let n=Number(t?.headers.get("retry-after"));return Number.isFinite(n)&&n>0?Math.min(n*1e3,e0):ZS}async function r0(t,n,e,r,s,i){let a="";for(let o=1;o<=2;o+=1){let d;try{d=await n(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),redirect:"error",signal:AbortSignal.timeout(QS)})}catch(c){a=`the webhook couldn't be reached (${c instanceof Error?c.message:String(c)})`}if(d?.ok===!0){t.print(`${r}: posted.`);return}if(d!==void 0&&(a=`the webhook answered ${d.status}`,d.status!==429&&d.status<500))break;o===1&&await e(n0(d))}t.error(`${r}: not posted; ${a}.`)}async function Uc(t,n,e,r,s,i){let a=[{name:"Slack",variable:"KWIKQA_SLACK_WEBHOOK_URL",message:Dy},{name:"Teams",variable:"KWIKQA_TEAMS_WEBHOOK_URL",message:My}];for(let o of a){let d=r[o.variable];if(d===void 0||d.trim()==="")continue;let c=t0(d);if(c===void 0){t.error(`${o.name}: not posted; ${o.variable} isn't an https URL.`);continue}if(i.when==="on-failure"&&!i.failures){t.print(`${o.name}: nothing failed, so nothing was posted (--notify always posts).`);continue}await r0(t,n,e,o.name,c,o.message(s))}}import{appendFile as s0,readFile as i0}from"node:fs/promises";var a0=30,Ly=100,o0=3e4,d0=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;async function c0(t){if(t===void 0||t==="")return{};try{let n=JSON.parse(await i0(t,"utf8"));return typeof n=="object"&&n!==null?n:{}}catch{return{}}}async function Kc(t){if(t.GITHUB_ACTIONS!=="true")return;let n=d0.test(t.GITHUB_REPOSITORY??"")?t.GITHUB_REPOSITORY:void 0,e=rt(t.GITHUB_API_URL,"https://api.github.com"),r=rt(t.GITHUB_SERVER_URL,"https://github.com"),s=/^\d+$/.test(t.GITHUB_RUN_ID??"")?t.GITHUB_RUN_ID:void 0,i=(await c0(t.GITHUB_EVENT_PATH)).pull_request,a=i?.number,o=i?.head?.repo?.full_name,d=i?.base?.repo?.full_name,c=(t.GITHUB_TOKEN??"").trim(),l=r===void 0||n===void 0?void 0:`${r}/${n}`,u=t.GITHUB_HEAD_REF||t.GITHUB_REF_NAME||void 0,p=/^[0-9a-f]{40}$/.test(t.GITHUB_SHA??"")?t.GITHUB_SHA:void 0;return{...e===void 0?{}:{apiUrl:e},...n===void 0?{}:{repository:n},...l===void 0||s===void 0?{}:{runUrl:`${l}/actions/runs/${s}`},workflow:t.GITHUB_WORKFLOW??"",job:t.GITHUB_JOB??"",...u===void 0?{}:{branch:u},...p===void 0?{}:{commit:{sha:p,...l===void 0?{}:{url:`${l}/commit/${p}`}}},...t.GITHUB_STEP_SUMMARY===void 0||t.GITHUB_STEP_SUMMARY===""?{}:{summaryPath:t.GITHUB_STEP_SUMMARY},...c===""?{}:{token:c},...typeof a=="number"&&Number.isSafeInteger(a)&&a>0?{pullRequest:{number:a,...l===void 0?{}:{url:`${l}/pull/${a}`},fork:t.GITHUB_EVENT_NAME!=="pull_request_target"&&(typeof o!="string"||o!==d)}}:{}}}function _y(t){return`<!-- kwikqa-ci workflow=${encodeURIComponent(t.workflow)} job=${encodeURIComponent(t.job)} -->`}async function qc(t){if(t.status===429||t.status===403&&(t.headers.get("x-ratelimit-remaining")==="0"||t.headers.has("retry-after")))return"GitHub's rate limit was reached";if(t.status===403)return"the token can't comment on this pull request; give the job `pull-requests: write` permission";if(t.status===401)return"GitHub refused the token";if(t.status===404)return"GitHub found no such pull request with this token";let n=await t.json().catch(()=>{}),e=typeof n?.message=="string"?`: ${n.message.replace(/\s+/g," ").slice(0,200)}`:"";return`GitHub answered ${t.status}${e}`}var Gc=class{constructor(n,e,r){this.send=n;this.apiUrl=e;this.token=r}send;apiUrl;token;call(n,e,r){return this.send(`${this.apiUrl}${e}`,{method:n,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28",...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error",signal:AbortSignal.timeout(o0)})}},fr=class extends Error{};async function l0(t,n,e){for(let r=1;r<=a0;r+=1){let s=await t.call("GET",`${n}/comments?per_page=${Ly}&page=${r}`);if(!s.ok)throw new fr(await qc(s));let i=await s.json(),a=i.find(o=>typeof o.body=="string"&&o.body.startsWith(e));if(typeof a?.id=="number")return a.id;if(i.length<Ly)return}}async function u0(t,n,e,r,s){let i=u=>t.print(`No pull-request comment: ${u}.`),a=e.pullRequest;if(a===void 0)return i("this run isn't for a pull request");if(a.fork)return i("the pull request comes from a fork, and GitHub gives its workflows a read-only token");if(e.token===void 0)return i("GITHUB_TOKEN isn't set; add `GITHUB_TOKEN: ${{ github.token }}` to the step's env");if(e.apiUrl===void 0||e.repository===void 0)return i("GITHUB_API_URL or GITHUB_REPOSITORY isn't what GitHub Actions sets");let o=new Gc(n,e.apiUrl,e.token),d=`/repos/${e.repository}/issues/${a.number}`,c=_y(e),l={body:`${c}
159
+ ${r}`};try{let u=await l0(o,d,c);if(u!==void 0){let f=await o.call("PATCH",`/repos/${e.repository}/issues/comments/${u}`,l);if(f.ok)return t.print("Pull-request comment: updated.");if(f.status!==403&&f.status!==404)throw new fr(await qc(f))}if(u===void 0&&!s)return i("nothing failed, and there is no earlier comment to update");let p=await o.call("POST",`${d}/comments`,l);if(!p.ok)throw new fr(await qc(p));t.print("Pull-request comment: posted.")}catch(u){let p=u instanceof fr?u.message:`GitHub couldn't be reached (${u instanceof Error?u.message:String(u)})`;t.error(`No pull-request comment: ${p}.`)}}async function Wc(t,n,e,r,s){if(e.summaryPath===void 0)t.print("No job summary: GITHUB_STEP_SUMMARY isn't set.");else try{await s0(e.summaryPath,`${r}
160
+ `),t.print("Job summary: written.")}catch(i){t.error(`No job summary: ${i.message}`)}await u0(t,n,e,r,s.failures)}var p0=30,jy=100,f0=3e4,h0=/^[\w.-]+(?:\/[\w.-]+)+$/;function As(t){let n=Number(t);return/^\d+$/.test(t??"")&&Number.isSafeInteger(n)&&n>0?n:void 0}function m0(t,n){let e=(t??"").split(",").filter(s=>s.trim()!=="");if(e.length!==1)return;let r=/^(.+)!(\d+)$/.exec(e[0]?.trim()??"");return r?.[1]===n?As(r[2]):void 0}function Yc(t){if(t.GITLAB_CI!=="true")return;let n=rt(t.CI_API_V4_URL),e=h0.test(t.CI_PROJECT_PATH??"")?t.CI_PROJECT_PATH:void 0,r=rt(t.CI_PROJECT_URL),s=As(t.CI_PROJECT_ID),i=As(t.CI_MERGE_REQUEST_IID),a=i??(e===void 0?void 0:m0(t.CI_OPEN_MERGE_REQUESTS,e)),o=i===void 0?s:As(t.CI_MERGE_REQUEST_PROJECT_ID),d=i===void 0?s:As(t.CI_MERGE_REQUEST_SOURCE_PROJECT_ID),c=i===void 0?r:rt(t.CI_MERGE_REQUEST_PROJECT_URL),l=/^[0-9a-f]{40}$/.test(t.CI_COMMIT_SHA??"")?t.CI_COMMIT_SHA:void 0,u=t.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME||t.CI_COMMIT_BRANCH||t.CI_COMMIT_TAG||t.CI_COMMIT_REF_NAME||void 0,p=rt(t.CI_JOB_URL),f=(t.GITLAB_TOKEN??"").trim();return{...n===void 0?{}:{apiUrl:n},...e===void 0?{}:{repository:e},...p===void 0?{}:{runUrl:p},...o===void 0?{}:{projectId:o},job:t.CI_JOB_NAME??"",...u===void 0?{}:{branch:u},...l===void 0?{}:{commit:{sha:l,...r===void 0?{}:{url:`${r}/-/commit/${l}`}}},...f===""?{}:{token:f},...a===void 0?{}:{pullRequest:{number:a,name:`Merge request !${a}`,...c===void 0?{}:{url:`${c}/-/merge_requests/${a}`},fork:d!==o&&s!==o}}}}function Fy(t){return`<!-- kwikqa-ci gitlab job=${encodeURIComponent(t.job)} -->`}async function Jc(t){if(t.status===429)return"GitLab's rate limit was reached";if(t.status===401)return"GitLab refused GITLAB_TOKEN";if(t.status===403)return"GITLAB_TOKEN can't comment on this merge request; it needs the `api` scope and at least the Reporter role";if(t.status===404)return"GitLab found no such merge request with GITLAB_TOKEN";let n=await t.json().catch(()=>{}),e=typeof n?.message=="string"?`: ${n.message.replace(/\s+/g," ").slice(0,200)}`:"";return`GitLab answered ${t.status}${e}`}var Xc=class{constructor(n,e,r){this.send=n;this.apiUrl=e;this.token=r}send;apiUrl;token;call(n,e,r){return this.send(`${this.apiUrl}${e}`,{method:n,headers:{Accept:"application/json","PRIVATE-TOKEN":this.token,...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error",signal:AbortSignal.timeout(f0)})}},hr=class extends Error{};async function y0(t,n,e){for(let r=1;r<=p0;r+=1){let s=await t.call("GET",`${n}?sort=asc&order_by=created_at&per_page=${jy}&page=${r}`);if(!s.ok)throw new hr(await Jc(s));let i=await s.json(),a=i.find(o=>o.system!==!0&&typeof o.body=="string"&&o.body.startsWith(e));if(typeof a?.id=="number")return a.id;if(i.length<jy)return}}async function g0(t,n,e,r,s){let i=u=>t.print(`No merge-request note: ${u}.`),a=e.pullRequest;if(a===void 0)return i("this pipeline isn't for a merge request, or its branch has more than one");if(a.fork)return i("the merge request comes from a fork, whose pipeline gets none of this project's variables");if(e.token===void 0)return i("GITLAB_TOKEN isn't set; CI_JOB_TOKEN can't write notes, so add a token with the `api` scope as a masked CI/CD variable");if(e.apiUrl===void 0||e.projectId===void 0)return i("CI_API_V4_URL or the merge request's project isn't what GitLab sets");let o=new Xc(n,e.apiUrl,e.token),d=`/projects/${e.projectId}/merge_requests/${a.number}/notes`,c=Fy(e),l={body:`${c}
161
+ ${r}`};try{let u=await y0(o,d,c);if(u!==void 0){let f=await o.call("PUT",`${d}/${u}`,l);if(f.ok)return t.print("Merge-request note: updated.");if(f.status!==403&&f.status!==404)throw new hr(await Jc(f))}if(u===void 0&&!s)return i("nothing failed, and there is no earlier note to update");let p=await o.call("POST",d,l);if(!p.ok)throw new hr(await Jc(p));t.print("Merge-request note: posted.")}catch(u){let p=u instanceof hr?u.message:`GitLab couldn't be reached (${u instanceof Error?u.message:String(u)})`;t.error(`No merge-request note: ${p}.`)}}async function Qc(t,n,e,r,s){t.print("");for(let i of r.trimEnd().split(`
162
+ `))t.print(i);t.print(""),await g0(t,n,e,r,s.failures)}var w0=20,By=10,b0=100;function mr(t,n){return`${t} ${n}${t===1?"":"s"}`}function Vy(t,n){let e=t.replace(/[\p{Cc}\u202a-\u202e\u2066-\u2069]/gu," ").replace(/\s+/g," ").trim();return e.length<=n?e:`${e.slice(0,n-1)}\u2026`}function Ts(t,n={}){let e=Vy(t,b0)||"(empty)",r=Math.max(0,...(e.match(/`+/g)??[]).map(o=>o.length)),s="`".repeat(r+1),i=e.startsWith("`")||e.endsWith("`")?" ":"",a=n.table===!0?e.replace(/\|/g,"\\|"):e;return`${s}${i}${a}${i}${s}`}function Ps(t){return Vy(t,1e3).replace(/[\\`*_{}[\]()#+!|<>~&]/g,"\\$&")}function x0(t){return`| ${[t.number===void 0?"\u2013":String(t.number),String(t.size),Ts(t.subject,{table:!0}),an[t.owner],t.grade===void 0?"\u2013":Ps(t.grade)].join(" | ")} |`}function v0(t,n){return t>0?`### KwikQA: ${mr(t,"test")} failed${n===0?"":`, ${n} flaky`}`:n===0?"### KwikQA: no failures":`### KwikQA: no failures, ${mr(n,"flaky test")}`}function Zc(t){let{model:n}=t;if(n===void 0)return`### KwikQA: no analysis
181
163
 
182
- ${Bs(n.message)}
183
- `;let e=l=>t.run.counts.find(u=>u.label===l)?.value??0,r=e("Failed"),s=e("Flaky"),i=t.run.counts.filter(l=>l.label==="Tests"||l.value>0).map(l=>l.label==="Tests"?xr(l.value,"test"):`${l.value} ${l.label.toLowerCase()}`),a=[_C(r,s),"",`${Bs(t.run.framework)} run: ${i.join(", ")}.`],o=t.groups.slice(0,DC);if(o.length>0){a.push("","| Group | Tests | Failure | Owner | Evidence |","| ---: | ---: | --- | --- | --- |",...o.map(LC));let l=t.groups.length-o.length;l>0&&a.push("",`${xr(l,"more group")} in the report.`)}let d=t.notAnalyzed.unclassified.length,c=t.notAnalyzed.runErrors.length;if(d>0||c>0){let l=[...d===0?[]:[`${xr(d,"failed test")} not grouped`],...c===0?[]:[xr(c,"run-level error")]];a.push("",`Also ${l.join(" and ")}; the report lists them.`)}if(t.flaky.length>0){a.push("","Flaky, passed on a retry:");for(let u of t.flaky.slice(0,Jg))a.push(`- ${Fs(u.title)} at ${Fs(u.location)}`);let l=t.flaky.length-Jg;l>0&&a.push(`- and ${l} more in the report`)}return n.notDiagnosed!==void 0&&a.push("",`Not diagnosed: ${Bs(n.notDiagnosed)}`),n.reportFile!==void 0&&a.push("",`Full report, with each group's evidence: ${Fs(n.reportFile)}${n.runUrl===void 0?"":`, in the artifacts of [this run](${n.runUrl})`}.`),`${a.join(`
164
+ ${Ps(t.message)}
165
+ `;let e=l=>n.run.counts.find(u=>u.label===l)?.value??0,r=e("Failed"),s=e("Flaky"),i=n.run.counts.filter(l=>l.label==="Tests"||l.value>0).map(l=>l.label==="Tests"?mr(l.value,"test"):`${l.value} ${l.label.toLowerCase()}`),a=[v0(r,s),"",`${Ps(n.run.framework)} run: ${i.join(", ")}.`],o=n.groups.slice(0,w0);if(o.length>0){a.push("","| Group | Tests | Failure | Owner | Evidence |","| ---: | ---: | --- | --- | --- |",...o.map(x0));let l=n.groups.length-o.length;l>0&&a.push("",`${mr(l,"more group")} in the report.`)}let d=n.notAnalyzed.unclassified.length,c=n.notAnalyzed.runErrors.length;if(d>0||c>0){let l=[...d===0?[]:[`${mr(d,"failed test")} not grouped`],...c===0?[]:[mr(c,"run-level error")]];a.push("",`Also ${l.join(" and ")}; the report lists them.`)}if(n.flaky.length>0){a.push("","Flaky, passed on a retry:");for(let u of n.flaky.slice(0,By))a.push(`- ${Ts(u.title)} at ${Ts(u.location)}`);let l=n.flaky.length-By;l>0&&a.push(`- and ${l} more in the report`)}return t.notDiagnosed!==void 0&&a.push("",`Not diagnosed: ${Ps(t.notDiagnosed)}`),t.reportFile!==void 0&&a.push("",`Full report, with each group's evidence: ${Ts(t.reportFile)}${t.runUrl===void 0?"":`, in the artifacts of [this run](${t.runUrl})`}.`),`${a.join(`
184
166
  `)}
185
- `}var En=class{#e=new Set;consume(t,e){return this.#e.has(t)?!1:(this.#e.add(t),!0)}};function Wa(n){return L({runId:n.manifest.runId,packetHash:n.manifest.packetHash,payloadHash:n.manifest.payloadHash,manifestHash:n.manifestHash,model:n.manifest.model,promptVersion:n.manifest.promptVersion,outputSchemaVersion:n.manifest.outputSchemaVersion,endpoint:n.endpoint,estimate:n.estimate,caps:n.caps})}function Kl(n,t){return{runId:n.manifest.runId,packetHash:n.manifest.packetHash,payloadManifestHash:n.manifestHash,authorizationBindingHash:t,model:n.manifest.model,estimate:n.estimate,caps:n.caps,evidence:n.manifest.evidence,artifactIds:n.manifest.artifactIds,channels:n.manifest.channels,omissionIds:n.manifest.omissionIds,redactionIds:n.manifest.redactionIds}}function Wl(n,t){return n.bindingHash===t&&n.authorizationId.trim().length>0&&n.authorizedAt.trim().length>0}var jC={purpose:"diagnosis",promptVersion:"1.3",outputSchemaVersion:"1.0"};function Jl(n){return{...n.extra,schemaVersion:"1.1",runId:n.runId,createdAt:n.createdAt,workspace:n.workspace,sourceHashes:n.sourceHashes,packetHash:n.packetHash,...n.request??jC,model:n.model,caps:n.caps,outcome:n.outcome,recordedAt:n.recordedAt}}function qe(n,t,e){return{kind:n,...t===void 0?{}:{reasonCode:t},...e===void 0?{}:{message:e}}}function Xl(n){if(n===void 0||n.trim().length===0)return;let t=Number(n);return Number.isFinite(t)&&t>=0?t:void 0}function FC(n){let t=[n.prompt,...n.overrides.map(s=>s.prompt)].map(Xl).filter(s=>s!==void 0),e=[n.completion,...n.overrides.map(s=>s.completion)].map(Xl).filter(s=>s!==void 0),r=[n.request??"0",...n.overrides.map(s=>s.request)].map(Xl).filter(s=>s!==void 0);if(!(t.length!==n.overrides.filter(s=>s.prompt!==void 0).length+1||e.length!==n.overrides.filter(s=>s.completion!==void 0).length+1||r.length!==n.overrides.filter(s=>s.request!==void 0).length+1))return{prompt:Math.max(...t),completion:Math.max(...e),request:Math.max(...r)}}function Ja(n,t,e){if(!Number.isInteger(t)||t<=0)return;let r=FC(e);if(r===void 0)return;let s=Buffer.byteLength(n,"utf8"),i=s+64,a=i*r.prompt+t*r.completion+r.request;if(Number.isFinite(a))return{method:"utf8-byte-upper-bound-v1",requestBytes:s,estimatedInputTokens:i,estimatedOutputTokens:t,estimatedDollars:a,promptDollarsPerToken:r.prompt,completionDollarsPerToken:r.completion,fixedRequestDollars:r.request}}function Yl(n){for(let[t,e]of[["request",n.request],["run",n.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 Ql(n,t){return n.estimatedInputTokens>t.request.maxInputTokens||n.estimatedOutputTokens>t.request.maxOutputTokens?{kind:"blocked",reasonCode:"request-token-budget-exceeded",message:"The conservative request token estimate exceeds the request cap."}:n.estimatedDollars>t.request.maxDollars?{kind:"blocked",reasonCode:"request-dollar-budget-exceeded",message:"The conservative request cost estimate exceeds the request cap."}:n.estimatedInputTokens>t.run.maxInputTokens||n.estimatedOutputTokens>t.run.maxOutputTokens?{kind:"blocked",reasonCode:"run-token-budget-exceeded",message:"The conservative request token estimate exceeds the remaining run cap."}:n.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 Vs(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0}function Ya(n){return typeof n=="string"&&n.trim().length>0?n:void 0}function Qa(n){return typeof n=="number"&&Number.isInteger(n)&&n>=0?n:void 0}function Qg(n){return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:void 0}function Zg(n){if(n!=null)return Qa(n)??null}function vr(n){if(typeof n!="string"||n.trim().length===0)return;let t=Number(n);return Number.isFinite(t)&&t>=0?n:void 0}function BC(n){let t=Vs(n);if(t===void 0)return;let e=t.prompt===void 0?void 0:vr(t.prompt),r=t.completion===void 0?void 0:vr(t.completion),s=t.request===void 0?void 0:vr(t.request),i=t.min_prompt_tokens===void 0?void 0:Qa(t.min_prompt_tokens),a=t.utc_start===void 0?void 0:Qg(t.utc_start),o=t.utc_end===void 0?void 0:Qg(t.utc_end),d=t.utc_days===void 0?void 0:Array.isArray(t.utc_days)?t.utc_days.map(Qa):void 0;if(!(t.prompt!==void 0&&e===void 0||t.completion!==void 0&&r===void 0||t.request!==void 0&&s===void 0||t.min_prompt_tokens!==void 0&&i===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},...r===void 0?{}:{completion:r},...s===void 0?{}:{request:s},...i===void 0?{}:{minPromptTokens:i},...a===void 0?{}:{utcStart:a},...o===void 0?{}:{utcEnd:o},...d===void 0?{}:{utcDays:d}}}function VC(n){let t=Vs(n);if(t===void 0)return;let e=vr(t.prompt),r=vr(t.completion),s=t.request===void 0?void 0:vr(t.request);if(e===void 0||r===void 0||t.request!==void 0&&s===void 0)return;let i=t.overrides;if(i!==void 0&&!Array.isArray(i))return;let a=(i??[]).map(BC);if(!a.includes(void 0))return{prompt:e,completion:r,...s===void 0?{}:{request:s},overrides:a}}function ew(n){return n.trim().toLocaleLowerCase("en-US")}function tw(n){return Ya(n.tag)}function Xa(n,t){return{kind:"unsupported",code:n,message:t}}function Zl(n,t){let e=Vs(n),s=Vs(e?.data)?.endpoints;if(!Array.isArray(s))return{kind:"failed",code:"invalid-metadata",message:"Endpoint metadata was malformed."};let i=ew(t.providerSlug),a=s.map(Vs).filter(g=>g!==void 0).filter(g=>{let y=tw(g);return y!==void 0&&ew(y)===i});if(a.length===0)return Xa("provider-unavailable",`The exact provider ${t.providerSlug} does not serve ${t.modelId}.`);if(a.length!==1)return Xa("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=Ya(o.model_id);if(d!==t.modelId)return Xa("model-mismatch","OpenRouter metadata did not preserve the configured exact model identifier.");let c=Array.isArray(o.supported_parameters)?o.supported_parameters.map(Ya):[];if(c.includes(void 0))return{kind:"failed",code:"invalid-metadata",message:"Supported parameters were malformed."};if(!c.includes("structured_outputs"))return Xa("structured-output-unsupported","The exact endpoint does not advertise structured output support.");let l=Qa(o.context_length),u=Zg(o.max_prompt_tokens),p=Zg(o.max_completion_tokens),f=VC(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:Ya(o.provider_name)??t.providerSlug,providerSlug:tw(o)??t.providerSlug,modelId:d,contextLength:l,...u===void 0?{}:{maxPromptTokens:u},...p===void 0?{}:{maxCompletionTokens:p},supportedParameters:c,pricing:f,status:h}}}function HC(n){return{...n.prompt===void 0?{}:{prompt:n.prompt},...n.completion===void 0?{}:{completion:n.completion},...n.request===void 0?{}:{request:n.request},...n.minPromptTokens===void 0?{}:{minPromptTokens:n.minPromptTokens},...n.utcStart===void 0?{}:{utcStart:String(n.utcStart)},...n.utcEnd===void 0?{}:{utcEnd:String(n.utcEnd)},...n.utcDays===void 0?{}:{utcDays:n.utcDays}}}function eu(n){let t={prompt:n.pricing.prompt,completion:n.pricing.completion,...n.pricing.request===void 0?{}:{request:n.pricing.request},overrides:n.pricing.overrides.map(HC)};return{modelId:n.modelId,providerId:n.providerSlug,providerName:n.providerName,contextLength:n.contextLength,...n.maxPromptTokens===void 0?{}:{maxPromptTokens:n.maxPromptTokens},...n.maxCompletionTokens===void 0?{}:{maxCompletionTokens:n.maxCompletionTokens},supportedParameters:n.supportedParameters,status:n.status,pricing:t}}var zC="https://openrouter.ai",UC=`${zC}/api/v1`,qC=3e4,GC=4*1024*1024;function Mt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Hs(n){if(n instanceof DOMException&&(n.name==="AbortError"||n.name==="TimeoutError"))return"timed out";let t=n?.cause;return typeof t?.code=="string"?t.code:typeof t?.message=="string"?t.message:n instanceof Error?n.message:"unknown error"}function tu(n,t){return n!==void 0&&Number.isInteger(n)&&n>0?n:t}function KC(n){let t=n.split("/");if(!(t.length!==2||t.some(e=>e.length===0)))return t.map(encodeURIComponent).join("/")}function nw(n){let t=n();return t===void 0||t.trim().length===0?void 0:t.trim()}async function rw(n,t){let e=n.headers.get("content-length");if(e!==null){let d=Number(e);if(Number.isFinite(d)&&d>t)return{kind:"too-large"}}if(n.body===null)return{kind:"invalid-json"};let r=n.body.getReader(),s=[],i=0;try{for(;;){let d=await r.read();if(d.done)break;if(i+=d.value.byteLength,i>t)return await r.cancel(),{kind:"too-large"};s.push(d.value)}}finally{r.releaseLock()}let a=new Uint8Array(i),o=0;for(let d of s)a.set(d,o),o+=d.byteLength;try{return{kind:"parsed",value:JSON.parse(new TextDecoder().decode(a))}}catch{return{kind:"invalid-json"}}}function Za(n){if(!Mt(n)||!Mt(n.error))return;let t=n.error.code;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function nu(n,t){let e=Mt(t)&&Mt(t.error)?t.error:void 0,r=Mt(e?.metadata)?e.metadata:void 0,s=[e?.message,r?.raw].filter(a=>typeof a=="string"&&a.trim()!=="").map(a=>a.replace(/\s+/g," ").trim()).join(": "),i=s.length>300?`${s.slice(0,299)}\u2026`:s;return`OpenRouter completion request failed (HTTP ${n})${i===""?".":`: ${i}`}`}function ru(n){return Mt(n)&&Mt(n.error)&&n.choices===void 0}function sw(n){return{Accept:"application/json",Authorization:`Bearer ${n}`}}function su(n){if(n.body.model!==n.route.modelId)return"The completion body does not preserve the configured exact model.";if("models"in n.body)return"Model fallback arrays are forbidden.";if("tools"in n.body||"tool_choice"in n.body)return"Model tools are forbidden for bounded diagnosis.";if(n.body.stream===!0)return"Streaming is not supported by bounded diagnosis.";let t=Mt(n.body.provider)?n.body.provider:void 0,e=Array.isArray(t?.only)?t.only:void 0;if(e?.length!==1||e[0]!==n.route.providerSlug||t?.allow_fallbacks!==!1||t.require_parameters!==!0)return"The completion body does not preserve the exact no-fallback provider route.";if((Mt(n.body.response_format)?n.body.response_format:void 0)?.type!=="json_schema")return"The completion body does not require JSON Schema output."}var On=class{#e;#n;#t;#r;#s;#i;#a;#o;constructor(t={}){this.#e=t.fetch??fetch,this.#n=tu(t.timeoutMs,qC),this.#t=tu(t.maxResponseBytes,GC),this.#r=t.apiRoot??UC,this.#s=t.readApiKey??(()=>process.env.OPENROUTER_API_KEY),this.#i=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=KC(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 r=nw(this.#s);if(r===void 0)return{kind:"failed",code:"credential-unavailable",message:`${this.#i} is not configured.`};let s=new AbortController,i=setTimeout(()=>s.abort(),this.#n);try{let a=await this.#e(`${this.#r}/models/${e}/endpoints`,{method:"GET",headers:{...this.#a(),...sw(r)},redirect:"error",signal:s.signal}),o=await rw(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?Zl(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 (${Hs(a)}).`}}finally{clearTimeout(i)}}async complete(t){let e=performance.now(),r=su(t);if(r!==void 0)return{kind:"failed",code:"invalid-request",message:r,elapsedMs:0};let s=nw(this.#s);if(s===void 0)return{kind:"failed",code:"credential-unavailable",message:`${this.#i} is not configured.`,elapsedMs:performance.now()-e};let i=tu(t.timeoutMs,this.#n),a=new AbortController,o=setTimeout(()=>a.abort(),i);try{let d=await this.#e(`${this.#r}/chat/completions`,{method:"POST",headers:{...this.#a(t.body),...sw(s),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(t.body),redirect:"error",signal:a.signal}),c=await rw(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||ru(c.value)){let u=Za(c.value),p=d.ok?u??502:d.status;return{kind:"failed",code:"http-error",message:nu(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 $n={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},WC={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:$n,contradictingEvidenceIds:$n,missingEvidence:$n,unresolvedAssumptions:$n,nextAction:{type:"string",minLength:1},statement:{type:"string",minLength:1}}},iu={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:WC,maxItems:3},symptomIds:$n,missingEvidence:$n,recommendedNextAction:{type:"string",minLength:1},repairEligibility:{type:"string",enum:["eligible","ineligible","undetermined"]},ownershipEvidenceIds:$n,packetHash:{type:"string",minLength:1}}},JC=["status","hypotheses","symptomIds","missingEvidence","recommendedNextAction","repairEligibility","ownershipEvidenceIds","packetHash"],XC=["hypothesisId","rank","causalCategory","probableOwner","evidenceGrade","supportingEvidenceIds","contradictingEvidenceIds","missingEvidence","unresolvedAssumptions","nextAction","statement"],YC=new Set(["conclusive","probable","inconclusive"]),QC=new Set(["strong","moderate","weak","insufficient"]),ZC=new Set(["test-support","application","environment","undetermined"]),e1=new Set(["eligible","ineligible","undetermined"]);function Rr(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;let t=Object.getPrototypeOf(n);return t===Object.prototype||t===null}function de(n,t,e,r){n.push({path:t,code:e,message:r})}function Ir(n,t,e,r){let s=new Set(t);for(let i of t)Object.hasOwn(n,i)||de(r,`${e}.${i}`,"missing-field","field is required");for(let i of Object.keys(n))s.has(i)||de(r,`${e}.${i}`,"unknown-field","field is not allowed")}function je(n,t,e){if(typeof n!="string"){de(e,t,"expected-string","expected a string");return}if(n.trim()===""){de(e,t,"empty-string","string must not be empty");return}return n}function kr(n,t,e,r){let s=je(n,e,r);if(s!==void 0){if(!t.has(s)){de(r,e,"invalid-enum",`unsupported value ${JSON.stringify(s)}`);return}return s}}function tt(n,t,e){if(!Array.isArray(n)){de(e,t,"expected-array","expected an array");return}let r=[],s=new Set;return n.forEach((i,a)=>{let o=je(i,`${t}[${a}]`,e);if(o!==void 0){if(s.has(o)){de(e,`${t}[${a}]`,"duplicate-item",`duplicate value ${JSON.stringify(o)}`);return}s.add(o),r.push(o)}}),r}function t1(n,t,e){let r=`$.hypotheses[${t}]`;if(!Rr(n)){de(e,r,"expected-object","expected an object");return}Ir(n,XC,r,e);let s=je(n.hypothesisId,`${r}.hypothesisId`,e),i=n.rank;!Number.isInteger(i)||typeof i!="number"?de(e,`${r}.rank`,"expected-integer","rank must be an integer"):(i<1||i>3)&&de(e,`${r}.rank`,"invalid-rank","rank must be between 1 and 3");let a=je(n.causalCategory,`${r}.causalCategory`,e),o=kr(n.probableOwner,ZC,`${r}.probableOwner`,e),d=kr(n.evidenceGrade,QC,`${r}.evidenceGrade`,e),c=tt(n.supportingEvidenceIds,`${r}.supportingEvidenceIds`,e),l=tt(n.contradictingEvidenceIds,`${r}.contradictingEvidenceIds`,e),u=tt(n.missingEvidence,`${r}.missingEvidence`,e),p=tt(n.unresolvedAssumptions,`${r}.unresolvedAssumptions`,e),f=je(n.nextAction,`${r}.nextAction`,e),h=je(n.statement,`${r}.statement`,e);if(c!==void 0&&l!==void 0){let m=new Set(l);for(let g of c)m.has(g)&&de(e,`${r}.contradictingEvidenceIds`,"citation-overlap",`${g} cannot both support and contradict a hypothesis`)}if(d!==void 0&&d!=="insufficient"&&c?.length===0&&de(e,`${r}.supportingEvidenceIds`,"support-required",`${d} evidence requires at least one supporting citation`),!(s===void 0||typeof i!="number"||!Number.isInteger(i)||i<1||i>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:s,rank:i,causalCategory:a,probableOwner:o,evidenceGrade:d,supportingEvidenceIds:c,contradictingEvidenceIds:l,missingEvidence:u,unresolvedAssumptions:p,nextAction:f,statement:h}}function eo(n){let t=[];if(!Rr(n))return{kind:"invalid",issues:[{path:"$",code:"expected-object",message:"diagnosis must be an object"}]};Ir(n,JC,"$",t);let e=kr(n.status,YC,"$.status",t),r=[];Array.isArray(n.hypotheses)?(n.hypotheses.length>3&&de(t,"$.hypotheses","too-many-items","at most three hypotheses are allowed"),n.hypotheses.forEach((p,f)=>{let h=t1(p,f,t);h!==void 0&&r.push(h)})):de(t,"$.hypotheses","expected-array","expected an array");let s=new Set;for(let p of r)s.has(p.hypothesisId)&&de(t,"$.hypotheses","duplicate-id",`duplicate hypothesis id ${JSON.stringify(p.hypothesisId)}`),s.add(p.hypothesisId);[...r].map(p=>p.rank).sort((p,f)=>p-f).forEach((p,f)=>{p!==f+1&&de(t,"$.hypotheses","invalid-rank","hypothesis ranks must be contiguous from 1")});let a=tt(n.symptomIds,"$.symptomIds",t),o=tt(n.missingEvidence,"$.missingEvidence",t),d=je(n.recommendedNextAction,"$.recommendedNextAction",t),c=kr(n.repairEligibility,e1,"$.repairEligibility",t),l=tt(n.ownershipEvidenceIds,"$.ownershipEvidenceIds",t),u=je(n.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:r,symptomIds:a,missingEvidence:o,recommendedNextAction:d,repairEligibility:c,ownershipEvidenceIds:l,packetHash:u}}}function bt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0}function to(n){return typeof n=="string"&&n.trim().length>0?n:void 0}function Dn(n){return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:void 0}function n1(n){if(n===void 0)return{valid:!0};let t=bt(n);if(t===void 0)return{valid:!1};let e=Dn(t.prompt_tokens),r=Dn(t.completion_tokens),s=Dn(t.total_tokens);if(e===void 0||r===void 0||s===void 0)return{valid:!1};let i=bt(t.completion_tokens_details),a=bt(t.prompt_tokens_details),o=bt(t.cost_details),d=Dn(i?.reasoning_tokens),c=Dn(a?.cached_tokens),l=Dn(t.cost),u=Dn(o?.upstream_inference_cost);return s!==e+r||d!==void 0&&d>r||c!==void 0&&c>e||t.completion_tokens_details!==void 0&&i===void 0||t.prompt_tokens_details!==void 0&&a===void 0||t.cost_details!==void 0&&o===void 0||i?.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:r,totalTokens:s,...d===void 0?{}:{reasoningTokens:d},...c===void 0?{}:{cachedTokens:c},...l===void 0?{}:{cost:l},...u===void 0?{}:{upstreamInferenceCost:u}}}}function r1(n){let e=bt(n?.endpoints)?.available;if(!Array.isArray(e))return;let r=e.map(bt).filter(s=>s!==void 0&&s.selected===!0);return r.length!==1?null:to(r[0]?.provider)??null}function iw(n,t,e){let r=bt(n),s=to(r?.model),i=r?.choices;if(r===void 0||s===void 0||!Array.isArray(i))return{kind:"malformed-response",message:"Completion response fields were malformed."};if(i.length!==1)return{kind:"malformed-response",message:"Completion response must contain exactly one choice."};let a=bt(i[0]),o=bt(a?.message),d=to(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=to(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=bt(r.openrouter_metadata),f=r1(p);if(f===null)return{kind:"malformed-response",message:"Router metadata did not identify exactly one selected provider."};let h=n1(r.usage);return h.valid?{kind:"parsed",value:{output:u.output,reportedModel:s,...f===void 0?{}:{reportedProvider:f},...h.usage===void 0?{}:{usage:h.usage},finishReason:d}}:{kind:"malformed-response",message:"Completion usage metadata was malformed."}}var s1=new Set(["$defs","$ref","additionalProperties","anyOf","const","definitions","description","enum","exclusiveMaximum","exclusiveMinimum","format","items","maxItems","maximum","minItems","minimum","multipleOf","pattern","properties","required","title","type"]),i1=new Set(["$defs","definitions","properties"]);function aw(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function no(n){return Array.isArray(n)?n.map(no):aw(n)?Object.fromEntries(Object.entries(n).filter(([t])=>s1.has(t)).map(([t,e])=>[t,i1.has(t)&&aw(e)?Object.fromEntries(Object.entries(e).map(([r,s])=>[r,no(s)])):t==="enum"||t==="const"||t==="required"?e:no(e)])):n}function ow(n,t){return t.startsWith("openai/")?no(n):n}var a1=`You diagnose test failures from one bounded, redacted evidence packet. The packet's framework field names the framework that ran the tests: an end-to-end framework (Playwright, Cypress, or WebdriverIO) or a test runner whose report KwikQA reads (Vitest, Jest, Mocha, pytest, JUnit, TestNG, Cucumber, or unknown); read errors, commands, and locators in that framework's terms.
167
+ `}import{createHash as tx}from"node:crypto";import{access as C2,appendFile as N2,mkdir as O2,readdir as $2,readFile as $o,realpath as $r,stat as nx,writeFile as ix}from"node:fs/promises";import{isAbsolute as ap,join as He,relative as ii,resolve as Do,sep as ax}from"node:path";import{mkdir as v1,writeFile as k1}from"node:fs/promises";import{join as yw}from"node:path";import{lstat as k0,readFile as zy,realpath as rl}from"node:fs/promises";import{dirname as el,isAbsolute as R0,join as ca,relative as la,resolve as da,sep as Hy}from"node:path";var Uy=["ts","mts","cts","js","mjs","cjs"],qy={playwright:"playwright.config",cypress:"cypress.config",webdriverio:"wdio.conf"},I0={playwright:["@playwright/test"],cypress:["cypress"],webdriverio:["@wdio/cli","webdriverio"]},pa={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"};function tl(t,n){let e=la(t,n);return e===""||!R0(e)&&e!==".."&&!e.startsWith(`..${Hy}`)}async function ua(t){return(await k0(t).catch(()=>{}))?.isFile()===!0}function nl(t){return t.split(Hy).join("/")}async function Gy(t){let n=await rl(t),e={};try{let s=JSON.parse(await zy(ca(n,"package.json"),"utf8"));e={...s.dependencies,...s.devDependencies}}catch{e={}}let r=[];for(let s of["playwright","cypress","webdriverio"]){let i=I0[s].find(o=>o in e),a;for(let o of Uy){let d=`${qy[s]}.${o}`;if(await ua(ca(n,d))){a=d;break}}(i!==void 0||a!==void 0)&&r.push({framework:s,...a===void 0?{}:{configFile:a},...i===void 0?{}:{packageName:i}})}return r}async function fa(t,n,e){let r=await rl(t),s=el(da(r,e));for(tl(r,s)||(s=r);;){for(let a of Uy){let o=ca(s,`${qy[n]}.${a}`);if(await ua(o))return nl(la(r,o))}if(s===r)return;let i=el(s);if(!tl(r,i))return;s=i}}async function ha(t,n){let e=await rl(t),r=n===void 0?e:el(da(e,n));if(n!==void 0){let s=await zy(da(e,n),"utf8").catch(()=>"");if(/\bsupportFile\s*:\s*false\b/.test(s))return null;let i=/\bsupportFile\s*:\s*["'`]([^"'`]+)["'`]/.exec(s)?.[1];if(i!==void 0){let a=da(r,i);return tl(e,a)&&await ua(a)?nl(la(e,a)):void 0}}for(let s of["ts","js","tsx","jsx"]){let i=ca(r,"cypress","support",`e2e.${s}`);if(await ua(i))return nl(la(e,i))}}import{readFile as S0,realpath as E0}from"node:fs/promises";import{createRequire as C0}from"node:module";import{delimiter as N0,dirname as Qy,isAbsolute as O0,join as In}from"node:path";import{spawn as Xy}from"node:child_process";var A0=["KWIKQA_TOKEN","KWIKQA_API_URL","OPENROUTER_API_KEY"],Ky=256*1024,T0=8e3;function ma(t,n={}){let e={...t,...n};for(let r of A0)delete e[r];return e}function Wy(t){return t.pid===void 0||t.exitCode!==null||t.signalCode!==null}function Jy(t,n){if(t.pid!==void 0)try{process.kill(-t.pid,n)}catch{t.kill(n)}}async function P0(t,n){if(!Wy(t)){if(process.platform==="win32"){await new Promise(e=>{let r=Xy("taskkill",["/pid",String(t.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});r.on("exit",()=>e()),r.on("error",()=>e())});return}Jy(t,"SIGINT"),await Promise.race([n,new Promise(e=>setTimeout(e,T0))]),Wy(t)||Jy(t,"SIGKILL")}}function sl(t,n,e){let r=Xy(t,[...n],{cwd:e.cwd,env:e.env,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),s="",i=o=>{s+=o.toString("utf8"),s.length>Ky&&(s=s.slice(-Ky))};r.stdout?.on("data",i),r.stderr?.on("data",i);let a=new Promise(o=>{r.on("exit",d=>o(d??void 0)),r.on("error",()=>o(void 0))});return{child:r,output:()=>s,exited:a,stop:async()=>{await P0(r,a),await Promise.race([a,new Promise(o=>setTimeout(o,2e3))])}}}async function ya(t,n,e){let r=sl(t,n,e),s=!1,i=setTimeout(()=>{s=!0,r.stop()},e.timeoutMs),a=await r.exited;return clearTimeout(i),{...a===void 0?{}:{exitCode:a},timedOut:s,output:r.output()}}async function Yy(t,n,e){let r=Date.now()+e,s=!1;for(t.exited.then(()=>{s=!0});Date.now()<r;){let i=n.exec(t.output());if(i!==null)return i;if(s)return n.exec(t.output())??void 0;await new Promise(a=>setTimeout(a,100))}}var eg="1.0",il=[1,59],$0=5,D0=6e4,M0=3e4,L0=12e4,_0=new Set(["generic","text","list","group","none","presentation"]),j0=new Set(["banner","navigation","main","contentinfo","complementary","region","form","search"]);function al(t){let[n=0,e=0]=t.split(".").map(r=>Number.parseInt(r,10));return n>il[0]||n===il[0]&&e>=il[1]}async function Zy(t){try{let n=JSON.parse(await S0(In(t,"package.json"),"utf8"));return n.name==="@playwright/cli"&&typeof n.version=="string"?n.version:void 0}catch{return}}async function tg(t,n){try{let r=C0(In(t,"package.json")).resolve("@playwright/cli/package.json"),s=Qy(r),i=await Zy(s);if(i!==void 0)return{entryPath:In(s,"playwright-cli.js"),version:i,source:"project"}}catch{}let e=process.platform==="win32"?["playwright-cli.cmd"]:["playwright-cli"];for(let r of(n.PATH??"").split(N0).filter(Boolean))for(let s of e){let i=In(r,s);try{let a=process.platform==="win32"?In(r,"node_modules","@playwright","cli"):Qy(await E0(i)),o=await Zy(a);if(o!==void 0)return{entryPath:In(a,"playwright-cli.js"),version:o,source:"path"}}catch{}}}function ol(t){return t.split(/\r?\n/).filter(n=>!/[║╔╚═]/.test(n)).join(`
168
+ `)}function ng(t){return/```yaml\r?\n([\s\S]*?)\r?\n```/.exec(ol(t))?.[1]?.split(/\r?\n/)}function rg(t){let n=ol(t).split(/\r?\n/),e=n.findIndex(r=>r.trim()==="### Result");if(!(e<0))return n.slice(e+1).map(r=>r.trim()).find(r=>r!==""&&!r.startsWith("###"))}function F0(t){return/getByRole\(\s*['"]([\w-]+)['"]/.exec(t??"")?.[1]?.toLowerCase()}function sg(t){return t.trim().replace(/^-\s+/,"").replace(/\s\[(?:ref|cursor)=[^\]]+\]/g,"").replace(/:$/,"").trim()}function ig(t,n,e=$0){let r=rr(n??""),s=F0(n);return t.map((a,o)=>{let d=/\[ref=(e\d+)\]/.exec(a)?.[1],c=sg(a),l=/^([\w-]+)/.exec(c)?.[1]?.toLowerCase()??"";if(d===void 0||_0.has(l))return;let u=c.toLowerCase(),p=r.filter(f=>u.includes(f)).length*3+(s!==void 0&&l===s?2:0);if(!(j0.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 ag(t){let{target:n}=t,e=[],r={logicalTestId:n.logicalTestId,title:n.title,file:n.file,line:n.line,...n.failingLine===void 0?{}:{failingLine:n.failingLine},...n.locator===void 0?{}:{locator:n.locator}};if(n.failingLine===void 0)return{...r,candidates:[],issues:["The report does not say which line failed."]};let s=ma(t.env,{PLAYWRIGHT_HTML_OPEN:"never"}),i=sl(t.playwright.executable,[...t.playwright.nodeArguments,"test",`${n.file}:${n.line}`,...n.project===void 0?[]:[`--project=${n.project}`],...t.configPath===void 0?[]:[`--config=${t.configPath}`],"--debug=cli","--timeout=0","--retries=0","--workers=1","--reporter=line"],{cwd:t.workspaceRoot,env:s}),a=(c,l=M0)=>ya(process.execPath,[t.cli.entryPath,...c],{cwd:t.scratchDirectory,env:s,timeoutMs:l}),o,d=[];try{if(o=(await Yy(i,/playwright-cli attach ([\w-]+)/,D0))?.[1],o===void 0)return e.push("The test did not stop in the debugger."),{...r,candidates:d,issues:e};if((await a(["attach",o])).exitCode!==0)return e.push("Playwright CLI could not attach to the paused test."),{...r,candidates:d,issues:e};let u=O0(n.file)?n.file:In(t.workspaceRoot,n.file),p=await a([`-s=${o}`,"pause-at",`${u}:${n.failingLine}`],L0);if(p.exitCode!==0||!/### Paused/.test(p.output))return e.push(`The test did not reach line ${n.failingLine}.`),{...r,candidates:d,issues:e};let f=ng((await a([`-s=${o}`,"snapshot"])).output);if(f===void 0)return e.push("Playwright CLI returned no page snapshot."),{...r,candidates:d,issues:e};for(let h of ig(f,n.locator)){let m=rg((await a([`-s=${o}`,"generate-locator",h.ref])).output);m!==void 0&&d.push({element:h.element,locator:m})}return d.length===0&&e.push("No locator could be generated for any candidate."),{...r,candidates:d,issues:e}}catch(c){return e.push(`The probe stopped: ${c instanceof Error?c.message:String(c)}`),{...r,candidates:d,issues:e}}finally{o!==void 0&&await a([`-s=${o}`,"detach"],1e4).catch(()=>{}),await i.stop()}}import{mkdir as uw,rm as lw}from"node:fs/promises";import{dirname as f1,join as Rr,relative as h1,resolve as m1}from"node:path";import{createHash as B0}from"node:crypto";function dl(t,n){if(t===null||typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError("canonical JSON cannot contain non-finite numbers");return t}if(Array.isArray(t))return t.map(e=>dl(e,n));if(typeof t!="object")throw new TypeError(`canonical JSON cannot contain ${typeof t}`);if(n.has(t))throw new TypeError("canonical JSON cannot contain cycles");n.add(t);try{let e=t,r={};for(let s of Object.keys(e).sort()){let i=e[s];if(i===void 0)throw new TypeError(`canonical JSON cannot contain undefined at ${JSON.stringify(s)}`);r[s]=dl(i,n)}return r}finally{n.delete(t)}}function pe(t){return JSON.stringify(dl(t,new Set))}function L(t){return B0("sha256").update(pe(t),"utf8").digest("hex")}function og(t){let n=new Map;for(let e of t){if(n.has(e.logicalTestId))throw new Error("Logical test observation is duplicated.");n.set(e.logicalTestId,e.status)}return n}function dg(t){return t!==void 0&&t!=="passed"}function cl(t){let n=new Set(t.targetLogicalTestIds);if(n.size===0||n.size!==t.targetLogicalTestIds.length)throw new Error("Target logical test identities must be unique and nonempty.");let e=og(t.baseline),r=[],s=new Set;for(let l of t.blockingReasons??[]){if(l.length===0)throw new Error("Blocking validation reasons must be nonempty.");r.push({classification:"incomplete-check",message:l})}for(let l of[...t.commands].sort((u,p)=>u.commandId.localeCompare(p.commandId))){if(!l.required)continue;if(l.timing==="post-patch")for(let p of l.expectedLogicalTestIds)s.add(p);if(!l.fresh){r.push({classification:"incomplete-check",commandId:l.commandId,message:"Required command evidence is not fresh."});continue}if(l.status==="unavailable"){r.push({classification:"unavailable-check",commandId:l.commandId,message:"Required command was unavailable."});continue}if(l.status==="incomplete"){r.push({classification:"incomplete-check",commandId:l.commandId,message:"Required command did not produce authoritative evidence."});continue}if(l.timing==="baseline")continue;let u=og(l.observations);for(let p of l.expectedLogicalTestIds){let f=u.get(p);if(f===void 0){r.push({classification:"incomplete-check",logicalTestId:p,commandId:l.commandId,message:"An expected logical test is missing from post-patch evidence."});continue}if(n.has(p)){r.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"&&r.push({classification:dg(h)?"unchanged-pre-existing-failure":"newly-introduced-failure",logicalTestId:p,commandId:l.commandId,message:dg(h)?"An affected test remains non-passing from its baseline.":"An affected test newly became non-passing."})}}for(let l of[...n].sort())s.has(l)||r.push({classification:"incomplete-check",logicalTestId:l,message:"No fresh focused evidence covers the target logical test."});let i=r.sort((l,u)=>`${l.classification}\0${l.logicalTestId??""}\0${l.commandId??""}`.localeCompare(`${u.classification}\0${u.logicalTestId??""}\0${u.commandId??""}`)),a=new Set(i.map(l=>l.classification)),o=[...n].every(l=>i.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")||t.commands.some(l=>l.required&&l.status==="failed")?"failed":"passed",classifications:i};return{...c,summaryHash:L(c)}}var wa="1.1",ll="1.0",ba="1.1";var xa="1.0",Kt=/^[a-z][a-z0-9_-]{0,63}$/,yr=32*1024*1024,An=16*1024*1024,Es="report.json",lg=["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 gr(t){return lg.includes(t)}var ke=/^[a-f0-9]{64}$/,Cs=Kt;function $e(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ug(t){return Array.isArray(t)&&t.every(n=>typeof n=="string")}function Ss(t,n=!0){return ug(t)&&(n||t.length>0)&&t.every(e=>e.length>0&&!e.includes("\0"))&&new Set(t).size===t.length}function Ce(t,n){let e=Object.keys(t).sort(),r=[...n].sort();return e.length===r.length&&e.every((s,i)=>s===r[i])}function V0(t){if(!$e(t))return!1;let n=["outputDirectory","maxArtifacts","maxArtifactBytes"];return t.reportFile!==void 0&&n.push("reportFile"),Ce(t,n)&&typeof t.outputDirectory=="string"&&t.outputDirectory.length>0&&!t.outputDirectory.includes("\0")&&(t.reportFile===void 0||typeof t.reportFile=="string"&&t.reportFile.length>0&&!t.reportFile.includes("\0"))&&Number.isInteger(t.maxArtifacts)&&t.maxArtifacts>0&&Number.isInteger(t.maxArtifactBytes)&&t.maxArtifactBytes>0&&t.maxArtifactBytes<=yr}function z0(t){if(!$e(t))return!1;let n=["kind","path","detail"];return t.sha256!==void 0&&n.push("sha256"),Ce(t,n)&&["package-root","package-manifest","package-entry","configuration","pnp-loader","source-graph","scope-escalation"].includes(String(t.kind))&&typeof t.path=="string"&&t.path.length>0&&!t.path.includes("\0")&&typeof t.detail=="string"&&t.detail.length>0&&(t.sha256===void 0||typeof t.sha256=="string"&&ke.test(t.sha256))}function pg(t){return!$e(t)||!Cs.test(String(t.commandId))||!Ce(t,["commandId","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","artifactPolicy","resolutionEvidence"])||!(gr(String(t.kind))||["parse","format","typecheck","lint"].includes(String(t.kind)))||t.timing!=="baseline"&&t.timing!=="post-patch"||typeof t.executable!="string"||t.executable.length===0||!ug(t.args)||t.args.some(n=>n.includes("\0"))||typeof t.workingDirectory!="string"||t.workingDirectory.length===0||t.workingDirectory.includes("\0")||!Number.isInteger(t.timeoutMs)||t.timeoutMs<=0||t.required!==!0||typeof t.purpose!="string"||t.purpose.length===0||!Ss(t.logicalTestIds)||!Ss(t.projectIds)||!$e(t.environmentDelta)||!V0(t.artifactPolicy)||!Array.isArray(t.resolutionEvidence)||!t.resolutionEvidence.every(z0)?!1:Object.entries(t.environmentDelta).every(([n,e])=>/^[A-Z][A-Z0-9_]*$/.test(n)&&typeof e=="string"&&!e.includes("\0"))}function ul(t){return $e(t)&&Ce(t,["path","sourceSha256","resultSha256"])&&typeof t.path=="string"&&t.path.length>0&&!t.path.includes("\0")&&typeof t.sourceSha256=="string"&&ke.test(t.sourceSha256)&&typeof t.resultSha256=="string"&&ke.test(t.resultSha256)}function H0(t){return $e(t)&&Ce(t,["baselineId","commandId","logicalTestIds","reason"])&&/^baseline_[a-f0-9]{24}$/.test(String(t.baselineId))&&Cs.test(String(t.commandId))&&Ss(t.logicalTestIds,!1)&&typeof t.reason=="string"&&t.reason.length>0}function U0(t){if(!$e(t))return!1;let n=["code","message"];return t.path!==void 0&&n.push("path"),Ce(t,n)&&["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(t.code))&&typeof t.message=="string"&&t.message.length>0&&(t.path===void 0||typeof t.path=="string"&&!t.path.includes("\0"))}function fg(t){return L({purpose:"kwikqa-validation-baseline",...t})}function va(t){return L({purpose:"kwikqa-validation-run",...t})}function ga(t){return typeof t=="string"&&t.length>0&&Number.isFinite(Date.parse(t))}function q0(t){if(!$e(t)||typeof t.kind!="string")return!1;if(t.kind==="exit")return Ce(t,["kind","exitCode"])&&Number.isInteger(t.exitCode);if(t.kind==="signal")return Ce(t,["kind","signal"])&&typeof t.signal=="string";if(t.kind==="spawn-error"){let n=["kind",...t.code===void 0?[]:["code"]];return Ce(t,n)&&(t.code===void 0||typeof t.code=="string")}return(t.kind==="timeout"||t.kind==="cancelled")&&Ce(t,["kind"])}function cg(t){return $e(t)&&Ce(t,["path","sha256","storedSha256","observedBytes","storedBytes","truncated","redacted"])&&typeof t.path=="string"&&t.path.length>0&&typeof t.sha256=="string"&&ke.test(t.sha256)&&typeof t.storedSha256=="string"&&ke.test(t.storedSha256)&&Number.isInteger(t.observedBytes)&&t.observedBytes>=0&&Number.isInteger(t.storedBytes)&&t.storedBytes>=0&&typeof t.truncated=="boolean"&&typeof t.redacted=="boolean"}function G0(t){return $e(t)&&Ce(t,["path","sha256","bytes"])&&typeof t.path=="string"&&t.path.length>0&&typeof t.sha256=="string"&&ke.test(t.sha256)&&Number.isInteger(t.bytes)&&t.bytes>=0}function pl(t){if(!fl(t))throw new Error("Validation command record is malformed or failed integrity validation.");return t}function K0(t){if(!$e(t))return!1;let n=["classification",...t.logicalTestId===void 0?[]:["logicalTestId"],...t.commandId===void 0?[]:["commandId"],"message"];return Ce(t,n)&&["fixed-target-failure","still-failing-target","unchanged-pre-existing-failure","newly-introduced-failure","unavailable-check","incomplete-check"].includes(String(t.classification))&&(t.logicalTestId===void 0||typeof t.logicalTestId=="string"&&t.logicalTestId.length>0)&&(t.commandId===void 0||typeof t.commandId=="string"&&Cs.test(t.commandId))&&typeof t.message=="string"&&t.message.length>0}function fl(t){if(!$e(t))return!1;let n=t,{recordHash:e,...r}=n;return Ce(t,["schemaVersion","validationRunId","commandId","commandHash","planHash","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","startedAt","durationMs","termination","stdout","stderr","artifacts","status","recordHash"])&&n.schemaVersion===ll&&/^vld_[a-f0-9]{24}$/.test(n.validationRunId)&&Cs.test(n.commandId)&&ke.test(n.commandHash)&&ke.test(n.planHash)&&n.required===!0&&pg({commandId:n.commandId,kind:n.kind,timing:n.timing,required:n.required,executable:n.executable,args:n.args,workingDirectory:n.workingDirectory,environmentDelta:n.environmentDelta,timeoutMs:n.timeoutMs,purpose:n.purpose,logicalTestIds:n.logicalTestIds,projectIds:n.projectIds,artifactPolicy:{outputDirectory:"artifacts",maxArtifacts:1,maxArtifactBytes:1},resolutionEvidence:[]})&&ga(n.startedAt)&&Number.isInteger(n.durationMs)&&n.durationMs>=0&&q0(n.termination)&&cg(n.stdout)&&cg(n.stderr)&&Array.isArray(n.artifacts)&&n.artifacts.every(G0)&&["blocked","passed","failed","unavailable","incomplete"].includes(n.status)&&ke.test(e)&&L(r)===e}function Ns(t){if(!$e(t))throw new Error("Baseline manifest is not an object.");let n=t,{baselineHash:e,...r}=n;if(!Ce(t,["schemaVersion","planHash","repositoryFingerprint","targetHashes","commandRecords","logicalTestOutcomes","capturedAt","baselineHash"])||n.schemaVersion!==ll||!ke.test(n.planHash)||!ke.test(n.repositoryFingerprint)||!Array.isArray(n.targetHashes)||!n.targetHashes.every(ul)||!Array.isArray(n.commandRecords)||!n.commandRecords.every(fl)||!$e(n.logicalTestOutcomes)||!Object.entries(n.logicalTestOutcomes).every(([s,i])=>s.length>0&&typeof i=="string"&&["passed","failed","skipped","interrupted"].includes(i))||!ga(n.capturedAt)||!ke.test(e)||fg(r)!==e)throw new Error("Baseline manifest is malformed or failed integrity validation.");return n}function Wt(t){if(!$e(t))throw new Error("Validation run manifest is not an object.");let n=t,{manifestHash:e,...r}=n;if(!Ce(t,["schemaVersion","validationRunId","transactionId","planHash","repositoryFingerprint","targetHashes","requiredCommandIds","status","commandRecords","classifications","startedAt","completedAt","manifestHash"])||n.schemaVersion!==ba||!/^vld_[a-f0-9]{24}$/.test(n.validationRunId)||!/^txn_[a-f0-9]{24}$/.test(n.transactionId)||!ke.test(n.planHash)||!ke.test(n.repositoryFingerprint)||!Array.isArray(n.targetHashes)||!n.targetHashes.every(ul)||!Ss(n.requiredCommandIds,!1)||!n.requiredCommandIds.every(s=>Cs.test(s))||!Array.isArray(n.commandRecords)||!n.commandRecords.every(fl)||!Array.isArray(n.classifications)||!n.classifications.every(K0)||!["blocked","passed","failed","unavailable","incomplete"].includes(n.status)||!ga(n.startedAt)||!ga(n.completedAt)||Date.parse(n.completedAt)<Date.parse(n.startedAt)||!ke.test(e)||va(r)!==e)throw new Error("Validation run manifest is malformed or failed integrity validation.");if(new Set(n.targetHashes.map(s=>s.path)).size!==n.targetHashes.length||new Set(n.commandRecords.map(s=>s.commandId)).size!==n.commandRecords.length||n.commandRecords.some(s=>s.validationRunId!==n.validationRunId||s.planHash!==n.planHash))throw new Error("Validation run manifest contains inconsistent evidence.");if(!W0(n))throw new Error("Validation run manifest status is inconsistent with its evidence.");return n}function W0(t){let n=new Set(t.requiredCommandIds),e=new Set(t.commandRecords.map(s=>s.commandId)),r=new Set(t.classifications.map(s=>s.classification));if(t.commandRecords.some(s=>!n.has(s.commandId)||s.timing!=="post-patch")||t.requiredCommandIds.some(s=>!e.has(s)&&!t.classifications.some(i=>i.classification==="incomplete-check"&&i.commandId===s)))return!1;switch(t.status){case"passed":return t.classifications.length>0&&[...r].every(s=>s==="fixed-target-failure")&&e.size===n.size&&t.commandRecords.every(s=>s.status==="passed");case"incomplete":return r.has("incomplete-check");case"unavailable":return!r.has("incomplete-check")&&r.has("unavailable-check");case"failed":return!r.has("incomplete-check")&&!r.has("unavailable-check");default:return!0}}function ka(t){return L({purpose:"kwikqa-resolved-validation-plan",...t})}function Tn(t){if(!$e(t))throw new Error("Resolved validation plan is not an object.");if(!Ce(t,["schemaVersion","policyVersion","status",...t.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 n=t,{planHash:e,...r}=n;if(n.schemaVersion!==wa||n.policyVersion!==xa||n.status!=="resolved"&&n.status!=="unavailable"||!ke.test(n.proposalHash)||!Ss(n.targetLogicalTestIds,!1)||!ke.test(n.advisoryPlanHash)||!ke.test(n.repositoryFingerprint)||!Array.isArray(n.commands)||!n.commands.every(pg)||n.transactionId!==void 0&&!/^txn_[a-f0-9]{24}$/.test(n.transactionId)||!Array.isArray(n.targetHashes)||!n.targetHashes.every(ul)||!Array.isArray(n.baselineRequirements)||!n.baselineRequirements.every(H0)||!Array.isArray(n.unresolvedReasons)||!n.unresolvedReasons.every(U0)||!ke.test(e)||ka(r)!==e)throw new Error("Resolved validation plan is malformed or failed integrity validation.");if(new Set(n.commands.map(i=>i.commandId)).size!==n.commands.length)throw new Error("Resolved validation plan contains duplicate command ids.");if(new Set(n.targetHashes.map(i=>i.path)).size!==n.targetHashes.length)throw new Error("Resolved validation plan contains duplicate targets.");if(new Set(n.baselineRequirements.map(i=>i.baselineId)).size!==n.baselineRequirements.length)throw new Error("Resolved validation plan contains duplicate baseline ids.");let s=new Map(n.commands.map(i=>[i.commandId,i]));if(n.baselineRequirements.some(i=>{let a=s.get(i.commandId);return a===void 0||a.timing!=="baseline"}))throw new Error("Resolved validation plan baseline references are invalid.");if(n.status==="resolved"&&n.unresolvedReasons.length>0||n.status==="unavailable"&&n.unresolvedReasons.length===0)throw new Error("Resolved validation plan status is inconsistent.");return n}var wg=oi(ns(),1);import{readdir as J0,realpath as yg}from"node:fs/promises";import{extname as X0,isAbsolute as gg,join as Y0,relative as Q0,resolve as Z0,sep as hg}from"node:path";import{dirname as eE,extname as gl,join as mg}from"node:path/posix";var hl=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],bg=new Set(hl),tE=new Set([".js",".mjs",".cjs"]),nE=[".ts",".tsx",".mts",".cts"],rE=/(?:^|\/)(?:[^/]+\.)?(?:spec|test|cy|e2e)\.(?:[cm]?[jt]sx?)$/i,sE=new Set([".git",".kwikqa","node_modules",".yarn",".pnpm-store","coverage","dist","build","out","test-results","playwright-report"]);function Os(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.type=="string"}function ml(t,n,e=new Set){if(!e.has(t)){e.add(t),n(t);for(let[r,s]of Object.entries(t))if(r!=="loc")if(Array.isArray(s))for(let i of s)Os(i)&&ml(i,n,e);else Os(s)&&ml(s,n,e)}}function iE(t){let n=gl(t).toLowerCase();return n===".tsx"?["typescript","jsx"]:[".ts",".mts",".cts"].includes(n)?["typescript"]:["jsx"]}function Ra(t){return Os(t)&&t.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function aE(t,n){try{let e=(0,wg.parse)(t,{sourceType:"unambiguous",allowReturnOutsideFunction:!0,errorRecovery:!1,plugins:iE(n)}),r=new Set,s=!1;return ml(e,i=>{if(i.type==="ImportDeclaration"||i.type==="ExportNamedDeclaration"||i.type==="ExportAllDeclaration"){let c=Ra(i.source);c!==void 0&&r.add(c),i.type==="ExportAllDeclaration"&&(s=!0);return}if(i.type==="ImportExpression"){let c=Ra(i.source);c===void 0?s=!0:r.add(c);return}if(i.type!=="CallExpression")return;let a=i.callee,o=Array.isArray(i.arguments)?i.arguments:[];if(Os(a)&&a.type==="Import"){let c=Ra(o[0]);c===void 0?s=!0:r.add(c);return}if(!Os(a)||a.type!=="Identifier"||a.name!=="require")return;let d=Ra(o[0]);d===void 0?s=!0:r.add(d)}),{imports:[...r].sort(),ambiguous:s}}catch{return{code:"parse-failed",message:"Source could not be parsed for validation discovery.",path:n}}}function yl(t){return t.length===0||t.includes("\0")||t.includes("\\")||gg(t)?!1:t.split("/").every(n=>n.length>0&&n!=="."&&n!=="..")}function oE(t,n){return t.split("/").some(r=>sE.has(r))?!0:n.some(r=>t===r||t.startsWith(`${r}/`))}function dE(t,n){let e=Q0(t,n);if(!(e===""||e===".."||e.startsWith(`..${hg}`)||gg(e)))return e.split(hg).join("/")}async function cE(t,n,e){let r=await yg(t),s=[],i=!1;async function a(o){if(i)return;let d=(await J0(o,{withFileTypes:!0})).sort((c,l)=>c.name.localeCompare(l.name,"en"));for(let c of d){if(c.isSymbolicLink())continue;let l=Y0(o,c.name),u=dE(r,l);if(!(u===void 0||oE(u,n))){if(c.isDirectory())await a(l);else if(c.isFile()&&bg.has(X0(c.name).toLowerCase())){if(s.length>=e){i=!0;return}s.push(u)}}}}return await a(r),{files:s.sort(),exhausted:i}}function lE(t,n){if(!t.startsWith("./")&&!t.startsWith("../"))return[];let e=mg(n,t),r=[e],s=gl(e).toLowerCase();if(tE.has(s)){let i=e.slice(0,e.length-s.length);for(let a of nE)r.push(`${i}${a}`)}if(s===""){for(let i of hl)r.push(`${e}${i}`);for(let i of hl)r.push(mg(e,`index${i}`))}return r.filter(yl)}function uE(t,n,e){return lE(t,eE(n)).find(r=>e.has(r))}async function pE(t){let n=[],e=await cE(t.workspaceRoot,t.ignoredPaths??[],t.limits.maxFiles);e.exhausted&&n.push({code:"budget-exceeded",message:"Source file discovery exceeded its file limit."});let r=new Set(e.files),s=new Map,i=0,a=0,o=!e.exhausted,d=e.exhausted;for(let u of e.files){let p=await Q(t.workspaceRoot,u,t.limits.maxFileBytes);if(p.kind!=="read"||p.relativePath!==u){o=!1,n.push({code:"unsafe-path",message:"Source could not be safely read.",path:u});continue}if(i+=p.bytes.byteLength,i>t.limits.maxTotalBytes){o=!1,d=!0,n.push({code:"budget-exceeded",message:"Source discovery exceeded its total byte limit."});break}let f=aE(new TextDecoder("utf-8",{fatal:!0}).decode(p.bytes),u);if("code"in f){o=!1,n.push(f),s.set(u,{path:u,imports:[],ambiguous:!0});continue}let h=[],m=f.ambiguous;for(let g of f.imports){if(!g.startsWith("./")&&!g.startsWith("../"))continue;let y=uE(g,u,r);if(y===void 0){m=!0,o=!1,n.push({code:"unresolved-local-import",message:`Local import ${JSON.stringify(g)} could not be resolved safely.`,path:u});continue}if(a+=1,a>t.limits.maxImportEdges){o=!1,d=!0,n.push({code:"budget-exceeded",message:"Import graph exceeded its edge limit."});break}h.push(y)}if(s.set(u,{path:u,imports:[...new Set(h)].sort(),ambiguous:m}),m&&(o=!1,n.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 s.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:s,reverse:l,edges:Math.min(a,t.limits.maxImportEdges),complete:o,exhausted:d,reasons:n}}function xg(t,n){return n.filter(e=>t===e.testDirectory||t.startsWith(`${e.testDirectory}/`)).sort((e,r)=>r.testDirectory.length-e.testDirectory.length||e.id.localeCompare(r.id))}function fE(t,n,e){let r=new Set,s=[];for(let i of[...t.map(a=>a.path),...n]){let o=xg(i,e)[0];o!==void 0&&!r.has(o.id)&&(r.add(o.id),s.push(o))}return s.sort((i,a)=>i.id.localeCompare(a.id))}function hE(t,n,e){let r=new Set,s=new Set(t),i=[...t].sort(),a=!0;for(let o=0;i.length>0;o+=1){if(o>=e){a=!1;break}let d=[];for(let c of i){n.modules.get(c)?.ambiguous===!0&&(a=!1);for(let u of n.reverse.get(c)??[])rE.test(u)&&r.add(u),s.has(u)||(s.add(u),d.push(u))}i=[...new Set(d)].sort()}return{tests:[...r].sort(),complete:a}}async function Ia(t,n){for(let e of n){let r=await Q(t,e,1e6);if(r.kind==="read"&&r.relativePath===e)return e}}async function vg(t,n){let e=[];n.some(o=>bg.has(gl(o).toLowerCase()))&&e.push({kind:"parse",tool:"kwikqa-babel",required:!0});let r=await Ia(t,["biome.json","biome.jsonc"]),s=await Ia(t,[".prettierrc",".prettierrc.json","prettier.config.js","prettier.config.cjs","prettier.config.mjs"]);r!==void 0?(e.push({kind:"format",tool:"biome",configPath:r,required:!0}),e.push({kind:"lint",tool:"biome",configPath:r,required:!0})):s!==void 0&&e.push({kind:"format",tool:"prettier",configPath:s,required:!0});let i=await Ia(t,["tsconfig.json"]);i!==void 0&&e.push({kind:"typecheck",tool:"typescript",configPath:i,required:!0});let a=await Ia(t,["eslint.config.js","eslint.config.mjs","eslint.config.cjs",".eslintrc.json"]);return r===void 0&&a!==void 0&&e.push({kind:"lint",tool:"eslint",configPath:a,required:!0}),e}function mE(t,n,e){return t.some(r=>r.class==="playwright-config"||r.class==="framework-config")?n.length===1?"project":"suite":e?"affected":n.length===1?"project":"suite"}async function wl(t){let n=await vg(t.workspaceRoot,t.targets.map(u=>u.path));if(t.targets.length===0||!yl(t.originalTestPath)||t.targets.some(u=>!yl(u.path))||t.limits.maxFiles<=0||t.limits.maxFileBytes<=0||t.limits.maxTotalBytes<=0||t.limits.maxImportEdges<=0||t.limits.maxImportDepth<=0)return{status:"unavailable",scope:"unavailable",testPaths:[],projectIds:[],staticChecks:n,indexedFiles:0,importEdges:0,completeGraph:!1,reasons:[{code:"unsafe-path",message:"Discovery input is unsafe or unbounded."}]};let e=await yg(t.workspaceRoot).catch(()=>{});if(e===void 0||Z0(e,t.originalTestPath)===e)return{status:"unavailable",scope:"unavailable",testPaths:[],projectIds:[],staticChecks:n,indexedFiles:0,importEdges:0,completeGraph:!1,reasons:[{code:"unsafe-path",message:"Workspace could not be resolved safely."}]};let r=await pE(t),s=t.targets.filter(u=>u.class!=="spec");if(s.length===0)return{status:"resolved",scope:"focused",testPaths:[t.originalTestPath],projectIds:xg(t.originalTestPath,t.projects).slice(0,1).map(u=>u.id),staticChecks:n,indexedFiles:r.modules.size,importEdges:r.edges,completeGraph:r.complete,reasons:[]};let i=hE(s.map(u=>u.path),r,t.limits.maxImportDepth),a=r.complete&&i.complete&&!r.exhausted,o=fE(t.targets,i.tests,t.projects),d=mE(t.targets,o,a),c=d==="affected"?[...new Set([t.originalTestPath,...i.tests])].sort():d==="project"?[...new Set([t.originalTestPath,...i.tests])].sort():[t.originalTestPath],l=[...r.reasons];return d==="suite"&&t.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:n,indexedFiles:r.modules.size,importEdges:r.edges,completeGraph:a,reasons:l}}import{spawn as yE}from"node:child_process";import{createHash as Aa,randomUUID as gE}from"node:crypto";import{lstat as Ds,mkdir as $s,readdir as wE,readFile as bE,realpath as Ta}from"node:fs/promises";import{isAbsolute as Ig,join as Qe,relative as Pa,resolve as Ag,sep as Sa}from"node:path";var xE=/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTH)/i,vE=["authorization","cookie","password","passwd","secret","token","api_key","private_key"];function bl(t,n){let e=Pa(t,n);return e===""||!Ig(e)&&e!==".."&&!e.startsWith(`..${Sa}`)}function kE(t){return/^[a-f0-9]{64}$/.test(t)}function RE(t){let n=Tn(t.plan),e=n.commands.find(r=>r.commandId===t.commandId);if(!/^txn_[a-f0-9]{24}$/.test(t.transactionId)||n.status!=="resolved"||!kE(n.planHash)||!Kt.test(t.commandId)||e===void 0||e.executable!==process.execPath||!Ig(e.workingDirectory)||e.args.some(r=>r.includes("\0"))||!Number.isInteger(e.timeoutMs)||e.timeoutMs<=0||!Number.isInteger(t.limits.maxStreamBytes)||t.limits.maxStreamBytes<=0||t.limits.maxStreamBytes>An||!Number.isInteger(t.limits.maxTotalStreamBytes)||t.limits.maxTotalStreamBytes<t.limits.maxStreamBytes||!Number.isInteger(t.limits.terminationGraceMs)||t.limits.terminationGraceMs<0)throw new Error("Validation command or execution limits are invalid.");for(let[r,s]of Object.entries(e.environmentDelta))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r)||s.includes("\0"))throw new Error("Validation environment delta is invalid.");return e}async function IE(t,n){let e=await Ta(t.workspaceRoot),r=Ag(e,".kwikqa","transactions",t.transactionId);if(!bl(e,r))throw new Error("Validation transaction escapes workspace.");let s=await Ds(r);if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Validation transaction is unsafe.");let i=t.validationRunId??`vld_${gE().replaceAll("-","").slice(0,24)}`;if(!/^vld_[a-f0-9]{24}$/.test(i))throw new Error("Validation run id is invalid.");let a=Qe(r,"validation");await $s(a,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let o=await Ds(a);if(!o.isDirectory()||o.isSymbolicLink())throw new Error("Validation directory is unsafe.");let d=Qe(a,i);await $s(d,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let c=await Ds(d);if(!c.isDirectory()||c.isSymbolicLink())throw new Error("Validation run directory is unsafe.");let l=Qe(d,"commands");await $s(l,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let u=await Ds(l);if(!u.isDirectory()||u.isSymbolicLink())throw new Error("Validation commands directory is unsafe.");let p=Qe(l,n.commandId);return await $s(p,{mode:448}),await $s(Qe(p,"artifacts"),{mode:448}),{root:d,commandDirectory:p,runId:i}}var Ea=class{constructor(n,e){this.cap=n;this.consumeGlobal=e}cap;consumeGlobal;#e=Aa("sha256");#n=[];#t=0;#r=0;add(n){this.#e.update(n),this.#t+=n.byteLength;let e=Math.max(0,this.cap-this.#r),r=this.consumeGlobal(Math.min(e,n.byteLength));r>0&&(this.#n.push(n.subarray(0,r)),this.#r+=r)}finish(){return{text:Buffer.concat(this.#n).toString("utf8"),observed:this.#t,hash:this.#e.digest("hex"),truncated:this.#r<this.#t}}};function kg(t,n){let e=Buffer.from(t,"utf8");if(e.byteLength<=n)return{text:t,truncated:!1};let r=n;for(;r>0&&(e[r]??0)>=128&&(e[r]??0)<192;)r-=1;return{text:e.subarray(0,r).toString("utf8"),truncated:!0}}function Rg(t){return Object.fromEntries(Object.entries(t).sort(([n],[e])=>n.localeCompare(e)).map(([n,e])=>[n,xE.test(n)?"[REDACTED]":e]))}function AE(t){return t.kind==="timeout"||t.kind==="cancelled"?"incomplete":t.kind==="spawn-error"?"unavailable":t.kind==="signal"?"incomplete":t.exitCode===0?"passed":"failed"}function TE(t){return new Promise(n=>setTimeout(n,t))}async function PE(t,n,e,r){let s=await wE(n,{withFileTypes:!0}),i=[],a=0;for(let o of s.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=Qe(n,o.name),c=await Ds(d),l=await Ta(d);if(!c.isFile()||c.isSymbolicLink()||!bl(n,l)||c.mtimeMs+1<r)throw new Error("Validation artifact is stale or unsafe.");let u=await bE(l);if(a+=u.byteLength,i.push({path:Pa(t,l).split(Sa).join("/"),sha256:Aa("sha256").update(u).digest("hex"),bytes:u.byteLength}),i.length>e.artifactPolicy.maxArtifacts||a>e.artifactPolicy.maxArtifactBytes)throw new Error("Validation artifact policy limit was exceeded.")}if(e.artifactPolicy.reportFile!==void 0&&!i.some(o=>o.path.split("/").at(-1)===e.artifactPolicy.reportFile))throw new Error("Required validation report artifact is missing.");return i}async function xl(t){let n=RE(t),e=await Ta(t.workspaceRoot),r=await Ta(n.workingDirectory);if(!bl(e,r))throw new Error("Validation working directory escapes workspace.");let s=t.repositoryRoot??e;for(let K of n.resolutionEvidence){if(K.sha256===void 0)continue;let te=await Q(s,Ag(e,K.path),16*1024*1024);if(te.kind!=="read"||te.sha256!==K.sha256)throw new Error("Validation resolution evidence changed after approval.")}let i=await IE(t,n),a=t.now??(()=>new Date),o=a(),d=t.limits.maxTotalStreamBytes,c=K=>{let te=Math.min(K,d);return d-=te,te},l=new Ea(t.limits.maxStreamBytes,c),u=new Ea(t.limits.maxStreamBytes,c),p=Qe(i.commandDirectory,"artifacts"),f={...t.inheritedEnvironment??process.env,...n.environmentDelta,...n.kind.startsWith("playwright-")?{PLAYWRIGHT_JSON_OUTPUT_NAME:Qe(p,n.artifactPolicy.reportFile??Es)}:{},...gr(n.kind)&&!n.kind.startsWith("playwright-")?{KWIKQA_REPORT_DIR:p}:{}},h=yE(n.executable,[...n.args],{cwd:n.workingDirectory,env:f,shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"]});h.stdout.on("data",K=>l.add(K)),h.stderr.on("data",K=>u.add(K));let m,g,y=K=>{m===void 0&&(m=K,h.kill(),g=setTimeout(()=>h.kill("SIGKILL"),t.limits.terminationGraceMs))},w=()=>y("cancelled");t.signal?.addEventListener("abort",w,{once:!0}),t.signal?.aborted&&y("cancelled");let x=setTimeout(()=>y("timeout"),n.timeoutMs),v=await new Promise(K=>{let te=!1;h.once("error",le=>{te||(te=!0,K({kind:"spawn-error",...le.code===void 0?{}:{code:le.code}}))}),h.once("close",(le,X)=>{te||(te=!0,K(m!==void 0?{kind:m}:X!==null?{kind:"signal",signal:X}:{kind:"exit",exitCode:le??1}))})});x!==void 0&&clearTimeout(x),g!==void 0&&clearTimeout(g),t.signal?.removeEventListener("abort",w),await TE(0);let R=t.sensitiveNames??vE,P=l.finish(),N=u.finish(),E=ce(P.text,"report","validation:stdout",R).value,M=kg(E,t.limits.maxStreamBytes),A=ce(N.text,"report","validation:stderr",R).value,C=kg(A,t.limits.maxStreamBytes),T=M.text,I=C.text,$=Qe(i.commandDirectory,"stdout.log"),D=Qe(i.commandDirectory,"stderr.log");await ye($,T,{mode:384,replace:!1}),await ye(D,I,{mode:384,replace:!1});let k=await PE(i.root,p,n,o.getTime()),S=a(),_={schemaVersion:"1.0",validationRunId:i.runId,commandId:n.commandId,commandHash:L(n),planHash:t.plan.planHash,kind:n.kind,timing:n.timing,required:n.required,executable:n.executable,args:n.args,workingDirectory:n.workingDirectory,environmentDelta:Rg(n.environmentDelta),timeoutMs:n.timeoutMs,purpose:n.purpose,logicalTestIds:n.logicalTestIds,projectIds:n.projectIds,startedAt:o.toISOString(),durationMs:Math.max(0,S.getTime()-o.getTime()),termination:v,stdout:{path:Pa(i.root,$).split(Sa).join("/"),observedBytes:P.observed,storedBytes:Buffer.byteLength(T),sha256:P.hash,storedSha256:Aa("sha256").update(T).digest("hex"),truncated:P.truncated||M.truncated,redacted:E!==P.text},stderr:{path:Pa(i.root,D).split(Sa).join("/"),observedBytes:N.observed,storedBytes:Buffer.byteLength(I),sha256:N.hash,storedSha256:Aa("sha256").update(I).digest("hex"),truncated:N.truncated||C.truncated,redacted:A!==N.text},artifacts:k,status:AE(v)},U={..._,recordHash:L(_)};return await ye(Qe(i.commandDirectory,"command.json"),`${pe({commandId:n.commandId,planHash:t.plan.planHash,executable:n.executable,args:n.args,workingDirectory:n.workingDirectory,environmentDelta:Rg(n.environmentDelta)})}
169
+ `,{mode:384,replace:!1}),await ye(Qe(i.commandDirectory,"result.json"),`${pe(U)}
170
+ `,{mode:384,replace:!1}),{directory:i.root,record:U}}import{realpath as UE}from"node:fs/promises";import{join as qE}from"node:path";import{createHash as SE}from"node:crypto";import{readdir as EE,readFile as Ca}from"node:fs/promises";import{join as $t}from"node:path";var Ms="1.0";function Tg(t){let n=JSON.parse(t);if(n===null||typeof n!="object"||Array.isArray(n))throw new Error("Journal record is not an object.");return n}function CE(t){if(t.schemaVersion!==Ms||typeof t.transactionId!="string"||!rn(t.transactionId)||typeof t.manifestHash!="string"||!Array.isArray(t.targets)||t.preview===null||typeof t.preview!="object"||t.authorization===null||typeof t.authorization!="object"||t.config===null||typeof t.config!="object"||typeof t.maxTargetBytes!="number"||typeof t.createdAt!="string")throw new Error("Transaction manifest is malformed.");let n=t,{manifestHash:e,...r}=n;if(L(r)!==e)throw new Error("Transaction manifest integrity check failed.");return n}function NE(t){let n=new Set(["prepared","applying","applied","validating","rolling-back","rolled-back","completed","conflicted"]);if(t.schemaVersion!==Ms||typeof t.transactionId!="string"||!rn(t.transactionId)||typeof t.manifestHash!="string"||typeof t.stateHash!="string"||typeof t.phase!="string"||!n.has(t.phase)||!Number.isInteger(t.revision)||t.revision<1||typeof t.updatedAt!="string"||!Array.isArray(t.history))throw new Error("Transaction state is malformed.");let e=t,{stateHash:r,...s}=e;if(L(s)!==r||e.history.length!==e.revision)throw new Error("Transaction state integrity check failed.");for(let[i,a]of e.history.entries())if(a===null||typeof a!="object"||a.sequence!==i+1||typeof a.type!="string"||a.type.length===0||typeof a.at!="string"||!n.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 OE(t){return L({purpose:"kwikqa-transaction-target",path:t}).slice(0,32)}function Pg(t){return SE("sha256").update(t).digest("hex")}async function Sg(t){if(!rn(t.transactionId))throw new Error("Transaction id is invalid.");let n=`.staging-${t.transactionId.slice(4)}`,e=await Fe(t.workspaceRoot,[".kwikqa","transactions",n]);await Fe(t.workspaceRoot,[".kwikqa","transactions",n,"preimages"]),await Fe(t.workspaceRoot,[".kwikqa","transactions",n,"results"]);let r=[];for(let c of t.targets){let l=OE(c.path),u=`preimages/${l}.bin`,p=`results/${l}.bin`;await ye($t(e,u),c.sourceBytes,{mode:384,replace:!1}),await ye($t(e,p),c.resultBytes,{mode:384,replace:!1}),r.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 s={schemaVersion:Ms,transactionId:t.transactionId,preview:t.preview,authorization:t.authorization,config:t.config,maxTargetBytes:t.maxTargetBytes,targets:r,createdAt:t.now},i={...s,manifestHash:L(s)};await ye($t(e,"manifest.json"),`${pe(i)}
171
+ `,{mode:384,replace:!1});let a={sequence:1,type:"prepared",at:t.now,phase:"prepared"},o={schemaVersion:Ms,transactionId:t.transactionId,manifestHash:i.manifestHash,phase:"prepared",revision:1,updatedAt:t.now,history:[a]},d={...o,stateHash:L(o)};return await ye($t(e,"state.json"),`${pe(d)}
172
+ `,{mode:384,replace:!1}),await Cp(t.workspaceRoot,n,t.transactionId),Re(t.workspaceRoot,t.transactionId)}async function Re(t,n){if(!rn(n))throw new Error("Transaction id is invalid.");let e=await li(t),r=await Fe(e.root,[".kwikqa","transactions",n]),s=CE(Tg(await Ca($t(r,"manifest.json"),"utf8"))),i=NE(Tg(await Ca($t(r,"state.json"),"utf8")));if(s.transactionId!==n||i.transactionId!==n||i.manifestHash!==s.manifestHash)throw new Error("Transaction identity mismatch.");let a=new Map,o=new Map;for(let d of s.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 Ca($t(r,d.preimageFile)),l=await Ca($t(r,d.resultFile));if(c.byteLength!==d.preimageBytes||l.byteLength!==d.resultBytes||Pg(c)!==d.sourceSha256||Pg(l)!==d.resultSha256)throw new Error("Transaction target bytes are malformed.");a.set(d.path,c),o.set(d.path,l)}return{directory:r,manifest:s,state:i,preimages:a,results:o}}function $E(t,n){return n==="conflicted"?t!=="completed"&&t!=="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:[]}[t].includes(n)}async function Ue(t){let n=await Re(t.transaction.manifest.preview.workspace.workspaceRoot,t.transaction.manifest.transactionId);if(n.state.revision!==t.transaction.state.revision)throw new Error("Transaction state changed concurrently.");if(!$E(n.state.phase,t.phase))throw new Error("Transaction phase transition is not permitted.");let e={sequence:n.state.history.length+1,type:t.type,at:t.now,phase:t.phase,...t.path===void 0?{}:{path:t.path},...t.message===void 0?{}:{message:t.message},...t.planHash===void 0?{}:{planHash:t.planHash},...t.validationRunId===void 0?{}:{validationRunId:t.validationRunId},...t.validationManifestHash===void 0?{}:{validationManifestHash:t.validationManifestHash}},r={schemaVersion:Ms,transactionId:n.manifest.transactionId,manifestHash:n.manifest.manifestHash,phase:t.phase,revision:n.state.revision+1,updatedAt:t.now,history:[...n.state.history,e]},s={...r,stateHash:L(r)};return await ye($t(n.directory,"state.json"),`${pe(s)}
173
+ `,{mode:384,replace:!0}),Re(n.manifest.preview.workspace.workspaceRoot,n.manifest.transactionId)}async function Ls(t){let n=await li(t);return(await EE(n.transactionsDirectory,{withFileTypes:!0}).catch(r=>{if(r.code==="ENOENT")return[];throw r})).filter(r=>r.isDirectory()&&!r.isSymbolicLink()&&rn(r.name)).map(r=>r.name).sort()}import{createHash as DE}from"node:crypto";import{lstat as Cg,readFile as Ng,realpath as Na}from"node:fs/promises";import{isAbsolute as ME,relative as LE,resolve as Og,sep as _E}from"node:path";var jE=2*1024*1024,$a=4*1024*1024;function Oa(t,n){let e=LE(t,n);return e===""||!ME(e)&&e!==".."&&!e.startsWith(`..${_E}`)}async function Pn(t,n,e){let r=await Na(t),s=Og(r,n);if(!Oa(r,s))throw new Error("Validation evidence path escapes its run.");let i=await Cg(s),a=await Na(s);if(!i.isFile()||i.isSymbolicLink()||!Oa(r,a)||i.size>e)throw new Error("Validation evidence file is unsafe or unbounded.");return JSON.parse(await Ng(a,"utf8"))}async function vl(t,n){if(!Kt.test(n))throw new Error("Validation command id is invalid.");return pl(await Pn(t,`commands/${n}/result.json`,jE))}async function Eg(t,n,e,r,s){let i=Og(t,n);if(!Oa(t,i))return!1;let a=await Cg(i).catch(()=>{}),o=await Na(i).catch(()=>{});if(a===void 0||o===void 0||!a.isFile()||a.isSymbolicLink()||!Oa(t,o)||a.size>s||a.size!==e)return!1;let d=await Ng(o).catch(()=>{});return d!==void 0&&d.byteLength===e&&DE("sha256").update(d).digest("hex")===r}async function kl(t,n,e){let r=await Na(t);for(let s of[n.stdout,n.stderr])if(!await Eg(r,s.path,s.storedBytes,s.storedSha256,An))return!1;for(let s of n.artifacts)if(!await Eg(r,s.path,s.bytes,s.sha256,e))return!1;return!0}async function $g(t,n,e){try{let r=await vl(t,n.commandId);return L(r)===L(n)&&await kl(t,n,e)}catch{return!1}}import{createHash as FE}from"node:crypto";import{lstat as Mg,readFile as Lg,realpath as Da}from"node:fs/promises";import{isAbsolute as BE,relative as VE,resolve as _g,sep as zE}from"node:path";function Ma(t,n){let e=VE(t,n);return e===""||!BE(e)&&e!==".."&&!e.startsWith(`..${zE}`)}function HE(t){return t.status==="expected"?"passed":t.status==="skipped"?"skipped":t.attempts.some(n=>n.status==="interrupted")?"interrupted":"failed"}var Dg={passed:0,skipped:1,interrupted:2,failed:3};function jg(t){let n=new Map;for(let e of t){let r=HE(e),s=n.get(e.logicalTestId);(s===void 0||Dg[r]>Dg[s])&&n.set(e.logicalTestId,r)}return[...n].map(([e,r])=>({logicalTestId:e,status:r})).sort((e,r)=>e.logicalTestId.localeCompare(r.logicalTestId))}async function Rl(t){if(!Number.isInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("Validation report byte limit is invalid.");let n=await Da(t.runDirectory).catch(()=>{});if(n===void 0)return{kind:"incomplete",reason:"Validation run directory is unavailable."};let e=_g(n,t.artifact.path);if(!Ma(n,e))return{kind:"incomplete",reason:"Validation report path escapes its run directory."};let r=await Mg(e).catch(()=>{}),s=await Da(e).catch(()=>{});if(r===void 0||s===void 0||!r.isFile()||r.isSymbolicLink()||!Ma(n,s)||r.size>t.maxBytes||r.size!==t.artifact.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unsafe."};let i=await Lg(s).catch(()=>{});if(i===void 0||i.byteLength>t.maxBytes||i.byteLength!==t.artifact.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unbounded."};let a=Kn(i,{workspaceRoot:t.workspaceRoot,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot},reportPath:t.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!==t.artifact.sha256)return{kind:"incomplete",reason:"Validation report content hash does not match its record."};let o=jg(a.run.logicalTests),d=new Set(o.map(c=>c.logicalTestId));return t.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 La=/^(?:cypress|wdio)-[^/]*\.json$/;async function Il(t){if(!Number.isInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("Validation report byte limit is invalid.");let n=await Da(t.runDirectory).catch(()=>{});if(n===void 0)return{kind:"incomplete",reason:"Validation run directory is unavailable."};let e=t.artifacts.filter(d=>La.test(d.path.split("/").at(-1)??""));if(e.length===0)return{kind:"incomplete",reason:"The test run wrote no KwikQA report."};let r=[],s=0;for(let d of e){let c=_g(n,d.path);if(!Ma(n,c))return{kind:"incomplete",reason:"Validation report path escapes its run directory."};let l=await Mg(c).catch(()=>{}),u=await Da(c).catch(()=>{});if(l===void 0||u===void 0||!l.isFile()||l.isSymbolicLink()||!Ma(n,u)||l.size!==d.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unsafe."};if(s+=l.size,s>t.maxBytes)return{kind:"incomplete",reason:"Validation reports exceed their byte limit."};let p=await Lg(u).catch(()=>{});if(p===void 0||p.byteLength!==d.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unbounded."};if(FE("sha256").update(p).digest("hex")!==d.sha256)return{kind:"incomplete",reason:"Validation report content hash does not match its record."};r.push({path:u,bytes:p})}let i=ji(r,{workspaceRoot:t.workspaceRoot,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot}});if(i.kind!=="parsed")return{kind:"incomplete",reason:`Validation report could not be parsed: ${i.diagnostic.reasonCode}.`};if(i.run.artifact.format!=="kwikqa-json")return{kind:"incomplete",reason:"Validation report was not written by KwikQA's reporter."};if(i.run.usability==="interrupted"||i.run.usability==="zero-tests")return{kind:"incomplete",reason:`Validation report is not analysis-ready: ${i.run.usability}.`};let a=jg(i.run.logicalTests),o=new Set(a.map(d=>d.logicalTestId));return t.expectedLogicalTestIds.some(d=>!o.has(d))?{kind:"incomplete",reason:"Validation report omits an expected logical test."}:{kind:"observed",reportSha256:i.run.sourceHashes.report,observations:a}}var GE=/^txn_[a-f0-9]{24}$/,KE=/^vld_[a-f0-9]{24}$/,WE=new Set(["rolling-back","rolled-back","conflicted"]);function JE(t){return t.length>0&&Number.isFinite(Date.parse(t))}function XE(t){return t.commands.filter(n=>n.required&&n.timing==="post-patch").sort((n,e)=>n.commandId.localeCompare(e.commandId))}function YE(t,n){let e=new Set(t);return e.size===t.length&&t.length===n.length&&n.every(r=>e.has(r))}function QE(t,n,e){let r=t.manifest.preview.authoritativeValidation,s=new Map(r.requiredCommands.map(i=>[i.commandId,i.commandHash]));return r.planHash===n.planHash&&r.repositoryFingerprint===n.repositoryFingerprint&&L(r.targetHashes)===L(n.targetHashes)&&YE(r.requiredCommandIds,e.map(i=>i.commandId))&&e.every(i=>s.get(i.commandId)===L(i))}async function ZE(t,n){for(let e of n.manifest.targets){let r=await Q(t,e.path,Math.max(1,e.resultBytes)).catch(()=>{});if(r?.kind!=="read"||r.relativePath!==e.path||r.sha256!==e.resultSha256)return!1}return!0}function eC(t){return t===void 0?[]:Object.entries(t.logicalTestOutcomes).map(([n,e])=>({logicalTestId:n,status:e})).sort((n,e)=>n.logicalTestId.localeCompare(e.logicalTestId))}async function tC(t,n,e,r,s,i){let a={classification:{commandId:s.commandId,required:!0,timing:"post-patch",status:"incomplete",fresh:!0,expectedLogicalTestIds:s.logicalTestIds,observations:[]}},o=await vl(e,s.commandId).catch(()=>{});if(o===void 0||o.validationRunId!==t.validationRunId||o.planHash!==r.planHash||o.commandId!==s.commandId||o.commandHash!==L(s)||o.timing!=="post-patch"||!await kl(e,o,s.artifactPolicy.maxArtifactBytes))return a;let d=[],c=o.status==="blocked"?"incomplete":o.status;if(gr(s.kind)&&!s.kind.startsWith("playwright-")&&o.status!=="unavailable"){let l=await Il({workspaceRoot:n,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot},runDirectory:e,artifacts:o.artifacts,expectedLogicalTestIds:s.logicalTestIds,maxBytes:t.reportMaxBytes});l.kind==="observed"?d=l.observations:c="incomplete"}else if(s.kind.startsWith("playwright-")&&o.status!=="unavailable"){let l=s.artifactPolicy.reportFile??Es,u=o.artifacts.find(p=>p.path.split("/").at(-1)===l);if(u===void 0)c="incomplete";else{let p=await Rl({workspaceRoot:n,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot},runDirectory:e,artifact:u,expectedLogicalTestIds:s.logicalTestIds,maxBytes:t.reportMaxBytes});p.kind==="observed"?d=p.observations:c="incomplete"}}return{record:o,classification:{commandId:s.commandId,required:!0,timing:"post-patch",status:c,fresh:Date.parse(o.startedAt)>=i&&!o.stdout.truncated&&!o.stderr.truncated,expectedLogicalTestIds:s.logicalTestIds,observations:d}}}async function nC(t,n,e,r){let s=await Re(n,t.transactionId),i=s.manifest.preview.authoritativeValidation,a=s.state.history,o=a.findLastIndex(R=>R.type==="validation-started"),d=a[o],c=XE(e);if(d===void 0||d.validationRunId!==t.validationRunId||d.planHash!==e.planHash||!QE(s,e,c))throw new Error("Validation run does not match the durable transaction approval.");if(i.baselineManifestHash!==r?.baselineHash||r!==void 0&&(r.planHash!==e.planHash||r.repositoryFingerprint!==e.repositoryFingerprint||L(r.targetHashes)!==L(e.targetHashes)))throw new Error("Required validation baseline is missing or mismatched.");let l=await Fe(n,[".kwikqa","transactions",t.transactionId,"validation",t.validationRunId]),u=await Pn(l,"manifest.json",$a).catch(R=>{if(R.code!=="ENOENT")throw R});if(u!==void 0){let R=Wt(u);if(R.transactionId!==t.transactionId||R.validationRunId!==t.validationRunId||R.planHash!==e.planHash)throw new Error("Validation run was already finalized for different evidence.");return{directory:l,manifest:R}}let p=[],f=s.state.phase;if(f==="validating")await ZE(n,s)||p.push("Applied validation targets changed before the run was finalized.");else if(WE.has(f)&&!a.slice(o+1).some(R=>R.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),m=t.completedAt??new Date().toISOString();if(Date.parse(m)<h)throw new Error("Validation completion precedes command execution.");let g=[],y=[];for(let R of c){let P=await tC(t,n,l,e,R,h);P.record!==void 0&&g.push(P.record),y.push(P.classification)}let w=cl({targetLogicalTestIds:e.targetLogicalTestIds,baseline:eC(r),commands:y,blockingReasons:p}),x={schemaVersion:ba,validationRunId:t.validationRunId,transactionId:t.transactionId,planHash:e.planHash,repositoryFingerprint:e.repositoryFingerprint,targetHashes:e.targetHashes,requiredCommandIds:c.map(R=>R.commandId),status:w.status,commandRecords:g,classifications:w.classifications,startedAt:d.at,completedAt:m},v=Wt({...x,manifestHash:va(x)});return await ye(qE(l,"manifest.json"),`${pe(v)}
174
+ `,{mode:384,replace:!1}),{directory:l,manifest:v}}async function Al(t){if(!GE.test(t.transactionId)||!KE.test(t.validationRunId)||!Number.isInteger(t.reportMaxBytes)||t.reportMaxBytes<=0||t.completedAt!==void 0&&!JE(t.completedAt))throw new Error("Validation finalization identity, timestamp, or limits are invalid.");let n=Tn(t.plan);if(n.status!=="resolved")throw new Error("Unavailable validation plan cannot be finalized.");if(n.transactionId!==void 0&&n.transactionId!==t.transactionId)throw new Error("Validation plan is bound to another transaction.");let e=t.baseline===void 0?void 0:Ns(t.baseline),r=await UE(t.workspaceRoot),s=await Ge(r,{operation:"finalize-validation",transactionId:t.transactionId,validationRunId:t.validationRunId});try{return await nC(t,r,n,e)}finally{await s.release().catch(()=>{})}}import{fileURLToPath as yC}from"node:url";import{execFile as rC}from"node:child_process";import{lstat as _a,realpath as Ze}from"node:fs/promises";import{createRequire as sC}from"node:module";import{dirname as Dt,isAbsolute as Vg,join as Pl,relative as zg,resolve as Sl,sep as Hg}from"node:path";import{fileURLToPath as iC}from"node:url";import{promisify as aC}from"node:util";var oC=aC(rC),Ug=128*1024,dC=64*1024,cC=/^[a-f0-9]{64}$/,Fg={"@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 Sn(t,n){let e=zg(t,n);return e===""||!Vg(e)&&e!==".."&&!e.startsWith(`..${Hg}`)}function Tl(t,n){return zg(t,n).split(Hg).join("/")}function _s(t,n,e){return{code:t,message:n,...e===void 0?{}:{path:e}}}function lC(t,n){let e=new TextDecoder("utf-8",{fatal:!0}).decode(t),r=JSON.parse(e);if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("Package manifest is not an object.");let s=r;if(s.name!==n||typeof s.version!="string"||s.version.trim().length===0)throw new Error("Package identity does not match the requested tool.");return{name:s.name,version:s.version}}async function uC(t,n){let e=await Ze(t),r=Vg(n)?n:Sl(e,n),s=await Ze(r).catch(()=>r);if(!Sn(e,s))return;let i=s;for((await _a(i).catch(()=>{}))?.isFile()&&(i=Dt(i));Sn(e,i);){let o=Pl(i,"package.json"),d=await _a(o).catch(()=>{});if(d?.isFile()&&!d.isSymbolicLink())return o;if(i===e)break;i=Dt(i)}}async function pC(t,n){let e=await Ze(t),r=Dt(n);for(;Sn(e,r);){let s=Pl(r,".pnp.cjs"),i=await _a(s).catch(()=>{});if(i?.isFile()&&!i.isSymbolicLink())return s;if(r===e)break;r=Dt(r)}}async function Bg(t,n,e){let r=Dt(t);for(;;){let s=Pl(r,"node_modules",...n.split("/"),"package.json");if(await _a(s).catch(()=>{})!==void 0){let o=await Ze(s),d=await Q(Dt(o),o,Ug).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 Ze(Sl(Dt(o),u));return{manifestPath:o,entryPath:p}}let a=Dt(r);if(a===r)throw new Error("Package is not installed.");r=a}}async function fC(t,n){let e=sC(t),r=Fg[n].bin,s;try{s=await Ze(e.resolve(`${n}/package.json`))}catch(a){if(r===void 0)throw a;return Bg(t,n,r)}let i;for(let a of Fg[n].entryRequests)try{i=await Ze(e.resolve(a));break}catch{}if(i===void 0){if(r!==void 0)return Bg(t,n,r);throw new Error("Package CLI entry could not be resolved.")}return{manifestPath:s,entryPath:i}}async function El(t,n){let e=await Ze(n),r=await Q(t,e,16*1024*1024);if(r.kind!=="read")throw new Error("PnP loader is not an authorized repository-local regular file.");return{path:e,relativePath:r.relativePath,sha256:r.sha256}}async function hC(t,n,e,r){let s=iC(new URL("./pnp-resolver.mjs",import.meta.url)),{stdout:i}=await oC(process.execPath,[s,t,n.path,n.sha256,e,r],{encoding:"utf8",maxBuffer:dC,timeout:1e4,windowsHide:!0,env:{PATH:process.env.PATH??""}}),a=JSON.parse(i);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!==n.sha256)throw new Error("PnP resolver output is incomplete or has the wrong loader identity.");let d=await El(t,n.path);if(d.path!==n.path||d.relativePath!==n.relativePath||d.sha256!==n.sha256)throw new Error("PnP loader identity changed during resolution.");return{manifestPath:await Ze(o.manifestPath),entryPath:await Ze(o.entryPath)}}async function mC(t){let n=await Q(t.root,t.paths.manifestPath,t.maxManifestBytes),e=await Q(t.root,t.paths.entryPath,16*1024*1024);if(n.kind!=="read"||e.kind!=="read")throw new Error("Resolved package files are not authorized repository-local regular files.");let r=lC(n.bytes,t.packageName),s=Dt(t.paths.manifestPath);if(!Sn(s,t.paths.entryPath))throw new Error("Package CLI entry escapes its package root.");let i=[],a=[];if(t.loader!==void 0){let o=await El(t.root,t.loader.path);if(o.path!==t.loader.path||o.relativePath!==t.loader.relativePath||o.sha256!==t.loader.sha256)throw new Error("PnP loader identity changed before tool authorization completed.");a.push("--require",t.loader.path),i.push({kind:"pnp-loader",path:Tl(t.workspace,t.loader.path),sha256:t.loader.sha256,detail:"Repository-local Yarn Plug'n'Play loader."})}return a.push(t.paths.entryPath),{packageName:t.packageName,packageVersion:r.version,packageRoot:s,packageManifest:t.paths.manifestPath,packageManifestSha256:n.sha256,entryPath:t.paths.entryPath,entrySha256:e.sha256,executable:process.execPath,nodeArguments:a,packageManagerLayout:t.layout,resolutionEvidence:[{kind:"package-root",path:s,detail:`Canonical repository-local ${t.packageName} package root.`},{kind:"package-manifest",path:Tl(t.workspace,t.paths.manifestPath),sha256:n.sha256,detail:`${r.name}@${r.version}`},{kind:"package-entry",path:Tl(t.workspace,t.paths.entryPath),sha256:e.sha256,detail:"JavaScript CLI entry executed directly through the current Node runtime."},...i]}}async function js(t){try{let n=await Ze(t.workspaceRoot),e=t.repositoryRoot===void 0?n:await Ze(t.repositoryRoot);if(!Sn(e,n))return{kind:"unavailable",reasons:[_s("entry-outside-workspace","The workspace is outside its containing repository.")]};let r=await uC(e,Sl(n,t.ownerPath));if(r===void 0)return{kind:"unavailable",reasons:[_s("ambiguous-package-root","No owning repository package was found.")]};let s=t.maxManifestBytes??Ug;if(!Number.isInteger(s)||s<=0)return{kind:"unavailable",reasons:[_s("budget-exceeded","Package manifest byte limit is invalid.")]};let i,a="node-modules",o;try{i=await fC(r,t.packageName)}catch{let c=await pC(e,r);if(c===void 0)throw new Error("No repository-local dependency resolution succeeded.");o=await El(e,c),a="pnp",i=await hC(e,o,r,t.packageName)}return!Sn(e,i.manifestPath)||!Sn(e,i.entryPath)?{kind:"unavailable",reasons:[_s("entry-outside-workspace","Resolved package files are outside the repository.")]}:{kind:"resolved",tool:await mC({root:e,workspace:n,packageName:t.packageName,paths:i,maxManifestBytes:s,layout:a,...o===void 0?{}:{loader:o}})}}catch{return{kind:"unavailable",reasons:[_s("missing-dependency",`Repository-local ${t.packageName} could not be resolved safely. No installation or global fallback was attempted.`)]}}}function Fs(t){if(t.tool.executable!==process.execPath||t.args.some(s=>s.includes("\0"))||t.workingDirectory.includes("\0")||!Number.isInteger(t.timeoutMs)||t.timeoutMs<=0)throw new Error("Resolved validation command is invalid.");let n=[...t.tool.nodeArguments,...t.args],e=[...t.tool.resolutionEvidence,...t.extraEvidence??[]],r=L({packageManifestSha256:t.tool.packageManifestSha256,entrySha256:t.tool.entrySha256,resolutionEvidence:e,kind:t.kind,timing:t.timing,executable:t.tool.executable,args:n,workingDirectory:t.workingDirectory,environmentDelta:t.environmentDelta,timeoutMs:t.timeoutMs,purpose:t.purpose,logicalTestIds:t.logicalTestIds,projectIds:t.projectIds,artifactPolicy:t.artifactPolicy});if(!cC.test(r))throw new Error("Command identity could not be constructed.");return{commandId:`cmd_${r.slice(0,24)}`,kind:t.kind,timing:t.timing,required:!0,executable:t.tool.executable,args:n,workingDirectory:t.workingDirectory,environmentDelta:t.environmentDelta,timeoutMs:t.timeoutMs,purpose:t.purpose,logicalTestIds:t.logicalTestIds,projectIds:t.projectIds,artifactPolicy:t.artifactPolicy,resolutionEvidence:e}}function Cl(t,n){return L({purpose:"kwikqa-validation-repository-fingerprint",evidence:t,targetHashes:n})}var gC=/^[a-f0-9]{64}$/,Ol=3,wC=/^rps_[a-f0-9]{24}$/,Nl=yC(new URL("./parse-check.mjs",import.meta.url));function bC(t,n){switch(t.tool){case"biome":return n.biome;case"prettier":return n.prettier;case"typescript":return n.typescript;case"eslint":return n.eslint;case"kwikqa-babel":return}}function xC(t,n){return n==="unavailable"?void 0:`${t}-${n}`}var qg={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"};function vC(t,n){let e=["test"];if(n==="focused"?e.push(`${t.originalTest.path}:${t.originalTest.line}`,`--repeat-each=${Ol}`):n==="affected"&&e.push(...t.discovery.testPaths),n!=="suite")for(let r of t.discovery.projectIds)r!==""&&e.push(`--project=${r}`);return t.originalTest.configPath!==void 0&&e.push(`--config=${t.originalTest.configPath}`),e.push("--reporter=json",`--output=${t.artifactRoot}`,"--trace=retain-on-failure","--retries=0"),e}function kC(t,n){let e=n.targets.map(r=>r.path);switch(t.tool){case"biome":return t.kind==="format"?["format",...e]:["lint",...e];case"prettier":return["--check",...e];case"typescript":return["--noEmit","--pretty","false",...t.configPath?["--project",t.configPath]:[]];case"eslint":return e;case"kwikqa-babel":return[]}}function ja(t){return{code:"resolution-failed",message:t}}function $l(t){if(!Number.isInteger(t.timeoutMs)||t.timeoutMs<=0||t.originalTest.line<=0||t.originalTest.logicalTestId.trim().length===0||t.originalTest.projectId.trim().length===0)throw new Error("Validation preparation input is invalid.");let n=L(t.advisoryPlan),e=[...new Set(t.affectedLogicalTestIds??[])].sort(),r=[...t.discovery.reasons.map(y=>({code:y.code==="budget-exceeded"?"budget-exceeded":"resolution-failed",message:y.message,...y.path===void 0?{}:{path:y.path}}))],s=[],i=[],a=t.framework??"playwright",o=t.tools[a],d=xC(a,t.discovery.scope),c=a==="playwright"?void 0:t.frameworkRun,l=()=>c?.args??vC(t,t.discovery.scope),u=c?.evidence??[],p=c?.workingDirectory??t.workspaceRoot;if(t.discovery.status!=="resolved"||d===void 0||o===void 0||a!=="playwright"&&c===void 0)r.push(ja(`Repository-local ${qg[a]} validation could not be resolved.`));else{let y=[t.originalTest.logicalTestId,...(t.companionLogicalTestIds??[]).filter(x=>x!==t.originalTest.logicalTestId)],w=a!=="playwright"&&t.discovery.scope==="focused"?Ol:1;for(let x=1;x<=w;x+=1)s.push(Fs({tool:o,kind:d,timing:"post-patch",args:l(),workingDirectory:p,environmentDelta:{},timeoutMs:t.timeoutMs,purpose:`Run the approved risk-based ${qg[a]} validation scope${w>1?` (run ${x} of ${w})`:""}.`,logicalTestIds:t.discovery.scope==="focused"?[...new Set(y)].sort():e,projectIds:t.discovery.projectIds,artifactPolicy:{outputDirectory:t.artifactRoot,...a==="playwright"?{reportFile:"report.json"}:{},maxArtifacts:100,maxArtifactBytes:32*1024*1024},extraEvidence:u}));if(t.discovery.scope!=="focused"){(e.length===0||!e.includes(t.originalTest.logicalTestId))&&r.push(ja("Shared validation scope lacks complete canonical affected-test identities."));let x=Fs({tool:o,kind:d,timing:"baseline",args:l(),workingDirectory:p,environmentDelta:{},timeoutMs:t.timeoutMs,purpose:"Capture required affected-test outcomes before shared-source mutation.",logicalTestIds:e,projectIds:t.discovery.projectIds,artifactPolicy:{outputDirectory:`${t.artifactRoot}-baseline`,...a==="playwright"?{reportFile:"report.json"}:{},maxArtifacts:100,maxArtifactBytes:32*1024*1024},extraEvidence:u});s.push(x);let v=`baseline_${L({commandId:x.commandId}).slice(0,24)}`;i.push({baselineId:v,commandId:x.commandId,logicalTestIds:e,reason:"Shared test support requires a pre-patch affected-test baseline."})}else t.originalTest.environmentEquivalent||r.push(ja("Original failure evidence is not environment-equivalent to validation."))}for(let y of t.discovery.staticChecks){if(y.tool==="kwikqa-babel"){let x=L({purpose:"kwikqa-parse-check-command",executable:process.execPath,shim:Nl,paths:t.proposal.targets.map(v=>v.path),workingDirectory:t.workspaceRoot});s.push({commandId:`cmd_${x.slice(0,24)}`,kind:"parse",timing:"post-patch",required:!0,executable:process.execPath,args:[Nl,...t.proposal.targets.map(v=>v.path)],workingDirectory:t.workspaceRoot,environmentDelta:{},timeoutMs:t.timeoutMs,purpose:"Parse every changed JavaScript or TypeScript source file.",logicalTestIds:[],projectIds:t.discovery.projectIds,artifactPolicy:{outputDirectory:t.artifactRoot,maxArtifacts:1,maxArtifactBytes:1e6},resolutionEvidence:[{kind:"configuration",path:Nl,detail:"KwikQA-owned Babel parse-only validation shim."}]});continue}let w=bC(y,t.tools);if(w===void 0){r.push(ja(`Required ${y.tool} check could not be resolved locally.`));continue}s.push(Fs({tool:w,kind:y.kind,timing:"post-patch",args:kC(y,t.proposal),workingDirectory:t.workspaceRoot,environmentDelta:{},timeoutMs:t.timeoutMs,purpose:`Run required ${y.kind} validation.`,logicalTestIds:[],projectIds:t.discovery.projectIds,artifactPolicy:{outputDirectory:t.artifactRoot,maxArtifacts:10,maxArtifactBytes:8*1024*1024}}))}let f=s.flatMap(y=>y.resolutionEvidence),h=t.proposal.targets.map(y=>({path:y.path,sourceSha256:y.sourceSha256,resultSha256:y.resultSha256})),m={schemaVersion:wa,policyVersion:xa,status:r.length===0?"resolved":"unavailable",proposalHash:t.proposal.proposalHash,targetLogicalTestIds:[t.originalTest.logicalTestId],targetHashes:h,advisoryPlanHash:n,repositoryFingerprint:Cl(f,h),commands:[...s].sort((y,w)=>y.commandId.localeCompare(w.commandId)),baselineRequirements:[...i].sort((y,w)=>y.baselineId.localeCompare(w.baselineId)),unresolvedReasons:r},g={...m,planHash:ka(m)};return{plan:g,requiredBaselineCommands:g.commands.filter(y=>y.timing==="baseline")}}function Dl(t){if(t.plan.status!=="resolved"||!gC.test(t.plan.planHash)||!wC.test(t.repairSessionId)||t.attemptOrdinal!==1&&t.attemptOrdinal!==2)throw new Error("Only a resolved plan can become application execution authority.");let n=t.plan.baselineRequirements.map(s=>s.baselineId),e;if(n.length>0){if(t.baseline===void 0)throw new Error("Required pre-application baseline is missing.");e=Ns(t.baseline);let s=new Map(t.plan.baselineRequirements.map(i=>[i.commandId,i]));if(e.planHash!==t.plan.planHash||e.repositoryFingerprint!==t.plan.repositoryFingerprint||L(e.targetHashes)!==L(t.plan.targetHashes)||e.commandRecords.length!==s.size||e.commandRecords.some(i=>{let a=s.get(i.commandId);return a===void 0||i.planHash!==t.plan.planHash||i.timing!=="baseline"||i.status!=="passed"||i.termination.kind!=="exit"||i.termination.exitCode!==0||i.stdout.truncated||i.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 r=t.plan.commands.filter(s=>s.timing==="post-patch"&&s.required).sort((s,i)=>s.commandId.localeCompare(i.commandId));return{schemaVersion:"1.0",policyVersion:"1.0",planHash:t.plan.planHash,repositoryFingerprint:t.plan.repositoryFingerprint,targetHashes:t.plan.targetHashes,advisoryPlanHash:L(t.advisoryPlan),...e===void 0?{}:{baselineManifestHash:e.baselineHash},requiredBaselineIds:n,requiredCommandIds:r.map(s=>s.commandId),requiredCommands:r.map(s=>({commandId:s.commandId,commandHash:L(s)})),repairSessionId:t.repairSessionId,attemptOrdinal:t.attemptOrdinal}}import{randomUUID as zC}from"node:crypto";import{lstat as Hs,mkdir as Ul,readFile as HC,realpath as UC,rm as qC}from"node:fs/promises";import{isAbsolute as GC,join as vr,relative as KC,resolve as WC,sep as JC}from"node:path";import{realpath as br}from"node:fs/promises";import{realpath as wr}from"node:fs/promises";var et=/^[a-f0-9]{64}$/,RC=/^rps_[a-f0-9]{24}$/;function Gg(t){let n=t.map(e=>e.trim());return n.every(e=>e.length>0)&&new Set(n).size===t.length}function IC(t){return{kind:"rejected",reasons:t}}function Jg(t){return t.length>0&&Number.isFinite(Date.parse(t))}function Fa(t){return Number.isFinite(t)&&t>0}function AC(t){let{proposalHash:n,...e}=t;return et.test(n)&&L(e)===n}function TC(t){let n=[];(!AC(t)||L(t.diff)!==t.diffHash)&&n.push({code:"invalid-proposal",message:"Proposal and diff integrity hashes must match their canonical contents."}),(t.targets.length===0||t.changedFiles!==t.targets.length||t.targets.some(s=>!et.test(s.sourceSha256)||!et.test(s.resultSha256)||s.sourceSha256===s.resultSha256))&&n.push({code:"invalid-proposal",message:"Proposal targets and their source/result hashes must be complete and consistent."});let e=new Set,r=new Map;for(let s of t.targets){let i=s.path.toLocaleLowerCase("en-US"),a=r.get(i);(e.has(s.path)||a!==void 0&&a!==s.path)&&n.push({code:"invalid-proposal",message:"Proposal targets may not duplicate or case-collide.",path:s.path}),e.add(s.path),r.set(i,s.path)}return(t.replacements.length===0||t.replacements.some(s=>!e.has(s.path)))&&n.push({code:"invalid-proposal",message:"Every approved replacement must resolve to an approved proposal target."}),n}function PC(t){let n=TC(t.proposal);(t.context.workspace.workspaceRoot.length===0||t.context.workspace.gitRoot.length===0||t.context.snapshot.workspaceRoot!==t.context.workspace.workspaceRoot||t.context.snapshot.gitRoot!==t.context.workspace.gitRoot)&&n.push({code:"invalid-workspace",message:"Confirmed workspace and git roots must match the repository snapshot identity."}),(!Number.isInteger(t.context.maxTargetBytes)||t.context.maxTargetBytes<=0||t.context.config.schemaVersion.length===0)&&n.push({code:"invalid-configuration",message:"Application configuration and target byte limit must be explicit and bounded."}),(t.interactiveSession.sessionId.trim().length===0||!Jg(t.previewedAt))&&n.push({code:"invalid-preview",message:"An interactive session identity and valid preview timestamp are required."});let e=t.costBounds;(!Number.isInteger(e.maxRequestTokens)||!Number.isInteger(e.maxRunTokens)||!Fa(e.maxRequestTokens)||!Fa(e.maxRunTokens)||!Fa(e.maxRequestDollars)||!Fa(e.maxRunDollars)||e.maxRequestTokens>e.maxRunTokens||e.maxRequestDollars>e.maxRunDollars)&&n.push({code:"invalid-preview",message:"Approved request and run token/dollar bounds must be positive and internally consistent."});let r=new Set;for(let i of t.payloadManifests){if(!et.test(i.manifestHash)||!et.test(i.payloadHash)||!et.test(i.packetHash)||i.model.trim().length===0||i.provider.trim().length===0||i.promptVersion.trim().length===0||i.outputSchemaVersion.trim().length===0||r.has(i.manifestHash)){n.push({code:"invalid-preview",message:"Model payload manifest references must be sanitized, complete, and unique."});break}r.add(i.manifestHash)}(t.scopes.baseline.some(i=>i.trim().length===0)||t.scopes.validation.some(i=>i.trim().length===0))&&n.push({code:"invalid-preview",message:"Baseline and validation scopes may not contain empty entries."});let s=t.authoritativeValidation;return(s.schemaVersion!=="1.0"||s.policyVersion!=="1.0"||!et.test(s.planHash)||!et.test(s.repositoryFingerprint)||!et.test(s.advisoryPlanHash)||s.targetHashes.length!==t.proposal.targets.length||s.targetHashes.some((i,a)=>{let o=t.proposal.targets[a];return o===void 0||i.path!==o.path||i.sourceSha256!==o.sourceSha256||i.resultSha256!==o.resultSha256})||s.baselineManifestHash!==void 0&&!et.test(s.baselineManifestHash)||!RC.test(s.repairSessionId)||s.attemptOrdinal!==1&&s.attemptOrdinal!==2||!Gg(s.requiredBaselineIds)||!Gg(s.requiredCommandIds)||s.requiredCommandIds.length===0||s.requiredCommands.length!==s.requiredCommandIds.length||s.requiredCommands.some((i,a)=>i.commandId!==s.requiredCommandIds[a]||!et.test(i.commandHash))||s.requiredBaselineIds.length>0&&s.baselineManifestHash===void 0)&&n.push({code:"invalid-preview",message:"Authoritative validation approval metadata is incomplete or inconsistent."}),n}function Ml(t){return L({purpose:"kwikqa-approved-application",...t})}function Ll(t){let n=PC(t);if(n.length>0)return IC(n);let e={schemaVersion:"2.0",bindingVersion:"2.0",proposal:t.proposal,workspace:t.context.workspace,checkoutPristine:t.context.snapshot.dirtyPaths.length===0,validationPlan:t.proposal.validationPlan,scopes:t.scopes,authoritativeValidation:t.authoritativeValidation,payloadManifests:t.payloadManifests,costBounds:t.costBounds,previewedAt:t.previewedAt,interactiveSession:t.interactiveSession};return{kind:"preview-ready",preview:{...e,bindingHash:Ml(e)}}}function Ba(t,n,e,r){return L({purpose:"kwikqa-interactive-application-authorization",previewBindingHash:t.bindingHash,authorizationId:n,authorizedAt:e,interactiveSession:r})}function _l(t,n){let{bindingHash:e,...r}=t;return et.test(e)&&Ml(r)===e&&n.authorizationId.trim().length>0&&Jg(n.authorizedAt)&&n.bindingHash===Ba(t,n.authorizationId,n.authorizedAt,n.interactiveSession)&&n.interactiveSession.sessionId===t.interactiveSession.sessionId}import{realpath as Va}from"node:fs/promises";import{isAbsolute as $C,relative as DC,sep as MC}from"node:path";import{createHash as SC}from"node:crypto";function EC(t){return SC("sha256").update(t,"utf8").digest("hex")}function jl(t,n,e){let r=[],s=[];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){r.push({code:"invalid-replacement",message:"Replacement fields must be meaningful, cited, and non-no-op.",path:t});continue}if(o.oldText===n){r.push({code:"invalid-replacement",message:"A replacement may not rewrite the complete file.",path:t});continue}let d=n.indexOf(o.oldText);if(d<0||n.indexOf(o.oldText,d+1)>=0){r.push({code:"non-unique-match",message:"Replacement preimage must occur exactly once.",path:t});continue}s.push({start:d,end:d+o.oldText.length,newText:o.newText})}let i=[...s].sort((o,d)=>o.start-d.start);for(let o=1;o<i.length;o+=1){let d=i[o-1],c=i[o];d!==void 0&&c!==void 0&&c.start<d.end&&r.push({code:"overlapping-replacement",message:"Exact replacements overlap in the original source.",path:t})}if(r.length>0)return{kind:"rejected",reasons:r};let a=n;for(let o of[...i].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:EC(a)}}function Xg(t){let n=[],e=[];for(let r of t){let s=jl(r.path,r.source,r.replacements);if(s.kind==="rejected"){n.push(...s.reasons);continue}e.push({...r,result:s.result,resultSha256:s.resultSha256})}return n.length>0?{kind:"rejected",reasons:n}:{kind:"applied",targets:e}}import{isAbsolute as CC}from"node:path";function NC(t){return t.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function Yg(t,n){let e=NC(t).replaceAll("**/","\0").replaceAll("**","").replaceAll("*","[^/]*").replaceAll("\0","(?:.*/)?").replaceAll("",".*");return new RegExp(`^${e}$`).test(n)}function Bs(t){return t.length===0||t.includes("\0")||t.includes("\\")||CC(t)||/^[A-Za-z]:/.test(t)?!0:t.split("/").some(n=>n===""||n==="."||n==="..")}function Vs(t,n){let e=t.toLowerCase(),r=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(r)?!0:n.generatedPaths.some(s=>Yg(s,t))}function zs(t,n){return n.find(e=>Yg(e.pattern,t))}function OC(t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return}}async function Qg(t,n,e,r){let s=[],i=new Map;for(let l of e){if(Bs(l.path)){s.push({code:"unauthorized-target",message:"Target path is not a safe repository-relative path.",path:l.path});continue}let u=i.get(l.path)??[];u.push(l),i.set(l.path,u)}if(s.length>0)return{kind:"rejected",reasons:s};let a=new Set(n.dirtyPaths.map(l=>l.replaceAll("\\","/").toLocaleLowerCase("en-US"))),o=new Set,d=new Map,c=[];for(let[l,u]of[...i].sort(([p],[f])=>p.localeCompare(f))){let p=zs(l,t.editablePaths);if(p===void 0||Vs(l,t)){s.push({code:"unauthorized-target",message:"Target is outside the configured test-support repair boundary.",path:l});continue}if(a.has(l.toLocaleLowerCase("en-US"))){s.push({code:"dirty-target-file",message:"Already-dirty target files are read-only.",path:l});continue}let f=await Q(n.workspaceRoot,l,r);if(f.kind!=="read"){s.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){s.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"),m=d.get(h);if(o.has(f.relativePath)||m!==void 0&&m!==f.relativePath){s.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 g=OC(f.bytes);if(g===void 0){s.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)){s.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:g,sourceSha256:f.sha256,replacements:u})}return s.length>0?{kind:"rejected",reasons:s}:{kind:"authorized",targets:c}}function LC(t,n){let e=DC(t,n);return e===""||!$C(e)&&e!==".."&&!e.startsWith(`..${MC}`)}function _C(t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return}}async function Zg(t){if(!Number.isInteger(t.maxTargetBytes)||t.maxTargetBytes<=0||t.maxTargetBytes>1e6)return{kind:"rejected",code:"invalid-limit",message:"Target limit is invalid."};let n,e,r,s;try{[n,e,r,s]=await Promise.all([Va(t.workspaceRoot),Va(t.gitRoot),Va(t.approvedWorkspaceRoot),Va(t.approvedGitRoot)])}catch{return{kind:"rejected",code:"workspace-mismatch",message:"Workspace roots are unreadable."}}if(n!==r||e!==s||!LC(e,n))return{kind:"rejected",code:"workspace-mismatch",message:"Current and approved canonical workspace identities differ."};let i=new Set(t.dirtyPaths.map(c=>c.replaceAll("\\","/").toLocaleLowerCase("en-US"))),a=new Map;for(let c of t.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 t.proposal.targets){let l=c.path.toLocaleLowerCase("en-US");if(o.has(l)||Bs(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=zs(c.path,t.config.editablePaths);if(u===void 0||u.class!==c.class||Vs(c.path,t.config))return{kind:"rejected",code:"unauthorized-target",message:"Target is outside the approved repair boundary.",path:c.path};if(i.has(l))return{kind:"rejected",code:"dirty-target-file",message:"An approved target is currently dirty.",path:c.path};let p=await Q(n,c.path,t.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=_C(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)??[],m=jl(c.path,f,h);if(m.kind!=="applied"||m.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:m.result,resultBytes:new TextEncoder().encode(m.result),resultSha256:m.resultSha256,replacements:h})}return{kind:"verified",workspaceRoot:n,gitRoot:e,targets:d,nonPristine:t.dirtyPaths.length>0}}var jC=new Set(["completed","rolled-back","conflicted"]);function En(t,n,e){return{code:t,message:n,...e===void 0?{}:{path:e}}}function Pe(t){return{schemaVersion:"2.0",transactionId:t.manifest.transactionId,authorizationId:t.manifest.authorization.authorizationId,approvalBindingHash:t.manifest.preview.bindingHash,proposalHash:t.manifest.preview.proposal.proposalHash,diffHash:t.manifest.preview.proposal.diffHash,workspace:t.manifest.preview.workspace,phase:t.state.phase,revision:t.state.revision,targets:t.manifest.targets.map(n=>({path:n.path,sourceSha256:n.sourceSha256,resultSha256:n.resultSha256,preimageBytes:n.preimageBytes,resultBytes:n.resultBytes})),validationPlan:t.manifest.preview.validationPlan,authoritativeValidation:t.manifest.preview.authoritativeValidation,createdAt:t.manifest.createdAt,updatedAt:t.state.updatedAt}}async function FC(t){return(await Promise.all((await Ls(t)).map(e=>Re(t,e)))).filter(e=>!jC.has(e.state.phase))}async function ew(t,n,e,r){let s=await Q(t,n,e);return s.kind==="read"&&s.relativePath===n&&s.sha256===r}async function Fl(t){return BC(t,{})}async function BC(t,n){if(!_l(t.preview,t.authorization))return{kind:"rejected",reasons:[En("authorization-mismatch","Authorization does not match this exact preview.")]};let e=t.now??new Date().toISOString(),r;try{let[s,i,a,o,d,c]=await Promise.all([wr(t.context.workspace.workspaceRoot),wr(t.context.snapshot.workspaceRoot),wr(t.preview.workspace.workspaceRoot),wr(t.context.workspace.gitRoot),wr(t.context.snapshot.gitRoot),wr(t.preview.workspace.gitRoot)]);if(s!==i||s!==a||o!==d||o!==c)return{kind:"rejected",reasons:[En("invalid-workspace","Application workspace identity changed.")]};let l=a;r=await Ge(l,{operation:"apply",authorizationId:t.authorization.authorizationId,at:e});let u=await FC(l);if(u.length>0)return{kind:"recovery-required",reasons:[En("transaction-blocked","A nonterminal transaction must be recovered before another application.")],transaction:Pe(u[0])};if((await Promise.all((await Ls(l)).map(g=>Re(l,g)))).some(g=>g.manifest.authorization.authorizationId===t.authorization.authorizationId))return{kind:"rejected",reasons:[En("authorization-replayed","Authorization has already been consumed.")]};let f=await Zg({workspaceRoot:t.context.snapshot.workspaceRoot,gitRoot:t.context.snapshot.gitRoot,approvedWorkspaceRoot:t.preview.workspace.workspaceRoot,approvedGitRoot:t.preview.workspace.gitRoot,config:t.context.config,dirtyPaths:t.context.snapshot.dirtyPaths,proposal:t.preview.proposal,maxTargetBytes:t.context.maxTargetBytes});if(f.kind!=="verified")return{kind:"rejected",reasons:[En(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=Ep(),m=await Sg({workspaceRoot:f.workspaceRoot,transactionId:h,preview:t.preview,authorization:t.authorization,config:t.context.config,maxTargetBytes:t.context.maxTargetBytes,targets:f.targets,now:e});await n.failpoint?.("journal-prepared"),m=await Ue({transaction:m,phase:"applying",type:"application-started",now:e}),await n.failpoint?.("phase-applying");for(let g of m.manifest.targets){if(!await ew(f.workspaceRoot,g.path,t.context.maxTargetBytes,g.sourceSha256))return{kind:"recovery-required",reasons:[En("source-hash-mismatch","Target changed immediately before mutation.",g.path)],transaction:Pe(m)};m=await Ue({transaction:m,phase:"applying",type:"target-write-intent",path:g.path,now:e}),await n.failpoint?.(`before-target:${g.path}`);let w=m.results.get(g.path);if(w===void 0)throw new Error("Journal result bytes are unavailable.");if(await ui(f.workspaceRoot,g.path,g.sourceSha256,w),await n.failpoint?.(`after-target:${g.path}`),!await ew(f.workspaceRoot,g.path,t.context.maxTargetBytes,g.resultSha256))throw new Error("Applied target hash could not be verified.");m=await Ue({transaction:m,phase:"applying",type:"target-write-complete",path:g.path,now:e})}return m=await Ue({transaction:m,phase:"applied",type:"application-complete",now:e}),await n.failpoint?.("phase-applied"),{kind:"applied",transaction:Pe(m)}}catch{return{kind:"failed",reasons:[En("application-failed","Application stopped safely; inspect transaction discovery before continuing.")]}}finally{await r?.release().catch(()=>{})}}var nw=new Set(["completed","rolled-back","conflicted"]);function Jt(t,n){return{code:"transaction-conflict",message:t,...n===void 0?{}:{path:n}}}async function Vl(t,n){let e=t.manifest.targets.find(s=>s.path===n);if(e===void 0)return"conflict";let r=await Q(t.manifest.preview.workspace.workspaceRoot,n,t.manifest.maxTargetBytes);return r.kind!=="read"||r.relativePath!==n?"conflict":r.sha256===e.sourceSha256?"preimage":r.sha256===e.resultSha256?"applied":"conflict"}async function za(t,n){let e=await Re(t,n),r=await Promise.all(e.manifest.targets.map(async s=>({path:s.path,classification:await Vl(e,s.path)})));return{transactionId:n,phase:e.state.phase,targets:r}}async function zl(t){try{let n=await Promise.all((await Ls(t)).map(r=>za(t,r))),e=n.filter(r=>!nw.has(r.phase));return e.some(r=>r.targets.some(s=>s.classification==="conflict"))?{kind:"conflicted",transactions:e}:e.length===0?{kind:"clear",transactions:n}:{kind:"recovery-required",transactions:e}}catch{return{kind:"failed",reasons:[Jt("Transaction discovery failed closed because a journal is unreadable.")]}}}async function Bl(t,n,e){return t.state.phase==="conflicted"?t:Ue({transaction:t,phase:"conflicted",type:"conflict-detected",message:e,now:n})}async function tw(t){let n=await Promise.all(t.manifest.targets.map(async e=>[e.path,await Vl(t,e.path)]));return new Map(n)}async function VC(t,n,e,r,s){let i;try{let[a,o,d,c]=await Promise.all([br(t.workspace.workspaceRoot),br(t.snapshot.workspaceRoot),br(t.workspace.gitRoot),br(t.snapshot.gitRoot)]);if(a!==o||d!==c)return{kind:"rejected",reasons:[Jt("Recovery workspace identity differs.")]};i=await Ge(a,{operation:e,transactionId:n,at:r});let l=await Re(a,n);if(await br(l.manifest.preview.workspace.workspaceRoot)!==a||await br(l.manifest.preview.workspace.gitRoot)!==d)return{kind:"rejected",reasons:[Jt("Recovery workspace identity differs.")]};if(nw.has(l.state.phase))return e==="rollback"&&l.state.phase==="rolled-back"?{kind:"rolled-back",transaction:Pe(l)}:{kind:"rejected",reasons:[Jt("Terminal transaction cannot perform this recovery operation.")],transaction:Pe(l)};let u=await tw(l),p=[...u].find(([,m])=>m==="conflict");if(p!==void 0)return l=await Bl(l,r,"Current target bytes match neither recorded preimage nor applied image."),{kind:"conflicted",reasons:[Jt("Developer or unknown target bytes prohibit automatic recovery.",p[0])],transaction:Pe(l)};e==="rollback"&&(l=await Ue({transaction:l,phase:"rolling-back",type:"rollback-started",now:r}),await s?.("phase-rolling-back"));for(let m of l.manifest.targets){let g=u.get(m.path);if(!(e==="resume"&&g==="preimage"||e==="rollback"&&g==="applied"))continue;let w=e==="resume"?"resume":"rollback";if(await s?.(`before-${w}-target:${m.path}`),await Vl(l,m.path)!==g)return l=await Bl(l,r,"Target changed after recovery classification."),{kind:"conflicted",reasons:[Jt("Target changed immediately before recovery mutation.",m.path)],transaction:Pe(l)};let v=e==="resume"?l.results.get(m.path):l.preimages.get(m.path);if(v===void 0)throw new Error("Recovery bytes are unavailable.");await ui(a,m.path,e==="resume"?m.sourceSha256:m.resultSha256,v),await s?.(`after-${w}-target:${m.path}`),l=await Ue({transaction:l,phase:e==="resume"?"applying":"rolling-back",type:`${e}-target-complete`,path:m.path,now:r})}let f=await tw(l),h=e==="resume"?"applied":"preimage";return[...f.values()].some(m=>m!==h)?(l=await Bl(l,r,"Recovery result hashes did not verify."),{kind:"conflicted",reasons:[Jt("Recovery completed with an unknown target state.")],transaction:Pe(l)}):(l=await Ue({transaction:l,phase:e==="resume"?"applied":"rolled-back",type:e==="resume"?"resume-complete":"rollback-complete",now:r}),{kind:e==="resume"?"resumed":"rolled-back",transaction:Pe(l)})}catch{return{kind:"failed",reasons:[Jt("Recovery stopped safely; rediscover transaction state.")]}}finally{await i?.release().catch(()=>{})}}async function Hl(t,n,e=new Date().toISOString()){return VC(t,n,"rollback",e)}var rw=/^rps_[a-f0-9]{24}$/,Ha=/^[a-f0-9]{64}$/,XC=new Set(["rolling-back","rolled-back","conflicted"]);function YC(t,n){let e=KC(t,n);return e===""||!GC(e)&&e!==".."&&!e.startsWith(`..${JC}`)}function xr(t){return t.length>0&&Number.isFinite(Date.parse(t))}function sw(t){if(t.ordinal!==1&&t.ordinal!==2||!Ha.test(t.proposalHash)||!/^txn_[a-f0-9]{24}$/.test(t.transactionId)||t.validationManifestHash!==void 0&&!Ha.test(t.validationManifestHash)||!xr(t.recordedAt))throw new Error("Repair attempt record is malformed.")}function QC(t){let{sessionHash:n,...e}=t;if(t.schemaVersion!=="1.0"||!rw.test(t.repairSessionId)||t.originalRunId.trim().length===0||!Ha.test(t.originalPacketHash)||t.maxAttempts!==2||!xr(t.createdAt)||!xr(t.updatedAt)||!Number.isInteger(t.revision)||t.revision<1||t.attempts.length>2||L(e)!==n)throw new Error("Repair session integrity check failed.");t.attempts.forEach(sw);for(let[r,s]of t.attempts.entries())if(s.ordinal!==r+1)throw new Error("Repair attempt order is malformed.");return t}async function Ua(t){let n=await UC(t),e=WC(n,".kwikqa");if(!YC(n,e))throw new Error("Repair session directory escapes workspace.");await Ul(e,{mode:448}).catch(a=>{if(a.code!=="EEXIST")throw a});let r=await Hs(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Repair session path is unsafe.");let s=vr(e,"repair-sessions");await Ul(s,{mode:448}).catch(a=>{if(a.code!=="EEXIST")throw a});let i=await Hs(s);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Repair session path is unsafe.");return s}function qa(t){return{...t,sessionHash:L(t)}}function ql(t){return{schemaVersion:t.schemaVersion,repairSessionId:t.repairSessionId,originalRunId:t.originalRunId,originalPacketHash:t.originalPacketHash,maxAttempts:t.maxAttempts,attempts:t.attempts,state:t.state,createdAt:t.createdAt,updatedAt:t.updatedAt,revision:t.revision}}async function Gl(t){if(t.originalRunId.trim().length===0||!Ha.test(t.originalPacketHash))throw new Error("Original repair evidence identity is invalid.");let n=t.now??new Date().toISOString();if(!xr(n))throw new Error("Repair session timestamp is invalid.");let e=`rps_${zC().replaceAll("-","").slice(0,24)}`,r=qa({schemaVersion:"1.0",repairSessionId:e,originalRunId:t.originalRunId,originalPacketHash:t.originalPacketHash,maxAttempts:2,attempts:[],state:"first-attempt",createdAt:n,updatedAt:n,revision:1}),s=await Ua(t.workspaceRoot);return await ye(vr(s,`${e}.json`),`${pe(r)}
175
+ `,{mode:384,replace:!1}),r}async function Xt(t,n){if(!rw.test(n))throw new Error("Repair session id is invalid.");let e=await Ua(t),r=vr(e,`${n}.json`),s=await Hs(r);if(!s.isFile()||s.isSymbolicLink())throw new Error("Repair session record is unsafe.");let i=JSON.parse(await HC(r,"utf8"));if(i===null||typeof i!="object"||Array.isArray(i))throw new Error("Repair session record is malformed.");return QC(i)}async function Kl(t,n){let e=await Ua(t),r=vr(e,`${n}.lock`);await Ul(r,{mode:448});let s=await Hs(r);if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Repair session lock is unsafe.");return{release:async()=>{let i=await Hs(r);if(i.dev!==s.dev||i.ino!==s.ino||i.isSymbolicLink())throw new Error("Repair session lock ownership changed.");await qC(r,{recursive:!0,force:!1})}}}async function Wl(t,n,e){let r=await Xt(t,n.repairSessionId);if(r.revision!==n.revision||r.sessionHash!==n.sessionHash)throw new Error("Repair session changed concurrently.");let s=await Ua(t);return await ye(vr(s,`${n.repairSessionId}.json`),`${pe(e)}
176
+ `,{mode:384,replace:!0}),Xt(t,n.repairSessionId)}async function Jl(t,n,e){sw(e);let r=await Kl(t,n);try{let s=await Xt(t,n);if(s.state==="repaired"||s.state==="stopped")throw new Error("Terminal repair session cannot accept another attempt.");if(e.ordinal!==s.attempts.length+1||e.ordinal>s.maxAttempts)throw new Error("Repair session attempt limit or ordering was violated.");if(e.ordinal===1&&s.state!=="first-attempt"||e.ordinal===2&&s.state!=="retry-approval-required")throw new Error("Repair session is not ready for this attempt.");let i=e.recordedAt,a=qa({...ql(s),attempts:[...s.attempts,e],state:e.ordinal===1?"first-attempt":"second-attempt",updatedAt:i,revision:s.revision+1});return await Wl(t,s,a)}finally{await r.release()}}function ZC(t,n){let e=t.status;if(e==="blocked")throw new Error("A blocked validation run has no attempt outcome.");let r=n.state.history,s=r.findLastIndex(d=>d.type==="validation-started"),i=r[s];if(i===void 0||i.validationRunId!==t.validationRunId||i.planHash!==t.planHash)throw new Error("Validation run was not started for this transaction approval.");let a=r.slice(s+1).find(d=>d.type==="validation-passed"),o=n.state.phase;if(a!==void 0){if(o!=="completed"||e!=="passed"||a.validationRunId!==t.validationRunId||a.planHash!==t.planHash||a.validationManifestHash!==t.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(XC.has(o))return e==="passed"?"incomplete":e;throw new Error("Validation outcome does not match the durable transaction state.")}async function Ga(t){if(!/^vld_[a-f0-9]{24}$/.test(t.validationRunId))throw new Error("Validation run id is invalid.");let n=t.now??new Date().toISOString();if(!xr(n))throw new Error("Repair session timestamp is invalid.");let e=await Kl(t.workspaceRoot,t.repairSessionId),r;try{r=await Ge(t.workspaceRoot,{operation:"record-repair-validation",repairSessionId:t.repairSessionId,validationRunId:t.validationRunId});let s=await Xt(t.workspaceRoot,t.repairSessionId),i=s.attempts.at(-1);if(i===void 0||i.ordinal!==t.ordinal)throw new Error("Repair attempt cannot be finalized from its current state.");let a=await Re(t.workspaceRoot,i.transactionId),o=a.manifest.preview.authoritativeValidation,d=vr(a.directory,"validation",t.validationRunId),c=Wt(await Pn(d,"manifest.json",$a)),l=new Map(o.requiredCommands.map(m=>[m.commandId,m.commandHash]));if(c.transactionId!==i.transactionId||c.validationRunId!==t.validationRunId||c.planHash!==o.planHash||c.repositoryFingerprint!==o.repositoryFingerprint||L(c.targetHashes)!==L(o.targetHashes)||c.requiredCommandIds.length!==l.size||c.requiredCommandIds.some(m=>!l.has(m))||c.commandRecords.some(m=>l.get(m.commandId)!==m.commandHash)||o.repairSessionId!==s.repairSessionId||o.attemptOrdinal!==i.ordinal||a.manifest.preview.proposal.proposalHash!==i.proposalHash)throw new Error("Validation manifest does not match the repair attempt authority.");for(let m of c.commandRecords)if(!await $g(d,m,yr))throw new Error("Validation manifest command evidence failed verification.");let u=ZC(c,a);if(i.outcome!=="applied"){if(i.validationManifestHash===c.manifestHash&&i.outcome===u)return{session:s};throw new Error("Repair attempt was already finalized with different evidence.")}let p={...i,validationManifestHash:c.manifestHash,outcome:u,recordedAt:n},f=u==="passed"?"repaired":"rollback-required",h=qa({...ql(s),attempts:[...s.attempts.slice(0,-1),p],state:f,updatedAt:n,revision:s.revision+1});return{session:await Wl(t.workspaceRoot,s,h)}}finally{await r?.release(),await e.release()}}async function Xl(t){if(!/^txn_[a-f0-9]{24}$/.test(t.proof.transactionId)||t.proof.phase!=="rolled-back"||!Number.isInteger(t.proof.transactionRevision)||t.proof.transactionRevision<1)throw new Error("Repair rollback proof is invalid.");let n=t.now??new Date().toISOString();if(!xr(n))throw new Error("Repair session timestamp is invalid.");let e=await Kl(t.workspaceRoot,t.repairSessionId),r;try{r=await Ge(t.workspaceRoot,{operation:"confirm-repair-rollback",repairSessionId:t.repairSessionId,transactionId:t.proof.transactionId});let s=await Xt(t.workspaceRoot,t.repairSessionId),i=s.attempts.at(-1);if(s.state!=="rollback-required"||i===void 0||i.ordinal!==t.ordinal||i.transactionId!==t.proof.transactionId||i.validationManifestHash===void 0||i.outcome==="passed"||i.outcome==="applied")throw new Error("Repair session does not match the rolled-back attempt.");let a=await Re(t.workspaceRoot,i.transactionId),o=a.manifest.preview.authoritativeValidation;if(a.state.phase!=="rolled-back"||a.state.revision!==t.proof.transactionRevision||o.repairSessionId!==s.repairSessionId||o.attemptOrdinal!==i.ordinal||a.manifest.preview.proposal.proposalHash!==i.proposalHash)throw new Error("Repair rollback proof does not match the durable transaction.");let d=await za(t.workspaceRoot,i.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=t.ordinal===1?"retry-approval-required":"stopped",l=qa({...ql(s),state:c,updatedAt:n,revision:s.revision+1}),u=await Wl(t.workspaceRoot,s,l);if(c!=="retry-approval-required")return{session:u};let p={repairSessionId:u.repairSessionId,failedTransactionId:i.transactionId,failedValidationManifestHash:i.validationManifestHash,nextAttemptOrdinal:2};return{session:u,retry:{...p,handoffHash:L(p)}}}finally{await r?.release(),await e.release()}}import{basename as u1,dirname as dw,join as kr,relative as nu,resolve as Mt,sep as p1}from"node:path";import{createHash as e1}from"node:crypto";import{lstat as t1,mkdir as n1,readFile as iw,realpath as Yl,rename as r1,writeFile as s1}from"node:fs/promises";import{isAbsolute as i1,join as aw,relative as Ql,sep as ow}from"node:path";import{fileURLToPath as a1}from"node:url";var o1=".kwikqa/runtime",d1=["cypress-reporter.cjs","cypress-capture.js","wdio-reporter.mjs","wdio-capture.mjs"];async function c1(t){return iw(a1(new URL(`./${t}`,import.meta.url)),"utf8")}function l1(t,n){let e=Ql(t,n);return e===""||!i1(e)&&e!==".."&&!e.startsWith(`..${ow}`)}async function Ka(t,n){let e=await Yl(t),r=e;for(let s of n.split("/").filter(i=>i!=="")){if(s==="."||s==="..")throw new Error("Unsafe KwikQA directory.");r=aw(r,s);let i=await t1(r).catch(()=>{});if(i===void 0)await n1(r);else if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${Ql(e,r)} must be a real directory inside the workspace.`)}if(!l1(e,await Yl(r)))throw new Error("KwikQA directory escapes workspace.");return r}async function Zl(t,n){let e=`${t}.${process.pid}.tmp`;await s1(e,n,{mode:420}),await r1(e,t)}function eu(t){return e1("sha256").update(t,"utf8").digest("hex")}async function Wa(t){let n=await Yl(t),e=await Ka(n,o1),r={};for(let s of d1){let i=await c1(s),a=aw(e,s);await iw(a,"utf8").catch(()=>{})!==i&&await Zl(a,i),r[s]={path:a,relativePath:Ql(n,a).split(ow).join("/"),sha256:eu(i)}}return r}function ru(t){return t.split(p1).join("/")}function Us(t,n){let e=ru(nu(t,n));return e.startsWith(".")?e:`./${e}`}async function tu(t,n,e){return await Zl(n,e),{path:n,relativePath:ru(nu(t,n)),sha256:eu(e)}}async function Ja(t){let n=t.workspaceRoot,e=t.configFile===void 0?n:dw(Mt(n,t.configFile)),r=["video=false","screenshotOnRunFailure=true",`screenshotsFolder=${Mt(n,t.screenshotsDirectory)}`,...t.noRetries?["retries=0"]:[]],s=[];if(t.capture!==void 0){let a=await Ka(n,t.capture.directory),o=await tu(n,kr(a,"kwikqa-settings.js"),`// Generated by KwikQA for one run.
177
+ globalThis.__kwikqaCapture = ${JSON.stringify({directory:ru(nu(e,kr(a,"pages"))),...t.capture.only===void 0?{}:{only:[...t.capture.only].sort()}})};
178
+ `),d=[`import ${JSON.stringify(Us(a,o.path))};`,`import ${JSON.stringify(Us(a,t.runtime["cypress-capture.js"].path))};`,...t.capture.supportFile===null||t.capture.supportFile===void 0?[]:[`import ${JSON.stringify(Us(a,Mt(n,t.capture.supportFile)))};`]],c=await tu(n,kr(a,"kwikqa-support.js"),`// Generated by KwikQA: its failure capture, then the project's support file.
179
+ ${d.join(`
180
+ `)}
181
+ `);s.push(o,c),r.push(`supportFile=${c.path}`)}return{args:["run","--project",e,...t.configFile===void 0?[]:["--config-file",u1(t.configFile)],...t.specs.length===0?[]:["--spec",t.specs.map(a=>Mt(n,a)).join(",")],"--reporter",t.runtime["cypress-reporter.cjs"].path,"--reporter-options",[`screenshotsFolder=${Mt(n,t.screenshotsDirectory)}`,...t.capture===void 0?[]:[`captureDir=${kr(Mt(n,t.capture.directory),"pages")}`]].join(","),"--config",r.join(",")],generated:s}}function cw(t){return t.filter(n=>n!=="").slice(-2).join(" ")}async function Xa(t){let n=t.workspaceRoot,e=await Ka(n,t.directory),r=Mt(n,t.configFile),s=/\.([cm]?ts)$/.exec(t.configFile)?.[1]??"mjs",i={rootDir:dw(r),noRetries:t.noRetries,...t.grep===void 0?{}:{grep:t.grep},...t.reportDirectory===void 0?{}:{reportDir:Mt(n,t.reportDirectory)},...t.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(Us(e,r))};`,`import { withKwikqa } from ${JSON.stringify(Us(e,t.runtime["wdio-capture.mjs"].path))};`,"",`export const config = withKwikqa(base, ${JSON.stringify(i,null,2)});`,""].join(`
182
+ `),o=await tu(n,kr(e,`wdio.kwikqa.conf.${s}`),a);return{args:["run",o.path,...t.specs.flatMap(c=>["--spec",Mt(n,c)])],generated:[o]}}var pw=".kwikqa/capture",y1=10*6e4,g1={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};function su(t){let n=h1(t.workspaceRoot,t.tool.entryPath).replaceAll("\\","/"),e=t.workspaceRoot,r=t.args.map(s=>{let i=s===e?".":s.split(`${e}/`).join("").split(`${e}\\`).join("").replaceAll("\\","/");return/[\s"']/.test(i)?JSON.stringify(i):i});return`node ${n} ${r.join(" ")}`}async function fw(t){let n=t.targets[0];if(n===void 0)return{kind:"unavailable",message:"No failing tests to capture."};let e=Je(t.run);if(e===void 0)return{kind:"unavailable",message:dt(t.run)};let r=g1[e],s=await js({workspaceRoot:t.workspaceRoot,...t.repositoryRoot===void 0?{}:{repositoryRoot:t.repositoryRoot},ownerPath:Rr(t.workspaceRoot,n.file),packageName:r});if(s.kind!=="resolved")return{kind:"unavailable",message:s.reasons[0]?.message??`The project's ${r} could not be resolved; nothing was installed.`};let i=`${pw}/${t.captureId}`,a={framework:e,tool:s.tool,workspaceRoot:t.workspaceRoot,directory:i,targets:t.targets};if(e==="playwright"){let f=[...new Set(t.targets.map(y=>`${y.file}:${y.line}`))],h=[...new Set(t.targets.map(y=>y.project).filter(y=>y!==void 0))],m=Rr(t.workspaceRoot,i,"report.json"),g=["test",...f,...h.map(y=>`--project=${y}`),...t.run.configFile===void 0?[]:[`--config=${t.run.configFile}`],"--trace=retain-on-failure","--retries=0","--reporter=json",`--output=${i}/results`];return{kind:"ready",plan:{...a,args:g,workingDirectory:t.workspaceRoot,environment:{PLAYWRIGHT_JSON_OUTPUT_NAME:m,PLAYWRIGHT_HTML_OPEN:"never"},reportPath:m,...t.run.configFile===void 0?{}:{configPath:t.run.configFile}}}}let o=[...new Set(t.targets.map(f=>f.file))],d=t.run.configFile??await fa(t.workspaceRoot,e,n.file),c=Rr(t.workspaceRoot,i,"reports"),l=await Wa(t.workspaceRoot);await uw(Rr(t.workspaceRoot,i),{recursive:!0});let u=d===void 0?t.workspaceRoot:f1(m1(t.workspaceRoot,d));if(e==="cypress"){let f=await Ja({workspaceRoot:t.workspaceRoot,runtime:l,...d===void 0?{}:{configFile:d},specs:o,screenshotsDirectory:`${i}/screenshots`,noRetries:!0,capture:{directory:i,supportFile:await ha(t.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 ${n.file}; nothing was run.`};let p=await Xa({workspaceRoot:t.workspaceRoot,runtime:l,configFile:d,specs:o,directory:i,noRetries:!0,reportDirectory:`${i}/reports`,capture:!0});return{kind:"ready",plan:{...a,args:p.args,workingDirectory:u,environment:{KWIKQA_REPORT_DIR:c},reportPath:c,configPath:d}}}async function hw(t,n){let e=Rr(t.workspaceRoot,t.directory);if(t.framework==="playwright")await lw(e,{recursive:!0,force:!0}),await uw(e,{recursive:!0});else for(let u of["reports","pages","screenshots"])await lw(Rr(e,u),{recursive:!0,force:!0});let r=await ya(t.tool.executable,[...t.tool.nodeArguments,...t.args],{cwd:t.workingDirectory,env:ma(n.env,t.environment),timeoutMs:n.timeoutMs??y1}),s=await ot(t.reportPath,{workspaceRoot:t.workspaceRoot}),i=pa[t.framework];if(s.kind!=="parsed"){let u=r.output.trim().split(`
183
+ `).slice(-5).join(`
184
+ `);return{kind:"failed",message:r.timedOut?`The capture run timed out before ${i} wrote its report.`:`${i} wrote no report.${u===""?"":`
185
+ ${u}`}`,reproduced:0,passed:0}}let a=new Set(t.targets.map(u=>u.logicalTestId)),o=s.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:t.reportPath,reproduced:c,passed:l,failedAgain:d,message:c===0?`None of the ${t.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 w1=/\b(?:getBy\w+|locator|frameLocator)\((?:[^()]|\([^()]*\))*\)/;function b1(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function x1(t,n){if(t===void 0)return;let r=new RegExp(`${b1(n)}:(\\d+):\\d+`).exec(t.replaceAll("\\","/"));return r?.[1]===void 0?void 0:Number(r[1])}function mw(t,n){if(t===void 0)return!1;let e=t.replaceAll("\\","/");return e===n||e.endsWith(`/${n}`)}function Ya(t){let n=new Map(t.projects.map(r=>[r.projectId,r.name])),e=[];for(let r of t.logicalTests){let s=lr(r),i=s.at(-1);if(i===void 0)continue;let a=r.location.file,o=i.errors.map(u=>`${u.message??""}
186
+ ${u.stack??""}`),d=(mw(i.errorLocation?.file,a)?i.errorLocation?.line:void 0)??i.errors.map(u=>mw(u.location?.file,a)?u.location?.line:x1(u.stack,a)).find(u=>u!==void 0),c=o.map(u=>w1.exec(u)?.[0]).find(u=>u!==void 0),l=n.get(r.projectId);e.push({logicalTestId:r.logicalTestId,title:r.title,file:a,line:r.location.line??1,...l===void 0||l===""?{}:{project:l},...d===void 0?{}:{failingLine:d},...c===void 0?{}:{locator:c},hasTrace:s.some(u=>u.attachments.some(p=>p.name==="trace")),hasPageSnapshot:s.some(u=>u.attachments.some(p=>p.name==="error-context"))})}return e}var gw=3;async function iu(t){let n=Ya(t.run),e=await fw({run:t.run,workspaceRoot:t.workspaceRoot,...t.repositoryRoot===void 0?{}:{repositoryRoot:t.repositoryRoot},targets:n,captureId:t.captureId});if(e.kind!=="ready")return e;let{plan:r}=e,s,i,a=r.framework;t.probe&&a==="playwright"&&(al(r.tool.packageVersion)?(s=await tg(t.workspaceRoot,t.env),s===void 0&&(i="Live probing needs Playwright CLI: add `@playwright/cli` to the project's dev dependencies (nothing was installed).")):i=`Live probing needs Playwright 1.59 or later; this project has ${r.tool.packageVersion}.`);let o=pa[a],d=`${n.length} failing test${n.length===1?"":"s"}`,c=new Set(n.map(u=>u.file)).size,l=a==="playwright"?[`Re-run ${d} with full tracing, using this project's Playwright ${r.tool.packageVersion}:`,` ${su(r)}`,...s===void 0?[]:[`Then pause up to ${gw} locator failures at their failing line and ask Playwright for locators, using Playwright CLI ${s.version} (${s.source==="project"?"project dependency":s.entryPath}).`],`Everything is written under ${r.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} ${r.tool.packageVersion} and its own config:`,` ${su(r)}`,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 ${r.directory}/. Your tests run on this machine, as they do in \`npx ${a==="cypress"?"cypress run":"wdio run"}\`.`];return{kind:"ready",prepared:{plan:r,...s===void 0?{}:{cli:s},...i===void 0?{}:{probeUnavailable:i},description:l}}}async function au(t,n){let e=await hw(t.plan,{env:n});if(t.cli===void 0||e.reportPath===void 0||e.reproduced===0)return{outcome:e};let r=await ot(e.reportPath,{workspaceRoot:t.plan.workspaceRoot}),i=(r.kind==="parsed"?Ya(r.run):[]).filter(l=>l.locator!==void 0).slice(0,gw);if(i.length===0)return{outcome:e};let a=yw(t.plan.workspaceRoot,t.plan.directory,"probe");await v1(a,{recursive:!0});let o=[];for(let l of i)o.push(await ag({workspaceRoot:t.plan.workspaceRoot,playwright:t.plan.tool,cli:t.cli,target:l,...t.plan.configPath===void 0?{}:{configPath:t.plan.configPath},scratchDirectory:a,env:n}));let d={schemaVersion:eg,tool:{name:"@playwright/cli",version:t.cli.version,source:t.cli.source},playwrightVersion:t.plan.tool.packageVersion,results:o},c=yw(t.plan.workspaceRoot,t.plan.directory,"probe.json");return await k1(c,`${JSON.stringify(d,null,2)}
187
+ `),{outcome:e,probePath:c,probe:d}}var Cn=class{#e=new Set;consume(n,e){return this.#e.has(n)?!1:(this.#e.add(n),!0)}};function Qa(t){return L({runId:t.manifest.runId,packetHash:t.manifest.packetHash,payloadHash:t.manifest.payloadHash,manifestHash:t.manifestHash,model:t.manifest.model,promptVersion:t.manifest.promptVersion,outputSchemaVersion:t.manifest.outputSchemaVersion,endpoint:t.endpoint,estimate:t.estimate,caps:t.caps})}function ou(t,n){return{runId:t.manifest.runId,packetHash:t.manifest.packetHash,payloadManifestHash:t.manifestHash,authorizationBindingHash:n,model:t.manifest.model,estimate:t.estimate,caps:t.caps,evidence:t.manifest.evidence,artifactIds:t.manifest.artifactIds,channels:t.manifest.channels,omissionIds:t.manifest.omissionIds,redactionIds:t.manifest.redactionIds}}function du(t,n){return t.bindingHash===n&&t.authorizationId.trim().length>0&&t.authorizedAt.trim().length>0}var R1={purpose:"diagnosis",promptVersion:"1.3",outputSchemaVersion:"1.0"};function cu(t){return{...t.extra,schemaVersion:"1.1",runId:t.runId,createdAt:t.createdAt,workspace:t.workspace,sourceHashes:t.sourceHashes,packetHash:t.packetHash,...t.request??R1,model:t.model,caps:t.caps,outcome:t.outcome,recordedAt:t.recordedAt}}function qe(t,n,e){return{kind:t,...n===void 0?{}:{reasonCode:n},...e===void 0?{}:{message:e}}}function lu(t){if(t===void 0||t.trim().length===0)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n:void 0}function I1(t){let n=[t.prompt,...t.overrides.map(s=>s.prompt)].map(lu).filter(s=>s!==void 0),e=[t.completion,...t.overrides.map(s=>s.completion)].map(lu).filter(s=>s!==void 0),r=[t.request??"0",...t.overrides.map(s=>s.request)].map(lu).filter(s=>s!==void 0);if(!(n.length!==t.overrides.filter(s=>s.prompt!==void 0).length+1||e.length!==t.overrides.filter(s=>s.completion!==void 0).length+1||r.length!==t.overrides.filter(s=>s.request!==void 0).length+1))return{prompt:Math.max(...n),completion:Math.max(...e),request:Math.max(...r)}}function Za(t,n,e){if(!Number.isInteger(n)||n<=0)return;let r=I1(e);if(r===void 0)return;let s=Buffer.byteLength(t,"utf8"),i=s+64,a=i*r.prompt+n*r.completion+r.request;if(Number.isFinite(a))return{method:"utf8-byte-upper-bound-v1",requestBytes:s,estimatedInputTokens:i,estimatedOutputTokens:n,estimatedDollars:a,promptDollarsPerToken:r.prompt,completionDollarsPerToken:r.completion,fixedRequestDollars:r.request}}function uu(t){for(let[n,e]of[["request",t.request],["run",t.run]]){if(!Number.isInteger(e.maxInputTokens)||e.maxInputTokens<=0)return`${n} maxInputTokens must be a positive integer.`;if(!Number.isInteger(e.maxOutputTokens)||e.maxOutputTokens<=0)return`${n} maxOutputTokens must be a positive integer.`;if(!Number.isFinite(e.maxDollars)||e.maxDollars<=0)return`${n} maxDollars must be a positive finite number.`}}function pu(t,n){return t.estimatedInputTokens>n.request.maxInputTokens||t.estimatedOutputTokens>n.request.maxOutputTokens?{kind:"blocked",reasonCode:"request-token-budget-exceeded",message:"The conservative request token estimate exceeds the request cap."}:t.estimatedDollars>n.request.maxDollars?{kind:"blocked",reasonCode:"request-dollar-budget-exceeded",message:"The conservative request cost estimate exceeds the request cap."}:t.estimatedInputTokens>n.run.maxInputTokens||t.estimatedOutputTokens>n.run.maxOutputTokens?{kind:"blocked",reasonCode:"run-token-budget-exceeded",message:"The conservative request token estimate exceeds the remaining run cap."}:t.estimatedDollars>n.run.maxDollars?{kind:"blocked",reasonCode:"run-dollar-budget-exceeded",message:"The conservative request cost estimate exceeds the remaining run cap."}:{kind:"within-budget"}}function qs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function to(t){return typeof t=="string"&&t.trim().length>0?t:void 0}function no(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0?t:void 0}function bw(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function xw(t){if(t!=null)return no(t)??null}function Ir(t){if(typeof t!="string"||t.trim().length===0)return;let n=Number(t);return Number.isFinite(n)&&n>=0?t:void 0}function A1(t){let n=qs(t);if(n===void 0)return;let e=n.prompt===void 0?void 0:Ir(n.prompt),r=n.completion===void 0?void 0:Ir(n.completion),s=n.request===void 0?void 0:Ir(n.request),i=n.min_prompt_tokens===void 0?void 0:no(n.min_prompt_tokens),a=n.utc_start===void 0?void 0:bw(n.utc_start),o=n.utc_end===void 0?void 0:bw(n.utc_end),d=n.utc_days===void 0?void 0:Array.isArray(n.utc_days)?n.utc_days.map(no):void 0;if(!(n.prompt!==void 0&&e===void 0||n.completion!==void 0&&r===void 0||n.request!==void 0&&s===void 0||n.min_prompt_tokens!==void 0&&i===void 0||n.utc_start!==void 0&&a===void 0||n.utc_end!==void 0&&o===void 0||n.utc_days!==void 0&&(d===void 0||d.includes(void 0))))return{...e===void 0?{}:{prompt:e},...r===void 0?{}:{completion:r},...s===void 0?{}:{request:s},...i===void 0?{}:{minPromptTokens:i},...a===void 0?{}:{utcStart:a},...o===void 0?{}:{utcEnd:o},...d===void 0?{}:{utcDays:d}}}function T1(t){let n=qs(t);if(n===void 0)return;let e=Ir(n.prompt),r=Ir(n.completion),s=n.request===void 0?void 0:Ir(n.request);if(e===void 0||r===void 0||n.request!==void 0&&s===void 0)return;let i=n.overrides;if(i!==void 0&&!Array.isArray(i))return;let a=(i??[]).map(A1);if(!a.includes(void 0))return{prompt:e,completion:r,...s===void 0?{}:{request:s},overrides:a}}function vw(t){return t.trim().toLocaleLowerCase("en-US")}function kw(t){return to(t.tag)}function eo(t,n){return{kind:"unsupported",code:t,message:n}}function fu(t,n){let e=qs(t),s=qs(e?.data)?.endpoints;if(!Array.isArray(s))return{kind:"failed",code:"invalid-metadata",message:"Endpoint metadata was malformed."};let i=vw(n.providerSlug),a=s.map(qs).filter(g=>g!==void 0).filter(g=>{let y=kw(g);return y!==void 0&&vw(y)===i});if(a.length===0)return eo("provider-unavailable",`The exact provider ${n.providerSlug} does not serve ${n.modelId}.`);if(a.length!==1)return eo("provider-ambiguous",`The provider route ${n.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=to(o.model_id);if(d!==n.modelId)return eo("model-mismatch","OpenRouter metadata did not preserve the configured exact model identifier.");let c=Array.isArray(o.supported_parameters)?o.supported_parameters.map(to):[];if(c.includes(void 0))return{kind:"failed",code:"invalid-metadata",message:"Supported parameters were malformed."};if(!c.includes("structured_outputs"))return eo("structured-output-unsupported","The exact endpoint does not advertise structured output support.");let l=no(o.context_length),u=xw(o.max_prompt_tokens),p=xw(o.max_completion_tokens),f=T1(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:to(o.provider_name)??n.providerSlug,providerSlug:kw(o)??n.providerSlug,modelId:d,contextLength:l,...u===void 0?{}:{maxPromptTokens:u},...p===void 0?{}:{maxCompletionTokens:p},supportedParameters:c,pricing:f,status:h}}}function P1(t){return{...t.prompt===void 0?{}:{prompt:t.prompt},...t.completion===void 0?{}:{completion:t.completion},...t.request===void 0?{}:{request:t.request},...t.minPromptTokens===void 0?{}:{minPromptTokens:t.minPromptTokens},...t.utcStart===void 0?{}:{utcStart:String(t.utcStart)},...t.utcEnd===void 0?{}:{utcEnd:String(t.utcEnd)},...t.utcDays===void 0?{}:{utcDays:t.utcDays}}}function hu(t){let n={prompt:t.pricing.prompt,completion:t.pricing.completion,...t.pricing.request===void 0?{}:{request:t.pricing.request},overrides:t.pricing.overrides.map(P1)};return{modelId:t.modelId,providerId:t.providerSlug,providerName:t.providerName,contextLength:t.contextLength,...t.maxPromptTokens===void 0?{}:{maxPromptTokens:t.maxPromptTokens},...t.maxCompletionTokens===void 0?{}:{maxCompletionTokens:t.maxCompletionTokens},supportedParameters:t.supportedParameters,status:t.status,pricing:n}}var S1="https://openrouter.ai",E1=`${S1}/api/v1`,C1=3e4,N1=4*1024*1024;function Lt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Gs(t){if(t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError"))return"timed out";let n=t?.cause;return typeof n?.code=="string"?n.code:typeof n?.message=="string"?n.message:t instanceof Error?t.message:"unknown error"}function mu(t,n){return t!==void 0&&Number.isInteger(t)&&t>0?t:n}function O1(t){let n=t.split("/");if(!(n.length!==2||n.some(e=>e.length===0)))return n.map(encodeURIComponent).join("/")}function Rw(t){let n=t();return n===void 0||n.trim().length===0?void 0:n.trim()}async function Iw(t,n){let e=t.headers.get("content-length");if(e!==null){let d=Number(e);if(Number.isFinite(d)&&d>n)return{kind:"too-large"}}if(t.body===null)return{kind:"invalid-json"};let r=t.body.getReader(),s=[],i=0;try{for(;;){let d=await r.read();if(d.done)break;if(i+=d.value.byteLength,i>n)return await r.cancel(),{kind:"too-large"};s.push(d.value)}}finally{r.releaseLock()}let a=new Uint8Array(i),o=0;for(let d of s)a.set(d,o),o+=d.byteLength;try{return{kind:"parsed",value:JSON.parse(new TextDecoder().decode(a))}}catch{return{kind:"invalid-json"}}}function ro(t){if(!Lt(t)||!Lt(t.error))return;let n=t.error.code;return typeof n=="number"&&Number.isFinite(n)?n:void 0}function yu(t,n){let e=Lt(n)&&Lt(n.error)?n.error:void 0,r=Lt(e?.metadata)?e.metadata:void 0,s=[e?.message,r?.raw].filter(a=>typeof a=="string"&&a.trim()!=="").map(a=>a.replace(/\s+/g," ").trim()).join(": "),i=s.length>300?`${s.slice(0,299)}\u2026`:s;return`OpenRouter completion request failed (HTTP ${t})${i===""?".":`: ${i}`}`}function gu(t){return Lt(t)&&Lt(t.error)&&t.choices===void 0}function Aw(t){return{Accept:"application/json",Authorization:`Bearer ${t}`}}function wu(t){if(t.body.model!==t.route.modelId)return"The completion body does not preserve the configured exact model.";if("models"in t.body)return"Model fallback arrays are forbidden.";if("tools"in t.body||"tool_choice"in t.body)return"Model tools are forbidden for bounded diagnosis.";if(t.body.stream===!0)return"Streaming is not supported by bounded diagnosis.";let n=Lt(t.body.provider)?t.body.provider:void 0,e=Array.isArray(n?.only)?n.only:void 0;if(e?.length!==1||e[0]!==t.route.providerSlug||n?.allow_fallbacks!==!1||n.require_parameters!==!0)return"The completion body does not preserve the exact no-fallback provider route.";if((Lt(t.body.response_format)?t.body.response_format:void 0)?.type!=="json_schema")return"The completion body does not require JSON Schema output."}var $n=class{#e;#n;#t;#r;#s;#i;#a;#o;constructor(n={}){this.#e=n.fetch??fetch,this.#n=mu(n.timeoutMs,C1),this.#t=mu(n.maxResponseBytes,N1),this.#r=n.apiRoot??E1,this.#s=n.readApiKey??(()=>process.env.OPENROUTER_API_KEY),this.#i=n.credentialName??"OPENROUTER_API_KEY",this.#a=n.extraHeaders??(()=>({})),this.#o=n.onCompletionBody??(()=>{})}async preflight(n){let e=await this.#d(n);return e.kind==="failed"&&(e.code==="network-error"||e.code==="timeout")?this.#d(n):e}async#d(n){let e=O1(n.modelId);if(e===void 0||n.providerSlug.trim().length===0)return{kind:"failed",code:"invalid-request",message:"An exact model and provider route are required."};let r=Rw(this.#s);if(r===void 0)return{kind:"failed",code:"credential-unavailable",message:`${this.#i} is not configured.`};let s=new AbortController,i=setTimeout(()=>s.abort(),this.#n);try{let a=await this.#e(`${this.#r}/models/${e}/endpoints`,{method:"GET",headers:{...this.#a(),...Aw(r)},redirect:"error",signal:s.signal}),o=await Iw(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?fu(o.value,n):{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 (${Gs(a)}).`}}finally{clearTimeout(i)}}async complete(n){let e=performance.now(),r=wu(n);if(r!==void 0)return{kind:"failed",code:"invalid-request",message:r,elapsedMs:0};let s=Rw(this.#s);if(s===void 0)return{kind:"failed",code:"credential-unavailable",message:`${this.#i} is not configured.`,elapsedMs:performance.now()-e};let i=mu(n.timeoutMs,this.#n),a=new AbortController,o=setTimeout(()=>a.abort(),i);try{let d=await this.#e(`${this.#r}/chat/completions`,{method:"POST",headers:{...this.#a(n.body),...Aw(s),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(n.body),redirect:"error",signal:a.signal}),c=await Iw(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||gu(c.value)){let u=ro(c.value),p=d.ok?u??502:d.status;return{kind:"failed",code:"http-error",message:yu(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 Dn={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},$1={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:Dn,contradictingEvidenceIds:Dn,missingEvidence:Dn,unresolvedAssumptions:Dn,nextAction:{type:"string",minLength:1},statement:{type:"string",minLength:1}}},bu={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:$1,maxItems:3},symptomIds:Dn,missingEvidence:Dn,recommendedNextAction:{type:"string",minLength:1},repairEligibility:{type:"string",enum:["eligible","ineligible","undetermined"]},ownershipEvidenceIds:Dn,packetHash:{type:"string",minLength:1}}},D1=["status","hypotheses","symptomIds","missingEvidence","recommendedNextAction","repairEligibility","ownershipEvidenceIds","packetHash"],M1=["hypothesisId","rank","causalCategory","probableOwner","evidenceGrade","supportingEvidenceIds","contradictingEvidenceIds","missingEvidence","unresolvedAssumptions","nextAction","statement"],L1=new Set(["conclusive","probable","inconclusive"]),_1=new Set(["strong","moderate","weak","insufficient"]),j1=new Set(["test-support","application","environment","undetermined"]),F1=new Set(["eligible","ineligible","undetermined"]);function Tr(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let n=Object.getPrototypeOf(t);return n===Object.prototype||n===null}function de(t,n,e,r){t.push({path:n,code:e,message:r})}function Pr(t,n,e,r){let s=new Set(n);for(let i of n)Object.hasOwn(t,i)||de(r,`${e}.${i}`,"missing-field","field is required");for(let i of Object.keys(t))s.has(i)||de(r,`${e}.${i}`,"unknown-field","field is not allowed")}function je(t,n,e){if(typeof t!="string"){de(e,n,"expected-string","expected a string");return}if(t.trim()===""){de(e,n,"empty-string","string must not be empty");return}return t}function Ar(t,n,e,r){let s=je(t,e,r);if(s!==void 0){if(!n.has(s)){de(r,e,"invalid-enum",`unsupported value ${JSON.stringify(s)}`);return}return s}}function tt(t,n,e){if(!Array.isArray(t)){de(e,n,"expected-array","expected an array");return}let r=[],s=new Set;return t.forEach((i,a)=>{let o=je(i,`${n}[${a}]`,e);if(o!==void 0){if(s.has(o)){de(e,`${n}[${a}]`,"duplicate-item",`duplicate value ${JSON.stringify(o)}`);return}s.add(o),r.push(o)}}),r}function B1(t,n,e){let r=`$.hypotheses[${n}]`;if(!Tr(t)){de(e,r,"expected-object","expected an object");return}Pr(t,M1,r,e);let s=je(t.hypothesisId,`${r}.hypothesisId`,e),i=t.rank;!Number.isInteger(i)||typeof i!="number"?de(e,`${r}.rank`,"expected-integer","rank must be an integer"):(i<1||i>3)&&de(e,`${r}.rank`,"invalid-rank","rank must be between 1 and 3");let a=je(t.causalCategory,`${r}.causalCategory`,e),o=Ar(t.probableOwner,j1,`${r}.probableOwner`,e),d=Ar(t.evidenceGrade,_1,`${r}.evidenceGrade`,e),c=tt(t.supportingEvidenceIds,`${r}.supportingEvidenceIds`,e),l=tt(t.contradictingEvidenceIds,`${r}.contradictingEvidenceIds`,e),u=tt(t.missingEvidence,`${r}.missingEvidence`,e),p=tt(t.unresolvedAssumptions,`${r}.unresolvedAssumptions`,e),f=je(t.nextAction,`${r}.nextAction`,e),h=je(t.statement,`${r}.statement`,e);if(c!==void 0&&l!==void 0){let m=new Set(l);for(let g of c)m.has(g)&&de(e,`${r}.contradictingEvidenceIds`,"citation-overlap",`${g} cannot both support and contradict a hypothesis`)}if(d!==void 0&&d!=="insufficient"&&c?.length===0&&de(e,`${r}.supportingEvidenceIds`,"support-required",`${d} evidence requires at least one supporting citation`),!(s===void 0||typeof i!="number"||!Number.isInteger(i)||i<1||i>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:s,rank:i,causalCategory:a,probableOwner:o,evidenceGrade:d,supportingEvidenceIds:c,contradictingEvidenceIds:l,missingEvidence:u,unresolvedAssumptions:p,nextAction:f,statement:h}}function so(t){let n=[];if(!Tr(t))return{kind:"invalid",issues:[{path:"$",code:"expected-object",message:"diagnosis must be an object"}]};Pr(t,D1,"$",n);let e=Ar(t.status,L1,"$.status",n),r=[];Array.isArray(t.hypotheses)?(t.hypotheses.length>3&&de(n,"$.hypotheses","too-many-items","at most three hypotheses are allowed"),t.hypotheses.forEach((p,f)=>{let h=B1(p,f,n);h!==void 0&&r.push(h)})):de(n,"$.hypotheses","expected-array","expected an array");let s=new Set;for(let p of r)s.has(p.hypothesisId)&&de(n,"$.hypotheses","duplicate-id",`duplicate hypothesis id ${JSON.stringify(p.hypothesisId)}`),s.add(p.hypothesisId);[...r].map(p=>p.rank).sort((p,f)=>p-f).forEach((p,f)=>{p!==f+1&&de(n,"$.hypotheses","invalid-rank","hypothesis ranks must be contiguous from 1")});let a=tt(t.symptomIds,"$.symptomIds",n),o=tt(t.missingEvidence,"$.missingEvidence",n),d=je(t.recommendedNextAction,"$.recommendedNextAction",n),c=Ar(t.repairEligibility,F1,"$.repairEligibility",n),l=tt(t.ownershipEvidenceIds,"$.ownershipEvidenceIds",n),u=je(t.packetHash,"$.packetHash",n);return n.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:n}:{kind:"valid",diagnosis:{status:e,hypotheses:r,symptomIds:a,missingEvidence:o,recommendedNextAction:d,repairEligibility:c,ownershipEvidenceIds:l,packetHash:u}}}function xt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function io(t){return typeof t=="string"&&t.trim().length>0?t:void 0}function Mn(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function V1(t){if(t===void 0)return{valid:!0};let n=xt(t);if(n===void 0)return{valid:!1};let e=Mn(n.prompt_tokens),r=Mn(n.completion_tokens),s=Mn(n.total_tokens);if(e===void 0||r===void 0||s===void 0)return{valid:!1};let i=xt(n.completion_tokens_details),a=xt(n.prompt_tokens_details),o=xt(n.cost_details),d=Mn(i?.reasoning_tokens),c=Mn(a?.cached_tokens),l=Mn(n.cost),u=Mn(o?.upstream_inference_cost);return s!==e+r||d!==void 0&&d>r||c!==void 0&&c>e||n.completion_tokens_details!==void 0&&i===void 0||n.prompt_tokens_details!==void 0&&a===void 0||n.cost_details!==void 0&&o===void 0||i?.reasoning_tokens!==void 0&&d===void 0||a?.cached_tokens!==void 0&&c===void 0||n.cost!==void 0&&l===void 0||o?.upstream_inference_cost!==void 0&&u===void 0?{valid:!1}:{valid:!0,usage:{promptTokens:e,completionTokens:r,totalTokens:s,...d===void 0?{}:{reasoningTokens:d},...c===void 0?{}:{cachedTokens:c},...l===void 0?{}:{cost:l},...u===void 0?{}:{upstreamInferenceCost:u}}}}function z1(t){let e=xt(t?.endpoints)?.available;if(!Array.isArray(e))return;let r=e.map(xt).filter(s=>s!==void 0&&s.selected===!0);return r.length!==1?null:io(r[0]?.provider)??null}function Tw(t,n,e){let r=xt(t),s=io(r?.model),i=r?.choices;if(r===void 0||s===void 0||!Array.isArray(i))return{kind:"malformed-response",message:"Completion response fields were malformed."};if(i.length!==1)return{kind:"malformed-response",message:"Completion response must contain exactly one choice."};let a=xt(i[0]),o=xt(a?.message),d=io(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 ${n} output.`};if(o.refusal!==void 0&&o.refusal!==null)return{kind:"provider-refusal",message:`The provider refused the ${n} request.`};if(d!=="stop")return{kind:"provider-refusal",message:`The provider did not complete the structured response (${d}).`};let c=io(o.content);if(c===void 0)return{kind:"malformed-response",message:`Structured ${n} content was missing.`};let l;try{l=JSON.parse(c)}catch{return{kind:"malformed-response",message:`Structured ${n} was not valid JSON.`}}let u=e(l);if(u.kind!=="valid")return{kind:"schema-invalid",message:u.message};let p=xt(r.openrouter_metadata),f=z1(p);if(f===null)return{kind:"malformed-response",message:"Router metadata did not identify exactly one selected provider."};let h=V1(r.usage);return h.valid?{kind:"parsed",value:{output:u.output,reportedModel:s,...f===void 0?{}:{reportedProvider:f},...h.usage===void 0?{}:{usage:h.usage},finishReason:d}}:{kind:"malformed-response",message:"Completion usage metadata was malformed."}}var H1=new Set(["$defs","$ref","additionalProperties","anyOf","const","definitions","description","enum","exclusiveMaximum","exclusiveMinimum","format","items","maxItems","maximum","minItems","minimum","multipleOf","pattern","properties","required","title","type"]),U1=new Set(["$defs","definitions","properties"]);function Pw(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ao(t){return Array.isArray(t)?t.map(ao):Pw(t)?Object.fromEntries(Object.entries(t).filter(([n])=>H1.has(n)).map(([n,e])=>[n,U1.has(n)&&Pw(e)?Object.fromEntries(Object.entries(e).map(([r,s])=>[r,ao(s)])):n==="enum"||n==="const"||n==="required"?e:ao(e)])):t}function Sw(t,n){return n.startsWith("openai/")?ao(t):t}var q1=`You diagnose test failures from one bounded, redacted evidence packet. The packet's framework field names the framework that ran the tests: an end-to-end framework (Playwright, Cypress, or WebdriverIO) or a test runner whose report KwikQA reads (Vitest, Jest, Mocha, pytest, JUnit, TestNG, Cucumber, or unknown); read errors, commands, and locators in that framework's terms.
186
188
  Deterministic observations are authoritative; your output contains causal hypotheses, not new facts.
187
189
  Cite only supplied evidence, artifact, and symptom IDs. State contradictions, missing evidence, and assumptions.
188
190
  Return no more than three ranked hypotheses and abstain with an inconclusive diagnosis when evidence cannot rank a cause.
189
191
  Owner and repair eligibility require positive cited evidence; absence of application evidence proves nothing.
190
192
  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.
191
- You have no tools, filesystem, shell, repository access, commands, or external lookup. Return only the required JSON object.`;function Mn(n,t){return[...n].sort((e,r)=>t(e).localeCompare(t(r)))}function o1(n){return{gitRootAvailable:n.workspace.gitRoot!==void 0,sourceHashes:n.sourceHashes}}function au(n){return n.replaceAll("\\","/").split("/").filter(Boolean).at(-1)??"<path>"}function cw(n){return n.type==="source-range"||n.type==="diff-hunk"?{...n,path:au(n.path)}:n.type==="report-field"?{...n,path:n.path.startsWith("/")?au(n.path):n.path}:n}function ou(n){return Mn(n,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 du(n){return Mn(n,t=>t.evidenceId).map(t=>({...t,locator:cw(t.locator)}))}function d1(n){return Mn(n.omissions,t=>t.omissionId).map(t=>({omissionId:t.omissionId,channel:t.channel,reason:t.reason,message:t.message,...t.locator===void 0?{}:{locator:au(t.locator)},...t.cap===void 0?{}:{cap:t.cap}}))}function c1(n,t,e){return{requestSchemaVersion:"1.0",promptVersion:"1.3",outputSchemaVersion:"1.0",runId:n.runId,packetHash:n.packetHash,framework:n.framework??"playwright",workspace:o1(n),artifacts:ou(n.artifacts),evidence:du(n.evidence),omissions:d1(n),accounting:Mn(n.accounting,r=>r.channel),symptoms:Mn(t.symptoms,r=>r.symptomId),unclassifiedAttemptIds:[...t.unclassifiedAttemptIds].sort(),clusters:Mn(e.clusters,r=>r.clusterId)}}function l1(n,t,e,r,s){let i=new Map(n.artifacts.map(o=>[o.artifactId,o.channel])),a=new Set(t.artifactIds);return{schemaVersion:"1.1",runId:n.runId,packetHash:n.packetHash,payloadHash:r,purpose:t.purpose,model:e,promptVersion:t.promptVersion,outputSchemaVersion:t.outputSchemaVersion,evidence:Mn(t.evidence,o=>o.evidenceId).map(o=>({evidenceId:o.evidenceId,artifactId:o.artifactId,channel:i.get(o.artifactId)??"report",locator:cw(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(n.artifacts.filter(o=>a.has(o.artifactId)).map(o=>o.channel))].sort(),serializedBytes:s}}function cu(n,t,e,r){let s={model:e.modelId,messages:[{role:"system",content:t.systemPrompt},{role:"user",content:pe(t.userContent)}],max_completion_tokens:r,...e.reasoningEffort===void 0?{}:{reasoning:{effort:e.reasoningEffort,exclude:!0}},response_format:{type:"json_schema",json_schema:{name:t.schemaName,strict:!0,schema:ow(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}}},i=pe(s),a=L(s);return{body:s,canonicalBody:i,payloadHash:a,manifest:l1(n,t,e,a,Buffer.byteLength(i,"utf8")),manifestHash:""}}function lu(n,t,e,r,s){return cu(n,{purpose:"diagnosis",schemaName:"kwikqa_diagnosis",schema:iu,systemPrompt:a1,promptVersion:"1.3",outputSchemaVersion:"1.0",userContent:c1(n,t,e),evidence:n.evidence,artifactIds:n.artifacts.map(i=>i.artifactId),symptomIds:t.symptoms.map(i=>i.symptomId),clusterIds:e.clusters.map(i=>i.clusterId),omissionIds:n.omissions.map(i=>i.omissionId),redactionIds:n.redactions.map(i=>i.redactionId)},r,s)}function uu(n,t){let e={...n.body,provider:{...n.body.provider,max_price:{prompt:t.promptDollarsPerToken*1e6,completion:t.completionDollarsPerToken*1e6,request:t.fixedRequestDollars}}},r=pe(e),s=L(e),i={...n.manifest,payloadHash:s,serializedBytes:Buffer.byteLength(r,"utf8")};return{body:e,canonicalBody:r,payloadHash:s,manifest:i,manifestHash:L(i)}}function u1(n){let{packetHash:t,...e}=n;return Yn(e)===t}function p1(n){if(!/^[^/\s]+\/[^/\s]+$/.test(n.modelId))return"An exact non-empty author/model identifier is required.";if(n.providerId.trim().length===0)return"An exact provider route is required."}function ut(n,t,e,r={}){return Jl({runId:n.packet.runId,createdAt:n.packet.createdAt,workspace:n.packet.workspace,sourceHashes:n.packet.sourceHashes,packetHash:n.packet.packetHash,model:n.model,caps:n.caps,recordedAt:t,outcome:e,request:n.request,extra:r})}function lt(n,t,e,r,s,i={}){return{kind:e,reasonCode:r,message:s,audit:ut(n,t,qe(e,r,s),i)}}function f1(n,t){if(n.kind==="available")return{kind:"supported",endpoint:eu(n.endpoint),checkedAt:t};let e=n.code==="structured-output-unsupported"?"schema-capability-unsupported":n.code==="provider-unavailable"||n.code==="model-mismatch"?"model-or-provider-mismatch":n.code==="credential-unavailable"?"credential-unavailable":"preflight-failed";return{kind:n.kind==="failed"?"failed":n.kind,reasonCode:e,message:n.message,checkedAt:t}}async function ro(n){let{identity:t,recordedAt:e}=n,r=p1(t.model)??Yl(t.caps);if(r!==void 0)return lt(t,e,"blocked","invalid-configuration",r);if(!u1(t.packet))return lt(t,e,"blocked","invalid-provenance","The evidence packet contents do not match its packet hash.");if(n.provenanceError!==void 0)return lt(t,e,"blocked","invalid-provenance",n.provenanceError);let s=await n.transport.preflight({modelId:t.model.modelId,providerSlug:t.model.providerId}),i=f1(s,e);if(i.kind!=="supported")return lt(t,e,i.kind==="failed"?"failed":"blocked",i.reasonCode,i.message,{preflight:i});if(i.endpoint.maxCompletionTokens!==void 0&&t.caps.request.maxOutputTokens>i.endpoint.maxCompletionTokens)return lt(t,e,"blocked","context-limit-exceeded","Requested output cap exceeds the exact endpoint limit.",{preflight:i});if(t.model.reasoningEffort!==void 0&&t.model.reasoningEffort!=="none"&&!i.endpoint.supportedParameters.includes("reasoning"))return lt(t,e,"blocked","schema-capability-unsupported","The exact endpoint does not support the requested reasoning effort.",{preflight:i});let a=n.buildPayload(t.caps.request.maxOutputTokens),o=Ja(a.canonicalBody,t.caps.request.maxOutputTokens,i.endpoint.pricing);if(o===void 0)return lt(t,e,"blocked","pricing-unavailable","A conservative dollar estimate could not be derived from endpoint pricing.",{preflight:i});let d=uu(a,o),c=Ja(d.canonicalBody,t.caps.request.maxOutputTokens,i.endpoint.pricing);if(c===void 0)return lt(t,e,"blocked","estimate-unavailable","A conservative final request estimate could not be computed.",{preflight:i});if(c.estimatedInputTokens+c.estimatedOutputTokens>i.endpoint.contextLength||i.endpoint.maxPromptTokens!==void 0&&c.estimatedInputTokens>i.endpoint.maxPromptTokens)return lt(t,e,"blocked","context-limit-exceeded","The conservative request estimate exceeds the exact endpoint context limit.",{preflight:i,estimate:c});let l=Ql(c,t.caps);if(l.kind==="blocked")return lt(t,e,"blocked",l.reasonCode,l.message,{preflight:i,estimate:c});let u={manifest:d.manifest,manifestHash:d.manifestHash,endpoint:i.endpoint,estimate:c,caps:t.caps},p=Wa(u);return{kind:"ready",prepared:{preflight:i,preparedAt:e,payload:d,estimate:c,preview:Kl(u,p),authorizationBindingHash:p}}}function h1(n){return n.code==="credential-unavailable"?"credential-unavailable":"transport-failed"}async function so(n){let{identity:t,prepared:e,recordedAt:r}=n,s={payloadHash:e.payload.payloadHash,payloadManifestHash:e.payload.manifestHash,authorizationBindingHash:e.authorizationBindingHash,preflight:e.preflight,estimate:e.estimate},i=(f,h,m,g={})=>lt(t,r,f,h,m,{...s,...g}),a=Wa({manifest:e.payload.manifest,manifestHash:e.payload.manifestHash,endpoint:e.preflight.endpoint,estimate:e.estimate,caps:t.caps});if(pe(e.payload.body)!==e.payload.canonicalBody||L(e.payload.body)!==e.payload.payloadHash||e.payload.manifest.payloadHash!==e.payload.payloadHash||L(e.payload.manifest)!==e.payload.manifestHash||!n.inputsIntact||a!==e.authorizationBindingHash||!Wl(n.authorization,a))return i("blocked","authorization-mismatch","Authorization does not match the exact prepared request.");if(!n.authorizationStore.consume(n.authorization.authorizationId,e.authorizationBindingHash))return i("blocked","authorization-replayed","Authorization has already been consumed for this prepared request.");let d=await n.transport.complete({route:{modelId:t.model.modelId,providerSlug:t.model.providerId},body:e.payload.body}),c={mode:n.authorization.mode,authorizationId:n.authorization.authorizationId,authorizedAt:n.authorization.authorizedAt};if(d.kind==="failed")return i("failed",h1(d),d.message,{authorization:c,latencyMs:d.elapsedMs});let l=iw(d.body,n.label,n.validate);if(l.kind!=="parsed")return i("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 i("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 i("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")?i("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:{...s,reportedModel:l.value.reportedModel,reportedProvider:l.value.reportedProvider,providerProvenance:"reported",...u,latencyMs:d.elapsedMs,authorization:c}}}var m1={purpose:"diagnosis",promptVersion:"1.3",outputSchemaVersion:"1.0"};function lw(n){return n??new Date().toISOString()}function uw(n,t){return L({packet:n,symptoms:t})}function pw(n){return{packet:n.packet,model:n.model,caps:n.caps,request:m1}}async function io(n){let t=lw(n.now),e=n.symptoms.runId===n.packet.runId&&n.clusters.runId===n.packet.runId&&n.symptoms.packetHash===n.packet.packetHash,r=await ro({identity:pw(n),transport:n.transport,recordedAt:t,...e?{}:{provenanceError:"M2 and M3 inputs do not identify the same run and packet."},buildPayload:s=>lu(n.packet,n.symptoms,n.clusters,n.model,s)});return r.kind!=="ready"?{...r,kind:r.kind==="failed"?"failed":"blocked"}:{kind:"preview-ready",prepared:{packet:n.packet,symptoms:n.symptoms,clusters:n.clusters,model:n.model,caps:n.caps,...r.prepared,gradingInputHash:uw(n.packet,n.symptoms)}}}async function pu(n){let t=lw(n.now),e=n.prepared,r=pw(e),s=await so({identity:r,prepared:e,inputsIntact:uw(e.packet,e.symptoms)===e.gradingInputHash,authorization:n.authorization,authorizationStore:n.authorizationStore,transport:n.transport,recordedAt:t,label:"diagnosis",validate:d=>{let c=eo(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(s.kind!=="parsed")return s;let i=s.output,a=_s(i,e.packet,e.symptoms),o={...s.audit,grading:a};if(!a.passed){let d="Diagnosis failed deterministic local grading.";return{kind:"rejected",reasonCode:"citation-or-grading-invalid",message:d,audit:ut(r,t,qe("rejected","citation-or-grading-invalid",d),o)}}return i.status==="inconclusive"?{kind:"abstained",reasonCode:"insufficient-evidence",diagnosis:i,grading:a,audit:ut(r,t,qe("abstained","insufficient-evidence"),o)}:{kind:"diagnosed",diagnosis:i,grading:a,audit:ut(r,t,qe("diagnosed"),o)}}var fu=20,ao={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},fw=["targetEvidenceId","oldText","newText","rationale","evidenceIds","expectedEffect","latencyContractEvidenceIds","brittleLocatorEvidenceIds"],hw=["statement","preservedBehavior","evidenceIds"],mw=["status","acceptedHypothesisId","declineReason","intent","replacements","packetHash"],hu={type:"object",additionalProperties:!1,required:mw,properties:{status:{type:"string",enum:["proposed","declined"]},acceptedHypothesisId:{type:"string",minLength:1},declineReason:{type:"string"},intent:{type:"object",additionalProperties:!1,required:hw,properties:{statement:{type:"string"},preservedBehavior:{type:"string"},evidenceIds:ao}},replacements:{type:"array",maxItems:fu,items:{type:"object",additionalProperties:!1,required:fw,properties:{targetEvidenceId:{type:"string",minLength:1},oldText:{type:"string",minLength:1},newText:{type:"string"},rationale:{type:"string",minLength:1},evidenceIds:ao,expectedEffect:{type:"string",minLength:1},latencyContractEvidenceIds:ao,brittleLocatorEvidenceIds:ao}}},packetHash:{type:"string",minLength:1}}},y1=new Set(["proposed","declined"]);function oo(n,t,e){if(typeof n=="string")return n;de(e,t,"expected-string","expected a string")}function g1(n,t,e){let r=`$.replacements[${t}]`;if(!Rr(n)){de(e,r,"expected-object","replacement must be an object");return}Ir(n,fw,r,e);let s=je(n.targetEvidenceId,`${r}.targetEvidenceId`,e),i=je(n.oldText,`${r}.oldText`,e),a=oo(n.newText,`${r}.newText`,e),o=je(n.rationale,`${r}.rationale`,e),d=tt(n.evidenceIds,`${r}.evidenceIds`,e),c=je(n.expectedEffect,`${r}.expectedEffect`,e),l=tt(n.latencyContractEvidenceIds,`${r}.latencyContractEvidenceIds`,e),u=tt(n.brittleLocatorEvidenceIds,`${r}.brittleLocatorEvidenceIds`,e);if(d!==void 0&&d.length===0&&de(e,`${r}.evidenceIds`,"support-required","a replacement must cite evidence"),!(s===void 0||i===void 0||a===void 0||o===void 0||d===void 0||c===void 0||l===void 0||u===void 0))return{targetEvidenceId:s,oldText:i,newText:a,rationale:o,evidenceIds:d,expectedEffect:c,latencyContractEvidenceIds:l,brittleLocatorEvidenceIds:u}}function mu(n){let t=[];if(!Rr(n))return{kind:"invalid",issues:[{path:"$",code:"expected-object",message:"proposal must be an object"}]};Ir(n,mw,"$",t);let e=kr(n.status,y1,"$.status",t),r=je(n.acceptedHypothesisId,"$.acceptedHypothesisId",t),s=oo(n.declineReason,"$.declineReason",t),i=je(n.packetHash,"$.packetHash",t),a;if(!Rr(n.intent))de(t,"$.intent","expected-object","intent must be an object");else{Ir(n.intent,hw,"$.intent",t);let d=oo(n.intent.statement,"$.intent.statement",t),c=oo(n.intent.preservedBehavior,"$.intent.preservedBehavior",t),l=tt(n.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(n.replacements)?(n.replacements.length>fu&&de(t,"$.replacements","too-many-items","too many replacements"),n.replacements.forEach((d,c)=>{let l=g1(d,c,t);l!==void 0&&o.push(l)})):de(t,"$.replacements","expected-array","expected an array"),e==="proposed"&&a!==void 0&&(o.length===0&&Array.isArray(n.replacements)&&de(t,"$.replacements","support-required","a proposal needs a replacement"),a.statement.trim()===""&&de(t,"$.intent.statement","empty-string","a proposal must state its intent"),a.preservedBehavior.trim()===""&&de(t,"$.intent.preservedBehavior","empty-string","a proposal must state the preserved behavior"),a.evidenceIds.length===0&&de(t,"$.intent.evidenceIds","support-required","intent must cite evidence")),e==="declined"&&(s!==void 0&&s.trim()===""&&de(t,"$.declineReason","empty-string","a decline must give its reason"),Array.isArray(n.replacements)&&n.replacements.length>0&&de(t,"$.replacements","too-many-items","a decline must not propose edits")),t.length>0||e===void 0||r===void 0||s===void 0||a===void 0||i===void 0?{kind:"invalid",issues:t}:{kind:"valid",proposal:{status:e,acceptedHypothesisId:r,declineReason:s,intent:a,replacements:o,packetHash:i}}}var yw="1.0",co="1.1",lo="1.0",w1={purpose:"repair-proposal",promptVersion:co,outputSchemaVersion:lo},b1=`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.
193
+ You have no tools, filesystem, shell, repository access, commands, or external lookup. Return only the required JSON object.`;function Ln(t,n){return[...t].sort((e,r)=>n(e).localeCompare(n(r)))}function G1(t){return{gitRootAvailable:t.workspace.gitRoot!==void 0,sourceHashes:t.sourceHashes}}function xu(t){return t.replaceAll("\\","/").split("/").filter(Boolean).at(-1)??"<path>"}function Cw(t){return t.type==="source-range"||t.type==="diff-hunk"?{...t,path:xu(t.path)}:t.type==="report-field"?{...t,path:t.path.startsWith("/")?xu(t.path):t.path}:t}function vu(t){return Ln(t,n=>n.artifactId).map(n=>({artifactId:n.artifactId,channel:n.channel,availability:n.availability,...n.sha256===void 0?{}:{sha256:n.sha256},...n.format===void 0?{}:{format:n.format},...n.producerVersion===void 0?{}:{producerVersion:n.producerVersion},...n.attemptId===void 0?{}:{attemptId:n.attemptId},warnings:n.warnings}))}function ku(t){return Ln(t,n=>n.evidenceId).map(n=>({...n,locator:Cw(n.locator)}))}function K1(t){return Ln(t.omissions,n=>n.omissionId).map(n=>({omissionId:n.omissionId,channel:n.channel,reason:n.reason,message:n.message,...n.locator===void 0?{}:{locator:xu(n.locator)},...n.cap===void 0?{}:{cap:n.cap}}))}function W1(t,n,e){return{requestSchemaVersion:"1.0",promptVersion:"1.3",outputSchemaVersion:"1.0",runId:t.runId,packetHash:t.packetHash,framework:t.framework??"playwright",workspace:G1(t),artifacts:vu(t.artifacts),evidence:ku(t.evidence),omissions:K1(t),accounting:Ln(t.accounting,r=>r.channel),symptoms:Ln(n.symptoms,r=>r.symptomId),unclassifiedAttemptIds:[...n.unclassifiedAttemptIds].sort(),clusters:Ln(e.clusters,r=>r.clusterId)}}function J1(t,n,e,r,s){let i=new Map(t.artifacts.map(o=>[o.artifactId,o.channel])),a=new Set(n.artifactIds);return{schemaVersion:"1.1",runId:t.runId,packetHash:t.packetHash,payloadHash:r,purpose:n.purpose,model:e,promptVersion:n.promptVersion,outputSchemaVersion:n.outputSchemaVersion,evidence:Ln(n.evidence,o=>o.evidenceId).map(o=>({evidenceId:o.evidenceId,artifactId:o.artifactId,channel:i.get(o.artifactId)??"report",locator:Cw(o.locator),...o.logicalTestId===void 0?{}:{logicalTestId:o.logicalTestId},...o.attemptId===void 0?{}:{attemptId:o.attemptId},redactionIds:[...o.redactionIds].sort()})),artifactIds:[...n.artifactIds].sort(),symptomIds:[...n.symptomIds].sort(),clusterIds:[...n.clusterIds].sort(),omissionIds:[...n.omissionIds].sort(),redactionIds:[...n.redactionIds].sort(),channels:[...new Set(t.artifacts.filter(o=>a.has(o.artifactId)).map(o=>o.channel))].sort(),serializedBytes:s}}function Ru(t,n,e,r){let s={model:e.modelId,messages:[{role:"system",content:n.systemPrompt},{role:"user",content:pe(n.userContent)}],max_completion_tokens:r,...e.reasoningEffort===void 0?{}:{reasoning:{effort:e.reasoningEffort,exclude:!0}},response_format:{type:"json_schema",json_schema:{name:n.schemaName,strict:!0,schema:Sw(n.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}}},i=pe(s),a=L(s);return{body:s,canonicalBody:i,payloadHash:a,manifest:J1(t,n,e,a,Buffer.byteLength(i,"utf8")),manifestHash:""}}function Iu(t,n,e,r,s){return Ru(t,{purpose:"diagnosis",schemaName:"kwikqa_diagnosis",schema:bu,systemPrompt:q1,promptVersion:"1.3",outputSchemaVersion:"1.0",userContent:W1(t,n,e),evidence:t.evidence,artifactIds:t.artifacts.map(i=>i.artifactId),symptomIds:n.symptoms.map(i=>i.symptomId),clusterIds:e.clusters.map(i=>i.clusterId),omissionIds:t.omissions.map(i=>i.omissionId),redactionIds:t.redactions.map(i=>i.redactionId)},r,s)}function Au(t,n){let e={...t.body,provider:{...t.body.provider,max_price:{prompt:n.promptDollarsPerToken*1e6,completion:n.completionDollarsPerToken*1e6,request:n.fixedRequestDollars}}},r=pe(e),s=L(e),i={...t.manifest,payloadHash:s,serializedBytes:Buffer.byteLength(r,"utf8")};return{body:e,canonicalBody:r,payloadHash:s,manifest:i,manifestHash:L(i)}}function X1(t){let{packetHash:n,...e}=t;return nr(e)===n}function Y1(t){if(!/^[^/\s]+\/[^/\s]+$/.test(t.modelId))return"An exact non-empty author/model identifier is required.";if(t.providerId.trim().length===0)return"An exact provider route is required."}function pt(t,n,e,r={}){return cu({runId:t.packet.runId,createdAt:t.packet.createdAt,workspace:t.packet.workspace,sourceHashes:t.packet.sourceHashes,packetHash:t.packet.packetHash,model:t.model,caps:t.caps,recordedAt:n,outcome:e,request:t.request,extra:r})}function ut(t,n,e,r,s,i={}){return{kind:e,reasonCode:r,message:s,audit:pt(t,n,qe(e,r,s),i)}}function Q1(t,n){if(t.kind==="available")return{kind:"supported",endpoint:hu(t.endpoint),checkedAt:n};let e=t.code==="structured-output-unsupported"?"schema-capability-unsupported":t.code==="provider-unavailable"||t.code==="model-mismatch"?"model-or-provider-mismatch":t.code==="credential-unavailable"?"credential-unavailable":"preflight-failed";return{kind:t.kind==="failed"?"failed":t.kind,reasonCode:e,message:t.message,checkedAt:n}}async function oo(t){let{identity:n,recordedAt:e}=t,r=Y1(n.model)??uu(n.caps);if(r!==void 0)return ut(n,e,"blocked","invalid-configuration",r);if(!X1(n.packet))return ut(n,e,"blocked","invalid-provenance","The evidence packet contents do not match its packet hash.");if(t.provenanceError!==void 0)return ut(n,e,"blocked","invalid-provenance",t.provenanceError);let s=await t.transport.preflight({modelId:n.model.modelId,providerSlug:n.model.providerId}),i=Q1(s,e);if(i.kind!=="supported")return ut(n,e,i.kind==="failed"?"failed":"blocked",i.reasonCode,i.message,{preflight:i});if(i.endpoint.maxCompletionTokens!==void 0&&n.caps.request.maxOutputTokens>i.endpoint.maxCompletionTokens)return ut(n,e,"blocked","context-limit-exceeded","Requested output cap exceeds the exact endpoint limit.",{preflight:i});if(n.model.reasoningEffort!==void 0&&n.model.reasoningEffort!=="none"&&!i.endpoint.supportedParameters.includes("reasoning"))return ut(n,e,"blocked","schema-capability-unsupported","The exact endpoint does not support the requested reasoning effort.",{preflight:i});let a=t.buildPayload(n.caps.request.maxOutputTokens),o=Za(a.canonicalBody,n.caps.request.maxOutputTokens,i.endpoint.pricing);if(o===void 0)return ut(n,e,"blocked","pricing-unavailable","A conservative dollar estimate could not be derived from endpoint pricing.",{preflight:i});let d=Au(a,o),c=Za(d.canonicalBody,n.caps.request.maxOutputTokens,i.endpoint.pricing);if(c===void 0)return ut(n,e,"blocked","estimate-unavailable","A conservative final request estimate could not be computed.",{preflight:i});if(c.estimatedInputTokens+c.estimatedOutputTokens>i.endpoint.contextLength||i.endpoint.maxPromptTokens!==void 0&&c.estimatedInputTokens>i.endpoint.maxPromptTokens)return ut(n,e,"blocked","context-limit-exceeded","The conservative request estimate exceeds the exact endpoint context limit.",{preflight:i,estimate:c});let l=pu(c,n.caps);if(l.kind==="blocked")return ut(n,e,"blocked",l.reasonCode,l.message,{preflight:i,estimate:c});let u={manifest:d.manifest,manifestHash:d.manifestHash,endpoint:i.endpoint,estimate:c,caps:n.caps},p=Qa(u);return{kind:"ready",prepared:{preflight:i,preparedAt:e,payload:d,estimate:c,preview:ou(u,p),authorizationBindingHash:p}}}function Z1(t){return t.code==="credential-unavailable"?"credential-unavailable":"transport-failed"}async function co(t){let{identity:n,prepared:e,recordedAt:r}=t,s={payloadHash:e.payload.payloadHash,payloadManifestHash:e.payload.manifestHash,authorizationBindingHash:e.authorizationBindingHash,preflight:e.preflight,estimate:e.estimate},i=(f,h,m,g={})=>ut(n,r,f,h,m,{...s,...g}),a=Qa({manifest:e.payload.manifest,manifestHash:e.payload.manifestHash,endpoint:e.preflight.endpoint,estimate:e.estimate,caps:n.caps});if(pe(e.payload.body)!==e.payload.canonicalBody||L(e.payload.body)!==e.payload.payloadHash||e.payload.manifest.payloadHash!==e.payload.payloadHash||L(e.payload.manifest)!==e.payload.manifestHash||!t.inputsIntact||a!==e.authorizationBindingHash||!du(t.authorization,a))return i("blocked","authorization-mismatch","Authorization does not match the exact prepared request.");if(!t.authorizationStore.consume(t.authorization.authorizationId,e.authorizationBindingHash))return i("blocked","authorization-replayed","Authorization has already been consumed for this prepared request.");let d=await t.transport.complete({route:{modelId:n.model.modelId,providerSlug:n.model.providerId},body:e.payload.body}),c={mode:t.authorization.mode,authorizationId:t.authorization.authorizationId,authorizedAt:t.authorization.authorizedAt};if(d.kind==="failed")return i("failed",Z1(d),d.message,{authorization:c,latencyMs:d.elapsedMs});let l=Tw(d.body,t.label,t.validate);if(l.kind!=="parsed")return i("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!==n.model.modelId)return i("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 i("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!==n.model.providerId.toLocaleLowerCase("en-US")&&p!==e.preflight.endpoint.providerName?.toLocaleLowerCase("en-US")?i("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:{...s,reportedModel:l.value.reportedModel,reportedProvider:l.value.reportedProvider,providerProvenance:"reported",...u,latencyMs:d.elapsedMs,authorization:c}}}var eN={purpose:"diagnosis",promptVersion:"1.3",outputSchemaVersion:"1.0"};function Nw(t){return t??new Date().toISOString()}function Ow(t,n){return L({packet:t,symptoms:n})}function $w(t){return{packet:t.packet,model:t.model,caps:t.caps,request:eN}}async function lo(t){let n=Nw(t.now),e=t.symptoms.runId===t.packet.runId&&t.clusters.runId===t.packet.runId&&t.symptoms.packetHash===t.packet.packetHash,r=await oo({identity:$w(t),transport:t.transport,recordedAt:n,...e?{}:{provenanceError:"M2 and M3 inputs do not identify the same run and packet."},buildPayload:s=>Iu(t.packet,t.symptoms,t.clusters,t.model,s)});return r.kind!=="ready"?{...r,kind:r.kind==="failed"?"failed":"blocked"}:{kind:"preview-ready",prepared:{packet:t.packet,symptoms:t.symptoms,clusters:t.clusters,model:t.model,caps:t.caps,...r.prepared,gradingInputHash:Ow(t.packet,t.symptoms)}}}async function Tu(t){let n=Nw(t.now),e=t.prepared,r=$w(e),s=await co({identity:r,prepared:e,inputsIntact:Ow(e.packet,e.symptoms)===e.gradingInputHash,authorization:t.authorization,authorizationStore:t.authorizationStore,transport:t.transport,recordedAt:n,label:"diagnosis",validate:d=>{let c=so(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(s.kind!=="parsed")return s;let i=s.output,a=Rs(i,e.packet,e.symptoms),o={...s.audit,grading:a};if(!a.passed){let d="Diagnosis failed deterministic local grading.";return{kind:"rejected",reasonCode:"citation-or-grading-invalid",message:d,audit:pt(r,n,qe("rejected","citation-or-grading-invalid",d),o)}}return i.status==="inconclusive"?{kind:"abstained",reasonCode:"insufficient-evidence",diagnosis:i,grading:a,audit:pt(r,n,qe("abstained","insufficient-evidence"),o)}:{kind:"diagnosed",diagnosis:i,grading:a,audit:pt(r,n,qe("diagnosed"),o)}}var Pu=20,uo={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Dw=["targetEvidenceId","oldText","newText","rationale","evidenceIds","expectedEffect","latencyContractEvidenceIds","brittleLocatorEvidenceIds"],Mw=["statement","preservedBehavior","evidenceIds"],Lw=["status","acceptedHypothesisId","declineReason","intent","replacements","packetHash"],Su={type:"object",additionalProperties:!1,required:Lw,properties:{status:{type:"string",enum:["proposed","declined"]},acceptedHypothesisId:{type:"string",minLength:1},declineReason:{type:"string"},intent:{type:"object",additionalProperties:!1,required:Mw,properties:{statement:{type:"string"},preservedBehavior:{type:"string"},evidenceIds:uo}},replacements:{type:"array",maxItems:Pu,items:{type:"object",additionalProperties:!1,required:Dw,properties:{targetEvidenceId:{type:"string",minLength:1},oldText:{type:"string",minLength:1},newText:{type:"string"},rationale:{type:"string",minLength:1},evidenceIds:uo,expectedEffect:{type:"string",minLength:1},latencyContractEvidenceIds:uo,brittleLocatorEvidenceIds:uo}}},packetHash:{type:"string",minLength:1}}},tN=new Set(["proposed","declined"]);function po(t,n,e){if(typeof t=="string")return t;de(e,n,"expected-string","expected a string")}function nN(t,n,e){let r=`$.replacements[${n}]`;if(!Tr(t)){de(e,r,"expected-object","replacement must be an object");return}Pr(t,Dw,r,e);let s=je(t.targetEvidenceId,`${r}.targetEvidenceId`,e),i=je(t.oldText,`${r}.oldText`,e),a=po(t.newText,`${r}.newText`,e),o=je(t.rationale,`${r}.rationale`,e),d=tt(t.evidenceIds,`${r}.evidenceIds`,e),c=je(t.expectedEffect,`${r}.expectedEffect`,e),l=tt(t.latencyContractEvidenceIds,`${r}.latencyContractEvidenceIds`,e),u=tt(t.brittleLocatorEvidenceIds,`${r}.brittleLocatorEvidenceIds`,e);if(d!==void 0&&d.length===0&&de(e,`${r}.evidenceIds`,"support-required","a replacement must cite evidence"),!(s===void 0||i===void 0||a===void 0||o===void 0||d===void 0||c===void 0||l===void 0||u===void 0))return{targetEvidenceId:s,oldText:i,newText:a,rationale:o,evidenceIds:d,expectedEffect:c,latencyContractEvidenceIds:l,brittleLocatorEvidenceIds:u}}function Eu(t){let n=[];if(!Tr(t))return{kind:"invalid",issues:[{path:"$",code:"expected-object",message:"proposal must be an object"}]};Pr(t,Lw,"$",n);let e=Ar(t.status,tN,"$.status",n),r=je(t.acceptedHypothesisId,"$.acceptedHypothesisId",n),s=po(t.declineReason,"$.declineReason",n),i=je(t.packetHash,"$.packetHash",n),a;if(!Tr(t.intent))de(n,"$.intent","expected-object","intent must be an object");else{Pr(t.intent,Mw,"$.intent",n);let d=po(t.intent.statement,"$.intent.statement",n),c=po(t.intent.preservedBehavior,"$.intent.preservedBehavior",n),l=tt(t.intent.evidenceIds,"$.intent.evidenceIds",n);d!==void 0&&c!==void 0&&l!==void 0&&(a={statement:d,preservedBehavior:c,evidenceIds:l})}let o=[];return Array.isArray(t.replacements)?(t.replacements.length>Pu&&de(n,"$.replacements","too-many-items","too many replacements"),t.replacements.forEach((d,c)=>{let l=nN(d,c,n);l!==void 0&&o.push(l)})):de(n,"$.replacements","expected-array","expected an array"),e==="proposed"&&a!==void 0&&(o.length===0&&Array.isArray(t.replacements)&&de(n,"$.replacements","support-required","a proposal needs a replacement"),a.statement.trim()===""&&de(n,"$.intent.statement","empty-string","a proposal must state its intent"),a.preservedBehavior.trim()===""&&de(n,"$.intent.preservedBehavior","empty-string","a proposal must state the preserved behavior"),a.evidenceIds.length===0&&de(n,"$.intent.evidenceIds","support-required","intent must cite evidence")),e==="declined"&&(s!==void 0&&s.trim()===""&&de(n,"$.declineReason","empty-string","a decline must give its reason"),Array.isArray(t.replacements)&&t.replacements.length>0&&de(n,"$.replacements","too-many-items","a decline must not propose edits")),n.length>0||e===void 0||r===void 0||s===void 0||a===void 0||i===void 0?{kind:"invalid",issues:n}:{kind:"valid",proposal:{status:e,acceptedHypothesisId:r,declineReason:s,intent:a,replacements:o,packetHash:i}}}var _w="1.0",fo="1.1",ho="1.0",rN={purpose:"repair-proposal",promptVersion:fo,outputSchemaVersion:ho},sN=`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.
192
194
  Edit only source excerpts listed in targetEvidenceIds. Each oldText must be copied exactly from that excerpt's text and identify one place to change.
193
195
  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.
194
196
  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.
195
197
  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.
196
198
  Stay within the file and line budget. If no edit can repair the accepted cause while preserving intent, decline and explain why.
197
- You have no tools, filesystem, shell, repository access, commands, or external lookup. Return only the required JSON object.`;function gw(n){return n??new Date().toISOString()}function ww(n){return{packet:n.packet,model:n.model,caps:n.caps,request:w1}}function x1(n){return n.locator.type==="source-range"?n.locator.path:void 0}function v1(n){let{packet:t,diagnosis:e,grading:r}=n;if(!r.passed||r.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 s=e.hypotheses.find(i=>i.hypothesisId===n.hypothesisId);return s===void 0||s.rank!==1?{message:"Only the rank-1 hypothesis of a graded diagnosis can be repaired."}:s.probableOwner!=="test-support"?{message:"The accepted hypothesis is not owned by test support."}:s.evidenceGrade!=="strong"&&s.evidenceGrade!=="moderate"||e.ownershipEvidenceIds.length===0?{message:"Test-side ownership is not supported by cited positive evidence."}:{hypothesis:s}}function bw(n){return L({packet:n.packet,diagnosis:n.diagnosis,hypothesisId:n.hypothesisId,targetEvidenceIds:n.targetEvidenceIds,budgets:n.budgets})}async function yu(n){let t=gw(n.now),e=ww(n),r=v1(n);if("message"in r)return{kind:"blocked",reasonCode:"repair-not-eligible",message:r.message,audit:ut(e,t,qe("blocked","repair-not-eligible",r.message))};let{packet:s,diagnosis:i}=n,a=new Set(n.editablePaths),o=new Set([...r.hypothesis.supportingEvidenceIds,...r.hypothesis.contradictingEvidenceIds,...i.ownershipEvidenceIds]),d=s.evidence.filter(g=>o.has(g.evidenceId)||g.kind==="source-range"),l=d.filter(g=>{let y=x1(g);return y!==void 0&&a.has(y)}).map(g=>g.evidenceId).sort();if(l.length===0){let g="No source excerpt in the evidence packet is an authorized repair target.";return{kind:"blocked",reasonCode:"repair-not-eligible",message:g,audit:ut(e,t,qe("blocked","repair-not-eligible",g))}}let u=new Set(d.map(g=>g.artifactId)),p=s.artifacts.filter(g=>u.has(g.artifactId)),f=[...new Set(d.flatMap(g=>g.redactionIds))],h=await ro({identity:e,transport:n.transport,recordedAt:t,buildPayload:g=>cu(s,{purpose:"repair-proposal",schemaName:"kwikqa_repair_proposal",schema:hu,systemPrompt:b1,promptVersion:co,outputSchemaVersion:lo,userContent:{requestSchemaVersion:yw,promptVersion:co,outputSchemaVersion:lo,runId:s.runId,packetHash:s.packetHash,framework:s.framework??"playwright",acceptedHypothesis:r.hypothesis,diagnosis:{status:i.status,symptomIds:i.symptomIds,ownershipEvidenceIds:i.ownershipEvidenceIds,recommendedNextAction:i.recommendedNextAction},budgets:n.budgets,targetEvidenceIds:l,artifacts:ou(p),evidence:du(d)},evidence:d,artifactIds:[...u],symptomIds:i.symptomIds,clusterIds:[],omissionIds:[],redactionIds:f},n.model,g)});if(h.kind!=="ready")return{...h,kind:h.kind==="failed"?"failed":"blocked"};let m={packet:s,diagnosis:i,hypothesisId:n.hypothesisId,targetEvidenceIds:l,budgets:n.budgets};return{kind:"preview-ready",prepared:{...h.prepared,...m,includedEvidenceIds:d.map(g=>g.evidenceId).sort(),model:n.model,caps:n.caps,inputHash:bw(m)}}}function k1(n){let t=n.observation.indexOf(`
198
- `);return t===-1?"":n.observation.slice(t+1)}function R1(n,t){let e=[],r=new Set(n.includedEvidenceIds),s=new Set(n.targetEvidenceIds),i=new Map(n.packet.evidence.map(d=>[d.evidenceId,d])),a=(d,c)=>{for(let l of d)r.has(l)||e.push(`${c} cites evidence that was not supplied: ${l}`)};t.packetHash!==n.packet.packetHash&&e.push("The proposal names a different evidence packet."),t.acceptedHypothesisId!==n.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=i.get(d.targetEvidenceId);if(u===void 0||!s.has(d.targetEvidenceId)||u.locator.type!=="source-range"){e.push(`${l} targets an excerpt that is not an authorized repair target.`);return}if(!k1(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 gu(n){let t=gw(n.now),e=n.prepared,r=ww(e),s=await so({identity:r,prepared:e,inputsIntact:bw(e)===e.inputHash,authorization:n.authorization,authorizationStore:n.authorizationStore,transport:n.transport,recordedAt:t,label:"repair proposal",validate:a=>{let o=mu(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(s.kind!=="parsed")return s;let i=R1(e,s.output);if("problems"in i){let a=`Repair proposal failed local checks: ${i.problems.join(" ")}`;return{kind:"rejected",reasonCode:"citation-or-grading-invalid",message:a,audit:ut(r,t,qe("rejected","citation-or-grading-invalid",a),s.audit)}}return s.output.status==="declined"?{kind:"declined",reasonCode:"model-declined-repair",message:s.output.declineReason,audit:ut(r,t,qe("declined","model-declined-repair",s.output.declineReason),s.audit)}:{kind:"proposed",draft:i.draft,audit:ut(r,t,qe("proposed"),s.audit)}}var xw=new Set(["spec","page-object","fixture","test-data","test-helper","playwright-config","framework-config"]),I1=new Set(["schemaVersion","editablePaths","generatedPaths","budgets"]),A1=new Set(["pattern","class"]),P1=new Set(["maxFiles","maxChangedLines"]);function wu(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0}function uo(n,t=!1){return n.length===0||n.includes("\0")||n.includes("\\")||n.startsWith("/")||/^[A-Za-z]:/.test(n)||n.split("/").some(r=>r===""||r==="."||r==="..")?!1:n!=="*"&&n!=="**"&&(t||!n.startsWith("**/"))}function S1(n){if(!(!Array.isArray(n)||n.some(t=>typeof t!="string")))return n}function vw(n,t){return Number.isInteger(n)&&typeof n=="number"&&n>0&&n<=t}function Ln(n){let t=wu(n);if(t===void 0)return{kind:"invalid",issues:["Configuration must be an object."]};let e=[];for(let o of Object.keys(t))I1.has(o)||e.push(`Unknown configuration field: ${o}.`);t.schemaVersion!=="1.0"&&e.push(`schemaVersion must be ${"1.0"}.`);let r=t.editablePaths,s=[];if(!Array.isArray(r)||r.length===0)e.push("editablePaths must contain at least one explicit rule.");else for(let[o,d]of r.entries()){let c=wu(d);if(c===void 0){e.push(`editablePaths[${o}] must be an object.`);continue}for(let l of Object.keys(c))A1.has(l)||e.push(`Unknown editablePaths[${o}] field: ${l}.`);(typeof c.pattern!="string"||!uo(c.pattern))&&e.push(`editablePaths[${o}].pattern is unsafe or overly broad.`),(typeof c.class!="string"||!xw.has(c.class))&&e.push(`editablePaths[${o}].class is invalid.`),typeof c.pattern=="string"&&uo(c.pattern)&&typeof c.class=="string"&&xw.has(c.class)&&s.push({pattern:c.pattern,class:c.class})}let i=S1(t.generatedPaths);(i===void 0||i.some(o=>!uo(o,!0)))&&e.push("generatedPaths must contain only safe repository-relative patterns.");let a=wu(t.budgets);if(a===void 0)e.push("budgets must be an object.");else{for(let o of Object.keys(a))P1.has(o)||e.push(`Unknown budgets field: ${o}.`);vw(a.maxFiles,3)||e.push(`budgets.maxFiles must be an integer from 1 to ${3}.`),vw(a.maxChangedLines,100)||e.push(`budgets.maxChangedLines must be an integer from 1 to ${100}.`)}return e.length>0||a===void 0||i===void 0?{kind:"invalid",issues:e}:{kind:"valid",config:{schemaVersion:"1.0",editablePaths:s,generatedPaths:i,budgets:{maxFiles:a.maxFiles,maxChangedLines:a.maxChangedLines}}}}var kw={schemaVersion:"1.0",editablePaths:[{pattern:"tests/**/*.ts",class:"spec"},{pattern:"tests/**/*.tsx",class:"spec"}],generatedPaths:["**/*.generated.ts","**/__snapshots__/**"],budgets:{maxFiles:3,maxChangedLines:100}};var T1=[{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"}]}],E1=[{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 bu(n){let t=n.repositoryPaths.map(a=>a.replaceAll("\\","/")).filter(a=>uo(a)),e=a=>t.some(o=>o.startsWith(a)),r=[];(e("tests/")||e("test/")&&!e("test/specs/"))&&r.push({pattern:"tests/**/*.ts",class:"spec"});for(let a of T1.slice(1))e(a.prefix)&&r.push(...a.rules);let s=[];r.length===0&&s.push("No standard test directory was found."),s.push("Shared support modules require explicit review before authorization.");for(let a of E1)e(a.prefix)&&s.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 i={...kw,editablePaths:r.length===0?kw.editablePaths:r};return{destination:"kwikqa.config.json",config:i,canonicalContents:`${pe(i)}
199
- `,reasons:r.map(a=>`Observed repository paths matching ${a.pattern}.`),ambiguities:s}}function Rw(n){let e=n.replaceAll(`\r
199
+ You have no tools, filesystem, shell, repository access, commands, or external lookup. Return only the required JSON object.`;function jw(t){return t??new Date().toISOString()}function Fw(t){return{packet:t.packet,model:t.model,caps:t.caps,request:rN}}function iN(t){return t.locator.type==="source-range"?t.locator.path:void 0}function aN(t){let{packet:n,diagnosis:e,grading:r}=t;if(!r.passed||r.packetHash!==n.packetHash||e.packetHash!==n.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 s=e.hypotheses.find(i=>i.hypothesisId===t.hypothesisId);return s===void 0||s.rank!==1?{message:"Only the rank-1 hypothesis of a graded diagnosis can be repaired."}:s.probableOwner!=="test-support"?{message:"The accepted hypothesis is not owned by test support."}:s.evidenceGrade!=="strong"&&s.evidenceGrade!=="moderate"||e.ownershipEvidenceIds.length===0?{message:"Test-side ownership is not supported by cited positive evidence."}:{hypothesis:s}}function Bw(t){return L({packet:t.packet,diagnosis:t.diagnosis,hypothesisId:t.hypothesisId,targetEvidenceIds:t.targetEvidenceIds,budgets:t.budgets})}async function Cu(t){let n=jw(t.now),e=Fw(t),r=aN(t);if("message"in r)return{kind:"blocked",reasonCode:"repair-not-eligible",message:r.message,audit:pt(e,n,qe("blocked","repair-not-eligible",r.message))};let{packet:s,diagnosis:i}=t,a=new Set(t.editablePaths),o=new Set([...r.hypothesis.supportingEvidenceIds,...r.hypothesis.contradictingEvidenceIds,...i.ownershipEvidenceIds]),d=s.evidence.filter(g=>o.has(g.evidenceId)||g.kind==="source-range"),l=d.filter(g=>{let y=iN(g);return y!==void 0&&a.has(y)}).map(g=>g.evidenceId).sort();if(l.length===0){let g="No source excerpt in the evidence packet is an authorized repair target.";return{kind:"blocked",reasonCode:"repair-not-eligible",message:g,audit:pt(e,n,qe("blocked","repair-not-eligible",g))}}let u=new Set(d.map(g=>g.artifactId)),p=s.artifacts.filter(g=>u.has(g.artifactId)),f=[...new Set(d.flatMap(g=>g.redactionIds))],h=await oo({identity:e,transport:t.transport,recordedAt:n,buildPayload:g=>Ru(s,{purpose:"repair-proposal",schemaName:"kwikqa_repair_proposal",schema:Su,systemPrompt:sN,promptVersion:fo,outputSchemaVersion:ho,userContent:{requestSchemaVersion:_w,promptVersion:fo,outputSchemaVersion:ho,runId:s.runId,packetHash:s.packetHash,framework:s.framework??"playwright",acceptedHypothesis:r.hypothesis,diagnosis:{status:i.status,symptomIds:i.symptomIds,ownershipEvidenceIds:i.ownershipEvidenceIds,recommendedNextAction:i.recommendedNextAction},budgets:t.budgets,targetEvidenceIds:l,artifacts:vu(p),evidence:ku(d)},evidence:d,artifactIds:[...u],symptomIds:i.symptomIds,clusterIds:[],omissionIds:[],redactionIds:f},t.model,g)});if(h.kind!=="ready")return{...h,kind:h.kind==="failed"?"failed":"blocked"};let m={packet:s,diagnosis:i,hypothesisId:t.hypothesisId,targetEvidenceIds:l,budgets:t.budgets};return{kind:"preview-ready",prepared:{...h.prepared,...m,includedEvidenceIds:d.map(g=>g.evidenceId).sort(),model:t.model,caps:t.caps,inputHash:Bw(m)}}}function oN(t){let n=t.observation.indexOf(`
200
+ `);return n===-1?"":t.observation.slice(n+1)}function dN(t,n){let e=[],r=new Set(t.includedEvidenceIds),s=new Set(t.targetEvidenceIds),i=new Map(t.packet.evidence.map(d=>[d.evidenceId,d])),a=(d,c)=>{for(let l of d)r.has(l)||e.push(`${c} cites evidence that was not supplied: ${l}`)};n.packetHash!==t.packet.packetHash&&e.push("The proposal names a different evidence packet."),n.acceptedHypothesisId!==t.hypothesisId&&e.push("The proposal names a different hypothesis than the accepted one."),a(n.intent.evidenceIds,"intent");let o=[];return n.replacements.forEach((d,c)=>{let l=`replacement ${c+1}`;a(d.evidenceIds,l),a(d.latencyContractEvidenceIds,l),a(d.brittleLocatorEvidenceIds,l);let u=i.get(d.targetEvidenceId);if(u===void 0||!s.has(d.targetEvidenceId)||u.locator.type!=="source-range"){e.push(`${l} targets an excerpt that is not an authorized repair target.`);return}if(!oN(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:n.acceptedHypothesisId,intent:n.intent,replacements:o}}}async function Nu(t){let n=jw(t.now),e=t.prepared,r=Fw(e),s=await co({identity:r,prepared:e,inputsIntact:Bw(e)===e.inputHash,authorization:t.authorization,authorizationStore:t.authorizationStore,transport:t.transport,recordedAt:n,label:"repair proposal",validate:a=>{let o=Eu(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(s.kind!=="parsed")return s;let i=dN(e,s.output);if("problems"in i){let a=`Repair proposal failed local checks: ${i.problems.join(" ")}`;return{kind:"rejected",reasonCode:"citation-or-grading-invalid",message:a,audit:pt(r,n,qe("rejected","citation-or-grading-invalid",a),s.audit)}}return s.output.status==="declined"?{kind:"declined",reasonCode:"model-declined-repair",message:s.output.declineReason,audit:pt(r,n,qe("declined","model-declined-repair",s.output.declineReason),s.audit)}:{kind:"proposed",draft:i.draft,audit:pt(r,n,qe("proposed"),s.audit)}}var Vw=new Set(["spec","page-object","fixture","test-data","test-helper","playwright-config","framework-config"]),cN=new Set(["schemaVersion","editablePaths","generatedPaths","budgets"]),lN=new Set(["pattern","class"]),uN=new Set(["maxFiles","maxChangedLines"]);function Ou(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function mo(t,n=!1){return t.length===0||t.includes("\0")||t.includes("\\")||t.startsWith("/")||/^[A-Za-z]:/.test(t)||t.split("/").some(r=>r===""||r==="."||r==="..")?!1:t!=="*"&&t!=="**"&&(n||!t.startsWith("**/"))}function pN(t){if(!(!Array.isArray(t)||t.some(n=>typeof n!="string")))return t}function zw(t,n){return Number.isInteger(t)&&typeof t=="number"&&t>0&&t<=n}function _n(t){let n=Ou(t);if(n===void 0)return{kind:"invalid",issues:["Configuration must be an object."]};let e=[];for(let o of Object.keys(n))cN.has(o)||e.push(`Unknown configuration field: ${o}.`);n.schemaVersion!=="1.0"&&e.push(`schemaVersion must be ${"1.0"}.`);let r=n.editablePaths,s=[];if(!Array.isArray(r)||r.length===0)e.push("editablePaths must contain at least one explicit rule.");else for(let[o,d]of r.entries()){let c=Ou(d);if(c===void 0){e.push(`editablePaths[${o}] must be an object.`);continue}for(let l of Object.keys(c))lN.has(l)||e.push(`Unknown editablePaths[${o}] field: ${l}.`);(typeof c.pattern!="string"||!mo(c.pattern))&&e.push(`editablePaths[${o}].pattern is unsafe or overly broad.`),(typeof c.class!="string"||!Vw.has(c.class))&&e.push(`editablePaths[${o}].class is invalid.`),typeof c.pattern=="string"&&mo(c.pattern)&&typeof c.class=="string"&&Vw.has(c.class)&&s.push({pattern:c.pattern,class:c.class})}let i=pN(n.generatedPaths);(i===void 0||i.some(o=>!mo(o,!0)))&&e.push("generatedPaths must contain only safe repository-relative patterns.");let a=Ou(n.budgets);if(a===void 0)e.push("budgets must be an object.");else{for(let o of Object.keys(a))uN.has(o)||e.push(`Unknown budgets field: ${o}.`);zw(a.maxFiles,3)||e.push(`budgets.maxFiles must be an integer from 1 to ${3}.`),zw(a.maxChangedLines,100)||e.push(`budgets.maxChangedLines must be an integer from 1 to ${100}.`)}return e.length>0||a===void 0||i===void 0?{kind:"invalid",issues:e}:{kind:"valid",config:{schemaVersion:"1.0",editablePaths:s,generatedPaths:i,budgets:{maxFiles:a.maxFiles,maxChangedLines:a.maxChangedLines}}}}var Hw={schemaVersion:"1.0",editablePaths:[{pattern:"tests/**/*.ts",class:"spec"},{pattern:"tests/**/*.tsx",class:"spec"}],generatedPaths:["**/*.generated.ts","**/__snapshots__/**"],budgets:{maxFiles:3,maxChangedLines:100}};var fN=[{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"}]}],hN=[{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 $u(t){let n=t.repositoryPaths.map(a=>a.replaceAll("\\","/")).filter(a=>mo(a)),e=a=>n.some(o=>o.startsWith(a)),r=[];(e("tests/")||e("test/")&&!e("test/specs/"))&&r.push({pattern:"tests/**/*.ts",class:"spec"});for(let a of fN.slice(1))e(a.prefix)&&r.push(...a.rules);let s=[];r.length===0&&s.push("No standard test directory was found."),s.push("Shared support modules require explicit review before authorization.");for(let a of hN)e(a.prefix)&&s.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 i={...Hw,editablePaths:r.length===0?Hw.editablePaths:r};return{destination:"kwikqa.config.json",config:i,canonicalContents:`${pe(i)}
201
+ `,reasons:r.map(a=>`Observed repository paths matching ${a.pattern}.`),ambiguities:s}}function Uw(t){let e=t.replaceAll(`\r
200
202
  `,`
201
203
  `).split(`
202
- `);return e.at(-1)===""?e.slice(0,-1):e}function C1(n,t){let e=Array.from({length:n.length+1},()=>Array(t.length+1).fill(0));for(let a=n.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]=n[a]===t[o]?(c[o+1]??0)+1:Math.max(c[o]??0,d[o+1]??0))}let r=[],s=0,i=0;for(;s<n.length||i<t.length;)s<n.length&&i<t.length&&n[s]===t[i]?(r.push({kind:"context",text:n[s]??""}),s+=1,i+=1):i<t.length&&(s>=n.length||(e[s]?.[i+1]??0)>=(e[s+1]?.[i]??0))?(r.push({kind:"add",text:t[i]??""}),i+=1):(r.push({kind:"delete",text:n[s]??""}),s+=1);return r}function N1(n){let t=Rw(n.source),e=Rw(n.result),r=C1(t,e),s=r.filter(a=>a.kind!=="context").length;return{text:`${[`diff --git a/${n.path} b/${n.path}`,`--- a/${n.path}`,`+++ b/${n.path}`,`@@ -1,${t.length} +1,${e.length} @@`,...r.map(a=>`${a.kind==="add"?"+":a.kind==="delete"?"-":" "}${a.text}`)].join(`
204
+ `);return e.at(-1)===""?e.slice(0,-1):e}function mN(t,n){let e=Array.from({length:t.length+1},()=>Array(n.length+1).fill(0));for(let a=t.length-1;a>=0;a-=1)for(let o=n.length-1;o>=0;o-=1){let d=e[a],c=e[a+1];d===void 0||c===void 0||(d[o]=t[a]===n[o]?(c[o+1]??0)+1:Math.max(c[o]??0,d[o+1]??0))}let r=[],s=0,i=0;for(;s<t.length||i<n.length;)s<t.length&&i<n.length&&t[s]===n[i]?(r.push({kind:"context",text:t[s]??""}),s+=1,i+=1):i<n.length&&(s>=t.length||(e[s]?.[i+1]??0)>=(e[s+1]?.[i]??0))?(r.push({kind:"add",text:n[i]??""}),i+=1):(r.push({kind:"delete",text:t[s]??""}),s+=1);return r}function yN(t){let n=Uw(t.source),e=Uw(t.result),r=mN(n,e),s=r.filter(a=>a.kind!=="context").length;return{text:`${[`diff --git a/${t.path} b/${t.path}`,`--- a/${t.path}`,`+++ b/${t.path}`,`@@ -1,${n.length} +1,${e.length} @@`,...r.map(a=>`${a.kind==="add"?"+":a.kind==="delete"?"-":" "}${a.text}`)].join(`
203
205
  `)}
204
- `,changed:s}}function xu(n){let t=[],e={},r=0;for(let s of[...n].sort((i,a)=>i.path.localeCompare(a.path))){let i=N1(s);t.push(i.text),e[s.path]=i.changed,r+=i.changed}return{text:t.join(""),changedFiles:n.length,changedLines:r,perFileChangedLines:e}}function Iw(n,t){return n.changedFiles<=t.maxFiles&&n.changedLines<=t.maxChangedLines?[]:[{code:"budget-exceeded",message:`Proposal changes ${n.changedFiles} files and ${n.changedLines} lines; configured limits are ${t.maxFiles} files and ${t.maxChangedLines} lines.`,manualRepairRecommended:!0}]}function Aw(n,t,e,r){let s=[];(t.packetHash!==n.packetHash||e.packetHash!==n.packetHash||!e.passed)&&s.push({code:"invalid-provenance",message:"Diagnosis and passing deterministic grading must match the evidence packet."});let i=[...t.hypotheses].sort((d,c)=>d.rank-c.rank)[0],a=new Set(n.evidence.map(d=>d.evidenceId)),o=new Set(t.ownershipEvidenceIds);return(t.repairEligibility!=="eligible"||i===void 0||i.probableOwner!=="test-support"||!new Set(["strong","moderate"]).has(i.evidenceGrade)||o.size===0||[...o].some(d=>!a.has(d)||!i.supportingEvidenceIds.includes(d)))&&s.push({code:"insufficient-ownership-evidence",message:"Repair requires a sufficiently graded test-support hypothesis with positive evidence."}),(r.statement.trim().length===0||r.preservedBehavior.trim().length===0||r.evidenceIds.length===0||r.evidenceIds.some(d=>!a.has(d)||!i?.supportingEvidenceIds.includes(d)))&&s.push({code:"intent-ambiguous",message:"Test intent and preserved behavior require valid positive evidence citations."}),s.length>0||i===void 0?{kind:"rejected",reasons:s}:{kind:"eligible",hypothesis:i}}var Pw=ri(Qr(),1),O1=/\.([cm]?[jt]sx?)$/i;function vu(n,t){let e=n.match(O1)?.[1]?.toLowerCase();if(e===void 0)return!1;let r=[];e.includes("t")&&r.push("typescript"),e.endsWith("x")&&r.push("jsx");try{return(0,Pw.parse)(t,{sourceType:"unambiguous",errorRecovery:!1,plugins:r}),!0}catch{return!1}}var $1=[{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 Us(n,t){return[...n.matchAll(t)].length}function Sw(n){return Us(n,/\bexpect\s*\(/g)+Us(n,/\bassert(?:\.|\s*\()/g)+Us(n,/\.(?:should|and)\s*\(/g)}function Tw(n){let t=new Map;for(let e of n.matchAll(/\.((?:(?:not|resolves|rejects)\.)*)(to[A-Z]\w*)\s*\(/g)){let r=`${e[1]??""}${e[2]??""}`;t.set(r,(t.get(r)??0)+1)}for(let e of n.matchAll(/\.(?:should|and)\s*\(\s*["'`]([\w.]+)["'`]/g)){let r=`should:${e[1]??""}`;t.set(r,(t.get(r)??0)+1)}return t}function D1(n,t){let e=Tw(t);return[...Tw(n)].filter(([r,s])=>(e.get(r)??0)<s).map(([r])=>r).sort()}function Ew(n){let t=[];for(let e of n){if(!vu(e.path,e.source)||!vu(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 r=D1(e.source,e.result);r.length>0&&t.push({code:"forbidden-edit",message:`The proposal removes, negates, or swaps assertion matchers: ${r.join(", ")}.`,path:e.path});for(let s of e.replacements){Sw(s.newText)<Sw(s.oldText)&&t.push({code:"forbidden-edit",message:"The proposal removes or weakens assertion coverage.",path:e.path});for(let i of $1){if(Us(s.newText,i.pattern)<=Us(s.oldText,i.pattern))continue;let a=i.exception==="latency"?s.latencyContractEvidenceIds??[]:i.exception==="locator"?s.brittleLocatorEvidenceIds??[]:[];i.exception!=="never"&&a.length>0||t.push({code:"forbidden-edit",message:i.message,path:e.path})}}}return t}var M1=/^(?:\.\/)?[A-Za-z0-9_./-]+$/,L1=/^[A-Z][A-Z0-9_]*$/,_1=/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTH)/i,j1=new Set(["focused","affected","static"]);function Cw(n){return n.length>0&&!n.includes("\0")&&!n.includes("\\")&&!n.startsWith("/")&&!/^[A-Za-z]:/.test(n)&&!n.split("/").some(t=>t===".."||t==="")}var F1=new Set(["page-object","fixture","test-data","test-helper","playwright-config","framework-config"]);function B1(n){let t=Object.entries(n.environment);return n.id.trim().length>0&&M1.test(n.executable)&&Cw(n.executable.replace(/^\.\//,""))&&!n.args.some(e=>e.includes("\0"))&&(n.workingDirectory==="."||Cw(n.workingDirectory))&&j1.has(n.scope)&&t.every(([e,r])=>L1.test(e)&&!_1.test(e)&&!r.includes("\0"))&&Number.isInteger(n.timeoutMs)&&n.timeoutMs>0&&n.reason.trim().length>0}function Nw(n,t){let e=t.some(i=>F1.has(i)),r=[...n.validation].sort((i,a)=>i.id.localeCompare(a.id));if(r.some(i=>!B1(i)))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 s=[];return r.length===0&&s.push("No deterministic validation steps were discovered."),e&&!r.some(i=>i.scope==="affected")&&s.push("Shared test-support edits require affected-test validation."),{plan:{status:s.length===0?"planned":"unresolved",steps:r,unresolvedReasons:s},reasons:[]}}var ku=1e6,Ru=1e3;function nt(n){return{kind:"rejected",reasons:n}}function V1(n){let{packetHash:t,...e}=n;return Yn(e)===t}function H1(n,t){let e=[];for(let r of n)[...r.evidenceIds,...r.latencyContractEvidenceIds??[],...r.brittleLocatorEvidenceIds??[]].some(i=>!t.has(i))&&e.push({code:"invalid-replacement",message:"Every replacement and policy exception must cite accepted supporting evidence.",path:r.path});return e}async function Iu(n){let t=Ln(n.config);if(t.kind!=="valid")return nt(t.issues.map(p=>({code:"invalid-config",message:p})));if(!V1(n.packet)||n.snapshot.workspaceRoot!==n.packet.workspace.root||n.packet.workspace.gitRoot!==void 0&&n.snapshot.gitRoot!==n.packet.workspace.gitRoot)return nt([{code:"invalid-provenance",message:"Packet integrity and repository snapshot identity must match."}]);let e=Aw(n.packet,n.diagnosis,n.grading,n.intent);if(e.kind!=="eligible")return nt(e.reasons);let r=n.maxSourceBytes??ku;if(!Number.isInteger(r)||r<=0||r>ku)return nt([{code:"invalid-provenance",message:`maxSourceBytes must be an integer from 1 to ${ku}.`}]);if(n.replacements.length===0)return nt([{code:"invalid-replacement",message:"Proposal has no replacements."}]);let s=H1(n.replacements,new Set(e.hypothesis.supportingEvidenceIds));if(s.length>0)return nt(s);let i=await Gy(t.config,n.snapshot,n.replacements,r);if(i.kind!=="authorized")return nt(i.reasons);if(i.targets.some(p=>p.source.split(/\r?\n/u).length>Ru||p.replacements.some(f=>f.newText.split(/\r?\n/u).length>Ru)))return nt([{code:"budget-exceeded",message:`M5 safely derives diffs only for targets and replacement text up to ${Ru} lines.`,manualRepairRecommended:!0}]);let a=Uy(i.targets);if(a.kind!=="applied")return nt(a.reasons);let o=Ew(a.targets);if(o.length>0)return nt(o);let d=xu(a.targets),c=Iw(d,t.config.budgets);if(c.length>0)return nt(c);let l=Nw(n.snapshot,a.targets.map(p=>p.class));if(l.reasons.length>0)return nt(l.reasons);let u={schemaVersion:"1.0",policyVersion:"1.0",runId:n.packet.runId,packetHash:n.packet.packetHash,acceptedHypothesisId:e.hypothesis.hypothesisId,intent:n.intent,budgets:t.config.budgets,changedFiles:d.changedFiles,changedLines:d.changedLines,replacements:n.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:L(d.text),validationPlan:l.plan};return{kind:"proposal-ready",proposal:{...u,proposalHash:L(u)}}}import{readFile as eN,realpath as Uw}from"node:fs/promises";import{join as tN,relative as nN,sep as rN}from"node:path";var z1=new Set(["failed","timedOut","interrupted"]);function U1(n){return n.status==="unexpected"||n.status==="flaky"}function Dw(n){return[...n.clusters].sort((t,e)=>e.logicalTestIds.length-t.logicalTestIds.length||t.clusterId.localeCompare(e.clusterId)).slice(0,6)}function q1(n){return n.attachments.reduce((t,e)=>t+(e.name==="trace"||e.contentType==="application/zip"?10:e.path===void 0?0:1),0)}function Mw(n,t){let e=new Set(t.logicalTestIds);return n.logicalTests.filter(s=>e.has(s.logicalTestId)).map(s=>{let i=s.attempts.filter(a=>z1.has(a.status));return{test:s,score:Math.max(0,...i.map(q1)),startedAt:i.map(a=>a.startTime).sort()[0]??""}}).sort((s,i)=>i.score-s.score||s.startedAt.localeCompare(i.startedAt)||s.test.logicalTestId.localeCompare(i.test.logicalTestId))[0]?.test}function Lw(n,t,e){let r=new Set(t.logicalTestIds);return{...n,logicalTests:n.logicalTests.map(s=>r.has(s.logicalTestId)?s.logicalTestId===e?s:{...s,attempts:s.attempts.map(i=>({...i,attachments:[]}))}:U1(s)?{...s,attempts:[]}:s)}}function _w(n,t,e){return{...e,runId:t.runId,clusters:[{...n,symptomIds:t.symptoms.filter(r=>r.logicalTestId!==void 0&&n.logicalTestIds.includes(r.logicalTestId)).map(r=>r.symptomId).sort()}]}}async function jw(n,t,e){let r=new Array(n.length),s=0,i=Array.from({length:Math.min(t,n.length)},async()=>{for(;s<n.length;){let a=s;s+=1,r[a]=await e(n[a])}});return await Promise.all(i),r}import{randomUUID as Fw}from"node:crypto";import{readdir as Bw,readFile as G1,realpath as K1}from"node:fs/promises";import{join as Ar,relative as W1,sep as J1}from"node:path";var Au=/^run_[a-f0-9]{24}$/,Pu=/^rec_[a-f0-9]{24}$/;function ho(){return`rec_${Fw().replaceAll("-","").slice(0,24)}`}function Pr(){return`auth_${Fw().replaceAll("-","").slice(0,24)}`}async function qs(n,t){if(!Au.test(t.runId)||!Pu.test(t.recordId))throw new Error("Run record identity is not path-safe.");let e=await He(n,[".kwikqa","runs",t.runId]),r=await He(n,[".kwikqa","runs",t.runId,"records"]),s=`${pe(t)}
205
- `,i=Ar(r,`${t.recordId}.json`);return await ye(i,s,{mode:384,replace:!1}),await ye(Ar(e,"result.json"),s,{mode:384,replace:!0}),W1(await K1(n),i).split(J1).join("/")}var X1=new Set(["analyze","fix","validate"]),Y1=["analysis","proposal","application","validation"];function Q1(n,t){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.schemaVersion=="string"&&e.schemaVersion.startsWith("1.")&&typeof e.recordId=="string"&&Pu.test(e.recordId)&&e.runId===t&&typeof e.command=="string"&&X1.has(e.command)&&typeof e.recordedAt=="string"&&typeof e.outcome=="string"&&typeof e.reasonCode=="string"&&typeof e.message=="string"&&Y1.every(r=>typeof e[r]=="object"&&e[r]!==null)}async function Vw(n,t){try{let e=JSON.parse(await G1(n,"utf8"));return Q1(e,t)?e:void 0}catch{return}}async function Su(n,t){if(!Au.test(t))return[];let e=Ar(n,".kwikqa","runs",t,"records"),r=await Bw(e).catch(()=>[]);return(await Promise.all(r.filter(i=>Pu.test(i.replace(/\.json$/,""))&&i.endsWith(".json")).map(i=>Vw(Ar(e,i),t)))).filter(i=>i!==void 0).sort((i,a)=>i.recordedAt.localeCompare(a.recordedAt)||i.recordId.localeCompare(a.recordId))}async function Tu(n){let t=Ar(n,".kwikqa","runs"),e=(await Bw(t).catch(()=>[])).filter(s=>Au.test(s)),r;for(let s of e){let i=await Vw(Ar(t,s,"result.json"),s);i!==void 0&&(r===void 0||i.recordedAt>r.recordedAt)&&(r=i)}return r?.runId}var yo=new Set(["context-limit-exceeded","request-token-budget-exceeded","request-dollar-budget-exceeded","run-token-budget-exceeded","run-dollar-budget-exceeded"]),sN={"test-support":"test-support-owned",application:"application-owned",environment:"environment-owned",undetermined:"owner-undetermined"};function iN(n){return n.logicalTests.filter(t=>t.status==="unexpected"||t.status==="flaky").map(t=>t.logicalTestId).sort()}function aN(n,t){switch(n.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}}async function Hw(n,t){let e=await Uw(t).catch(()=>t);return nN(n,e).split(rN).join("/")}async function oN(n,t){return{report:await Hw(t,n.reportPath),...n.framework===void 0?{}:{framework:n.framework},...n.probePath===void 0?{}:{probe:await Hw(t,n.probePath)},changeHistory:n.includeChangeHistory===!0,currentDiff:n.includeCurrentDiff===!0,maxPacketBytes:n.evidencePolicy.maxPacketBytes}}function go(n){let t=[...n.hypotheses].sort((e,r)=>e.rank-r.rank)[0];return sN[t?.probableOwner??"undetermined"]??"owner-undetermined"}function dN(n,t){return n==="operation-failed"?"failed":t?"insufficient-evidence":"completed"}async function Ks(n,t){let e=await at(n.reportPath,{workspaceRoot:n.workspaceRoot,...n.gitRoot===void 0?{}:{gitRoot:n.gitRoot},...n.framework===void 0?{}:{framework:n.framework}});if(e.kind==="unreadable")return{kind:"unreadable",outcome:"inconclusive",reasonCode:e.artifact.availability==="unavailable"?"report-unavailable":"report-unreadable",message:e.diagnostic.message};let r=e.run,s=iN(r),i=await oN(n,r.workspace.root),a=(x,R={})=>({kind:"analyzed",stage:{run:r,failing:s,inputs:i,...R,result:x}});if(n.repairableOnly===!0&&We(r)===void 0)return a({outcome:"inconclusive",reasonCode:"report-only-framework",message:ot(r),insufficient:!0});let o=await Qi(r,{artifactRoot:n.artifactRoot??r.workspace.root,includeCurrentDiff:n.includeCurrentDiff===!0,includeChangeHistory:n.includeChangeHistory===!0,...n.probePath===void 0?{}:{probePath:n.probePath}},{...n.evidencePolicy,workspaceRoot:r.workspace.root});if(o.kind!=="built")return a(o.kind==="invalid-policy"?{outcome:"operation-failed",reasonCode:"invalid-evidence-policy",message:o.message}:{outcome:"inconclusive",reasonCode:"evidence-budget-exceeded",message:o.message,insufficient:!0});let d=o.packet,c=qa(r,d),l=$l(c),u={packet:d,symptoms:c,clusters:l},p={...u,triage:u},f=aN(r,s);if(f!==void 0)return a({outcome:"inconclusive",...f,insufficient:!0},p);if(n.remote===void 0)return a({outcome:"inconclusive",reasonCode:"remote-diagnosis-not-configured",message:"Local evidence analysis completed; no remote diagnosis was configured."},p);let h=await hN(n,r,l,t),m=uN(h);if(m===void 0)return a({outcome:"inconclusive",reasonCode:"no-failures",message:"No failing test produced a symptom to diagnose.",insufficient:!0},p);let g=h.filter(x=>x.result.reasonCode!=="cluster-not-requested"),y=g.filter(x=>x.result.outcome==="diagnosed").length,w=l.clusters.length-g.length,v=l.clusters.length>1?`${y} of ${l.clusters.length} failure groups diagnosed.${w>0?` ${w} not sent: ${cN(h)}`:""}`:m.result.message;return a({...m.result,message:v},{triage:u,...m.packet===void 0?p:{packet:m.packet},...m.symptoms===void 0?{}:{symptoms:m.symptoms},...m.clusters===void 0?{}:{clusters:m.clusters},clusterStages:[m,...h.filter(x=>x!==m)],representativeId:m.representativeId})}function cN(n){return n.find(e=>e.result.reasonCode==="cluster-not-requested")?.result.message??"at most 6 groups are sent per analysis."}var lN={strong:3,moderate:2,weak:1,insufficient:0};function zw(n){let[t]=[...n.result.diagnosis?.hypotheses??[]].sort((e,r)=>e.rank-r.rank);return lN[t?.evidenceGrade??""]??0}function wo(n){return n.map((t,e)=>({item:t,index:e})).filter(({item:t})=>t.result.outcome==="diagnosed"&&t.result.reasonCode==="test-support-owned").sort((t,e)=>zw(e.item)-zw(t.item)||e.item.cluster.logicalTestIds.length-t.item.cluster.logicalTestIds.length||t.index-e.index).map(({item:t})=>t)}function uN(n){let t=n.filter(e=>e.result.outcome==="diagnosed");return wo(n)[0]??t[0]??n[0]}var pN=new Set(["provider-refusal","malformed-response","schema-invalid","citation-or-grading-invalid"]);async function qw(n,t,e,r){let s=Mw(t,r);if(s===void 0)return;let i=Lw(t,r,s.logicalTestId),a=await Qi(i,{artifactRoot:n.artifactRoot??t.workspace.root,includeCurrentDiff:n.includeCurrentDiff===!0,includeChangeHistory:n.includeChangeHistory===!0,...n.probePath===void 0?{}:{probePath:n.probePath}},{...n.evidencePolicy,workspaceRoot:t.workspace.root});if(a.kind!=="built")return{cluster:r,representativeId:s.logicalTestId,result:{outcome:"inconclusive",reasonCode:"evidence-budget-exceeded",message:a.message,insufficient:!0}};let o=qa(i,a.packet);return{cluster:r,representativeId:s.logicalTestId,packet:a.packet,symptoms:o,clusters:_w(r,o,e)}}var fN={approveDiagnosis:async()=>!1};async function Eu(n,t){let e=await Ks({...n,interaction:fN,persist:!1},()=>new Date().toISOString());if(e.kind==="unreadable")return{kind:"unreadable",message:e.message};let{run:r,triage:s}=e.stage;if(s===void 0)return{kind:"rebuilt",run:r};let i={};for(let a of s.clusters.clusters){if(!t.includes(a.clusterId))continue;let o=await qw(n,r,s.clusters,a);o?.packet!==void 0&&(i[a.clusterId]=o.packet)}return{kind:"rebuilt",run:r,detail:{...s,groupPackets:i}}}async function hN(n,t,e,r){let s=n.remote;if(s===void 0)return[];let i=Dw(e),a=[],o=[];for(let g of i){let y=await qw(n,t,e,g);y!==void 0&&("result"in y?a.push(y):o.push(y))}let d=[];for(let g of o){let y=n.reuseDiagnosis===!0?await yN(t.workspace.root,t.runId,g.packet,g.symptoms):void 0;y===void 0?d.push(g):a.push(Xt(g,y))}let c=a.some(g=>g.result.reasonCode==="test-support-owned"),l=(g,y)=>{for(let w of g)a.push(Xt(w,{outcome:"inconclusive",reasonCode:"cluster-not-requested",message:y}))};if(n.reuseDiagnosis===!0&&c)return l(d,"A recorded diagnosis of another group already supports a repair."),Gs(a,i);let u=s.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 g=>({item:g,prepared:await io({packet:g.packet,symptoms:g.symptoms,clusters:g.clusters,model:s.model,caps:s.caps,transport:s.transport,now:r()})})))).flatMap(({item:g,prepared:y})=>y.kind==="preview-ready"?[{item:g,prepared:y.prepared}]:(a.push(Xt(g,{outcome:yo.has(y.reasonCode)?"inconclusive":"operation-failed",reasonCode:y.reasonCode,message:y.message,audit:y.audit})),[]));if(f.length===0)return Gs(a,i);let h=f.map(g=>g.prepared.preview),m;if(n.interaction.approveDiagnoses!==void 0)m=await n.interaction.approveDiagnoses(h);else{m=!0;for(let g of h)await n.interaction.approveDiagnosis(g)||(m=!1)}if(!m){for(let g of f)a.push(Xt(g.item,{outcome:"inconclusive",reasonCode:"remote-consent-declined",message:"The developer declined the diagnosis request; no evidence was sent."}));return Gs(a,i)}if(s.session!==void 0)try{await s.session.open(f.length)}catch(g){let y=g instanceof Error?g.message:"The analysis session could not be opened.";for(let w of f)a.push(Xt(w.item,{outcome:"operation-failed",reasonCode:"session-unavailable",message:y}));return Gs(a,i)}try{let g=await jw(f,3,async y=>{let w=await Gw(n,y.prepared,s.transport,r),v=s.escalation;if(v===void 0||!pN.has(w.reasonCode))return Xt(y.item,w);let x=await mN(n,y.item,v,s.transport,r);return x===void 0?Xt(y.item,w):{...Xt(y.item,x),escalated:!0}});a.push(...g)}finally{await s.session?.close().catch(()=>{})}return Gs(a,i)}function Gs(n,t){let e=new Map(t.map((r,s)=>[r.clusterId,s]));return[...n].sort((r,s)=>(e.get(r.cluster.clusterId)??0)-(e.get(s.cluster.clusterId)??0))}function Xt(n,t){return{cluster:n.cluster,representativeId:n.representativeId,packet:n.packet,symptoms:n.symptoms,clusters:n.clusters,result:t}}async function Gw(n,t,e,r){let s=await pu({prepared:t,authorization:{bindingHash:t.authorizationBindingHash,mode:"interactive",authorizedAt:r(),authorizationId:Pr()},authorizationStore:n.authorizationStore??new En,transport:e,now:r()});switch(s.kind){case"diagnosed":return{outcome:"diagnosed",reasonCode:go(s.diagnosis),message:"The diagnosis passed schema validation and local grading.",diagnosis:s.diagnosis,grading:s.grading,audit:s.audit};case"abstained":return{outcome:"inconclusive",reasonCode:s.reasonCode,message:"The evidence was insufficient for a supported diagnosis.",diagnosis:s.diagnosis,grading:s.grading,audit:s.audit};default:return{outcome:yo.has(s.reasonCode)?"inconclusive":"operation-failed",reasonCode:s.reasonCode,message:s.message,audit:s.audit}}}async function mN(n,t,e,r,s){let i=await io({packet:t.packet,symptoms:t.symptoms,clusters:t.clusters,model:e.model,caps:e.caps,transport:r,now:s()});if(i.kind==="preview-ready"&&await n.interaction.approveDiagnosis(i.prepared.preview))return Gw(n,i.prepared,r,s)}async function yN(n,t,e,r){if(/^run_[a-f0-9]{24}$/.test(t))try{let s=await Uw(n),i=JSON.parse(await eN(tN(s,".kwikqa","runs",t,"result.json"),"utf8")),a=u=>u==="diagnosed"||u==="inconclusive",o=[...(i.clusters??[]).filter(u=>a(u.outcome)),...a(i.outcome)?[i]:[]].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=_s(d,e,r);if(!c.passed)return;let l=o.outcome==="inconclusive";return{outcome:l?"inconclusive":"diagnosed",reasonCode:l?o.reasonCode??"insufficient-evidence":go(d),message:"Reused the graded diagnosis recorded for this exact evidence packet.",diagnosis:d,grading:c,audit:o.diagnosisAudit}}catch{return}}function gN(n){return{clusterId:n.cluster.clusterId,logicalTestIds:n.cluster.logicalTestIds,representativeId:n.representativeId,signals:n.cluster.signals,...n.packet===void 0?{}:{packetHash:n.packet.packetHash},outcome:n.result.outcome,reasonCode:n.result.reasonCode,message:n.result.message,...n.result.diagnosis===void 0?{}:{diagnosis:n.result.diagnosis},...n.result.grading===void 0?{}:{grading:n.result.grading},...n.result.audit===void 0?{}:{diagnosisAudit:n.result.audit},...n.escalated===!0?{escalated:!0}:{}}}function bo(n,t,e,r,s={}){let{run:i,packet:a,symptoms:o,clusters:d}=n,c=n.result;return{schemaVersion:"1.1",recordId:ho(),command:t,runId:i.runId,createdAt:i.createdAt,recordedAt:r(),workspace:i.workspace,sourceHashes:a?.sourceHashes??i.sourceHashes,usability:i.usability,failingLogicalTestIds:n.failing,inputs:n.inputs,analysis:{status:dN(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}},...n.clusterStages===void 0||n.clusterStages.length===0?{}:{clusters:n.clusterStages.map(gN)},...c.diagnosis===void 0?{}:{diagnosis:c.diagnosis},...c.grading===void 0?{}:{grading:c.grading},...c.audit===void 0?{}:{diagnosisAudit:c.audit},...s,outcome:e.outcome,reasonCode:e.reasonCode,message:e.message}}function wN(n,t){let e={};for(let r of t.clusterStages??[])r.packet!==void 0&&(e[r.cluster.clusterId]=r.packet);return{...n,groupPackets:e}}async function xo(n,t,e){let r={run:n.run,...n.packet===void 0?{}:{packet:n.packet},...n.symptoms===void 0?{}:{symptoms:n.symptoms},...n.clusters===void 0?{}:{clusters:n.clusters},...n.triage===void 0?{}:{detail:wN(n.triage,n)}},s=(i,a)=>({outcome:i.outcome,reasonCode:i.reasonCode,message:i.message,record:i,...a===void 0?{}:{recordPath:a},...r});if(!e)return s(t);try{return s(t,await qs(n.run.workspace.root,t))}catch{return s({...t,outcome:"operation-failed",reasonCode:"record-write-failed",message:"The run record could not be written safely under .kwikqa/runs/."})}}async function vo(n){let t=n.now??(()=>new Date().toISOString()),e=await Ks(n,t);if(e.kind==="unreadable")return{outcome:e.outcome,reasonCode:e.reasonCode,message:e.message};let{stage:r}=e;return xo(r,bo(r,"analyze",r.result,t),n.persist!==!1)}import{randomUUID as _N}from"node:crypto";import{relative as jN,resolve as FN,sep as BN}from"node:path";import{createHash as Kw}from"node:crypto";import{lstat as bN,readFile as xN,realpath as ko}from"node:fs/promises";import{isAbsolute as vN,join as kN,relative as RN,resolve as IN,sep as AN}from"node:path";var Yt=/^[a-f0-9]{64}$/,Jw=/^vld_[a-f0-9]{24}$/,PN=Ht,SN=4*1024*1024,TN=2*1024*1024;function _n(n){return{code:"transaction-unavailable",message:n}}function Ws(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Nu(n,t){let e=Object.keys(n).sort(),r=[...t].sort();return e.length===r.length&&e.every((s,i)=>s===r[i])}function Cu(n){return Array.isArray(n)&&n.every(t=>typeof t=="string"&&t.length>0&&!t.includes("\0"))}function EN(n,t){let e=RN(n,t);return e===""||!vN(e)&&e!==".."&&!e.startsWith(`..${AN}`)}function CN(n){return typeof n=="string"&&n.length>0&&Number.isFinite(Date.parse(n))}function Ww(n){return Ws(n)?Nu(n,["path","observedBytes","storedBytes","sha256","storedSha256","truncated","redacted"])&&typeof n.path=="string"&&n.path.length>0&&typeof n.sha256=="string"&&Yt.test(n.sha256)&&typeof n.storedSha256=="string"&&Yt.test(n.storedSha256)&&Number.isInteger(n.observedBytes)&&n.observedBytes>=0&&Number.isInteger(n.storedBytes)&&n.storedBytes>=0&&typeof n.truncated=="boolean"&&typeof n.redacted=="boolean":!1}function Xw(n){if(!Ws(n))throw new Error("Validation command record is not an object.");let t=n,{recordHash:e,...r}=t;if(!Nu(n,["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"||!Jw.test(t.validationRunId)||!PN.test(t.commandId)||!Yt.test(t.commandHash)||!Yt.test(t.planHash)||t.timing!=="post-patch"||t.required!==!0||t.executable!==process.execPath||!Cu(t.args)||typeof t.kind!="string"||t.kind.length===0||typeof t.workingDirectory!="string"||t.workingDirectory.length===0||!Ws(t.environmentDelta)||!Object.entries(t.environmentDelta).every(([s,i])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)&&typeof i=="string"&&!i.includes("\0"))||!Number.isInteger(t.timeoutMs)||t.timeoutMs<=0||typeof t.purpose!="string"||t.purpose.length===0||!Cu(t.logicalTestIds)||!Cu(t.projectIds)||!CN(t.startedAt)||!Number.isInteger(t.durationMs)||t.durationMs<0||!Ws(t.termination)||t.termination.kind!=="exit"||t.termination.exitCode!==0||!Ww(t.stdout)||!Ww(t.stderr)||t.stdout.truncated||t.stderr.truncated||!Array.isArray(t.artifacts)||!t.artifacts.every(s=>Ws(s)&&Nu(s,["path","sha256","bytes"])&&typeof s.path=="string"&&s.path.length>0&&typeof s.sha256=="string"&&Yt.test(s.sha256)&&Number.isInteger(s.bytes)&&s.bytes>=0)||t.status!=="passed"||!Yt.test(e)||L(r)!==e)throw new Error("Validation command record is malformed or non-passing.");return t}function NN(n){let t=zt(JSON.parse(n));if(t.status!=="passed")throw new Error("Validation manifest is not passing.");for(let e of t.commandRecords)Xw(e);return t}async function Yw(n){let[t,e,r,s]=await Promise.all([ko(n.workspace.workspaceRoot),ko(n.snapshot.workspaceRoot),ko(n.workspace.gitRoot),ko(n.snapshot.gitRoot)]);if(t!==e||r!==s)throw new Error("Validation workspace identity changed.");return t}async function Qw(n,t,e){for(let r of e.manifest.targets){let s=await Q(n,r.path,t.maxTargetBytes);if(s.kind!=="read"||s.relativePath!==r.path||s.sha256!==r.resultSha256)return!1}return!0}function Zw(n){return Yt.test(n.planHash)&&Jw.test(n.validationRunId)}async function Ro(n,t,e){let r=IN(n,t);if(!EN(n,r))throw new Error("Validation record path escapes its run.");let s=await bN(r);if(!s.isFile()||s.isSymbolicLink()||s.size>e)throw new Error("Validation record path is unsafe or unbounded.");return xN(r)}async function ON(n,t,e){let r=new Map(e.requiredCommands.map(s=>[s.commandId,s.commandHash]));for(let s of t.commandRecords){if(s.validationRunId!==t.validationRunId||s.planHash!==t.planHash||r.get(s.commandId)===void 0)return!1;let i=r.get(s.commandId);if(i===void 0||s.commandHash!==i)return!1;let a=await Ro(n,`commands/${s.commandId}/result.json`,TN),o=Xw(JSON.parse(a.toString("utf8")));if(L(o)!==L(s))return!1;for(let d of[s.stdout,s.stderr]){let c=await Ro(n,d.path,bn);if(c.byteLength!==d.storedBytes||Kw("sha256").update(c).digest("hex")!==d.storedSha256)return!1}for(let d of s.artifacts){let c=await Ro(n,d.path,ar);if(c.byteLength!==d.bytes||Kw("sha256").update(c).digest("hex")!==d.sha256)return!1}}return!0}async function Ou(n){if(!Zw(n))return{kind:"rejected",reasons:[_n("Validation identity is invalid.")]};let t=n.now??new Date().toISOString(),e;try{let r=await Yw(n.context);e=await Ye(r,{operation:"begin-validation",transactionId:n.transactionId,validationRunId:n.validationRunId,at:t});let s=await Re(r,n.transactionId),i=s.state.history.at(-1);return s.state.phase==="validating"&&i?.type==="validation-started"&&i.planHash===n.planHash&&i.validationRunId===n.validationRunId?{kind:"validating",transaction:Se(s)}:s.state.phase!=="applied"||s.manifest.preview.authoritativeValidation.planHash!==n.planHash||!await Qw(r,n.context,s)?{kind:"rejected",reasons:[_n("Applied transaction does not match the approved validation handoff.")],transaction:Se(s)}:(s=await Ue({transaction:s,phase:"validating",type:"validation-started",planHash:n.planHash,validationRunId:n.validationRunId,now:t}),{kind:"validating",transaction:Se(s)})}catch{return{kind:"failed",reasons:[_n("Validation transition failed closed.")]}}finally{await e?.release().catch(()=>{})}}async function $u(n){if(!Zw(n)||!Yt.test(n.validationManifestHash))return{kind:"rejected",reasons:[_n("Validation completion identity is invalid.")]};let t=n.now??new Date().toISOString(),e;try{let r=await Yw(n.context);e=await Ye(r,{operation:"complete-validation",transactionId:n.transactionId,validationRunId:n.validationRunId,at:t});let s=await Re(r,n.transactionId),i=s.manifest.preview.authoritativeValidation,a=s.state.history.at(-1);if(s.state.phase==="completed"&&a?.type==="validation-passed"&&a.planHash===n.planHash&&a.validationRunId===n.validationRunId&&a.validationManifestHash===n.validationManifestHash)return{kind:"completed",transaction:Se(s)};if(s.state.phase!=="validating"||i.planHash!==n.planHash||a?.type!=="validation-started"||a.validationRunId!==n.validationRunId||a.planHash!==n.planHash||!await Qw(r,n.context,s))return{kind:"rejected",reasons:[_n("Transaction is not validating this exact approved run.")],transaction:Se(s)};let o=kN(s.directory,"validation",n.validationRunId),d=await Ro(o,"manifest.json",SN),c=NN(d.toString("utf8")),l=new Set(c.requiredCommandIds),u=new Set(c.commandRecords.map(f=>f.commandId)),p=i.targetHashes;return c.manifestHash!==n.validationManifestHash||c.transactionId!==n.transactionId||c.validationRunId!==n.validationRunId||c.planHash!==n.planHash||c.repositoryFingerprint!==i.repositoryFingerprint||L(c.targetHashes)!==L(p)||l.size!==c.requiredCommandIds.length||u.size!==c.commandRecords.length||i.requiredCommandIds.some(f=>!l.has(f)||!u.has(f))||l.size!==i.requiredCommandIds.length||u.size!==i.requiredCommandIds.length||!await ON(o,c,i)?{kind:"rejected",reasons:[_n("Validation manifest does not prove the exact approved command set.")],transaction:Se(s)}:(s=await Ue({transaction:s,phase:"completed",type:"validation-passed",planHash:n.planHash,validationRunId:n.validationRunId,validationManifestHash:c.manifestHash,now:t}),{kind:"completed",transaction:Se(s)})}catch{return{kind:"failed",reasons:[_n("Validation completion failed closed.")]}}finally{await e?.release().catch(()=>{})}}import{join as $N}from"node:path";var eb="1.0",DN=/^rps_[a-f0-9]{24}$/,MN=8*1024*1024;function LN(n){if(typeof n!="object"||n===null)return;let t=n;if(!(typeof t.reportPath!="string"||!Array.isArray(t.logicalTestIds)||!t.logicalTestIds.every(e=>typeof e=="string")||t.framework!==void 0&&!ft.includes(t.framework)))return{reportPath:t.reportPath,...t.framework===void 0?{}:{framework:t.framework},logicalTestIds:t.logicalTestIds}}function tb(n){if(!DN.test(n))throw new Error("Repair session id is invalid.");return[".kwikqa","repairs",n]}async function nb(n,t){let e=await He(n,tb(t.repairSessionId));await ye($N(e,`attempt-${t.attempt}.json`),`${pe(t)}
206
- `,{mode:384,replace:!1})}async function rb(n,t,e){let r=await He(n,tb(t)),s=await Rn(r,`attempt-${e}.json`,MN),i=Ln(s.config);if(s.schemaVersion!==eb||s.repairSessionId!==t||s.attempt!==e||typeof s.transactionId!="string"||s.workspace===void 0||typeof s.maxTargetBytes!="number"||s.record===void 0||i.kind!=="valid")throw new Error("Repair attempt state is malformed.");let a=LN(s.group);return{schemaVersion:eb,repairSessionId:t,attempt:e,transactionId:s.transactionId,plan:xn(s.plan),workspace:s.workspace,config:i.config,maxTargetBytes:s.maxTargetBytes,record:s.record,...a===void 0?{}:{group:a}}}import{dirname as sb,resolve as ib}from"node:path";function Sr(n,t){return{kind:"configuration",path:n.relativePath,sha256:n.sha256,detail:t}}async function ab(n){let{run:t,test:e,discovery:r}=n,s=We(t);if(s===void 0)return{kind:"unavailable",message:ot(t)};if(s==="playwright")return{kind:"unavailable",message:"Playwright validation needs no prepared run."};let i=t.configFile??await ci(n.workspaceRoot,s,e.location.file),a=r.scope==="focused"?[e.location.file]:r.scope==="affected"?r.testPaths:[],o=await La(n.workspaceRoot);if(s==="cypress"){let c=await li(n.workspaceRoot,i),l=r.scope==="focused"?t.logicalTests.filter(f=>f.location.file===e.location.file&&f.projectId===e.projectId&&f.status==="expected"):[],u=await _a({workspaceRoot:n.workspaceRoot,runtime:o,...i===void 0?{}:{configFile:i},specs:a,screenshotsDirectory:`${n.artifactRoot}/screenshots`,noRetries:!0,capture:{directory:`${n.artifactRoot}/capture`,supportFile:c,...r.scope==="focused"?{only:[e,...l].map(f=>f.titlePath.join(" "))}:{}}}),p=l.map(f=>f.logicalTestId);return{kind:"prepared",prepared:{args:u.args,workingDirectory:i===void 0?n.workspaceRoot:sb(ib(n.workspaceRoot,i)),evidence:[Sr(o["cypress-reporter.cjs"],"KwikQA's Cypress reporter."),Sr(o["cypress-capture.js"],"KwikQA's Cypress failure capture."),...u.generated.map(f=>Sr(f,"Support file KwikQA generated for this validation."))],companionLogicalTestIds:p}}}if(i===void 0)return{kind:"unavailable",message:"No wdio.conf was found for the failing spec, so its validation run is unknown."};let d=await ja({workspaceRoot:n.workspaceRoot,runtime:o,configFile:i,specs:a,directory:`${n.artifactRoot}/runner`,noRetries:!0,...r.scope==="focused"?{grep:rg(e.titlePath)}:{},capture:!0});return{kind:"prepared",prepared:{args:d.args,workingDirectory:sb(ib(n.workspaceRoot,i)),evidence:[Sr(o["wdio-reporter.mjs"],"KwikQA's WebdriverIO reporter."),Sr(o["wdio-capture.mjs"],"KwikQA's WebdriverIO run wrapper."),...d.generated.map(c=>Sr(c,"WebdriverIO config KwikQA generated for this validation."))],companionLogicalTestIds:[]}}}var VN=600*1e3,ob=1e6,HN={maxFiles:5e3,maxFileBytes:1024*1024,maxTotalBytes:64*1024*1024,maxImportEdges:5e4,maxImportDepth:20},zN={biome:"@biomejs/biome",prettier:"prettier",typescript:"typescript",eslint:"eslint"};function Io(n,t,e,r){let s=n.logicalTests.filter(l=>l.status==="unexpected"||l.status==="flaky"),i=[...t.hypotheses].sort((l,u)=>l.rank-u.rank)[0],a=new Set([...i?.supportingEvidenceIds??[],...t.ownershipEvidenceIds]),o=new Set(e.evidence.filter(l=>a.has(l.evidenceId)&&l.logicalTestId!==void 0).map(l=>l.logicalTestId)),d=s.filter(l=>o.has(l.logicalTestId));if(d.length===1)return d[0];let c=s.find(l=>l.logicalTestId===r);return c!==void 0&&(d.length===0||d.includes(c))?c:s.length===1?s[0]:void 0}function UN(n){return Io(n.run,n.diagnosis,n.packet,n.representativeId)}function db(n){return n.payloadManifestHash===void 0||n.payloadHash===void 0?[]:[{manifestHash:n.payloadManifestHash,payloadHash:n.payloadHash,packetHash:n.packetHash,model:n.model.modelId,provider:n.model.providerId,promptVersion:n.promptVersion,outputSchemaVersion:n.outputSchemaVersion}]}function qN(n){return{maxRequestTokens:n.request.maxInputTokens+n.request.maxOutputTokens,maxRunTokens:n.run.maxInputTokens+n.run.maxOutputTokens,maxRequestDollars:n.request.maxDollars,maxRunDollars:n.run.maxDollars}}var GN={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};async function KN(n,t,e,r){let s=async o=>{let d=await Ps({workspaceRoot:n.workspaceRoot,repositoryRoot:n.gitRoot,ownerPath:t,packageName:o});return d.kind==="resolved"?d.tool:void 0},i={},a=await s(GN[e]);a!==void 0&&(i[e]=a);for(let o of new Set(r)){if(o==="kwikqa-babel")continue;let d=await s(zN[o]);d!==void 0&&(i[o]=d)}return i}async function cb(n){let{input:t,now:e,run:r,proposal:s,repository:i}=n,a={repairProposal:s,repairAudit:n.repairAudit},o=(I,$)=>n.finish({outcome:"validation-unavailable",reasonCode:I,message:$},{...a,proposal:{status:"ready"},application:{status:"not-run"},validation:{status:"unavailable"}}),d=We(r);if(d===void 0)return o("report-only-framework",ot(r));let c=UN(n);if(c===void 0)return o("original-test-ambiguous","The repair cannot be validated because the original failing test is ambiguous.");let l=r.projects.find(I=>I.projectId===c.projectId),u=await $c({workspaceRoot:i.workspaceRoot,targets:s.targets.map(I=>({path:I.path,class:I.class})),originalTestPath:c.location.file,projects:r.projects.map(I=>({id:I.name,testDirectory:I.testDir??"",...r.configFile===void 0?{}:{configPath:r.configFile}})),limits:HN}),p=u.scope==="focused"&&u.projectIds.length===0&&l!==void 0&&l.name!==""?{...u,projectIds:[l.name]}:u,f=await KN(i,c.location.file,d,p.staticChecks.map(I=>I.tool)),h=`.kwikqa/validation-artifacts/${s.proposalHash.slice(0,24)}`,m;if(d!=="playwright"&&p.status==="resolved"){let I=await ab({workspaceRoot:i.workspaceRoot,run:r,test:c,discovery:p,artifactRoot:h});if(I.kind==="unavailable")return o("validation-scope-unavailable",I.message);m=I.prepared}let g=Qc({proposal:s,advisoryPlan:s.validationPlan,discovery:p,tools:f,workspaceRoot:i.workspaceRoot,originalTest:{path:c.location.file,line:c.location.line??1,logicalTestId:c.logicalTestId,projectId:l===void 0||l.name===""?c.projectId:l.name,...r.configFile===void 0?{}:{configPath:r.configFile},environmentEquivalent:t.environmentEquivalent!==!1},artifactRoot:h,timeoutMs:t.validationTimeoutMs??VN,framework:d,...m===void 0?{}:{frameworkRun:{args:m.args,workingDirectory:m.workingDirectory,evidence:m.evidence},companionLogicalTestIds:m.companionLogicalTestIds}}),y=g.plan;if(y.status!=="resolved")return o("validation-scope-unavailable",y.unresolvedReasons.map(I=>I.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 w=n.retry===void 0?1:2,v=n.retry?.repairSessionId??(await ul({workspaceRoot:i.workspaceRoot,originalRunId:r.runId,originalPacketHash:n.packet.packetHash,now:e()})).repairSessionId,x={config:n.config,snapshot:{workspaceRoot:i.workspaceRoot,gitRoot:i.gitRoot,dirtyPaths:i.dirtyPaths,validation:[]},workspace:{workspaceRoot:i.workspaceRoot,gitRoot:i.gitRoot},maxTargetBytes:ob},R={sessionId:`kwikqa-${_N()}`},S=tl({proposal:s,context:x,payloadManifests:[...n.diagnosisAudit===void 0?[]:db(n.diagnosisAudit),...db(n.repairAudit)],costBounds:qN(n.caps),scopes:{baseline:[],validation:[p.scope]},authoritativeValidation:Zc({plan:y,advisoryPlan:s.validationPlan,repairSessionId:v,attemptOrdinal:w}),previewedAt:e(),interactiveSession:R}),N={repairSessionId:v,attempt:w,planHash:y.planHash};if(S.kind!=="preview-ready")return n.finish({outcome:"operation-failed",reasonCode:"application-rejected",message:S.reasons.map(I=>I.message).join(" ")},{...a,proposal:{status:"ready"},application:{status:"blocked"}});if(!await t.interaction.approveApplication(S.preview,y))return n.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:N});let E=Pr(),M=e(),A=await sl({preview:S.preview,authorization:{authorizationId:E,bindingHash:Ta(S.preview,E,M,R),authorizedAt:M,interactiveSession:R},context:x,now:M});if(A.kind!=="applied")return n.finish({outcome:"operation-failed",reasonCode:A.kind==="recovery-required"?"application-recovery-required":"application-rejected",message:A.reasons.map(I=>I.message).join(" ")},{...a,proposal:{status:"approved"},application:{status:A.kind==="recovery-required"?"recovery-required":"failed"},repair:N});let C=A.transaction.transactionId;await hl(i.workspaceRoot,v,{ordinal:w,proposalHash:s.proposalHash,transactionId:C,outcome:"applied",recordedAt:e()});let P=(n.memberIds??[]).filter(I=>I!==c.logicalTestId);return await nb(i.workspaceRoot,{schemaVersion:"1.0",repairSessionId:v,attempt:w,transactionId:C,plan:y,workspace:x.workspace,config:n.config,maxTargetBytes:ob,...P.length===0?{}:{group:{reportPath:jN(i.workspaceRoot,FN(i.workspaceRoot,t.reportPath)).split(BN).join("/"),...t.framework===void 0?{}:{framework:t.framework},logicalTestIds:P}},record:{runId:r.runId,createdAt:r.createdAt,workspace:r.workspace,sourceHashes:n.packet.sourceHashes,usability:r.usability,failingLogicalTestIds:r.logicalTests.filter(I=>I.status==="unexpected"||I.status==="flaky").map(I=>I.logicalTestId).sort()}}),n.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:{...N,transactionId:C}})}import{execFile as WN}from"node:child_process";import{realpath as Js}from"node:fs/promises";import{isAbsolute as JN,relative as XN,resolve as Du,sep as lb}from"node:path";import{promisify as YN}from"node:util";var QN=YN(WN),ZN=3e4,eO=16*1024*1024;async function Ao(n,t){return(await QN("git",["-C",n,"--no-optional-locks",...t],{timeout:ZN,maxBuffer:eO,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}function ub(n){let t=n.split("\0"),e=[];for(let r=0;r<t.length;r+=1){let s=t[r]??"";if(s.length<4)continue;let i=s.slice(0,2);if(e.push(s.slice(3)),i.includes("R")||i.includes("C")){let a=t[r+1];a!==void 0&&a.length>0&&e.push(a),r+=1}}return e}function tO(n,t,e){let r=XN(n,Du(t,e));if(!(r===""||JN(r)||r===".."||r.startsWith(`..${lb}`)))return r.split(lb).join("/")}async function Po(n){let t=await Js(n);try{return await Js(Du((await Ao(t,["rev-parse","--show-toplevel"])).trim()))}catch{return t}}async function Mu(n){let t=await Js(n);return(await Ao(t,["-c","core.quotePath=false","ls-files","-z"])).split("\0").filter(r=>r.length>0).sort()}async function jn(n){let t,e,r;try{t=await Js(n),e=await Js(Du((await Ao(t,["rev-parse","--show-toplevel"])).trim())),r=await Ao(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(`
207
- `)[0]??"";return{kind:"unavailable",message:`Repository status could not be read: ${d===""?"git failed.":d}`}}let s=ub(r),i=[...new Set(s.map(a=>tO(t,e,a)).filter(a=>a!==void 0))].sort();return{kind:"read",status:{workspaceRoot:t,gitRoot:e,dirtyPaths:i,pristine:s.length===0}}}var nO="kwikqa.config.json",rO=256*1024;async function sO(n,t){let e=await Q(n,t,rO);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 r;try{r=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 s=Ln(r);return s.kind!=="valid"?{kind:"repair-config-invalid",message:s.issues.join(" ")}:s}function iO(n,t,e){let r=new Set(e.map(i=>i.toLocaleLowerCase("en-US"))),s=new Set;for(let i of n.evidence){if(i.locator.type!=="source-range")continue;let a=i.locator.path;Cs(a,t.editablePaths)!==void 0&&!Es(a,t)&&!Ts(a)&&!r.has(a.toLocaleLowerCase("en-US"))&&s.add(a)}return[...s].sort()}async function Lu(n){let t=n.now??(()=>new Date().toISOString()),e=await jn(n.workspaceRoot);if(e.kind==="unavailable")return{outcome:"operation-failed",reasonCode:"repository-status-unavailable",message:e.message};let{workspaceRoot:r,gitRoot:s,dirtyPaths:i,pristine:a}=e.status,o=await sO(r,n.configPath??nO);if(o.kind!=="valid")return{outcome:"operation-failed",reasonCode:o.kind,message:o.message};let d=o.config;if(n.retryRepairSessionId!==void 0&&(await Gt(r,n.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 Ks({...n,workspaceRoot:r,gitRoot:s,repairableOnly:!0},t);if(c.kind==="unreadable")return{outcome:c.outcome,reasonCode:c.reasonCode,message:c.message};let{stage:l}=c,u={workspaceRoot:r,gitRoot:s,dirtyPaths:i},p=(m,g=[])=>(y,w={})=>xo(m,bo(m,"fix",g.length===0?y:{...y,message:`${g.join(" ")} ${y.message}`},t,{repository:{pristine:a,dirtyPaths:i},...w}),n.persist!==!1),f=uO(l,n);if("refusal"in f)return p(l)(f.refusal);if(f.groups.length===0){let{packet:m}=l,{diagnosis:g,grading:y}=l.result;return l.result.outcome!=="diagnosed"||m===void 0||g===void 0||y===void 0?p(l)(l.result):pb(n,l,{packet:m,diagnosis:g,grading:y},d,t,p(l),u)}let h=[];f.groups.length>0&&await n.repairSession?.open(f.groups.length);try{let m;for(let g of f.groups){let y=lO(l,g),{packet:w}=y,{diagnosis:v,grading:x}=g.result;if(!(w===void 0||v===void 0||x===void 0)){if(m=await pb(n,y,{packet:w,diagnosis:v,grading:x},d,t,p(y,h),u),!dO(m))return m;h.push(`Failure group ${cO(l,g)}: ${m.message}`)}}return m??p(l)(l.result)}finally{await n.repairSession?.close()}}var aO=3,oO=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 dO(n){return n.outcome==="abstained-from-repair"?oO.has(n.reasonCode):n.outcome==="validation-unavailable"&&n.record?.application.status==="not-run"}function cO(n,t){return(n.clusterStages??[]).indexOf(t)+1}function lO(n,t){return{...n,...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,...(n.clusterStages??[]).filter(e=>e!==t)],representativeId:t.representativeId}}function uO(n,t){let e=n.clusterStages??[];if(t.group!==void 0){let i=e[t.group-1];return i===void 0?{refusal:{outcome:"operation-failed",reasonCode:"group-not-found",message:`There is no failure group ${t.group}; this run has ${e.length}.`}}:wo([i]).includes(i)?{groups:[i]}:{refusal:{outcome:"abstained-from-repair",reasonCode:"group-not-repairable",message:`Failure group ${t.group} is not diagnosed as the test's fault (${i.result.reasonCode}); KwikQA repairs only test-side causes.`}}}let r=wo(e),s=t.repairSession===void 0||t.retryRepairSessionId!==void 0?1:aO;return{groups:r.slice(0,s)}}async function pO(n,t){let{interaction:e}=n;if(e.confirmFailure===void 0||n.retryRepairSessionId!==void 0)return;let r=t.clusterStages?.[0]?.cluster.logicalTestIds??t.failing,s=t.representativeId??r[0];if(s===void 0)return;let i=await e.confirmFailure(t.run,r);if(i.kind==="declined")return{status:"declined",logicalTestIds:r,message:"The developer chose not to re-run the failing tests first."};if(i.kind==="unavailable")return{status:"unavailable",logicalTestIds:r,message:i.message};let a=r.filter(d=>i.failedAgain.includes(d));if(a.includes(s))return{status:"reproduced",logicalTestIds:r,failedAgain:a};let o=t.run.logicalTests.find(d=>d.logicalTestId===s)?.title;return{status:"not-reproduced",logicalTestIds:r,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 pb(n,t,e,r,s,i,a){let{packet:o,diagnosis:d,grading:c}=e,l=[...d.hypotheses].sort((y,w)=>y.rank-w.rank)[0],u=n.repairCaps??n.remote.caps,p=await yu({packet:o,diagnosis:d,grading:c,hypothesisId:l?.hypothesisId??"",editablePaths:iO(o,r,a.dirtyPaths),budgets:r.budgets,model:n.repairModel??n.remote.model,caps:u,transport:n.remote.transport,now:s()});if(p.kind!=="preview-ready"){let y=p.reasonCode==="repair-not-eligible"&&l?.probableOwner!=="test-support"?go(d):p.reasonCode,w=p.reasonCode==="repair-not-eligible"||yo.has(p.reasonCode);return i({outcome:w?"abstained-from-repair":"operation-failed",reasonCode:y,message:p.message},{proposal:{status:w?"not-eligible":"failed"},repairAudit:p.audit})}let f=await pO(n,t),h=(y,w={})=>i(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 n.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 m=await gu({prepared:p.prepared,authorization:{bindingHash:p.prepared.authorizationBindingHash,mode:"interactive",authorizedAt:s(),authorizationId:Pr()},authorizationStore:n.authorizationStore??new En,transport:n.remote.transport,now:s()});if(m.kind==="declined")return h({outcome:"abstained-from-repair",reasonCode:m.reasonCode,message:m.message},{proposal:{status:"not-eligible"},repairAudit:m.audit});if(m.kind!=="proposed")return h({outcome:"operation-failed",reasonCode:m.reasonCode,message:m.message},{proposal:{status:"failed"},repairAudit:m.audit});let g=await Iu({packet:o,diagnosis:d,grading:c,config:r,snapshot:{workspaceRoot:a.workspaceRoot,gitRoot:a.gitRoot,dirtyPaths:a.dirtyPaths,validation:[]},intent:m.draft.intent,replacements:m.draft.replacements});if(g.kind==="rejected"){let[y]=g.reasons;return h({outcome:"abstained-from-repair",reasonCode:y?.code??"invalid-replacement",message:g.reasons.map(w=>w.message).join(" ")},{proposal:{status:"not-eligible"},repairAudit:m.audit,proposalRejections:g.reasons})}return n.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:m.audit,repairProposal:g.proposal}):cb({input:n,now:s,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:g.proposal,config:r,repository:a,diagnosisAudit:t.result.audit,repairAudit:m.audit,caps:u,...n.retryRepairSessionId===void 0?{}:{retry:{repairSessionId:n.retryRepairSessionId}},finish:h})}import{randomUUID as fO}from"node:crypto";import{realpath as hO}from"node:fs/promises";import{join as mO,relative as yO,sep as _u}from"node:path";var gO={maxStreamBytes:4*1024*1024,maxTotalStreamBytes:16*1024*1024,terminationGraceMs:5e3},wO=32*1024*1024,bO=new Set(["applied","validating"]);function xO(){return`vld_${fO().replaceAll("-","").slice(0,24)}`}function vO(n){return{config:n.config,snapshot:{workspaceRoot:n.workspace.workspaceRoot,gitRoot:n.workspace.gitRoot,dirtyPaths:[],validation:[]},workspace:n.workspace,maxTargetBytes:n.maxTargetBytes}}function kO(n,t,e){let r=s=>yO(n,`${t}${_u}${s.split("/").join(_u)}`).split(_u).join("/");for(let s of e.commandRecords){let i=s.artifacts.find(d=>d.path.endsWith("/report.json"));if(i!==void 0)return r(i.path);let o=s.artifacts.filter(d=>Ia.test(d.path.split("/").at(-1)??""))[0];if(o!==void 0)return r(o.path.split("/").slice(0,-1).join("/"))}}async function RO(n,t,e){let r=t.group;if(r===void 0||r.logicalTestIds.length===0||n.checkGroup===void 0)return;let{logicalTestIds:s}=r,i=`${s.length} other test${s.length===1?"":"s"}`,a=await at(mO(e,r.reportPath),{workspaceRoot:e,gitRoot:t.workspace.gitRoot,...r.framework===void 0?{}:{framework:r.framework}}),o=a.kind==="parsed"?new Set(a.run.logicalTests.map(u=>u.logicalTestId)):void 0;if(a.kind!=="parsed"||!s.every(u=>o?.has(u)))return{status:"unavailable",logicalTestIds:s,message:`The report fix read has changed, so the group's ${i} were not re-run.`};let d=await n.checkGroup(a.run,s);if(d.kind==="declined")return{status:"declined",logicalTestIds:s,message:`The group's ${i} were not re-run.`};if(d.kind==="unavailable")return{status:"unavailable",logicalTestIds:s,message:d.message};let c=s.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:s,stillFailing:c,message:c.length===0?`The group's ${i} pass now as well.`:`${c.length} of the group's ${i} still fail${c.length===1?"s":""}: ${l}. The patch stays; run \`kwikqa fix\` again for them.`}}async function Fu(n){let t=n.now??(()=>new Date().toISOString()),e=()=>new Date().toISOString(),r=await hO(n.workspaceRoot),s=await ol(r);if(s.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-recovery-required",message:s.reasons.map(S=>S.message).join(" ")};let i=s.transactions.filter(S=>bO.has(S.phase));if(i.length!==1||i[0]===void 0)return{outcome:"operation-failed",reasonCode:"no-pending-repair",message:i.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 Re(r,i[0].transactionId),o=a.manifest.preview.authoritativeValidation,d=await rb(r,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=vO(d),l=d.transactionId,u=d.plan,p;if(a.state.phase==="validating"){let S=a.state.history.findLast(N=>N.type==="validation-started");if(S?.validationRunId===void 0)throw new Error("Validating transaction has no started validation run.");p=S.validationRunId}else{p=xO();let S=await Ou({context:c,transactionId:l,planHash:u.planHash,validationRunId:p,now:e()});if(S.kind==="rejected"||S.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-rejected",message:S.reasons.map(N=>N.message).join(" ")};for(let N of u.commands)if(!(!N.required||N.timing!=="post-patch")){if(n.signal?.aborted===!0)break;await Fc({workspaceRoot:r,repositoryRoot:d.workspace.gitRoot,transactionId:l,validationRunId:p,plan:u,commandId:N.commandId,limits:gO,...n.signal===void 0?{}:{signal:n.signal}}).catch(()=>{})}}let f=await Uc({workspaceRoot:r,gitRoot:d.workspace.gitRoot,transactionId:l,validationRunId:p,plan:u,reportMaxBytes:wO,completedAt:e()}),h=f.manifest,m={repairSessionId:d.repairSessionId,attempt:d.attempt,transactionId:l,planHash:u.planHash,validationRunId:p,validationManifestHash:h.manifestHash};if(h.status==="passed"&&(await $u({context:c,transactionId:l,planHash:u.planHash,validationRunId:p,validationManifestHash:h.manifestHash,now:e()})).kind==="completed"){await Da({workspaceRoot:r,repairSessionId:d.repairSessionId,ordinal:d.attempt,validationRunId:p,now:t()});let N=await RO(n,d,r);return ju(n,d,t,{outcome:"repaired",reasonCode:"validation-passed",message:`Every required validation check passed; the repair is complete.${N?.message===void 0?"":` ${N.message}`}`,application:"applied",validation:"passed",repair:m,...N===void 0?{}:{groupCheck:N}})}await Da({workspaceRoot:r,repairSessionId:d.repairSessionId,ordinal:d.attempt,validationRunId:p,now:t()});let g=await dl(c,l,e()),y=h.status==="passed"?"incomplete":h.status,w=y==="failed"?"validation-failed":y==="unavailable"?"validation-unavailable":"validation-incomplete";if(g.kind!=="rolled-back")return ju(n,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:m});let x=(await ml({workspaceRoot:r,repairSessionId:d.repairSessionId,ordinal:d.attempt,proof:{transactionId:l,phase:"rolled-back",transactionRevision:g.transaction.revision},now:t()})).retry!==void 0,R=x?kO(r,f.directory,h):void 0;return ju(n,d,t,{outcome:"repair-failed",reasonCode:w,message:x?"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:{...m,retryAvailable:x,...R===void 0?{}:{retryReportPath:R}}})}async function ju(n,t,e,r){let s={schemaVersion:"1.1",recordId:ho(),command:"validate",...t.record,recordedAt:e(),analysis:{status:"completed"},proposal:{status:"approved"},application:{status:r.application},validation:{status:r.validation},repair:r.repair,...r.groupCheck===void 0?{}:{groupCheck:r.groupCheck},outcome:r.outcome,reasonCode:r.reasonCode,message:r.message};if(n.persist===!1)return{outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s};try{let i=await qs(t.workspace.workspaceRoot,s);return{outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s,recordPath:i}}catch{return{outcome:"operation-failed",reasonCode:"record-write-failed",message:`${s.message} The run record could not be written safely under .kwikqa/runs/.`,record:s}}}var IO=1200*1e3,AO=10,PO=1e3,SO=15e3,TO=3e3,EO=6e4,fb=3e4,CO=2;function Vu(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}async function mb(n){try{let t=await n.json();return Vu(t)?t:void 0}catch{return}}async function NO(n){return await mb(n)??{}}function hb(n){return typeof n=="number"&&Number.isFinite(n)?Math.min(SO,Math.max(PO,n)):TO}function Bu(n){let t=Vu(n.error)?n.error:void 0;return typeof t?.message=="string"?t.message:void 0}var So=class{constructor(t){this.options=t}options;preflight(t){return this.options.preflight.preflight(t)}async complete(t){let e=performance.now(),r=()=>performance.now()-e;for(let s=0;;s+=1){let i=await this.#e(t,r);if(i!=="interrupted")return i;if(s===CO)return{kind:"failed",code:"http-error",message:"The model request was interrupted on our side; nothing was charged. Try again.",httpStatus:503,elapsedMs:r()};this.options.onRestart?.()}}async#e(t,e){let r=(u,p)=>({kind:"failed",code:u,message:p,elapsedMs:e()}),s=su(t);if(s!==void 0)return{kind:"failed",code:"invalid-request",message:s,elapsedMs:0};let i;try{i=await this.#t("POST","/v1/jobs",EO,{headers:{...this.options.headers(t.body),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(t.body)})}catch(u){return r("network-error",`The model request could not reach the KwikQA service (${Hs(u)}).`)}let a=await NO(i);if(i.status!==202){let u=Za(a);return{kind:"failed",code:"http-error",message:Bu(a)??"The KwikQA service refused the model request.",httpStatus:i.status,...u===void 0?{}:{providerCode:u},elapsedMs:e()}}let o=a.jobId;if(typeof o!="string"||o==="")return r("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=hb(a.pollAfterMs),l=0;for(;;){if(e()>(this.options.maxWaitMs??IO))return await this.#n(o),r("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}`,fb)}catch{u=new Response(null,{status:599})}let p=u.status>=500?void 0:await mb(u);if(u.status===404)return"interrupted";if(u.status<500&&!u.ok)return{kind:"failed",code:"http-error",message:Bu(p??{})??"The KwikQA service refused to report the job.",httpStatus:u.status,elapsedMs:e()};if(p===void 0){if(l+=1,l>AO)return r("network-error","Lost contact with the KwikQA service while the model was working. If it answered, it is given back unused.");continue}if(l=0,p.status==="running"){this.options.onProgress?.(e()),c=hb(p.pollAfterMs);continue}if(p.status==="failed")return Vu(p.error)&&p.error.code==="job-interrupted"?"interrupted":{kind:"failed",code:"http-error",message:Bu(p)??"The model request was interrupted; nothing was charged.",httpStatus:503,elapsedMs:e()};if(p.status!=="answered")return r("invalid-json","The KwikQA service reported a job state the CLI does not know.");await this.#n(o);let f=typeof p.httpStatus=="number"?p.httpStatus:502,h=p.result,m=f>=200&&f<300;if(!m||ru(h)){let g=Za(h),y=m?g??502:f;return{kind:"failed",code:"http-error",message:nu(y,h),httpStatus:y,...g===void 0?{}:{providerCode:g},elapsedMs:e()}}return this.options.onCompletionBody?.(h),{kind:"response",httpStatus:f,body:h,elapsedMs:e()}}}async#n(t){try{await this.#t("DELETE",`/v1/jobs/${t}`,fb)}catch{}}#t(t,e,r,s={}){return this.options.fetch(`${this.options.baseUrl}${e}`,{method:t,headers:{Accept:"application/json",Authorization:`Bearer ${this.options.token}`,...s.headers},...s.body===void 0?{}:{body:s.body},redirect:"error",signal:AbortSignal.timeout(r)})}};var OO="https://api.kwikqa.com",Tr="https://kwikqa.com/dashboard/";function yb(n){return n.hosted??!(n.plan==="byo"||n.plan==="byo-team")}function $O(n){return n?.response_format?.json_schema?.name==="kwikqa_diagnosis"}var pt=class extends Error{constructor(e,r,s){super(s);this.status=e;this.code=r}status;code};function Qt(n,t){return(n.KWIKQA_API_URL??(t===void 0||t===""?OO:t)).replace(/\/+$/,"")}function gb(n){let t=n?.messages;if(!Array.isArray(t))return;let e=t.find(r=>typeof r=="object"&&r!==null&&r.role==="user"&&typeof r.content=="string");if(e!==void 0)try{let r=JSON.parse(e.content).framework;return r==="playwright"||r==="cypress"||r==="webdriverio"?r:void 0}catch{return}}var xt=class{constructor(t,e,r=fetch){this.baseUrl=t;this.token=e;this.fetchImpl=r}baseUrl;token;fetchImpl;async#e(t,e,r,s,i){let a=()=>this.fetchImpl(`${this.baseUrl}${e}`,{method:t,headers:{Accept:"application/json",...r===void 0?{}:{"Content-Type":"application/json"},...this.token===void 0?{}:{Authorization:`Bearer ${this.token}`},...s===void 0?{}:{"X-KwikQA-Retry-Ticket":s},...i===void 0?{}:{"X-KwikQA-Session":i}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error"}),o;try{o=await a().catch(c=>{if(t==="GET")return a();throw c})}catch(c){throw new pt(0,"network-error",`Could not reach the KwikQA service at ${this.baseUrl} (${Hs(c)}).`)}let d;try{d=await o.json()}catch{d=void 0}if(!o.ok){let c=d?.error;throw new pt(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,r){return this.#e("POST","/v1/usage/reserve",t,e,r)}openSession(t,e="diagnosis"){return this.#e("POST","/v1/usage/session",e==="diagnosis"?{requests:t}:{requests:t,kind:e})}async closeSession(t){let r=(await this.#e("DELETE","/v1/usage/session",void 0,void 0,t))?.retryTicket;return typeof r=="string"&&r!==""?{retryTicket:r}:{}}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=i=>{let a=gb(i),o=$O(i)?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}}},r=i=>{let a=i?.kwikqa?.retryTicket;typeof a=="string"&&a!==""&&t.onRetryTicket?.(a)},s=new On({apiRoot:`${this.baseUrl}/v1/openrouter`,credentialName:"A KwikQA login (run `npx kwikqa login`)",readApiKey:()=>this.token,fetch:this.fetchImpl,timeoutMs:6e5,extraHeaders:e,onCompletionBody:r});return t.jobs!==!0||this.token===void 0?s:new So({baseUrl:this.baseUrl,token:this.token,fetch:this.fetchImpl,preflight:s,headers:e,onCompletionBody:r,...t.onProgress===void 0?{}:{onProgress:t.onProgress},...t.onRestart===void 0?{}:{onRestart:t.onRestart},...t.sleep===void 0?{}:{sleep:t.sleep}})}},To=class{constructor(t,e,r={}){this.inner=t;this.client=e;this.options=r}inner;client;options;preflight(t){return this.inner.preflight(t)}async complete(t){let r=t.body.response_format?.json_schema?.name==="kwikqa_repair_proposal"?"repair":"diagnosis",s;try{let a=gb(t.body);s=await this.client.reserveUsage({kind:r,model:t.route.modelId,provider:t.route.providerSlug,...a===void 0?{}:{framework:a}},this.options.retryTicket,r==="diagnosis"?this.options.session?.():this.options.repairSession?.())}catch(a){if(!(a instanceof pt))throw a;return{kind:"failed",code:"http-error",message:a.message,elapsedMs:0,...a.status===0?{}:{httpStatus:a.status}}}s.retryTicket!==void 0&&this.options.onRetryTicket?.(s.retryTicket);let i=await this.inner.complete(t);return i.kind!=="response"&&await this.client.releaseUsage(s.id,i.httpStatus??599).catch(()=>{}),i}};import{mkdir as DO,readFile as MO,rm as LO,writeFile as _O}from"node:fs/promises";import{homedir as wb}from"node:os";import{join as Xs}from"node:path";function bb(n){return n.KWIKQA_CONFIG_DIR!==void 0&&n.KWIKQA_CONFIG_DIR!==""?n.KWIKQA_CONFIG_DIR:process.platform==="win32"?Xs(n.APPDATA??Xs(wb(),"AppData","Roaming"),"kwikqa"):Xs(n.XDG_CONFIG_HOME??Xs(wb(),".config"),"kwikqa")}function Hu(n){return Xs(bb(n),"credentials.json")}async function Zt(n){if(n.KWIKQA_TOKEN!==void 0&&n.KWIKQA_TOKEN.trim()!=="")return{token:n.KWIKQA_TOKEN.trim(),login:"(KWIKQA_TOKEN)",apiUrl:""};try{let t=JSON.parse(await MO(Hu(n),"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 xb(n,t){await DO(bb(n),{recursive:!0,mode:448}),await _O(Hu(n),`${JSON.stringify(t)}
208
- `,{mode:384})}async function vb(n){await LO(Hu(n),{force:!0})}import{createHash as jO}from"node:crypto";import{basename as FO}from"node:path";var BO=100;function kb(n){return jO("sha256").update(n).digest("hex")}function Rb(n,t){let e=n.projects.find(i=>i.projectId===t.projectId)?.name??"",r=t.location.file,s=t.titlePath.filter(i=>i!==""&&i!==r&&i!==FO(r));return{key:kb([e,r,...t.titlePath].join("\0")).slice(0,32),title:(s.length===0?[t.title]:s).join(" \u203A ").slice(0,300),file:r.slice(0,300),project:e.slice(0,100)}}function Ib(n){return n===void 0?void 0:kb(n).slice(0,32)}function zu(n){if(n.run===void 0)return;let t=n.run,e=t.logicalTests.filter(r=>r.status==="unexpected"||r.status==="flaky").slice(0,BO).map(r=>({...Rb(t,r),status:r.status==="flaky"?"flaky":"failed"}));return{kind:"analysis",outcome:n.outcome,reasonCode:n.reasonCode,framework:t.framework,tests:e}}function Ab(n){let t=n.record,e=n.run===void 0||n.packet===void 0||t?.diagnosis===void 0?void 0:Io(n.run,t.diagnosis,n.packet,t.clusters?.[0]?.representativeId),r=Ib(t?.repair?.repairSessionId);return{kind:"fix",outcome:n.outcome,reasonCode:n.reasonCode,...n.run===void 0?{}:{framework:n.run.framework},...r===void 0?{}:{session:r},...t?.repair?.attempt===void 0?{}:{attempt:t.repair.attempt},...e===void 0||n.run===void 0?{}:{test:Rb(n.run,e)},...t?.repairProposal===void 0?{}:{changedFiles:t.repairProposal.changedFiles,changedLines:t.repairProposal.changedLines}}}function Pb(n){let t=n.record?.repair,e=Ib(t?.repairSessionId);if(!(e===void 0||t===void 0))return{kind:"validation",outcome:n.outcome,reasonCode:n.reasonCode,session:e,attempt:t.attempt}}async function Ys(n,t,e,r){if(r===void 0||e.team?.insights!==!0)return;try{await t.reportInsights([r])}catch{n.print("Team insights: couldn't share this result; nothing else changed.");return}let s=r.kind==="analysis"?`${r.tests.length} failing or flaky test name${r.tests.length===1?"":"s"} and the result`:r.kind==="fix"?"this fix's test and outcome":"the validation result";n.print(`Team insights: shared ${s} with ${e.team.owner}'s team.`)}var VO={npm:"npx",pnpm:"pnpm exec",yarn:"yarn",bun:"bunx"},HO={npm:"npm i -D",pnpm:"pnpm add -D",yarn:"yarn add -D",bun:"bun add -d"};function Sb(n){let t=(n.npm_config_user_agent??"").split("/")[0];return t==="pnpm"||t==="yarn"||t==="bun"?t:"npm"}function vt(n){return`${VO[Sb(n)]} kwikqa`}function Uu(n,t){return`${HO[Sb(n)]} ${t}`}import{basename as zO}from"node:path";function en(n,t){return`${n} ${t}${n===1?"":"s"}`}function Tb(n){return`$${n.toFixed(n<.1?4:2)}`}function UO(n){let t=n.evidence.flatMap(s=>s.locator.type==="diff-hunk"?[s.locator]:[]);if(t.length===0)return[];let e=new Set(t.flatMap(s=>s.commit===void 0?[]:[s.commit])),r=[...e.size===0?[]:[en(e.size,"commit")],...t.some(s=>s.commit===void 0)?["uncommitted changes"]:[]].join(" and ");return[` Changes: ${en(t.length,"changed hunk")} from ${r} that mention the failures (--no-changes leaves them out)`]}function Qs(n,t,e){let r=t.model.reasoningEffort===void 0?"":`, effort ${t.model.reasoningEffort}`,s=t.model.zeroDataRetention===!0?", zero data retention":"";return[`${n==="diagnosis"?"Diagnosis":"Repair proposal"} request -> ${e}`,` Model: ${t.model.modelId} via ${t.model.providerId}${r}${s}`,` Evidence: ${en(t.evidence.length,"redacted item")} from ${t.channels.join(", ")||"the report"}`,` ${en(t.redactionIds.length,"redaction")} applied, ${en(t.omissionIds.length,"item")} withheld by policy`,...UO(t),` Estimate: at most ${t.estimate.estimatedInputTokens.toLocaleString("en-US")} input + ${t.estimate.estimatedOutputTokens.toLocaleString("en-US")} output tokens, at most ${Tb(t.estimate.estimatedDollars)}`,` Caps: ${Tb(t.caps.request.maxDollars)} per request`,` Payload: ${t.payloadManifestHash.slice(0,16)}... (exactly this redacted payload is sent)`]}function Eb(n,t){let e=n.proposal,r=["Proposed repair",` Intent: ${e.intent.statement}`,` Preserves: ${e.intent.preservedBehavior}`,` Changes: ${en(e.changedFiles,"file")}, ${en(e.changedLines,"line")}`,"",...e.diff.trimEnd().split(`
209
- `),"","Validation commands (run later by `kwikqa validate`):"],s=new Map;for(let i of t.commands.filter(a=>a.timing==="post-patch")){let a=i.args.map(d=>/\s/.test(d)?JSON.stringify(d):d),o=` ${zO(i.executable)} ${a.join(" ")}`;s.set(o,(s.get(o)??0)+1)}for(let[i,a]of s)r.push(a===1?i:`${i} (${a} runs)`);return n.checkoutPristine||r.push("","Note: this checkout has other uncommitted changes; they are not touched."),r}function Cb(n,t){let e=r=>t?.logicalTests.find(s=>s.logicalTestId===r)?.title;return n.flatMap((r,s)=>{let i=r.logicalTestIds.map(d=>e(d)??d),a=i.length<=3?i.join(", "):`${i.slice(0,3).join(", ")} and ${i.length-3} more`,o=`${i.length} test${i.length===1?"":"s"}`;return[`Failure group ${s+1} of ${n.length}: ${o} (${a})${r.escalated===!0?", answered by the stronger model":""}`,...r.diagnosis!==void 0&&r.diagnosis.hypotheses.length>0?qu(r.diagnosis):[` ${r.outcome} (${r.reasonCode}): ${r.message}`],""]})}function qu(n){if(n.hypotheses.length===0)return["No cause is supported by the evidence.",` Next: ${n.recommendedNextAction}`];let t=[];for(let e of[...n.hypotheses].sort((r,s)=>r.rank-s.rank))t.push(`#${e.rank} ${e.statement}`,` owner: ${e.probableOwner}, evidence: ${e.evidenceGrade}, cause: ${e.causalCategory}`);return t.push(` Next: ${n.recommendedNextAction}`),t}function Nb(n,t,e,r){switch(t){case"diagnosed":return r!==void 0&&We(r)===void 0?ot(r):n?.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 n?.repair?.retryAvailable===!0?`Run \`${e} fix --retry\` to re-diagnose from the validation evidence (one retry left).`:void 0;default:return}}function Ob(n){if(n===void 0)return;let t=n.artifact.formatVersion===void 0?"":` ${n.artifact.formatVersion}`,e=n.artifact.format===void 0?void 0:Bt[n.artifact.format],r=n.logicalTests.filter(a=>a.status==="unexpected").length,s=n.logicalTests.filter(a=>a.status==="flaky").length;return`Read a ${n.framework==="unknown"?"run from an unidentified framework":`${gt[n.framework]}${t} run`}${e===void 0?"":` (${e})`}: ${en(n.logicalTests.length,"test")}, ${r} failing${s===0?"":`, ${s} flaky`}.`}function $b(n,t){if(n===void 0||We(n)===void 0)return;let e=n.framework==="playwright",r=e?"trace":"kwikqa-capture",s=0,i=0;for(let c of n.logicalTests)for(let l of ir(c))s+=1,l.attachments.some(u=>u.name===r)&&(i+=1);if(s===0||i===s)return;let a=s-i;return[`Note: ${a===s?s===1?`The failing attempt has no ${e?"Playwright trace":"KwikQA failure capture"}`:`None of the ${s} failing attempts has ${e?"a Playwright trace":"a KwikQA failure capture"}`:`${a} of ${s} 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(`
210
- `)}var Zs="0.2.2";var q={ok:0,failed:1,usage:2,account:3},ei=(()=>{let{workspaceRoot:n,...t}=zd;return{...t,maxPacketBytes:6e5}})(),JO=.85;function Ku(n){if(n===void 0)return ei;let t=Math.min(n.diagnosis.caps.request.maxInputTokens,n.repairCaps.request.maxInputTokens);return{...ei,maxPacketBytes:Math.min(ei.maxPacketBytes,Math.floor(t*JO))}}var Lb=["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"],Bb=ze(".kwikqa","cli-state.json");function Wu(n){return`Not signed in. Run \`${vt(n.env)} login\` first.`}async function Er(n){return qO(n).then(()=>!0,()=>!1)}async function Ju(n){try{return JSON.parse(await Eo(ze(n,Bb),"utf8"))}catch{return{}}}async function Xu(n,t){await KO(ze(n,".kwikqa"),{recursive:!0,mode:448}),await jb(ze(n,Bb),`${JSON.stringify(t)}
211
- `,{mode:384})}async function No(n,t,e){if(e!==void 0)return Gu(e)?e:Co(n.cwd,e);for(let r of[n.env.PLAYWRIGHT_JSON_OUTPUT_NAME,n.env.KWIKQA_REPORT_DIR])if(r!==void 0&&r!==""){let s=Gu(r)?r:Co(t,r);if(await Er(s))return s}for(let r of Lb)if(await Er(ze(t,r)))return ze(t,r);return ze(t,Lb[0]??"report.json")}async function Vb(n){try{if((await Mb(n)).isDirectory()){let t=Db("sha256");for(let e of(await WO(n)).sort()){let r=ze(n,e);(await Mb(r)).isFile()&&t.update(`${e}\0`).update(await Eo(r))}return t.digest("hex")}return Db("sha256").update(await Eo(n)).digest("hex")}catch{return}}async function XO(n,t,e){let r=t.capture;if(r===void 0)return;let s=ze(n,r.reportPath);if(await Vb(e)!==r.sourceSha256||!await Er(s))return;let i=r.probePath===void 0?void 0:ze(n,r.probePath);return{reportPath:s,...i!==void 0&&await Er(i)?{probePath:i}:{}}}async function YO(n,t,e,r){let s=await at(e,{workspaceRoot:t,...r.framework===void 0?{}:{framework:r.framework}});if(s.kind!=="parsed"){n.io.error(`Capture skipped: ${s.diagnostic.message}`);return}let i=s.run.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest",a=await Il({run:s.run,workspaceRoot:t,repositoryRoot:await Po(t),captureId:i,env:n.env,probe:r.probe});if(a.kind!=="ready"){n.io.print(`Capture skipped: ${a.message}`);return}for(let c of a.prepared.description)n.io.print(c);if(a.prepared.probeUnavailable!==void 0&&n.io.print(`Note: ${a.prepared.probeUnavailable}`),r.yes)n.io.print("Run these tests? yes (--yes)");else if(!await n.io.confirm("Run these tests?")){n.io.print("Capture declined; analyzing the existing report.");return}let o=await Al(a.prepared,n.env);if(n.io.print(o.outcome.message),o.probe!==void 0){let c=o.probe.results.reduce((l,u)=>l+u.candidates.length,0);n.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 Vb(e);if(d!==void 0){let c=await Ju(t);await Xu(t,{...c,capture:{sourceSha256:d,reportPath:ti(t,o.outcome.reportPath),...o.probePath===void 0?{}:{probePath:ti(t,o.probePath)}}})}return{reportPath:o.outcome.reportPath,...o.probePath===void 0?{}:{probePath:o.probePath}}}function _b(n,t){if(n===void 0||n==="")return{...t,evaluationStatus:"unverified-model"};let[e,r]=n.split("@");if(e===void 0||r===void 0||r==="")throw new pt(0,"invalid-model",`Model routes look like author/model@provider, not ${n}.`);return{modelId:e,providerId:r,evaluationStatus:"unverified-model"}}async function Yu(n,t,e){let r=await Zt(n.env);if(r===void 0)return{exit:q.account,messages:[Wu(n)]};let s=new xt(Qt(n.env,r.apiUrl),r.token,n.fetch),i=await s.status(),a=await s.hostedConfig(),o=yb(i);if(!o&&(n.env.OPENROUTER_API_KEY??"").trim()==="")return{exit:q.account,messages:["The BYOK plans need OPENROUTER_API_KEY in the environment."]};let d=t==="analysis"?i.usage.analyses:i.usage.repairs;if(e===void 0&&d.limit!==void 0&&d.used>=d.limit){let x=t==="analysis"?"analyses":"fixes";return{exit:q.account,messages:[`You have used all ${d.limit} ${x} on the ${i.plan} plan until ${i.periodEnd.slice(0,10)}.`,i.team?.role==="member"?`Ask ${i.team.owner}, who manages your team's plan, to add seats.`:`Run \`${vt(n.env)} upgrade\` to see plans with more.`]}}let c,l,u=a.sessions===!0&&e===void 0?{open:async x=>{l=(await s.openSession(x)).sessionTicket},close:async()=>{let x=l;l=void 0,x!==void 0&&await s.closeSession(x)}}:void 0,p,f=a.repairSessions===!0&&e===void 0?{open:async x=>{p=(await s.openSession(x,"repair")).sessionTicket},close:async()=>{let x=p;if(p=void 0,x===void 0)return;let R=await s.closeSession(x);R.retryTicket!==void 0&&(c=R.retryTicket)}}:void 0,h={...e===void 0?{}:{retryTicket:e},onRetryTicket:x=>{c=x},session:()=>l,repairSession:()=>p};if(!o){let x=new To(new On({readApiKey:()=>n.env.OPENROUTER_API_KEY,fetch:n.fetch}),s,h);return{diagnosis:{model:_b(n.env.KWIKQA_DIAGNOSIS_MODEL,a.models.diagnosis),caps:a.caps.diagnosis,transport:x,...u===void 0?{}:{session:u}},repairModel:_b(n.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:s,status:i}}let m=s.transport({...h,jobs:a.jobs===!0,onProgress:e2(n),onRestart:()=>n.io.print(" The KwikQA service restarted while the model was working; sending the request again (nothing was charged)."),...n.sleep===void 0?{}:{sleep:n.sleep}}),g=e!==void 0&&a.models.escalation!==void 0&&a.caps.escalation!==void 0,y=g?a.models.escalation:void 0,w=g?a.caps.escalation:void 0,v=!g&&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:m,...u===void 0?{}:{session:u},...v===void 0?{}:{escalation:v}},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:s,status:i}}function Hb(n,t){for(let e of t.messages)n.io.error(e);return t.exit}var QO=3e4;function ZO(n){let t=Math.floor(n/1e3),e=Math.floor(t/60);return e===0?`${t}s`:`${e}m ${String(t%60).padStart(2,"0")}s`}function e2(n){let t=0;return e=>{let r=Math.floor(e/QO);r<=t||(t=r,n.io.print(` The model is still working (${ZO(e)})\u2026`))}}function Qu(n,t,e){let r=async(s,i)=>{for(let a of s)n.io.print(a);return e?(n.io.print(`${i} yes (--yes)`),!0):n.io.confirm(i)};return{approveDiagnosis:s=>r(Qs("diagnosis",s,t),"Send this request?"),approveDiagnoses:s=>{let[i]=s;return s.length===1&&i!==void 0?r(Qs("diagnosis",i,t),"Send this request?"):r([`${s.length} diagnosis requests, one for each group of failures with a shared cause:`,...s.flatMap((a,o)=>["",`Request ${o+1} of ${s.length}`,...Qs("diagnosis",a,t)])],`Send these ${s.length} requests?`)},approveRepairRequest:s=>r(Qs("repair proposal",s,t),"Send this request?"),approveApplication:async(s,i)=>{for(let a of Eb(s,i))n.io.print(a);return n.io.confirm("Apply this patch?")}}}async function zb(n,t,e,r,s){let i=new Set(r),a=await Il({run:{...e,logicalTests:e.logicalTests.filter(d=>i.has(d.logicalTestId))},workspaceRoot:t,repositoryRoot:await Po(t),captureId:`${s.purpose}-${e.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest"}`,env:n.env,probe:!1});if(a.kind!=="ready")return{kind:"unavailable",message:a.message};n.io.print(""),n.io.print(s.intro);for(let d of a.prepared.description)n.io.print(d);if(!await n.io.confirm(s.question))return{kind:"declined"};let o=await Al(a.prepared,n.env);return n.io.print(o.outcome.message),o.outcome.kind==="failed"?{kind:"unavailable",message:o.outcome.message}:{kind:"rerun",failedAgain:o.outcome.failedAgain??[]}}function t2(n){return n==="repair-failed"||n==="validation-unavailable"||n==="operation-failed"?q.failed:q.ok}function Oo(n,t){n.io.print("");let e=Ob("run"in t?t.run:void 0);e!==void 0&&t.record?.command!=="validate"&&n.io.print(e);let r=t.record?.clusters??[];if(r.length>1&&t.record?.command!=="validate")for(let o of Cb(r,"run"in t?t.run:void 0))n.io.print(o);else if(t.record?.diagnosis!==void 0&&t.record.command!=="validate"){for(let o of qu(t.record.diagnosis))n.io.print(o);n.io.print("")}n.io.print(`Result: ${t.outcome} (${t.reasonCode})`),n.io.print(t.message);let s=vt(n.env),i=$b("run"in t?t.run:void 0,s);i!==void 0&&n.io.print(i);let a=Nb(t.record,t.outcome,s,"run"in t?t.run:void 0);return a!==void 0&&n.io.print(a),t.recordPath!==void 0&&n.io.print(`Record: ${t.recordPath}`),t2(t.outcome)}async function Fn(n,t){try{return await t()}catch(e){if(e instanceof pt)return n.io.error(e.message),[401,402,403,409].includes(e.status)?q.account:q.failed;throw e}}function Ub(n){return n.sleep??(t=>new Promise(e=>setTimeout(e,t)))}async function qb(n){return Fn(n,async()=>{let t=new xt(Qt(n.env),void 0,n.fetch),e=await t.startDeviceLogin();n.io.print(`Open ${e.verificationUri} and enter the code: ${e.userCode}`);let r=Ub(n),s=Math.max(1,e.interval),i=Date.now()+e.expiresIn*1e3;for(;Date.now()<i;){await r(s*1e3);let a=await t.pollDeviceLogin(e.deviceCode);if(a.status==="complete")return await xb(n.env,{token:a.token,login:a.login,apiUrl:t.baseUrl}),n.io.print(`Signed in as ${a.login}.`),q.ok;if(a.status==="slow_down"&&(s+=5),a.status==="expired"||a.status==="denied")return n.io.error(a.status==="denied"?"Sign-in was denied.":"The code expired."),q.account}return n.io.error("The code expired before sign-in finished."),q.account})}async function Gb(n){let t=(n.env.KWIKQA_TOKEN??"").trim()!=="",e=t?void 0:await Zt(n.env);if(e!==void 0)try{await new xt(Qt(n.env,e.apiUrl),e.token,n.fetch).logout()}catch{n.io.error(`Could not reach the KwikQA service to revoke this token; revoke it at ${Tr}account/.`)}return await vb(n.env),n.io.print("Signed out."),t&&n.io.print("KWIKQA_TOKEN is still set in this environment; unset it to stop using it."),q.ok}function n2(n){let t=[...n.seats!==void 0&&n.seats>1?[`${n.seats} seats`]:[],...n.interval===void 0?[]:[n.interval==="year"?"billed yearly":"billed monthly"]];return`on the ${n.plan} plan${t.length===0?"":` (${t.join(", ")})`}`}async function Kb(n){return Fn(n,async()=>{let t=await Zt(n.env);if(t===void 0)return n.io.print(Wu(n)),q.account;let r=await new xt(Qt(n.env,t.apiUrl),t.token,n.fetch).status(),s=(i,a)=>a===void 0?`${i} (unlimited)`:`${i} of ${a}`;return n.io.print(`Signed in as ${r.login} ${n2(r)}.`),r.team!==void 0&&(n.io.print(r.team.role==="member"?`Team: ${r.team.owner}'s team; usage below is the team's shared pool.`:`Team: yours, with ${r.team.members} member${r.team.members===1?"":"s"}; usage below is the shared pool.`),n.io.print(r.team.insights===!0?"Team insights: on. Test names and fix outcomes from your runs are shared with your team.":"Team insights: off.")),n.io.print(`Analyses this period: ${s(r.usage.analyses.used,r.usage.analyses.limit)}`),n.io.print(`Fixes this period: ${s(r.usage.repairs.used,r.usage.repairs.limit)}`),n.io.print(`Period ends: ${r.periodEnd.slice(0,10)}`),n.io.print(`Manage your account, team, and tokens: ${Tr}`),q.ok})}async function Wb(n){let t=await Zt(n.env);if(t===void 0){n.io.error(Wu(n));return}return new xt(Qt(n.env,t.apiUrl),t.token,n.fetch)}function r2(n){let t=n.perSeat?"/seat":"",e=n.monthlyUsd===0?"$0":`$${n.monthlyUsd}${t}/mo or $${n.annualUsd}${t}/yr`,r=n.analyses===void 0?"unlimited analyses and fixes":`${n.analyses} analyses and ${n.repairs} fixes a month${n.perSeat?" per seat, shared":""}`,s=[...n.hosted?[]:["your OpenRouter key"],...n.perSeat?[`${n.minSeats}+ seats`]:[]];return{price:e,limits:s.length===0?r:`${r} (${s.join(", ")})`}}async function Jb(n,t,e={annual:!1}){return Fn(n,async()=>{let r=await Zt(n.env),s=await new xt(Qt(n.env,r?.apiUrl),void 0,n.fetch).plans(),i=s.paidPlansOpen!==!1,o=s.plans.filter(m=>m.id!=="free").find(m=>m.id===t);if(o===void 0||!i){t!==void 0&&o===void 0&&n.io.error(`Unknown plan: ${t}`),n.io.print(`Plans (monthly, or yearly with ${12-s.annualMonthsCharged} months free):`);let m=Math.max(...s.plans.map(g=>g.id.length));for(let g of s.plans){let{price:y,limits:w}=r2(g);n.io.print(` ${g.id.padEnd(m)} ${y}: ${w}`)}if(i)n.io.print(`Run \`${vt(n.env)} upgrade <plan> [--annual] [--seats <n>]\` to get a checkout link.`);else if(n.io.print("Paid plans are coming soon. Until they open, every account uses Free."),o!==void 0)return q.account;return t===void 0?q.ok:q.usage}let d;if(e.seats!==void 0&&(d=Number(e.seats),!(o.perSeat?Number.isInteger(d)&&d>=o.minSeats&&d<=s.maxSeats:d===1)))return n.io.error(o.perSeat?`${o.name} needs ${o.minSeats} to ${s.maxSeats} seats.`:`${o.name} is for one person; --seats applies to team plans.`),q.usage;let c=await Wb(n);if(c===void 0)return q.account;let l=await c.status();if(l.team?.role==="member")return n.io.print(`You're on ${l.team.owner}'s team, so ${l.team.owner} manages billing.`),q.ok;if(l.plan!=="free")return n.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:`),n.io.print(`${Tr}billing/`),q.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 n.io.print(`Open this link to subscribe to ${o.name}${o.perSeat?` with ${f} seats`:""} for $${h} a ${e.annual?"year":"month"}:`),n.io.print(p.url),q.ok})}async function Xb(n){return Fn(n,async()=>{let t=await Wb(n);if(t===void 0)return q.account;try{let{url:e}=await t.billingPortal();return n.io.print("Open this link to update your payment method or download invoices:"),n.io.print(e),n.io.print(`To change or cancel your plan: ${Tr}billing/`),q.ok}catch(e){if(e instanceof pt&&e.code==="no-billing-account")return n.io.print("You don't have a paid subscription yet."),n.io.print(`Run \`${vt(n.env)} upgrade <plan>\` to choose one.`),q.ok;if(e instanceof pt&&e.code==="team-member")return n.io.print(e.message),q.ok;throw e}})}async function Yb(n){let t=await Cr(n.cwd),e=ze(t,"kwikqa.config.json");if(await Er(e))n.io.print("kwikqa.config.json already exists; review it to change what KwikQA may edit.");else{let p=bu({repositoryPaths:await Mu(t)});n.io.print("Proposed kwikqa.config.json (what KwikQA may edit when repairing tests):");for(let f of p.canonicalContents.trimEnd().split(`
212
- `))n.io.print(` ${f}`);for(let f of[...p.reasons,...p.ambiguities])n.io.print(` - ${f}`);await n.io.confirm("Write kwikqa.config.json?")&&(await jb(e,p.canonicalContents,{flag:"wx"}),n.io.print("Wrote kwikqa.config.json. Commit it so the policy is reviewed like code."))}let r=ze(t,".gitignore"),s=await Er(r)?await Eo(r,"utf8"):"",i=p=>p.trim().replace(/^\//,"").replace(/\/$/,""),a=new Set(s.split(/\r?\n/).map(i)),o=[{entry:".kwikqa/",what:"local run records"},{entry:Va,what:"the failure report"}].filter(p=>!a.has(i(p.entry))),d=o.map(p=>`${p.entry} (${p.what})`).join(" and ");o.length>0&&await n.io.confirm(`Add ${d} to .gitignore?`)&&await GO(r,`
206
+ `,changed:s}}function Du(t){let n=[],e={},r=0;for(let s of[...t].sort((i,a)=>i.path.localeCompare(a.path))){let i=yN(s);n.push(i.text),e[s.path]=i.changed,r+=i.changed}return{text:n.join(""),changedFiles:t.length,changedLines:r,perFileChangedLines:e}}function qw(t,n){return t.changedFiles<=n.maxFiles&&t.changedLines<=n.maxChangedLines?[]:[{code:"budget-exceeded",message:`Proposal changes ${t.changedFiles} files and ${t.changedLines} lines; configured limits are ${n.maxFiles} files and ${n.maxChangedLines} lines.`,manualRepairRecommended:!0}]}function Gw(t,n,e,r){let s=[];(n.packetHash!==t.packetHash||e.packetHash!==t.packetHash||!e.passed)&&s.push({code:"invalid-provenance",message:"Diagnosis and passing deterministic grading must match the evidence packet."});let i=[...n.hypotheses].sort((d,c)=>d.rank-c.rank)[0],a=new Set(t.evidence.map(d=>d.evidenceId)),o=new Set(n.ownershipEvidenceIds);return(n.repairEligibility!=="eligible"||i===void 0||i.probableOwner!=="test-support"||!new Set(["strong","moderate"]).has(i.evidenceGrade)||o.size===0||[...o].some(d=>!a.has(d)||!i.supportingEvidenceIds.includes(d)))&&s.push({code:"insufficient-ownership-evidence",message:"Repair requires a sufficiently graded test-support hypothesis with positive evidence."}),(r.statement.trim().length===0||r.preservedBehavior.trim().length===0||r.evidenceIds.length===0||r.evidenceIds.some(d=>!a.has(d)||!i?.supportingEvidenceIds.includes(d)))&&s.push({code:"intent-ambiguous",message:"Test intent and preserved behavior require valid positive evidence citations."}),s.length>0||i===void 0?{kind:"rejected",reasons:s}:{kind:"eligible",hypothesis:i}}var Kw=oi(ns(),1),gN=/\.([cm]?[jt]sx?)$/i;function Mu(t,n){let e=t.match(gN)?.[1]?.toLowerCase();if(e===void 0)return!1;let r=[];e.includes("t")&&r.push("typescript"),e.endsWith("x")&&r.push("jsx");try{return(0,Kw.parse)(n,{sourceType:"unambiguous",errorRecovery:!1,plugins:r}),!0}catch{return!1}}var wN=[{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 Ws(t,n){return[...t.matchAll(n)].length}function Ww(t){return Ws(t,/\bexpect\s*\(/g)+Ws(t,/\bassert(?:\.|\s*\()/g)+Ws(t,/\.(?:should|and)\s*\(/g)}function Jw(t){let n=new Map;for(let e of t.matchAll(/\.((?:(?:not|resolves|rejects)\.)*)(to[A-Z]\w*)\s*\(/g)){let r=`${e[1]??""}${e[2]??""}`;n.set(r,(n.get(r)??0)+1)}for(let e of t.matchAll(/\.(?:should|and)\s*\(\s*["'`]([\w.]+)["'`]/g)){let r=`should:${e[1]??""}`;n.set(r,(n.get(r)??0)+1)}return n}function bN(t,n){let e=Jw(n);return[...Jw(t)].filter(([r,s])=>(e.get(r)??0)<s).map(([r])=>r).sort()}function Xw(t){let n=[];for(let e of t){if(!Mu(e.path,e.source)||!Mu(e.path,e.result)){n.push({code:"parse-failed",message:"Original and resulting source must parse as supported JavaScript or TypeScript.",path:e.path});continue}let r=bN(e.source,e.result);r.length>0&&n.push({code:"forbidden-edit",message:`The proposal removes, negates, or swaps assertion matchers: ${r.join(", ")}.`,path:e.path});for(let s of e.replacements){Ww(s.newText)<Ww(s.oldText)&&n.push({code:"forbidden-edit",message:"The proposal removes or weakens assertion coverage.",path:e.path});for(let i of wN){if(Ws(s.newText,i.pattern)<=Ws(s.oldText,i.pattern))continue;let a=i.exception==="latency"?s.latencyContractEvidenceIds??[]:i.exception==="locator"?s.brittleLocatorEvidenceIds??[]:[];i.exception!=="never"&&a.length>0||n.push({code:"forbidden-edit",message:i.message,path:e.path})}}}return n}var xN=/^(?:\.\/)?[A-Za-z0-9_./-]+$/,vN=/^[A-Z][A-Z0-9_]*$/,kN=/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTH)/i,RN=new Set(["focused","affected","static"]);function Yw(t){return t.length>0&&!t.includes("\0")&&!t.includes("\\")&&!t.startsWith("/")&&!/^[A-Za-z]:/.test(t)&&!t.split("/").some(n=>n===".."||n==="")}var IN=new Set(["page-object","fixture","test-data","test-helper","playwright-config","framework-config"]);function AN(t){let n=Object.entries(t.environment);return t.id.trim().length>0&&xN.test(t.executable)&&Yw(t.executable.replace(/^\.\//,""))&&!t.args.some(e=>e.includes("\0"))&&(t.workingDirectory==="."||Yw(t.workingDirectory))&&RN.has(t.scope)&&n.every(([e,r])=>vN.test(e)&&!kN.test(e)&&!r.includes("\0"))&&Number.isInteger(t.timeoutMs)&&t.timeoutMs>0&&t.reason.trim().length>0}function Qw(t,n){let e=n.some(i=>IN.has(i)),r=[...t.validation].sort((i,a)=>i.id.localeCompare(a.id));if(r.some(i=>!AN(i)))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 s=[];return r.length===0&&s.push("No deterministic validation steps were discovered."),e&&!r.some(i=>i.scope==="affected")&&s.push("Shared test-support edits require affected-test validation."),{plan:{status:s.length===0?"planned":"unresolved",steps:r,unresolvedReasons:s},reasons:[]}}var Lu=1e6,_u=1e3;function nt(t){return{kind:"rejected",reasons:t}}function TN(t){let{packetHash:n,...e}=t;return nr(e)===n}function PN(t,n){let e=[];for(let r of t)[...r.evidenceIds,...r.latencyContractEvidenceIds??[],...r.brittleLocatorEvidenceIds??[]].some(i=>!n.has(i))&&e.push({code:"invalid-replacement",message:"Every replacement and policy exception must cite accepted supporting evidence.",path:r.path});return e}async function ju(t){let n=_n(t.config);if(n.kind!=="valid")return nt(n.issues.map(p=>({code:"invalid-config",message:p})));if(!TN(t.packet)||t.snapshot.workspaceRoot!==t.packet.workspace.root||t.packet.workspace.gitRoot!==void 0&&t.snapshot.gitRoot!==t.packet.workspace.gitRoot)return nt([{code:"invalid-provenance",message:"Packet integrity and repository snapshot identity must match."}]);let e=Gw(t.packet,t.diagnosis,t.grading,t.intent);if(e.kind!=="eligible")return nt(e.reasons);let r=t.maxSourceBytes??Lu;if(!Number.isInteger(r)||r<=0||r>Lu)return nt([{code:"invalid-provenance",message:`maxSourceBytes must be an integer from 1 to ${Lu}.`}]);if(t.replacements.length===0)return nt([{code:"invalid-replacement",message:"Proposal has no replacements."}]);let s=PN(t.replacements,new Set(e.hypothesis.supportingEvidenceIds));if(s.length>0)return nt(s);let i=await Qg(n.config,t.snapshot,t.replacements,r);if(i.kind!=="authorized")return nt(i.reasons);if(i.targets.some(p=>p.source.split(/\r?\n/u).length>_u||p.replacements.some(f=>f.newText.split(/\r?\n/u).length>_u)))return nt([{code:"budget-exceeded",message:`M5 safely derives diffs only for targets and replacement text up to ${_u} lines.`,manualRepairRecommended:!0}]);let a=Xg(i.targets);if(a.kind!=="applied")return nt(a.reasons);let o=Xw(a.targets);if(o.length>0)return nt(o);let d=Du(a.targets),c=qw(d,n.config.budgets);if(c.length>0)return nt(c);let l=Qw(t.snapshot,a.targets.map(p=>p.class));if(l.reasons.length>0)return nt(l.reasons);let u={schemaVersion:"1.0",policyVersion:"1.0",runId:t.packet.runId,packetHash:t.packet.packetHash,acceptedHypothesisId:e.hypothesis.hypothesisId,intent:t.intent,budgets:n.config.budgets,changedFiles:d.changedFiles,changedLines:d.changedLines,replacements:t.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:L(d.text),validationPlan:l.plan};return{kind:"proposal-ready",proposal:{...u,proposalHash:L(u)}}}import{readFile as FN,realpath as ub}from"node:fs/promises";import{join as BN,relative as VN,sep as zN}from"node:path";var SN=new Set(["failed","timedOut","interrupted"]);function EN(t){return t.status==="unexpected"||t.status==="flaky"}function tb(t){return[...t.clusters].sort((n,e)=>e.logicalTestIds.length-n.logicalTestIds.length||n.clusterId.localeCompare(e.clusterId)).slice(0,6)}function CN(t){return t.attachments.reduce((n,e)=>n+(e.name==="trace"||e.contentType==="application/zip"?10:e.path===void 0?0:1),0)}function nb(t,n){let e=new Set(n.logicalTestIds);return t.logicalTests.filter(s=>e.has(s.logicalTestId)).map(s=>{let i=s.attempts.filter(a=>SN.has(a.status));return{test:s,score:Math.max(0,...i.map(CN)),startedAt:i.map(a=>a.startTime).sort()[0]??""}}).sort((s,i)=>i.score-s.score||s.startedAt.localeCompare(i.startedAt)||s.test.logicalTestId.localeCompare(i.test.logicalTestId))[0]?.test}function rb(t,n,e){let r=new Set(n.logicalTestIds);return{...t,logicalTests:t.logicalTests.map(s=>r.has(s.logicalTestId)?s.logicalTestId===e?s:{...s,attempts:s.attempts.map(i=>({...i,attachments:[]}))}:EN(s)?{...s,attempts:[]}:s)}}function sb(t,n,e){return{...e,runId:n.runId,clusters:[{...t,symptomIds:n.symptoms.filter(r=>r.logicalTestId!==void 0&&t.logicalTestIds.includes(r.logicalTestId)).map(r=>r.symptomId).sort()}]}}async function ib(t,n,e){let r=new Array(t.length),s=0,i=Array.from({length:Math.min(n,t.length)},async()=>{for(;s<t.length;){let a=s;s+=1,r[a]=await e(t[a])}});return await Promise.all(i),r}import{randomUUID as ab}from"node:crypto";import{readdir as ob,readFile as NN,realpath as ON}from"node:fs/promises";import{join as Sr,relative as $N,sep as DN}from"node:path";var Fu=/^run_[a-f0-9]{24}$/,Bu=/^rec_[a-f0-9]{24}$/;function wo(){return`rec_${ab().replaceAll("-","").slice(0,24)}`}function Er(){return`auth_${ab().replaceAll("-","").slice(0,24)}`}async function Js(t,n){if(!Fu.test(n.runId)||!Bu.test(n.recordId))throw new Error("Run record identity is not path-safe.");let e=await Fe(t,[".kwikqa","runs",n.runId]),r=await Fe(t,[".kwikqa","runs",n.runId,"records"]),s=`${pe(n)}
207
+ `,i=Sr(r,`${n.recordId}.json`);return await ye(i,s,{mode:384,replace:!1}),await ye(Sr(e,"result.json"),s,{mode:384,replace:!0}),$N(await ON(t),i).split(DN).join("/")}var MN=new Set(["analyze","fix","validate"]),LN=["analysis","proposal","application","validation"];function _N(t,n){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.schemaVersion=="string"&&e.schemaVersion.startsWith("1.")&&typeof e.recordId=="string"&&Bu.test(e.recordId)&&e.runId===n&&typeof e.command=="string"&&MN.has(e.command)&&typeof e.recordedAt=="string"&&typeof e.outcome=="string"&&typeof e.reasonCode=="string"&&typeof e.message=="string"&&LN.every(r=>typeof e[r]=="object"&&e[r]!==null)}async function db(t,n){try{let e=JSON.parse(await NN(t,"utf8"));return _N(e,n)?e:void 0}catch{return}}async function Vu(t,n){if(!Fu.test(n))return[];let e=Sr(t,".kwikqa","runs",n,"records"),r=await ob(e).catch(()=>[]);return(await Promise.all(r.filter(i=>Bu.test(i.replace(/\.json$/,""))&&i.endsWith(".json")).map(i=>db(Sr(e,i),n)))).filter(i=>i!==void 0).sort((i,a)=>i.recordedAt.localeCompare(a.recordedAt)||i.recordId.localeCompare(a.recordId))}async function zu(t){let n=Sr(t,".kwikqa","runs"),e=(await ob(n).catch(()=>[])).filter(s=>Fu.test(s)),r;for(let s of e){let i=await db(Sr(n,s,"result.json"),s);i!==void 0&&(r===void 0||i.recordedAt>r.recordedAt)&&(r=i)}return r?.runId}var xo=new Set(["context-limit-exceeded","request-token-budget-exceeded","request-dollar-budget-exceeded","run-token-budget-exceeded","run-dollar-budget-exceeded"]),HN={"test-support":"test-support-owned",application:"application-owned",environment:"environment-owned",undetermined:"owner-undetermined"};function UN(t){return t.logicalTests.filter(n=>n.status==="unexpected"||n.status==="flaky").map(n=>n.logicalTestId).sort()}function qN(t,n){switch(t.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 n.length===0?{reasonCode:"no-failures",message:"The run has no failing or flaky tests."}:void 0}}async function cb(t,n){let e=await ub(n).catch(()=>n);return VN(t,e).split(zN).join("/")}async function GN(t,n){return{report:await cb(n,t.reportPath),...t.framework===void 0?{}:{framework:t.framework},...t.probePath===void 0?{}:{probe:await cb(n,t.probePath)},changeHistory:t.includeChangeHistory===!0,currentDiff:t.includeCurrentDiff===!0,maxPacketBytes:t.evidencePolicy.maxPacketBytes}}function vo(t){let n=[...t.hypotheses].sort((e,r)=>e.rank-r.rank)[0];return HN[n?.probableOwner??"undetermined"]??"owner-undetermined"}function KN(t,n){return t==="operation-failed"?"failed":n?"insufficient-evidence":"completed"}async function Ys(t,n){let e=await ot(t.reportPath,{workspaceRoot:t.workspaceRoot,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot},...t.framework===void 0?{}:{framework:t.framework}});if(e.kind==="unreadable")return{kind:"unreadable",outcome:"inconclusive",reasonCode:e.artifact.availability==="unavailable"?"report-unavailable":"report-unreadable",message:e.diagnostic.message};let r=e.run,s=UN(r),i=await GN(t,r.workspace.root),a=(v,R={})=>({kind:"analyzed",stage:{run:r,failing:s,inputs:i,...R,result:v}});if(t.repairableOnly===!0&&Je(r)===void 0)return a({outcome:"inconclusive",reasonCode:"report-only-framework",message:dt(r),insufficient:!0});let o=await ta(r,{artifactRoot:t.artifactRoot??r.workspace.root,includeCurrentDiff:t.includeCurrentDiff===!0,includeChangeHistory:t.includeChangeHistory===!0,...t.probePath===void 0?{}:{probePath:t.probePath}},{...t.evidencePolicy,workspaceRoot:r.workspace.root});if(o.kind!=="built")return a(o.kind==="invalid-policy"?{outcome:"operation-failed",reasonCode:"invalid-evidence-policy",message:o.message}:{outcome:"inconclusive",reasonCode:"evidence-budget-exceeded",message:o.message,insufficient:!0});let d=o.packet,c=ia(r,d),l=Lc(c),u={packet:d,symptoms:c,clusters:l},p={...u,triage:u},f=qN(r,s);if(f!==void 0)return a({outcome:"inconclusive",...f,insufficient:!0},p);if(t.remote===void 0)return a({outcome:"inconclusive",reasonCode:"remote-diagnosis-not-configured",message:"Local evidence analysis completed; no remote diagnosis was configured."},p);let h=await ZN(t,r,l,n),m=XN(h);if(m===void 0)return a({outcome:"inconclusive",reasonCode:"no-failures",message:"No failing test produced a symptom to diagnose.",insufficient:!0},p);let g=h.filter(v=>v.result.reasonCode!=="cluster-not-requested"),y=g.filter(v=>v.result.outcome==="diagnosed").length,w=l.clusters.length-g.length,x=l.clusters.length>1?`${y} of ${l.clusters.length} failure groups diagnosed.${w>0?` ${w} not sent: ${WN(h)}`:""}`:m.result.message;return a({...m.result,message:x},{triage:u,...m.packet===void 0?p:{packet:m.packet},...m.symptoms===void 0?{}:{symptoms:m.symptoms},...m.clusters===void 0?{}:{clusters:m.clusters},clusterStages:[m,...h.filter(v=>v!==m)],representativeId:m.representativeId})}function WN(t){return t.find(e=>e.result.reasonCode==="cluster-not-requested")?.result.message??"at most 6 groups are sent per analysis."}var JN={strong:3,moderate:2,weak:1,insufficient:0};function lb(t){let[n]=[...t.result.diagnosis?.hypotheses??[]].sort((e,r)=>e.rank-r.rank);return JN[n?.evidenceGrade??""]??0}function ko(t){return t.map((n,e)=>({item:n,index:e})).filter(({item:n})=>n.result.outcome==="diagnosed"&&n.result.reasonCode==="test-support-owned").sort((n,e)=>lb(e.item)-lb(n.item)||e.item.cluster.logicalTestIds.length-n.item.cluster.logicalTestIds.length||n.index-e.index).map(({item:n})=>n)}function XN(t){let n=t.filter(e=>e.result.outcome==="diagnosed");return ko(t)[0]??n[0]??t[0]}var YN=new Set(["provider-refusal","malformed-response","schema-invalid","citation-or-grading-invalid"]);async function pb(t,n,e,r){let s=nb(n,r);if(s===void 0)return;let i=rb(n,r,s.logicalTestId),a=await ta(i,{artifactRoot:t.artifactRoot??n.workspace.root,includeCurrentDiff:t.includeCurrentDiff===!0,includeChangeHistory:t.includeChangeHistory===!0,...t.probePath===void 0?{}:{probePath:t.probePath}},{...t.evidencePolicy,workspaceRoot:n.workspace.root});if(a.kind!=="built")return{cluster:r,representativeId:s.logicalTestId,result:{outcome:"inconclusive",reasonCode:"evidence-budget-exceeded",message:a.message,insufficient:!0}};let o=ia(i,a.packet);return{cluster:r,representativeId:s.logicalTestId,packet:a.packet,symptoms:o,clusters:sb(r,o,e)}}var QN={approveDiagnosis:async()=>!1};async function Hu(t,n){let e=await Ys({...t,interaction:QN,persist:!1},()=>new Date().toISOString());if(e.kind==="unreadable")return{kind:"unreadable",message:e.message};let{run:r,triage:s}=e.stage;if(s===void 0)return{kind:"rebuilt",run:r};let i={};for(let a of s.clusters.clusters){if(!n.includes(a.clusterId))continue;let o=await pb(t,r,s.clusters,a);o?.packet!==void 0&&(i[a.clusterId]=o.packet)}return{kind:"rebuilt",run:r,detail:{...s,groupPackets:i}}}async function ZN(t,n,e,r){let s=t.remote;if(s===void 0)return[];let i=tb(e),a=[],o=[];for(let g of i){let y=await pb(t,n,e,g);y!==void 0&&("result"in y?a.push(y):o.push(y))}let d=[];for(let g of o){let y=t.reuseDiagnosis===!0?await tO(n.workspace.root,n.runId,g.packet,g.symptoms):void 0;y===void 0?d.push(g):a.push(Yt(g,y))}let c=a.some(g=>g.result.reasonCode==="test-support-owned"),l=(g,y)=>{for(let w of g)a.push(Yt(w,{outcome:"inconclusive",reasonCode:"cluster-not-requested",message:y}))};if(t.reuseDiagnosis===!0&&c)return l(d,"A recorded diagnosis of another group already supports a repair."),Xs(a,i);let u=s.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 g=>({item:g,prepared:await lo({packet:g.packet,symptoms:g.symptoms,clusters:g.clusters,model:s.model,caps:s.caps,transport:s.transport,now:r()})})))).flatMap(({item:g,prepared:y})=>y.kind==="preview-ready"?[{item:g,prepared:y.prepared}]:(a.push(Yt(g,{outcome:xo.has(y.reasonCode)?"inconclusive":"operation-failed",reasonCode:y.reasonCode,message:y.message,audit:y.audit})),[]));if(f.length===0)return Xs(a,i);let h=f.map(g=>g.prepared.preview),m;if(t.interaction.approveDiagnoses!==void 0)m=await t.interaction.approveDiagnoses(h);else{m=!0;for(let g of h)await t.interaction.approveDiagnosis(g)||(m=!1)}if(!m){for(let g of f)a.push(Yt(g.item,{outcome:"inconclusive",reasonCode:"remote-consent-declined",message:"The developer declined the diagnosis request; no evidence was sent."}));return Xs(a,i)}if(s.session!==void 0)try{await s.session.open(f.length)}catch(g){let y=g instanceof Error?g.message:"The analysis session could not be opened.";for(let w of f)a.push(Yt(w.item,{outcome:"operation-failed",reasonCode:"session-unavailable",message:y}));return Xs(a,i)}try{let g=await ib(f,3,async y=>{let w=await fb(t,y.prepared,s.transport,r),x=s.escalation;if(x===void 0||!YN.has(w.reasonCode))return Yt(y.item,w);let v=await eO(t,y.item,x,s.transport,r);return v===void 0?Yt(y.item,w):{...Yt(y.item,v),escalated:!0}});a.push(...g)}finally{await s.session?.close().catch(()=>{})}return Xs(a,i)}function Xs(t,n){let e=new Map(n.map((r,s)=>[r.clusterId,s]));return[...t].sort((r,s)=>(e.get(r.cluster.clusterId)??0)-(e.get(s.cluster.clusterId)??0))}function Yt(t,n){return{cluster:t.cluster,representativeId:t.representativeId,packet:t.packet,symptoms:t.symptoms,clusters:t.clusters,result:n}}async function fb(t,n,e,r){let s=await Tu({prepared:n,authorization:{bindingHash:n.authorizationBindingHash,mode:"interactive",authorizedAt:r(),authorizationId:Er()},authorizationStore:t.authorizationStore??new Cn,transport:e,now:r()});switch(s.kind){case"diagnosed":return{outcome:"diagnosed",reasonCode:vo(s.diagnosis),message:"The diagnosis passed schema validation and local grading.",diagnosis:s.diagnosis,grading:s.grading,audit:s.audit};case"abstained":return{outcome:"inconclusive",reasonCode:s.reasonCode,message:"The evidence was insufficient for a supported diagnosis.",diagnosis:s.diagnosis,grading:s.grading,audit:s.audit};default:return{outcome:xo.has(s.reasonCode)?"inconclusive":"operation-failed",reasonCode:s.reasonCode,message:s.message,audit:s.audit}}}async function eO(t,n,e,r,s){let i=await lo({packet:n.packet,symptoms:n.symptoms,clusters:n.clusters,model:e.model,caps:e.caps,transport:r,now:s()});if(i.kind==="preview-ready"&&await t.interaction.approveDiagnosis(i.prepared.preview))return fb(t,i.prepared,r,s)}async function tO(t,n,e,r){if(/^run_[a-f0-9]{24}$/.test(n))try{let s=await ub(t),i=JSON.parse(await FN(BN(s,".kwikqa","runs",n,"result.json"),"utf8")),a=u=>u==="diagnosed"||u==="inconclusive",o=[...(i.clusters??[]).filter(u=>a(u.outcome)),...a(i.outcome)?[i]:[]].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=Rs(d,e,r);if(!c.passed)return;let l=o.outcome==="inconclusive";return{outcome:l?"inconclusive":"diagnosed",reasonCode:l?o.reasonCode??"insufficient-evidence":vo(d),message:"Reused the graded diagnosis recorded for this exact evidence packet.",diagnosis:d,grading:c,audit:o.diagnosisAudit}}catch{return}}function nO(t){return{clusterId:t.cluster.clusterId,logicalTestIds:t.cluster.logicalTestIds,representativeId:t.representativeId,signals:t.cluster.signals,...t.packet===void 0?{}:{packetHash:t.packet.packetHash},outcome:t.result.outcome,reasonCode:t.result.reasonCode,message:t.result.message,...t.result.diagnosis===void 0?{}:{diagnosis:t.result.diagnosis},...t.result.grading===void 0?{}:{grading:t.result.grading},...t.result.audit===void 0?{}:{diagnosisAudit:t.result.audit},...t.escalated===!0?{escalated:!0}:{}}}function Ro(t,n,e,r,s={}){let{run:i,packet:a,symptoms:o,clusters:d}=t,c=t.result;return{schemaVersion:"1.1",recordId:wo(),command:n,runId:i.runId,createdAt:i.createdAt,recordedAt:r(),workspace:i.workspace,sourceHashes:a?.sourceHashes??i.sourceHashes,usability:i.usability,failingLogicalTestIds:t.failing,inputs:t.inputs,analysis:{status:KN(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}},...t.clusterStages===void 0||t.clusterStages.length===0?{}:{clusters:t.clusterStages.map(nO)},...c.diagnosis===void 0?{}:{diagnosis:c.diagnosis},...c.grading===void 0?{}:{grading:c.grading},...c.audit===void 0?{}:{diagnosisAudit:c.audit},...s,outcome:e.outcome,reasonCode:e.reasonCode,message:e.message}}function rO(t,n){let e={};for(let r of n.clusterStages??[])r.packet!==void 0&&(e[r.cluster.clusterId]=r.packet);return{...t,groupPackets:e}}async function Io(t,n,e){let r={run:t.run,...t.packet===void 0?{}:{packet:t.packet},...t.symptoms===void 0?{}:{symptoms:t.symptoms},...t.clusters===void 0?{}:{clusters:t.clusters},...t.triage===void 0?{}:{detail:rO(t.triage,t)}},s=(i,a)=>({outcome:i.outcome,reasonCode:i.reasonCode,message:i.message,record:i,...a===void 0?{}:{recordPath:a},...r});if(!e)return s(n);try{return s(n,await Js(t.run.workspace.root,n))}catch{return s({...n,outcome:"operation-failed",reasonCode:"record-write-failed",message:"The run record could not be written safely under .kwikqa/runs/."})}}async function Ao(t){let n=t.now??(()=>new Date().toISOString()),e=await Ys(t,n);if(e.kind==="unreadable")return{outcome:e.outcome,reasonCode:e.reasonCode,message:e.message};let{stage:r}=e;return Io(r,Ro(r,"analyze",r.result,n),t.persist!==!1)}import{randomUUID as kO}from"node:crypto";import{relative as RO,resolve as IO,sep as AO}from"node:path";import{createHash as hb}from"node:crypto";import{lstat as sO,readFile as iO,realpath as To}from"node:fs/promises";import{isAbsolute as aO,join as oO,relative as dO,resolve as cO,sep as lO}from"node:path";var Qt=/^[a-f0-9]{64}$/,yb=/^vld_[a-f0-9]{24}$/,uO=Kt,pO=4*1024*1024,fO=2*1024*1024;function jn(t){return{code:"transaction-unavailable",message:t}}function Qs(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function qu(t,n){let e=Object.keys(t).sort(),r=[...n].sort();return e.length===r.length&&e.every((s,i)=>s===r[i])}function Uu(t){return Array.isArray(t)&&t.every(n=>typeof n=="string"&&n.length>0&&!n.includes("\0"))}function hO(t,n){let e=dO(t,n);return e===""||!aO(e)&&e!==".."&&!e.startsWith(`..${lO}`)}function mO(t){return typeof t=="string"&&t.length>0&&Number.isFinite(Date.parse(t))}function mb(t){return Qs(t)?qu(t,["path","observedBytes","storedBytes","sha256","storedSha256","truncated","redacted"])&&typeof t.path=="string"&&t.path.length>0&&typeof t.sha256=="string"&&Qt.test(t.sha256)&&typeof t.storedSha256=="string"&&Qt.test(t.storedSha256)&&Number.isInteger(t.observedBytes)&&t.observedBytes>=0&&Number.isInteger(t.storedBytes)&&t.storedBytes>=0&&typeof t.truncated=="boolean"&&typeof t.redacted=="boolean":!1}function gb(t){if(!Qs(t))throw new Error("Validation command record is not an object.");let n=t,{recordHash:e,...r}=n;if(!qu(t,["schemaVersion","validationRunId","commandId","commandHash","planHash","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","startedAt","durationMs","termination","stdout","stderr","artifacts","status","recordHash"])||n.schemaVersion!=="1.0"||!yb.test(n.validationRunId)||!uO.test(n.commandId)||!Qt.test(n.commandHash)||!Qt.test(n.planHash)||n.timing!=="post-patch"||n.required!==!0||n.executable!==process.execPath||!Uu(n.args)||typeof n.kind!="string"||n.kind.length===0||typeof n.workingDirectory!="string"||n.workingDirectory.length===0||!Qs(n.environmentDelta)||!Object.entries(n.environmentDelta).every(([s,i])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)&&typeof i=="string"&&!i.includes("\0"))||!Number.isInteger(n.timeoutMs)||n.timeoutMs<=0||typeof n.purpose!="string"||n.purpose.length===0||!Uu(n.logicalTestIds)||!Uu(n.projectIds)||!mO(n.startedAt)||!Number.isInteger(n.durationMs)||n.durationMs<0||!Qs(n.termination)||n.termination.kind!=="exit"||n.termination.exitCode!==0||!mb(n.stdout)||!mb(n.stderr)||n.stdout.truncated||n.stderr.truncated||!Array.isArray(n.artifacts)||!n.artifacts.every(s=>Qs(s)&&qu(s,["path","sha256","bytes"])&&typeof s.path=="string"&&s.path.length>0&&typeof s.sha256=="string"&&Qt.test(s.sha256)&&Number.isInteger(s.bytes)&&s.bytes>=0)||n.status!=="passed"||!Qt.test(e)||L(r)!==e)throw new Error("Validation command record is malformed or non-passing.");return n}function yO(t){let n=Wt(JSON.parse(t));if(n.status!=="passed")throw new Error("Validation manifest is not passing.");for(let e of n.commandRecords)gb(e);return n}async function wb(t){let[n,e,r,s]=await Promise.all([To(t.workspace.workspaceRoot),To(t.snapshot.workspaceRoot),To(t.workspace.gitRoot),To(t.snapshot.gitRoot)]);if(n!==e||r!==s)throw new Error("Validation workspace identity changed.");return n}async function bb(t,n,e){for(let r of e.manifest.targets){let s=await Q(t,r.path,n.maxTargetBytes);if(s.kind!=="read"||s.relativePath!==r.path||s.sha256!==r.resultSha256)return!1}return!0}function xb(t){return Qt.test(t.planHash)&&yb.test(t.validationRunId)}async function Po(t,n,e){let r=cO(t,n);if(!hO(t,r))throw new Error("Validation record path escapes its run.");let s=await sO(r);if(!s.isFile()||s.isSymbolicLink()||s.size>e)throw new Error("Validation record path is unsafe or unbounded.");return iO(r)}async function gO(t,n,e){let r=new Map(e.requiredCommands.map(s=>[s.commandId,s.commandHash]));for(let s of n.commandRecords){if(s.validationRunId!==n.validationRunId||s.planHash!==n.planHash||r.get(s.commandId)===void 0)return!1;let i=r.get(s.commandId);if(i===void 0||s.commandHash!==i)return!1;let a=await Po(t,`commands/${s.commandId}/result.json`,fO),o=gb(JSON.parse(a.toString("utf8")));if(L(o)!==L(s))return!1;for(let d of[s.stdout,s.stderr]){let c=await Po(t,d.path,An);if(c.byteLength!==d.storedBytes||hb("sha256").update(c).digest("hex")!==d.storedSha256)return!1}for(let d of s.artifacts){let c=await Po(t,d.path,yr);if(c.byteLength!==d.bytes||hb("sha256").update(c).digest("hex")!==d.sha256)return!1}}return!0}async function Gu(t){if(!xb(t))return{kind:"rejected",reasons:[jn("Validation identity is invalid.")]};let n=t.now??new Date().toISOString(),e;try{let r=await wb(t.context);e=await Ge(r,{operation:"begin-validation",transactionId:t.transactionId,validationRunId:t.validationRunId,at:n});let s=await Re(r,t.transactionId),i=s.state.history.at(-1);return s.state.phase==="validating"&&i?.type==="validation-started"&&i.planHash===t.planHash&&i.validationRunId===t.validationRunId?{kind:"validating",transaction:Pe(s)}:s.state.phase!=="applied"||s.manifest.preview.authoritativeValidation.planHash!==t.planHash||!await bb(r,t.context,s)?{kind:"rejected",reasons:[jn("Applied transaction does not match the approved validation handoff.")],transaction:Pe(s)}:(s=await Ue({transaction:s,phase:"validating",type:"validation-started",planHash:t.planHash,validationRunId:t.validationRunId,now:n}),{kind:"validating",transaction:Pe(s)})}catch{return{kind:"failed",reasons:[jn("Validation transition failed closed.")]}}finally{await e?.release().catch(()=>{})}}async function Ku(t){if(!xb(t)||!Qt.test(t.validationManifestHash))return{kind:"rejected",reasons:[jn("Validation completion identity is invalid.")]};let n=t.now??new Date().toISOString(),e;try{let r=await wb(t.context);e=await Ge(r,{operation:"complete-validation",transactionId:t.transactionId,validationRunId:t.validationRunId,at:n});let s=await Re(r,t.transactionId),i=s.manifest.preview.authoritativeValidation,a=s.state.history.at(-1);if(s.state.phase==="completed"&&a?.type==="validation-passed"&&a.planHash===t.planHash&&a.validationRunId===t.validationRunId&&a.validationManifestHash===t.validationManifestHash)return{kind:"completed",transaction:Pe(s)};if(s.state.phase!=="validating"||i.planHash!==t.planHash||a?.type!=="validation-started"||a.validationRunId!==t.validationRunId||a.planHash!==t.planHash||!await bb(r,t.context,s))return{kind:"rejected",reasons:[jn("Transaction is not validating this exact approved run.")],transaction:Pe(s)};let o=oO(s.directory,"validation",t.validationRunId),d=await Po(o,"manifest.json",pO),c=yO(d.toString("utf8")),l=new Set(c.requiredCommandIds),u=new Set(c.commandRecords.map(f=>f.commandId)),p=i.targetHashes;return c.manifestHash!==t.validationManifestHash||c.transactionId!==t.transactionId||c.validationRunId!==t.validationRunId||c.planHash!==t.planHash||c.repositoryFingerprint!==i.repositoryFingerprint||L(c.targetHashes)!==L(p)||l.size!==c.requiredCommandIds.length||u.size!==c.commandRecords.length||i.requiredCommandIds.some(f=>!l.has(f)||!u.has(f))||l.size!==i.requiredCommandIds.length||u.size!==i.requiredCommandIds.length||!await gO(o,c,i)?{kind:"rejected",reasons:[jn("Validation manifest does not prove the exact approved command set.")],transaction:Pe(s)}:(s=await Ue({transaction:s,phase:"completed",type:"validation-passed",planHash:t.planHash,validationRunId:t.validationRunId,validationManifestHash:c.manifestHash,now:n}),{kind:"completed",transaction:Pe(s)})}catch{return{kind:"failed",reasons:[jn("Validation completion failed closed.")]}}finally{await e?.release().catch(()=>{})}}import{join as wO}from"node:path";var vb="1.0",bO=/^rps_[a-f0-9]{24}$/,xO=8*1024*1024;function vO(t){if(typeof t!="object"||t===null)return;let n=t;if(!(typeof n.reportPath!="string"||!Array.isArray(n.logicalTestIds)||!n.logicalTestIds.every(e=>typeof e=="string")||n.framework!==void 0&&!ht.includes(n.framework)))return{reportPath:n.reportPath,...n.framework===void 0?{}:{framework:n.framework},logicalTestIds:n.logicalTestIds}}function kb(t){if(!bO.test(t))throw new Error("Repair session id is invalid.");return[".kwikqa","repairs",t]}async function Rb(t,n){let e=await Fe(t,kb(n.repairSessionId));await ye(wO(e,`attempt-${n.attempt}.json`),`${pe(n)}
208
+ `,{mode:384,replace:!1})}async function Ib(t,n,e){let r=await Fe(t,kb(n)),s=await Pn(r,`attempt-${e}.json`,xO),i=_n(s.config);if(s.schemaVersion!==vb||s.repairSessionId!==n||s.attempt!==e||typeof s.transactionId!="string"||s.workspace===void 0||typeof s.maxTargetBytes!="number"||s.record===void 0||i.kind!=="valid")throw new Error("Repair attempt state is malformed.");let a=vO(s.group);return{schemaVersion:vb,repairSessionId:n,attempt:e,transactionId:s.transactionId,plan:Tn(s.plan),workspace:s.workspace,config:i.config,maxTargetBytes:s.maxTargetBytes,record:s.record,...a===void 0?{}:{group:a}}}import{dirname as Ab,resolve as Tb}from"node:path";function Cr(t,n){return{kind:"configuration",path:t.relativePath,sha256:t.sha256,detail:n}}async function Pb(t){let{run:n,test:e,discovery:r}=t,s=Je(n);if(s===void 0)return{kind:"unavailable",message:dt(n)};if(s==="playwright")return{kind:"unavailable",message:"Playwright validation needs no prepared run."};let i=n.configFile??await fa(t.workspaceRoot,s,e.location.file),a=r.scope==="focused"?[e.location.file]:r.scope==="affected"?r.testPaths:[],o=await Wa(t.workspaceRoot);if(s==="cypress"){let c=await ha(t.workspaceRoot,i),l=r.scope==="focused"?n.logicalTests.filter(f=>f.location.file===e.location.file&&f.projectId===e.projectId&&f.status==="expected"):[],u=await Ja({workspaceRoot:t.workspaceRoot,runtime:o,...i===void 0?{}:{configFile:i},specs:a,screenshotsDirectory:`${t.artifactRoot}/screenshots`,noRetries:!0,capture:{directory:`${t.artifactRoot}/capture`,supportFile:c,...r.scope==="focused"?{only:[e,...l].map(f=>f.titlePath.join(" "))}:{}}}),p=l.map(f=>f.logicalTestId);return{kind:"prepared",prepared:{args:u.args,workingDirectory:i===void 0?t.workspaceRoot:Ab(Tb(t.workspaceRoot,i)),evidence:[Cr(o["cypress-reporter.cjs"],"KwikQA's Cypress reporter."),Cr(o["cypress-capture.js"],"KwikQA's Cypress failure capture."),...u.generated.map(f=>Cr(f,"Support file KwikQA generated for this validation."))],companionLogicalTestIds:p}}}if(i===void 0)return{kind:"unavailable",message:"No wdio.conf was found for the failing spec, so its validation run is unknown."};let d=await Xa({workspaceRoot:t.workspaceRoot,runtime:o,configFile:i,specs:a,directory:`${t.artifactRoot}/runner`,noRetries:!0,...r.scope==="focused"?{grep:cw(e.titlePath)}:{},capture:!0});return{kind:"prepared",prepared:{args:d.args,workingDirectory:Ab(Tb(t.workspaceRoot,i)),evidence:[Cr(o["wdio-reporter.mjs"],"KwikQA's WebdriverIO reporter."),Cr(o["wdio-capture.mjs"],"KwikQA's WebdriverIO run wrapper."),...d.generated.map(c=>Cr(c,"WebdriverIO config KwikQA generated for this validation."))],companionLogicalTestIds:[]}}}var TO=600*1e3,Sb=1e6,PO={maxFiles:5e3,maxFileBytes:1024*1024,maxTotalBytes:64*1024*1024,maxImportEdges:5e4,maxImportDepth:20},SO={biome:"@biomejs/biome",prettier:"prettier",typescript:"typescript",eslint:"eslint"};function So(t,n,e,r){let s=t.logicalTests.filter(l=>l.status==="unexpected"||l.status==="flaky"),i=[...n.hypotheses].sort((l,u)=>l.rank-u.rank)[0],a=new Set([...i?.supportingEvidenceIds??[],...n.ownershipEvidenceIds]),o=new Set(e.evidence.filter(l=>a.has(l.evidenceId)&&l.logicalTestId!==void 0).map(l=>l.logicalTestId)),d=s.filter(l=>o.has(l.logicalTestId));if(d.length===1)return d[0];let c=s.find(l=>l.logicalTestId===r);return c!==void 0&&(d.length===0||d.includes(c))?c:s.length===1?s[0]:void 0}function EO(t){return So(t.run,t.diagnosis,t.packet,t.representativeId)}function Eb(t){return t.payloadManifestHash===void 0||t.payloadHash===void 0?[]:[{manifestHash:t.payloadManifestHash,payloadHash:t.payloadHash,packetHash:t.packetHash,model:t.model.modelId,provider:t.model.providerId,promptVersion:t.promptVersion,outputSchemaVersion:t.outputSchemaVersion}]}function CO(t){return{maxRequestTokens:t.request.maxInputTokens+t.request.maxOutputTokens,maxRunTokens:t.run.maxInputTokens+t.run.maxOutputTokens,maxRequestDollars:t.request.maxDollars,maxRunDollars:t.run.maxDollars}}var NO={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};async function OO(t,n,e,r){let s=async o=>{let d=await js({workspaceRoot:t.workspaceRoot,repositoryRoot:t.gitRoot,ownerPath:n,packageName:o});return d.kind==="resolved"?d.tool:void 0},i={},a=await s(NO[e]);a!==void 0&&(i[e]=a);for(let o of new Set(r)){if(o==="kwikqa-babel")continue;let d=await s(SO[o]);d!==void 0&&(i[o]=d)}return i}async function Cb(t){let{input:n,now:e,run:r,proposal:s,repository:i}=t,a={repairProposal:s,repairAudit:t.repairAudit},o=(I,$)=>t.finish({outcome:"validation-unavailable",reasonCode:I,message:$},{...a,proposal:{status:"ready"},application:{status:"not-run"},validation:{status:"unavailable"}}),d=Je(r);if(d===void 0)return o("report-only-framework",dt(r));let c=EO(t);if(c===void 0)return o("original-test-ambiguous","The repair cannot be validated because the original failing test is ambiguous.");let l=r.projects.find(I=>I.projectId===c.projectId),u=await wl({workspaceRoot:i.workspaceRoot,targets:s.targets.map(I=>({path:I.path,class:I.class})),originalTestPath:c.location.file,projects:r.projects.map(I=>({id:I.name,testDirectory:I.testDir??"",...r.configFile===void 0?{}:{configPath:r.configFile}})),limits:PO}),p=u.scope==="focused"&&u.projectIds.length===0&&l!==void 0&&l.name!==""?{...u,projectIds:[l.name]}:u,f=await OO(i,c.location.file,d,p.staticChecks.map(I=>I.tool)),h=`.kwikqa/validation-artifacts/${s.proposalHash.slice(0,24)}`,m;if(d!=="playwright"&&p.status==="resolved"){let I=await Pb({workspaceRoot:i.workspaceRoot,run:r,test:c,discovery:p,artifactRoot:h});if(I.kind==="unavailable")return o("validation-scope-unavailable",I.message);m=I.prepared}let g=$l({proposal:s,advisoryPlan:s.validationPlan,discovery:p,tools:f,workspaceRoot:i.workspaceRoot,originalTest:{path:c.location.file,line:c.location.line??1,logicalTestId:c.logicalTestId,projectId:l===void 0||l.name===""?c.projectId:l.name,...r.configFile===void 0?{}:{configPath:r.configFile},environmentEquivalent:n.environmentEquivalent!==!1},artifactRoot:h,timeoutMs:n.validationTimeoutMs??TO,framework:d,...m===void 0?{}:{frameworkRun:{args:m.args,workingDirectory:m.workingDirectory,evidence:m.evidence},companionLogicalTestIds:m.companionLogicalTestIds}}),y=g.plan;if(y.status!=="resolved")return o("validation-scope-unavailable",y.unresolvedReasons.map(I=>I.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 w=t.retry===void 0?1:2,x=t.retry?.repairSessionId??(await Gl({workspaceRoot:i.workspaceRoot,originalRunId:r.runId,originalPacketHash:t.packet.packetHash,now:e()})).repairSessionId,v={config:t.config,snapshot:{workspaceRoot:i.workspaceRoot,gitRoot:i.gitRoot,dirtyPaths:i.dirtyPaths,validation:[]},workspace:{workspaceRoot:i.workspaceRoot,gitRoot:i.gitRoot},maxTargetBytes:Sb},R={sessionId:`kwikqa-${kO()}`},P=Ll({proposal:s,context:v,payloadManifests:[...t.diagnosisAudit===void 0?[]:Eb(t.diagnosisAudit),...Eb(t.repairAudit)],costBounds:CO(t.caps),scopes:{baseline:[],validation:[p.scope]},authoritativeValidation:Dl({plan:y,advisoryPlan:s.validationPlan,repairSessionId:x,attemptOrdinal:w}),previewedAt:e(),interactiveSession:R}),N={repairSessionId:x,attempt:w,planHash:y.planHash};if(P.kind!=="preview-ready")return t.finish({outcome:"operation-failed",reasonCode:"application-rejected",message:P.reasons.map(I=>I.message).join(" ")},{...a,proposal:{status:"ready"},application:{status:"blocked"}});if(!await n.interaction.approveApplication(P.preview,y))return t.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:N});let E=Er(),M=e(),A=await Fl({preview:P.preview,authorization:{authorizationId:E,bindingHash:Ba(P.preview,E,M,R),authorizedAt:M,interactiveSession:R},context:v,now:M});if(A.kind!=="applied")return t.finish({outcome:"operation-failed",reasonCode:A.kind==="recovery-required"?"application-recovery-required":"application-rejected",message:A.reasons.map(I=>I.message).join(" ")},{...a,proposal:{status:"approved"},application:{status:A.kind==="recovery-required"?"recovery-required":"failed"},repair:N});let C=A.transaction.transactionId;await Jl(i.workspaceRoot,x,{ordinal:w,proposalHash:s.proposalHash,transactionId:C,outcome:"applied",recordedAt:e()});let T=(t.memberIds??[]).filter(I=>I!==c.logicalTestId);return await Rb(i.workspaceRoot,{schemaVersion:"1.0",repairSessionId:x,attempt:w,transactionId:C,plan:y,workspace:v.workspace,config:t.config,maxTargetBytes:Sb,...T.length===0?{}:{group:{reportPath:RO(i.workspaceRoot,IO(i.workspaceRoot,n.reportPath)).split(AO).join("/"),...n.framework===void 0?{}:{framework:n.framework},logicalTestIds:T}},record:{runId:r.runId,createdAt:r.createdAt,workspace:r.workspace,sourceHashes:t.packet.sourceHashes,usability:r.usability,failingLogicalTestIds:r.logicalTests.filter(I=>I.status==="unexpected"||I.status==="flaky").map(I=>I.logicalTestId).sort()}}),t.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:{...N,transactionId:C}})}import{execFile as $O}from"node:child_process";import{realpath as Zs}from"node:fs/promises";import{isAbsolute as DO,relative as MO,resolve as Wu,sep as Nb}from"node:path";import{promisify as LO}from"node:util";var _O=LO($O),jO=3e4,FO=16*1024*1024;async function Eo(t,n){return(await _O("git",["-C",t,"--no-optional-locks",...n],{timeout:jO,maxBuffer:FO,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}function Ob(t){let n=t.split("\0"),e=[];for(let r=0;r<n.length;r+=1){let s=n[r]??"";if(s.length<4)continue;let i=s.slice(0,2);if(e.push(s.slice(3)),i.includes("R")||i.includes("C")){let a=n[r+1];a!==void 0&&a.length>0&&e.push(a),r+=1}}return e}function BO(t,n,e){let r=MO(t,Wu(n,e));if(!(r===""||DO(r)||r===".."||r.startsWith(`..${Nb}`)))return r.split(Nb).join("/")}async function Co(t){let n=await Zs(t);try{return await Zs(Wu((await Eo(n,["rev-parse","--show-toplevel"])).trim()))}catch{return n}}async function Ju(t){let n=await Zs(t);return(await Eo(n,["-c","core.quotePath=false","ls-files","-z"])).split("\0").filter(r=>r.length>0).sort()}async function Fn(t){let n,e,r;try{n=await Zs(t),e=await Zs(Wu((await Eo(n,["rev-parse","--show-toplevel"])).trim())),r=await Eo(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(`
209
+ `)[0]??"";return{kind:"unavailable",message:`Repository status could not be read: ${d===""?"git failed.":d}`}}let s=Ob(r),i=[...new Set(s.map(a=>BO(n,e,a)).filter(a=>a!==void 0))].sort();return{kind:"read",status:{workspaceRoot:n,gitRoot:e,dirtyPaths:i,pristine:s.length===0}}}var VO="kwikqa.config.json",zO=256*1024;async function HO(t,n){let e=await Q(t,n,zO);if(e.kind==="unavailable")return{kind:"repair-config-missing",message:`Repair requires a reviewed ${n}; none was found in the workspace.`};if(e.kind!=="read")return{kind:"repair-config-invalid",message:`${n} could not be read: ${e.message}`};let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.bytes))}catch{return{kind:"repair-config-invalid",message:`${n} is not valid UTF-8 JSON.`}}let s=_n(r);return s.kind!=="valid"?{kind:"repair-config-invalid",message:s.issues.join(" ")}:s}function UO(t,n,e){let r=new Set(e.map(i=>i.toLocaleLowerCase("en-US"))),s=new Set;for(let i of t.evidence){if(i.locator.type!=="source-range")continue;let a=i.locator.path;zs(a,n.editablePaths)!==void 0&&!Vs(a,n)&&!Bs(a)&&!r.has(a.toLocaleLowerCase("en-US"))&&s.add(a)}return[...s].sort()}async function Xu(t){let n=t.now??(()=>new Date().toISOString()),e=await Fn(t.workspaceRoot);if(e.kind==="unavailable")return{outcome:"operation-failed",reasonCode:"repository-status-unavailable",message:e.message};let{workspaceRoot:r,gitRoot:s,dirtyPaths:i,pristine:a}=e.status,o=await HO(r,t.configPath??VO);if(o.kind!=="valid")return{outcome:"operation-failed",reasonCode:o.kind,message:o.message};let d=o.config;if(t.retryRepairSessionId!==void 0&&(await Xt(r,t.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 Ys({...t,workspaceRoot:r,gitRoot:s,repairableOnly:!0},n);if(c.kind==="unreadable")return{outcome:c.outcome,reasonCode:c.reasonCode,message:c.message};let{stage:l}=c,u={workspaceRoot:r,gitRoot:s,dirtyPaths:i},p=(m,g=[])=>(y,w={})=>Io(m,Ro(m,"fix",g.length===0?y:{...y,message:`${g.join(" ")} ${y.message}`},n,{repository:{pristine:a,dirtyPaths:i},...w}),t.persist!==!1),f=XO(l,t);if("refusal"in f)return p(l)(f.refusal);if(f.groups.length===0){let{packet:m}=l,{diagnosis:g,grading:y}=l.result;return l.result.outcome!=="diagnosed"||m===void 0||g===void 0||y===void 0?p(l)(l.result):$b(t,l,{packet:m,diagnosis:g,grading:y},d,n,p(l),u)}let h=[];f.groups.length>0&&await t.repairSession?.open(f.groups.length);try{let m;for(let g of f.groups){let y=JO(l,g),{packet:w}=y,{diagnosis:x,grading:v}=g.result;if(!(w===void 0||x===void 0||v===void 0)){if(m=await $b(t,y,{packet:w,diagnosis:x,grading:v},d,n,p(y,h),u),!KO(m))return m;h.push(`Failure group ${WO(l,g)}: ${m.message}`)}}return m??p(l)(l.result)}finally{await t.repairSession?.close()}}var qO=3,GO=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 KO(t){return t.outcome==="abstained-from-repair"?GO.has(t.reasonCode):t.outcome==="validation-unavailable"&&t.record?.application.status==="not-run"}function WO(t,n){return(t.clusterStages??[]).indexOf(n)+1}function JO(t,n){return{...t,...n.packet===void 0?{}:{packet:n.packet},...n.symptoms===void 0?{}:{symptoms:n.symptoms},...n.clusters===void 0?{}:{clusters:n.clusters},result:n.result,clusterStages:[n,...(t.clusterStages??[]).filter(e=>e!==n)],representativeId:n.representativeId}}function XO(t,n){let e=t.clusterStages??[];if(n.group!==void 0){let i=e[n.group-1];return i===void 0?{refusal:{outcome:"operation-failed",reasonCode:"group-not-found",message:`There is no failure group ${n.group}; this run has ${e.length}.`}}:ko([i]).includes(i)?{groups:[i]}:{refusal:{outcome:"abstained-from-repair",reasonCode:"group-not-repairable",message:`Failure group ${n.group} is not diagnosed as the test's fault (${i.result.reasonCode}); KwikQA repairs only test-side causes.`}}}let r=ko(e),s=n.repairSession===void 0||n.retryRepairSessionId!==void 0?1:qO;return{groups:r.slice(0,s)}}async function YO(t,n){let{interaction:e}=t;if(e.confirmFailure===void 0||t.retryRepairSessionId!==void 0)return;let r=n.clusterStages?.[0]?.cluster.logicalTestIds??n.failing,s=n.representativeId??r[0];if(s===void 0)return;let i=await e.confirmFailure(n.run,r);if(i.kind==="declined")return{status:"declined",logicalTestIds:r,message:"The developer chose not to re-run the failing tests first."};if(i.kind==="unavailable")return{status:"unavailable",logicalTestIds:r,message:i.message};let a=r.filter(d=>i.failedAgain.includes(d));if(a.includes(s))return{status:"reproduced",logicalTestIds:r,failedAgain:a};let o=n.run.logicalTests.find(d=>d.logicalTestId===s)?.title;return{status:"not-reproduced",logicalTestIds:r,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 $b(t,n,e,r,s,i,a){let{packet:o,diagnosis:d,grading:c}=e,l=[...d.hypotheses].sort((y,w)=>y.rank-w.rank)[0],u=t.repairCaps??t.remote.caps,p=await Cu({packet:o,diagnosis:d,grading:c,hypothesisId:l?.hypothesisId??"",editablePaths:UO(o,r,a.dirtyPaths),budgets:r.budgets,model:t.repairModel??t.remote.model,caps:u,transport:t.remote.transport,now:s()});if(p.kind!=="preview-ready"){let y=p.reasonCode==="repair-not-eligible"&&l?.probableOwner!=="test-support"?vo(d):p.reasonCode,w=p.reasonCode==="repair-not-eligible"||xo.has(p.reasonCode);return i({outcome:w?"abstained-from-repair":"operation-failed",reasonCode:y,message:p.message},{proposal:{status:w?"not-eligible":"failed"},repairAudit:p.audit})}let f=await YO(t,n),h=(y,w={})=>i(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 t.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 m=await Nu({prepared:p.prepared,authorization:{bindingHash:p.prepared.authorizationBindingHash,mode:"interactive",authorizedAt:s(),authorizationId:Er()},authorizationStore:t.authorizationStore??new Cn,transport:t.remote.transport,now:s()});if(m.kind==="declined")return h({outcome:"abstained-from-repair",reasonCode:m.reasonCode,message:m.message},{proposal:{status:"not-eligible"},repairAudit:m.audit});if(m.kind!=="proposed")return h({outcome:"operation-failed",reasonCode:m.reasonCode,message:m.message},{proposal:{status:"failed"},repairAudit:m.audit});let g=await ju({packet:o,diagnosis:d,grading:c,config:r,snapshot:{workspaceRoot:a.workspaceRoot,gitRoot:a.gitRoot,dirtyPaths:a.dirtyPaths,validation:[]},intent:m.draft.intent,replacements:m.draft.replacements});if(g.kind==="rejected"){let[y]=g.reasons;return h({outcome:"abstained-from-repair",reasonCode:y?.code??"invalid-replacement",message:g.reasons.map(w=>w.message).join(" ")},{proposal:{status:"not-eligible"},repairAudit:m.audit,proposalRejections:g.reasons})}return t.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:m.audit,repairProposal:g.proposal}):Cb({input:t,now:s,run:n.run,packet:o,diagnosis:d,...n.representativeId===void 0?{}:{representativeId:n.representativeId},...n.clusterStages?.[0]===void 0?{}:{memberIds:n.clusterStages[0].cluster.logicalTestIds},proposal:g.proposal,config:r,repository:a,diagnosisAudit:n.result.audit,repairAudit:m.audit,caps:u,...t.retryRepairSessionId===void 0?{}:{retry:{repairSessionId:t.retryRepairSessionId}},finish:h})}import{randomUUID as QO}from"node:crypto";import{realpath as ZO}from"node:fs/promises";import{join as e2,relative as t2,sep as Yu}from"node:path";var n2={maxStreamBytes:4*1024*1024,maxTotalStreamBytes:16*1024*1024,terminationGraceMs:5e3},r2=32*1024*1024,s2=new Set(["applied","validating"]);function i2(){return`vld_${QO().replaceAll("-","").slice(0,24)}`}function a2(t){return{config:t.config,snapshot:{workspaceRoot:t.workspace.workspaceRoot,gitRoot:t.workspace.gitRoot,dirtyPaths:[],validation:[]},workspace:t.workspace,maxTargetBytes:t.maxTargetBytes}}function o2(t,n,e){let r=s=>t2(t,`${n}${Yu}${s.split("/").join(Yu)}`).split(Yu).join("/");for(let s of e.commandRecords){let i=s.artifacts.find(d=>d.path.endsWith("/report.json"));if(i!==void 0)return r(i.path);let o=s.artifacts.filter(d=>La.test(d.path.split("/").at(-1)??""))[0];if(o!==void 0)return r(o.path.split("/").slice(0,-1).join("/"))}}async function d2(t,n,e){let r=n.group;if(r===void 0||r.logicalTestIds.length===0||t.checkGroup===void 0)return;let{logicalTestIds:s}=r,i=`${s.length} other test${s.length===1?"":"s"}`,a=await ot(e2(e,r.reportPath),{workspaceRoot:e,gitRoot:n.workspace.gitRoot,...r.framework===void 0?{}:{framework:r.framework}}),o=a.kind==="parsed"?new Set(a.run.logicalTests.map(u=>u.logicalTestId)):void 0;if(a.kind!=="parsed"||!s.every(u=>o?.has(u)))return{status:"unavailable",logicalTestIds:s,message:`The report fix read has changed, so the group's ${i} were not re-run.`};let d=await t.checkGroup(a.run,s);if(d.kind==="declined")return{status:"declined",logicalTestIds:s,message:`The group's ${i} were not re-run.`};if(d.kind==="unavailable")return{status:"unavailable",logicalTestIds:s,message:d.message};let c=s.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:s,stillFailing:c,message:c.length===0?`The group's ${i} pass now as well.`:`${c.length} of the group's ${i} still fail${c.length===1?"s":""}: ${l}. The patch stays; run \`kwikqa fix\` again for them.`}}async function Zu(t){let n=t.now??(()=>new Date().toISOString()),e=()=>new Date().toISOString(),r=await ZO(t.workspaceRoot),s=await zl(r);if(s.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-recovery-required",message:s.reasons.map(P=>P.message).join(" ")};let i=s.transactions.filter(P=>s2.has(P.phase));if(i.length!==1||i[0]===void 0)return{outcome:"operation-failed",reasonCode:"no-pending-repair",message:i.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 Re(r,i[0].transactionId),o=a.manifest.preview.authoritativeValidation,d=await Ib(r,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=a2(d),l=d.transactionId,u=d.plan,p;if(a.state.phase==="validating"){let P=a.state.history.findLast(N=>N.type==="validation-started");if(P?.validationRunId===void 0)throw new Error("Validating transaction has no started validation run.");p=P.validationRunId}else{p=i2();let P=await Gu({context:c,transactionId:l,planHash:u.planHash,validationRunId:p,now:e()});if(P.kind==="rejected"||P.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-rejected",message:P.reasons.map(N=>N.message).join(" ")};for(let N of u.commands)if(!(!N.required||N.timing!=="post-patch")){if(t.signal?.aborted===!0)break;await xl({workspaceRoot:r,repositoryRoot:d.workspace.gitRoot,transactionId:l,validationRunId:p,plan:u,commandId:N.commandId,limits:n2,...t.signal===void 0?{}:{signal:t.signal}}).catch(()=>{})}}let f=await Al({workspaceRoot:r,gitRoot:d.workspace.gitRoot,transactionId:l,validationRunId:p,plan:u,reportMaxBytes:r2,completedAt:e()}),h=f.manifest,m={repairSessionId:d.repairSessionId,attempt:d.attempt,transactionId:l,planHash:u.planHash,validationRunId:p,validationManifestHash:h.manifestHash};if(h.status==="passed"&&(await Ku({context:c,transactionId:l,planHash:u.planHash,validationRunId:p,validationManifestHash:h.manifestHash,now:e()})).kind==="completed"){await Ga({workspaceRoot:r,repairSessionId:d.repairSessionId,ordinal:d.attempt,validationRunId:p,now:n()});let N=await d2(t,d,r);return Qu(t,d,n,{outcome:"repaired",reasonCode:"validation-passed",message:`Every required validation check passed; the repair is complete.${N?.message===void 0?"":` ${N.message}`}`,application:"applied",validation:"passed",repair:m,...N===void 0?{}:{groupCheck:N}})}await Ga({workspaceRoot:r,repairSessionId:d.repairSessionId,ordinal:d.attempt,validationRunId:p,now:n()});let g=await Hl(c,l,e()),y=h.status==="passed"?"incomplete":h.status,w=y==="failed"?"validation-failed":y==="unavailable"?"validation-unavailable":"validation-incomplete";if(g.kind!=="rolled-back")return Qu(t,d,n,{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:m});let v=(await Xl({workspaceRoot:r,repairSessionId:d.repairSessionId,ordinal:d.attempt,proof:{transactionId:l,phase:"rolled-back",transactionRevision:g.transaction.revision},now:n()})).retry!==void 0,R=v?o2(r,f.directory,h):void 0;return Qu(t,d,n,{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:{...m,retryAvailable:v,...R===void 0?{}:{retryReportPath:R}}})}async function Qu(t,n,e,r){let s={schemaVersion:"1.1",recordId:wo(),command:"validate",...n.record,recordedAt:e(),analysis:{status:"completed"},proposal:{status:"approved"},application:{status:r.application},validation:{status:r.validation},repair:r.repair,...r.groupCheck===void 0?{}:{groupCheck:r.groupCheck},outcome:r.outcome,reasonCode:r.reasonCode,message:r.message};if(t.persist===!1)return{outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s};try{let i=await Js(n.workspace.workspaceRoot,s);return{outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s,recordPath:i}}catch{return{outcome:"operation-failed",reasonCode:"record-write-failed",message:`${s.message} The run record could not be written safely under .kwikqa/runs/.`,record:s}}}var c2=1200*1e3,l2=10,u2=1e3,p2=15e3,f2=3e3,h2=6e4,Db=3e4,m2=2;function tp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function Lb(t){try{let n=await t.json();return tp(n)?n:void 0}catch{return}}async function y2(t){return await Lb(t)??{}}function Mb(t){return typeof t=="number"&&Number.isFinite(t)?Math.min(p2,Math.max(u2,t)):f2}function ep(t){let n=tp(t.error)?t.error:void 0;return typeof n?.message=="string"?n.message:void 0}var No=class{constructor(n){this.options=n}options;preflight(n){return this.options.preflight.preflight(n)}async complete(n){let e=performance.now(),r=()=>performance.now()-e;for(let s=0;;s+=1){let i=await this.#e(n,r);if(i!=="interrupted")return i;if(s===m2)return{kind:"failed",code:"http-error",message:"The model request was interrupted on our side; nothing was charged. Try again.",httpStatus:503,elapsedMs:r()};this.options.onRestart?.()}}async#e(n,e){let r=(u,p)=>({kind:"failed",code:u,message:p,elapsedMs:e()}),s=wu(n);if(s!==void 0)return{kind:"failed",code:"invalid-request",message:s,elapsedMs:0};let i;try{i=await this.#t("POST","/v1/jobs",h2,{headers:{...this.options.headers(n.body),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(n.body)})}catch(u){return r("network-error",`The model request could not reach the KwikQA service (${Gs(u)}).`)}let a=await y2(i);if(i.status!==202){let u=ro(a);return{kind:"failed",code:"http-error",message:ep(a)??"The KwikQA service refused the model request.",httpStatus:i.status,...u===void 0?{}:{providerCode:u},elapsedMs:e()}}let o=a.jobId;if(typeof o!="string"||o==="")return r("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=Mb(a.pollAfterMs),l=0;for(;;){if(e()>(this.options.maxWaitMs??c2))return await this.#n(o),r("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}`,Db)}catch{u=new Response(null,{status:599})}let p=u.status>=500?void 0:await Lb(u);if(u.status===404)return"interrupted";if(u.status<500&&!u.ok)return{kind:"failed",code:"http-error",message:ep(p??{})??"The KwikQA service refused to report the job.",httpStatus:u.status,elapsedMs:e()};if(p===void 0){if(l+=1,l>l2)return r("network-error","Lost contact with the KwikQA service while the model was working. If it answered, it is given back unused.");continue}if(l=0,p.status==="running"){this.options.onProgress?.(e()),c=Mb(p.pollAfterMs);continue}if(p.status==="failed")return tp(p.error)&&p.error.code==="job-interrupted"?"interrupted":{kind:"failed",code:"http-error",message:ep(p)??"The model request was interrupted; nothing was charged.",httpStatus:503,elapsedMs:e()};if(p.status!=="answered")return r("invalid-json","The KwikQA service reported a job state the CLI does not know.");await this.#n(o);let f=typeof p.httpStatus=="number"?p.httpStatus:502,h=p.result,m=f>=200&&f<300;if(!m||gu(h)){let g=ro(h),y=m?g??502:f;return{kind:"failed",code:"http-error",message:yu(y,h),httpStatus:y,...g===void 0?{}:{providerCode:g},elapsedMs:e()}}return this.options.onCompletionBody?.(h),{kind:"response",httpStatus:f,body:h,elapsedMs:e()}}}async#n(n){try{await this.#t("DELETE",`/v1/jobs/${n}`,Db)}catch{}}#t(n,e,r,s={}){return this.options.fetch(`${this.options.baseUrl}${e}`,{method:n,headers:{Accept:"application/json",Authorization:`Bearer ${this.options.token}`,...s.headers},...s.body===void 0?{}:{body:s.body},redirect:"error",signal:AbortSignal.timeout(r)})}};var g2="https://api.kwikqa.com",Nr="https://kwikqa.com/dashboard/";function _b(t){return t.hosted??!(t.plan==="byo"||t.plan==="byo-team")}function w2(t){return t?.response_format?.json_schema?.name==="kwikqa_diagnosis"}var ft=class extends Error{constructor(e,r,s){super(s);this.status=e;this.code=r}status;code};function Zt(t,n){return(t.KWIKQA_API_URL??(n===void 0||n===""?g2:n)).replace(/\/+$/,"")}function jb(t){let n=t?.messages;if(!Array.isArray(n))return;let e=n.find(r=>typeof r=="object"&&r!==null&&r.role==="user"&&typeof r.content=="string");if(e!==void 0)try{let r=JSON.parse(e.content).framework;return r==="playwright"||r==="cypress"||r==="webdriverio"?r:void 0}catch{return}}var vt=class{constructor(n,e,r=fetch){this.baseUrl=n;this.token=e;this.fetchImpl=r}baseUrl;token;fetchImpl;async#e(n,e,r,s,i){let a=()=>this.fetchImpl(`${this.baseUrl}${e}`,{method:n,headers:{Accept:"application/json",...r===void 0?{}:{"Content-Type":"application/json"},...this.token===void 0?{}:{Authorization:`Bearer ${this.token}`},...s===void 0?{}:{"X-KwikQA-Retry-Ticket":s},...i===void 0?{}:{"X-KwikQA-Session":i}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error"}),o;try{o=await a().catch(c=>{if(n==="GET")return a();throw c})}catch(c){throw new ft(0,"network-error",`Could not reach the KwikQA service at ${this.baseUrl} (${Gs(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(n){return this.#e("POST","/v1/auth/token",{deviceCode:n})}status(){return this.#e("GET","/v1/me")}hostedConfig(){return this.#e("GET","/v1/config")}plans(){return this.#e("GET","/v1/plans")}checkout(n,e){return this.#e("POST","/v1/billing/checkout",{plan:n,...e})}billingPortal(){return this.#e("POST","/v1/billing/portal")}reserveUsage(n,e,r){return this.#e("POST","/v1/usage/reserve",n,e,r)}openSession(n,e="diagnosis"){return this.#e("POST","/v1/usage/session",e==="diagnosis"?{requests:n}:{requests:n,kind:e})}async closeSession(n){let r=(await this.#e("DELETE","/v1/usage/session",void 0,void 0,n))?.retryTicket;return typeof r=="string"&&r!==""?{retryTicket:r}:{}}reportInsights(n){return this.#e("POST","/v1/insights",{events:n})}releaseUsage(n,e){return this.#e("POST","/v1/usage/release",{id:n,status:e})}logout(){return this.#e("POST","/v1/auth/logout")}transport(n){let e=i=>{let a=jb(i),o=w2(i)?n.session?.():n.repairSession?.();return{...n.retryTicket===void 0?{}:{"X-KwikQA-Retry-Ticket":n.retryTicket},...o===void 0?{}:{"X-KwikQA-Session":o},...a===void 0?{}:{"X-KwikQA-Framework":a}}},r=i=>{let a=i?.kwikqa?.retryTicket;typeof a=="string"&&a!==""&&n.onRetryTicket?.(a)},s=new $n({apiRoot:`${this.baseUrl}/v1/openrouter`,credentialName:"A KwikQA login (run `npx kwikqa login`)",readApiKey:()=>this.token,fetch:this.fetchImpl,timeoutMs:6e5,extraHeaders:e,onCompletionBody:r});return n.jobs!==!0||this.token===void 0?s:new No({baseUrl:this.baseUrl,token:this.token,fetch:this.fetchImpl,preflight:s,headers:e,onCompletionBody:r,...n.onProgress===void 0?{}:{onProgress:n.onProgress},...n.onRestart===void 0?{}:{onRestart:n.onRestart},...n.sleep===void 0?{}:{sleep:n.sleep}})}},Oo=class{constructor(n,e,r={}){this.inner=n;this.client=e;this.options=r}inner;client;options;preflight(n){return this.inner.preflight(n)}async complete(n){let r=n.body.response_format?.json_schema?.name==="kwikqa_repair_proposal"?"repair":"diagnosis",s;try{let a=jb(n.body);s=await this.client.reserveUsage({kind:r,model:n.route.modelId,provider:n.route.providerSlug,...a===void 0?{}:{framework:a}},this.options.retryTicket,r==="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}}}s.retryTicket!==void 0&&this.options.onRetryTicket?.(s.retryTicket);let i=await this.inner.complete(n);return i.kind!=="response"&&await this.client.releaseUsage(s.id,i.httpStatus??599).catch(()=>{}),i}};import{mkdir as b2,readFile as x2,rm as v2,writeFile as k2}from"node:fs/promises";import{homedir as Fb}from"node:os";import{join as ei}from"node:path";function Bb(t){return t.KWIKQA_CONFIG_DIR!==void 0&&t.KWIKQA_CONFIG_DIR!==""?t.KWIKQA_CONFIG_DIR:process.platform==="win32"?ei(t.APPDATA??ei(Fb(),"AppData","Roaming"),"kwikqa"):ei(t.XDG_CONFIG_HOME??ei(Fb(),".config"),"kwikqa")}function np(t){return ei(Bb(t),"credentials.json")}async function en(t){if(t.KWIKQA_TOKEN!==void 0&&t.KWIKQA_TOKEN.trim()!=="")return{token:t.KWIKQA_TOKEN.trim(),login:"(KWIKQA_TOKEN)",apiUrl:""};try{let n=JSON.parse(await x2(np(t),"utf8"));return typeof n.token!="string"||n.token===""||typeof n.login!="string"||typeof n.apiUrl!="string"?void 0:{token:n.token,login:n.login,apiUrl:n.apiUrl}}catch{return}}async function Vb(t,n){await b2(Bb(t),{recursive:!0,mode:448}),await k2(np(t),`${JSON.stringify(n)}
210
+ `,{mode:384})}async function zb(t){await v2(np(t),{force:!0})}import{createHash as R2}from"node:crypto";import{basename as I2}from"node:path";var A2=100;function Hb(t){return R2("sha256").update(t).digest("hex")}function Ub(t,n){let e=t.projects.find(i=>i.projectId===n.projectId)?.name??"",r=n.location.file,s=n.titlePath.filter(i=>i!==""&&i!==r&&i!==I2(r));return{key:Hb([e,r,...n.titlePath].join("\0")).slice(0,32),title:(s.length===0?[n.title]:s).join(" \u203A ").slice(0,300),file:r.slice(0,300),project:e.slice(0,100)}}function qb(t){return t===void 0?void 0:Hb(t).slice(0,32)}function rp(t){if(t.run===void 0)return;let n=t.run,e=n.logicalTests.filter(r=>r.status==="unexpected"||r.status==="flaky").slice(0,A2).map(r=>({...Ub(n,r),status:r.status==="flaky"?"flaky":"failed"}));return{kind:"analysis",outcome:t.outcome,reasonCode:t.reasonCode,framework:n.framework,tests:e}}function Gb(t){let n=t.record,e=t.run===void 0||t.packet===void 0||n?.diagnosis===void 0?void 0:So(t.run,n.diagnosis,t.packet,n.clusters?.[0]?.representativeId),r=qb(n?.repair?.repairSessionId);return{kind:"fix",outcome:t.outcome,reasonCode:t.reasonCode,...t.run===void 0?{}:{framework:t.run.framework},...r===void 0?{}:{session:r},...n?.repair?.attempt===void 0?{}:{attempt:n.repair.attempt},...e===void 0||t.run===void 0?{}:{test:Ub(t.run,e)},...n?.repairProposal===void 0?{}:{changedFiles:n.repairProposal.changedFiles,changedLines:n.repairProposal.changedLines}}}function Kb(t){let n=t.record?.repair,e=qb(n?.repairSessionId);if(!(e===void 0||n===void 0))return{kind:"validation",outcome:t.outcome,reasonCode:t.reasonCode,session:e,attempt:n.attempt}}async function ti(t,n,e,r){if(r===void 0||e.team?.insights!==!0)return;try{await n.reportInsights([r])}catch{t.print("Team insights: couldn't share this result; nothing else changed.");return}let s=r.kind==="analysis"?`${r.tests.length} failing or flaky test name${r.tests.length===1?"":"s"} and the result`:r.kind==="fix"?"this fix's test and outcome":"the validation result";t.print(`Team insights: shared ${s} with ${e.team.owner}'s team.`)}var T2={npm:"npx",pnpm:"pnpm exec",yarn:"yarn",bun:"bunx"},P2={npm:"npm i -D",pnpm:"pnpm add -D",yarn:"yarn add -D",bun:"bun add -d"};function Wb(t){let n=(t.npm_config_user_agent??"").split("/")[0];return n==="pnpm"||n==="yarn"||n==="bun"?n:"npm"}function kt(t){return`${T2[Wb(t)]} kwikqa`}function sp(t,n){return`${P2[Wb(t)]} ${n}`}import{basename as S2}from"node:path";function tn(t,n){return`${t} ${n}${t===1?"":"s"}`}function Jb(t){return`$${t.toFixed(t<.1?4:2)}`}function E2(t){let n=t.evidence.flatMap(s=>s.locator.type==="diff-hunk"?[s.locator]:[]);if(n.length===0)return[];let e=new Set(n.flatMap(s=>s.commit===void 0?[]:[s.commit])),r=[...e.size===0?[]:[tn(e.size,"commit")],...n.some(s=>s.commit===void 0)?["uncommitted changes"]:[]].join(" and ");return[` Changes: ${tn(n.length,"changed hunk")} from ${r} that mention the failures (--no-changes leaves them out)`]}function ni(t,n,e){let r=n.model.reasoningEffort===void 0?"":`, effort ${n.model.reasoningEffort}`,s=n.model.zeroDataRetention===!0?", zero data retention":"";return[`${t==="diagnosis"?"Diagnosis":"Repair proposal"} request -> ${e}`,` Model: ${n.model.modelId} via ${n.model.providerId}${r}${s}`,` Evidence: ${tn(n.evidence.length,"redacted item")} from ${n.channels.join(", ")||"the report"}`,` ${tn(n.redactionIds.length,"redaction")} applied, ${tn(n.omissionIds.length,"item")} withheld by policy`,...E2(n),` Estimate: at most ${n.estimate.estimatedInputTokens.toLocaleString("en-US")} input + ${n.estimate.estimatedOutputTokens.toLocaleString("en-US")} output tokens, at most ${Jb(n.estimate.estimatedDollars)}`,` Caps: ${Jb(n.caps.request.maxDollars)} per request`,` Payload: ${n.payloadManifestHash.slice(0,16)}... (exactly this redacted payload is sent)`]}function Xb(t,n){let e=t.proposal,r=["Proposed repair",` Intent: ${e.intent.statement}`,` Preserves: ${e.intent.preservedBehavior}`,` Changes: ${tn(e.changedFiles,"file")}, ${tn(e.changedLines,"line")}`,"",...e.diff.trimEnd().split(`
211
+ `),"","Validation commands (run later by `kwikqa validate`):"],s=new Map;for(let i of n.commands.filter(a=>a.timing==="post-patch")){let a=i.args.map(d=>/\s/.test(d)?JSON.stringify(d):d),o=` ${S2(i.executable)} ${a.join(" ")}`;s.set(o,(s.get(o)??0)+1)}for(let[i,a]of s)r.push(a===1?i:`${i} (${a} runs)`);return t.checkoutPristine||r.push("","Note: this checkout has other uncommitted changes; they are not touched."),r}function Yb(t,n){let e=r=>n?.logicalTests.find(s=>s.logicalTestId===r)?.title;return t.flatMap((r,s)=>{let i=r.logicalTestIds.map(d=>e(d)??d),a=i.length<=3?i.join(", "):`${i.slice(0,3).join(", ")} and ${i.length-3} more`,o=`${i.length} test${i.length===1?"":"s"}`;return[`Failure group ${s+1} of ${t.length}: ${o} (${a})${r.escalated===!0?", answered by the stronger model":""}`,...r.diagnosis!==void 0&&r.diagnosis.hypotheses.length>0?ip(r.diagnosis):[` ${r.outcome} (${r.reasonCode}): ${r.message}`],""]})}function ip(t){if(t.hypotheses.length===0)return["No cause is supported by the evidence.",` Next: ${t.recommendedNextAction}`];let n=[];for(let e of[...t.hypotheses].sort((r,s)=>r.rank-s.rank))n.push(`#${e.rank} ${e.statement}`,` owner: ${e.probableOwner}, evidence: ${e.evidenceGrade}, cause: ${e.causalCategory}`);return n.push(` Next: ${t.recommendedNextAction}`),n}function Qb(t,n,e,r,s={}){switch(n){case"diagnosed":return r!==void 0&&Je(r)===void 0?dt(r):t?.diagnosis?.repairEligibility!=="eligible"?void 0:s.ci===!0?`To repair it, run \`${e} analyze\` and then \`${e} fix\` on your machine.`:`Run \`${e} fix\` to propose a repair.`;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 t?.repair?.retryAvailable===!0?`Run \`${e} fix --retry\` to re-diagnose from the validation evidence (one retry left).`:void 0;default:return}}function Zb(t){if(t===void 0)return;let n=t.artifact.formatVersion===void 0?"":` ${t.artifact.formatVersion}`,e=t.artifact.format===void 0?void 0:zt[t.artifact.format],r=t.logicalTests.filter(a=>a.status==="unexpected").length,s=t.logicalTests.filter(a=>a.status==="flaky").length;return`Read a ${t.framework==="unknown"?"run from an unidentified framework":`${wt[t.framework]}${n} run`}${e===void 0?"":` (${e})`}: ${tn(t.logicalTests.length,"test")}, ${r} failing${s===0?"":`, ${s} flaky`}.`}function ex(t,n){if(t===void 0||Je(t)===void 0)return;let e=t.framework==="playwright",r=e?"trace":"kwikqa-capture",s=0,i=0;for(let c of t.logicalTests)for(let l of lr(c))s+=1,l.attachments.some(u=>u.name===r)&&(i+=1);if(s===0||i===s)return;let a=s-i;return[`Note: ${a===s?s===1?`The failing attempt has no ${e?"Playwright trace":"KwikQA failure capture"}`:`None of the ${s} failing attempts has ${e?"a Playwright trace":"a KwikQA failure capture"}`:`${a} of ${s} 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 \`${n} analyze --capture\` to re-run them with full tracing, or set`:` Run \`${n} 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(`
212
+ `)}var ri="0.2.4";var q={ok:0,failed:1,usage:2,account:3},si=(()=>{let{workspaceRoot:t,...n}=nc;return{...n,maxPacketBytes:6e5}})(),D2=.85;function op(t){if(t===void 0)return si;let n=Math.min(t.diagnosis.caps.request.maxInputTokens,t.repairCaps.request.maxInputTokens);return{...si,maxPacketBytes:Math.min(si.maxPacketBytes,Math.floor(n*D2))}}var rx=["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"],ox=He(".kwikqa","cli-state.json");function dp(t){return`Not signed in. Run \`${kt(t.env)} login\` first.`}async function Or(t){return C2(t).then(()=>!0,()=>!1)}async function cp(t){try{return JSON.parse(await $o(He(t,ox),"utf8"))}catch{return{}}}async function lp(t,n){await O2(He(t,".kwikqa"),{recursive:!0,mode:448}),await ix(He(t,ox),`${JSON.stringify(n)}
213
+ `,{mode:384})}async function Mo(t,n,e){if(e!==void 0)return ap(e)?e:Do(t.cwd,e);for(let r of[t.env.PLAYWRIGHT_JSON_OUTPUT_NAME,t.env.KWIKQA_REPORT_DIR])if(r!==void 0&&r!==""){let s=ap(r)?r:Do(n,r);if(await Or(s))return s}for(let r of rx)if(await Or(He(n,r)))return He(n,r);return He(n,rx[0]??"report.json")}async function dx(t){try{if((await nx(t)).isDirectory()){let n=tx("sha256");for(let e of(await $2(t)).sort()){let r=He(t,e);(await nx(r)).isFile()&&n.update(`${e}\0`).update(await $o(r))}return n.digest("hex")}return tx("sha256").update(await $o(t)).digest("hex")}catch{return}}async function M2(t,n,e){let r=n.capture;if(r===void 0)return;let s=He(t,r.reportPath);if(await dx(e)!==r.sourceSha256||!await Or(s))return;let i=r.probePath===void 0?void 0:He(t,r.probePath);return{reportPath:s,...i!==void 0&&await Or(i)?{probePath:i}:{}}}async function L2(t,n,e,r){let s=await ot(e,{workspaceRoot:n,...r.framework===void 0?{}:{framework:r.framework}});if(s.kind!=="parsed"){t.io.error(`Capture skipped: ${s.diagnostic.message}`);return}let i=s.run.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest",a=await iu({run:s.run,workspaceRoot:n,repositoryRoot:await Co(n),captureId:i,env:t.env,probe:r.probe});if(a.kind!=="ready"){t.io.print(`Capture skipped: ${a.message}`);return}for(let c of a.prepared.description)t.io.print(c);if(a.prepared.probeUnavailable!==void 0&&t.io.print(`Note: ${a.prepared.probeUnavailable}`),r.yes)t.io.print("Run these tests? yes (--yes)");else if(!await t.io.confirm("Run these tests?")){t.io.print("Capture declined; analyzing the existing report.");return}let o=await au(a.prepared,t.env);if(t.io.print(o.outcome.message),o.probe!==void 0){let c=o.probe.results.reduce((l,u)=>l+u.candidates.length,0);t.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 dx(e);if(d!==void 0){let c=await cp(n);await lp(n,{...c,capture:{sourceSha256:d,reportPath:ii(n,o.outcome.reportPath),...o.probePath===void 0?{}:{probePath:ii(n,o.probePath)}}})}return{reportPath:o.outcome.reportPath,...o.probePath===void 0?{}:{probePath:o.probePath}}}function sx(t,n){if(t===void 0||t==="")return{...n,evaluationStatus:"unverified-model"};let[e,r]=t.split("@");if(e===void 0||r===void 0||r==="")throw new ft(0,"invalid-model",`Model routes look like author/model@provider, not ${t}.`);return{modelId:e,providerId:r,evaluationStatus:"unverified-model"}}async function up(t,n,e){let r=await en(t.env);if(r===void 0)return{exit:q.account,messages:[dp(t)]};let s=new vt(Zt(t.env,r.apiUrl),r.token,t.fetch),i=await s.status(),a=await s.hostedConfig(),o=_b(i);if(!o&&(t.env.OPENROUTER_API_KEY??"").trim()==="")return{exit:q.account,messages:["The BYOK plans need OPENROUTER_API_KEY in the environment."]};let d=n==="analysis"?i.usage.analyses:i.usage.repairs;if(e===void 0&&d.limit!==void 0&&d.used>=d.limit){let v=n==="analysis"?"analyses":"fixes";return{exit:q.account,messages:[`You have used all ${d.limit} ${v} on the ${i.plan} plan until ${i.periodEnd.slice(0,10)}.`,i.team?.role==="member"?`Ask ${i.team.owner}, who manages your team's plan, to add seats.`:`Run \`${kt(t.env)} upgrade\` to see plans with more.`]}}let c,l,u=a.sessions===!0&&e===void 0?{open:async v=>{l=(await s.openSession(v)).sessionTicket},close:async()=>{let v=l;l=void 0,v!==void 0&&await s.closeSession(v)}}:void 0,p,f=a.repairSessions===!0&&e===void 0?{open:async v=>{p=(await s.openSession(v,"repair")).sessionTicket},close:async()=>{let v=p;if(p=void 0,v===void 0)return;let R=await s.closeSession(v);R.retryTicket!==void 0&&(c=R.retryTicket)}}:void 0,h={...e===void 0?{}:{retryTicket:e},onRetryTicket:v=>{c=v},session:()=>l,repairSession:()=>p};if(!o){let v=new Oo(new $n({readApiKey:()=>t.env.OPENROUTER_API_KEY,fetch:t.fetch}),s,h);return{diagnosis:{model:sx(t.env.KWIKQA_DIAGNOSIS_MODEL,a.models.diagnosis),caps:a.caps.diagnosis,transport:v,...u===void 0?{}:{session:u}},repairModel:sx(t.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:s,status:i}}let m=s.transport({...h,jobs:a.jobs===!0,onProgress:F2(t),onRestart:()=>t.io.print(" The KwikQA service restarted while the model was working; sending the request again (nothing was charged)."),...t.sleep===void 0?{}:{sleep:t.sleep}}),g=e!==void 0&&a.models.escalation!==void 0&&a.caps.escalation!==void 0,y=g?a.models.escalation:void 0,w=g?a.caps.escalation:void 0,x=!g&&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:m,...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:s,status:i}}function cx(t,n){for(let e of n.messages)t.io.error(e);return n.exit}var _2=3e4;function j2(t){let n=Math.floor(t/1e3),e=Math.floor(n/60);return e===0?`${n}s`:`${e}m ${String(n%60).padStart(2,"0")}s`}function F2(t){let n=0;return e=>{let r=Math.floor(e/_2);r<=n||(n=r,t.io.print(` The model is still working (${j2(e)})\u2026`))}}function pp(t,n,e){let r=async(s,i)=>{for(let a of s)t.io.print(a);return e?(t.io.print(`${i} yes (--yes)`),!0):t.io.confirm(i)};return{approveDiagnosis:s=>r(ni("diagnosis",s,n),"Send this request?"),approveDiagnoses:s=>{let[i]=s;return s.length===1&&i!==void 0?r(ni("diagnosis",i,n),"Send this request?"):r([`${s.length} diagnosis requests, one for each group of failures with a shared cause:`,...s.flatMap((a,o)=>["",`Request ${o+1} of ${s.length}`,...ni("diagnosis",a,n)])],`Send these ${s.length} requests?`)},approveRepairRequest:s=>r(ni("repair proposal",s,n),"Send this request?"),approveApplication:async(s,i)=>{for(let a of Xb(s,i))t.io.print(a);return t.io.confirm("Apply this patch?")}}}async function lx(t,n,e,r,s){let i=new Set(r),a=await iu({run:{...e,logicalTests:e.logicalTests.filter(d=>i.has(d.logicalTestId))},workspaceRoot:n,repositoryRoot:await Co(n),captureId:`${s.purpose}-${e.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest"}`,env:t.env,probe:!1});if(a.kind!=="ready")return{kind:"unavailable",message:a.message};t.io.print(""),t.io.print(s.intro);for(let d of a.prepared.description)t.io.print(d);if(!await t.io.confirm(s.question))return{kind:"declined"};let o=await au(a.prepared,t.env);return t.io.print(o.outcome.message),o.outcome.kind==="failed"?{kind:"unavailable",message:o.outcome.message}:{kind:"rerun",failedAgain:o.outcome.failedAgain??[]}}function B2(t){return t==="repair-failed"||t==="validation-unavailable"||t==="operation-failed"?q.failed:q.ok}function Lo(t,n,e={}){t.io.print("");let r=Zb("run"in n?n.run:void 0);r!==void 0&&n.record?.command!=="validate"&&t.io.print(r);let s=n.record?.clusters??[];if(s.length>1&&n.record?.command!=="validate")for(let d of Yb(s,"run"in n?n.run:void 0))t.io.print(d);else if(n.record?.diagnosis!==void 0&&n.record.command!=="validate"){for(let d of ip(n.record.diagnosis))t.io.print(d);t.io.print("")}t.io.print(`Result: ${n.outcome} (${n.reasonCode})`),t.io.print(n.message);let i=kt(t.env),a=ex("run"in n?n.run:void 0,i);a!==void 0&&t.io.print(a);let o=Qb(n.record,n.outcome,i,"run"in n?n.run:void 0,e);return o!==void 0&&t.io.print(o),n.recordPath!==void 0&&t.io.print(`Record: ${n.recordPath}`),B2(n.outcome)}async function Bn(t,n){try{return await n()}catch(e){if(e instanceof ft)return t.io.error(e.message),[401,402,403,409].includes(e.status)?q.account:q.failed;throw e}}function ux(t){return t.sleep??(n=>new Promise(e=>setTimeout(e,n)))}async function px(t){return Bn(t,async()=>{let n=new vt(Zt(t.env),void 0,t.fetch),e=await n.startDeviceLogin();t.io.print(`Open ${e.verificationUri} and enter the code: ${e.userCode}`);let r=ux(t),s=Math.max(1,e.interval),i=Date.now()+e.expiresIn*1e3;for(;Date.now()<i;){await r(s*1e3);let a=await n.pollDeviceLogin(e.deviceCode);if(a.status==="complete")return await Vb(t.env,{token:a.token,login:a.login,apiUrl:n.baseUrl}),t.io.print(`Signed in as ${a.login}.`),q.ok;if(a.status==="slow_down"&&(s+=5),a.status==="expired"||a.status==="denied")return t.io.error(a.status==="denied"?"Sign-in was denied.":"The code expired."),q.account}return t.io.error("The code expired before sign-in finished."),q.account})}async function fx(t){let n=(t.env.KWIKQA_TOKEN??"").trim()!=="",e=n?void 0:await en(t.env);if(e!==void 0)try{await new vt(Zt(t.env,e.apiUrl),e.token,t.fetch).logout()}catch{t.io.error(`Could not reach the KwikQA service to revoke this token; revoke it at ${Nr}account/.`)}return await zb(t.env),t.io.print("Signed out."),n&&t.io.print("KWIKQA_TOKEN is still set in this environment; unset it to stop using it."),q.ok}function V2(t){let n=[...t.seats!==void 0&&t.seats>1?[`${t.seats} seats`]:[],...t.interval===void 0?[]:[t.interval==="year"?"billed yearly":"billed monthly"]];return`on the ${t.plan} plan${n.length===0?"":` (${n.join(", ")})`}`}async function hx(t){return Bn(t,async()=>{let n=await en(t.env);if(n===void 0)return t.io.print(dp(t)),q.account;let r=await new vt(Zt(t.env,n.apiUrl),n.token,t.fetch).status(),s=(i,a)=>a===void 0?`${i} (unlimited)`:`${i} of ${a}`;return t.io.print(`Signed in as ${r.login} ${V2(r)}.`),r.team!==void 0&&(t.io.print(r.team.role==="member"?`Team: ${r.team.owner}'s team; usage below is the team's shared pool.`:`Team: yours, with ${r.team.members} member${r.team.members===1?"":"s"}; usage below is the shared pool.`),t.io.print(r.team.insights===!0?"Team insights: on. Test names and fix outcomes from your runs are shared with your team.":"Team insights: off.")),t.io.print(`Analyses this period: ${s(r.usage.analyses.used,r.usage.analyses.limit)}`),t.io.print(`Fixes this period: ${s(r.usage.repairs.used,r.usage.repairs.limit)}`),t.io.print(`Period ends: ${r.periodEnd.slice(0,10)}`),t.io.print(`Manage your account, team, and tokens: ${Nr}`),q.ok})}async function mx(t){let n=await en(t.env);if(n===void 0){t.io.error(dp(t));return}return new vt(Zt(t.env,n.apiUrl),n.token,t.fetch)}function z2(t){let n=t.perSeat?"/seat":"",e=t.monthlyUsd===0?"$0":`$${t.monthlyUsd}${n}/mo or $${t.annualUsd}${n}/yr`,r=t.analyses===void 0?"unlimited analyses and fixes":`${t.analyses} analyses and ${t.repairs} fixes a month${t.perSeat?" per seat, shared":""}`,s=[...t.hosted?[]:["your OpenRouter key"],...t.perSeat?[`${t.minSeats}+ seats`]:[]];return{price:e,limits:s.length===0?r:`${r} (${s.join(", ")})`}}async function yx(t,n,e={annual:!1}){return Bn(t,async()=>{let r=await en(t.env),s=await new vt(Zt(t.env,r?.apiUrl),void 0,t.fetch).plans(),i=s.paidPlansOpen!==!1,o=s.plans.filter(m=>m.id!=="free").find(m=>m.id===n);if(o===void 0||!i){n!==void 0&&o===void 0&&t.io.error(`Unknown plan: ${n}`),t.io.print(`Plans (monthly, or yearly with ${12-s.annualMonthsCharged} months free):`);let m=Math.max(...s.plans.map(g=>g.id.length));for(let g of s.plans){let{price:y,limits:w}=z2(g);t.io.print(` ${g.id.padEnd(m)} ${y}: ${w}`)}if(i)t.io.print(`Run \`${kt(t.env)} upgrade <plan> [--annual] [--seats <n>]\` to get a checkout link.`);else if(t.io.print("Paid plans are coming soon. Until they open, every account uses Free."),o!==void 0)return q.account;return n===void 0?q.ok:q.usage}let d;if(e.seats!==void 0&&(d=Number(e.seats),!(o.perSeat?Number.isInteger(d)&&d>=o.minSeats&&d<=s.maxSeats:d===1)))return t.io.error(o.perSeat?`${o.name} needs ${o.minSeats} to ${s.maxSeats} seats.`:`${o.name} is for one person; --seats applies to team plans.`),q.usage;let c=await mx(t);if(c===void 0)return q.account;let l=await c.status();if(l.team?.role==="member")return t.io.print(`You're on ${l.team.owner}'s team, so ${l.team.owner} manages billing.`),q.ok;if(l.plan!=="free")return t.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:`),t.io.print(`${Nr}billing/`),q.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 t.io.print(`Open this link to subscribe to ${o.name}${o.perSeat?` with ${f} seats`:""} for $${h} a ${e.annual?"year":"month"}:`),t.io.print(p.url),q.ok})}async function gx(t){return Bn(t,async()=>{let n=await mx(t);if(n===void 0)return q.account;try{let{url:e}=await n.billingPortal();return t.io.print("Open this link to update your payment method or download invoices:"),t.io.print(e),t.io.print(`To change or cancel your plan: ${Nr}billing/`),q.ok}catch(e){if(e instanceof ft&&e.code==="no-billing-account")return t.io.print("You don't have a paid subscription yet."),t.io.print(`Run \`${kt(t.env)} upgrade <plan>\` to choose one.`),q.ok;if(e instanceof ft&&e.code==="team-member")return t.io.print(e.message),q.ok;throw e}})}async function wx(t){let n=await $r(t.cwd),e=He(n,"kwikqa.config.json");if(await Or(e))t.io.print("kwikqa.config.json already exists; review it to change what KwikQA may edit.");else{let p=$u({repositoryPaths:await Ju(n)});t.io.print("Proposed kwikqa.config.json (what KwikQA may edit when repairing tests):");for(let f of p.canonicalContents.trimEnd().split(`
214
+ `))t.io.print(` ${f}`);for(let f of[...p.reasons,...p.ambiguities])t.io.print(` - ${f}`);await t.io.confirm("Write kwikqa.config.json?")&&(await ix(e,p.canonicalContents,{flag:"wx"}),t.io.print("Wrote kwikqa.config.json. Commit it so the policy is reviewed like code."))}let r=He(n,".gitignore"),s=await Or(r)?await $o(r,"utf8"):"",i=p=>p.trim().replace(/^\//,"").replace(/\/$/,""),a=new Set(s.split(/\r?\n/).map(i)),o=[{entry:".kwikqa/",what:"local run records"},{entry:fi,what:"the failure report"}].filter(p=>!a.has(i(p.entry))),d=o.map(p=>`${p.entry} (${p.what})`).join(" and ");o.length>0&&await t.io.confirm(`Add ${d} to .gitignore?`)&&await N2(r,`
213
215
  ${o.map(p=>p.entry).join(`
214
216
  `)}
215
- `);let c=new Set((await op(t)).map(p=>p.framework)),l=p=>c.size===0||c.has(p),u=vt(n.env);return l("playwright")&&(n.io.print(""),n.io.print("Playwright: add a JSON reporter to playwright.config so KwikQA can read your runs:"),n.io.print(' reporter: [["list"], ["json", { outputFile: "test-results/kwikqa-report.json" }]],'),n.io.print(' use: { trace: "retain-on-failure" },')),l("cypress")&&(n.io.print(""),n.io.print(`Cypress: with kwikqa installed (${Uu(n.env,"kwikqa")}), set KwikQA's reporter in cypress.config`),n.io.print("so every attempt and its code frame is kept:"),n.io.print(' reporter: "node_modules/kwikqa/dist/cypress-reporter.cjs",'),n.io.print(` Mochawesome and JUnit reports work too: ${u} analyze --report mochawesome-report`)),l("webdriverio")&&(n.io.print(""),n.io.print(`WebdriverIO: with kwikqa installed (${Uu(n.env,"kwikqa")}), add KwikQA's reporter in wdio.conf:`),n.io.print(' import KwikqaReporter from "kwikqa/wdio-reporter";'),n.io.print(' reporters: ["spec", [KwikqaReporter, {}]],'),n.io.print(` @wdio/json-reporter and JUnit reports work too: ${u} analyze --report <directory>`)),(c.has("cypress")||c.has("webdriverio"))&&(n.io.print(""),n.io.print(`Then \`${u} analyze --capture\` re-runs failing specs and records each failure's page.`)),q.ok}async function Qb(n,t){return Fn(n,async()=>{let e=await Cr(n.cwd);if(t.output!==void 0&&t.html!==!0)return n.io.error("--output names where --html writes the report; add --html."),q.usage;let r=t.html===!0?await yr(e,t.output):void 0;if(r?.kind==="refused")return n.io.error(r.message),q.usage;let s=await No(n,e,t.report);if(t.capture===!0&&!n.io.interactive&&!t.yes)return n.io.error("Capturing re-runs your failing tests: run in a terminal, or pass --yes."),q.usage;let i=t.local?void 0:await Yu(n,"analysis");if(i!==void 0&&"exit"in i)return Hb(n,i);if(i!==void 0&&!n.io.interactive&&!t.yes)return n.io.error("Sending evidence needs approval: run in a terminal, or pass --yes, or use --local."),q.usage;let a=t.capture===!0?await YO(n,e,s,{yes:t.yes,probe:t.probe!==!1,...t.framework===void 0?{}:{framework:t.framework}}):void 0,o=a?.reportPath??s,d=await jn(e),c=await vo({reportPath:o,...t.framework===void 0?{}:{framework:t.framework},...a?.probePath===void 0?{}:{probePath:a.probePath},workspaceRoot:e,...d.kind==="read"?{gitRoot:d.status.gitRoot}:{},evidencePolicy:Ku(i),includeChangeHistory:t.changes!==!1,...i===void 0?{}:{remote:i.diagnosis},interaction:Qu(n,i?.destination??"",t.yes)}),l=Oo(n,c),u=r===void 0?l:await i2(n,e,r.path,c,l);return i!==void 0&&await Ys(n.io,i.client,i.status,zu(c)),u})}async function s2(n,t,e){if(t)return{notDiagnosed:"--local analyzes without asking a model."};if(await Zt(n.env)===void 0)return{notDiagnosed:e?.pullRequest?.fork===!0?"the pull request comes from a fork, and GitHub gives its workflows no secrets, so there is no KWIKQA_TOKEN.":`there is no KwikQA token. Set KWIKQA_TOKEN to a CI token from ${Tr}account/ to diagnose failures.`};try{let r=await Yu(n,"analysis");return"exit"in r?{notDiagnosed:r.messages.join(" ")}:{setup:r}}catch(r){if(r instanceof pt)return{notDiagnosed:r.message};throw r}}async function Zb(n,t){return Fn(n,async()=>{let e=await Cr(n.cwd),r=await yr(e,t.output);if(r.kind==="refused")return n.io.error(r.message),q.usage;let s=await Ul(n.env),i=await No(n,e,t.report),a=await s2(n,t.local,s);a.notDiagnosed!==void 0&&n.io.print(`Not diagnosed: ${a.notDiagnosed} Analyzing locally.`);let o=await jn(e),d=await vo({reportPath:i,...t.framework===void 0?{}:{framework:t.framework},workspaceRoot:e,...o.kind==="read"?{gitRoot:o.status.gitRoot}:{},evidencePolicy:Ku(a.setup),includeChangeHistory:t.changes!==!1,...a.setup===void 0?{}:{remote:a.setup.diagnosis},interaction:Qu(n,a.setup?.destination??"",!0)}),c=Oo(n,d),l=d.run===void 0||d.record===void 0?void 0:ex(d.run,d.record,d),u=l===void 0?void 0:await Zu(n,e,r.path,$s(l));a.setup!==void 0&&await Ys(n.io,a.setup.client,a.setup.status,zu(d));let p=Gl({model:l,message:d.message,...a.notDiagnosed===void 0?{}:{notDiagnosed:a.notDiagnosed},...u===void 0?{}:{reportFile:u.split(Fb).join("/")},...s?.runUrl===void 0?{}:{runUrl:s.runUrl}}),f=l?.run.counts.find(g=>g.label==="Failed")?.value??0,h=l===void 0||f>0;s===void 0?n.io.print("Not running in GitHub Actions, the CI system supported so far: no job summary or comment."):await ql(n.io,n.fetch,s,p,{failures:h});let m=Bl({model:l,message:d.message,...a.notDiagnosed===void 0?{}:{notDiagnosed:a.notDiagnosed},...s===void 0?{}:{run:s}});return await Vl(n.io,n.fetch,Ub(n),n.env,m,{when:t.notify??"on-failure",failures:h}),c})}async function Zu(n,t,e,r){let s=await Tl(e,r);if(s.kind==="refused"){n.io.error(s.message);return}let i=ti(t,e),a=i.startsWith("..")||Gu(i)?e:i;return n.io.print(`Report: ${a}`),a}async function i2(n,t,e,r,s){if(r.run===void 0||r.record===void 0)return n.io.error("No failure report: the test report could not be read."),s;let i=$s(ex(r.run,r.record,r));return await Zu(n,t,e,i)===void 0?q.usage:s}function ex(n,t,e){return Ga({run:n,record:t,...e.detail===void 0?{}:{detail:e.detail},kwikqaVersion:Zs})}async function tx(n,t){let e=await Cr(n.cwd),r=vt(n.env);if(t.run!==void 0&&!/^run_[a-f0-9]{24}$/.test(t.run))return n.io.error("--run takes a run id as named under .kwikqa/runs/, such as run_0123456789abcdef01234567."),q.usage;let s=await yr(e,t.output);if(s.kind==="refused")return n.io.error(s.message),q.usage;let i=t.run??await Tu(e),a=i===void 0?[]:await Su(e,i),o=h=>[...a].reverse().find(h),d=o(h=>h.command==="analyze")??o(h=>h.command==="fix"&&h.clusters!==void 0);if(d===void 0)return n.io.error(i===void 0?`No analysis is recorded here yet. Run \`${r} analyze\` first.`:`Run ${i} has no recorded analysis. Run \`${r} analyze\` first.`),q.usage;let c=o(h=>h.command!=="analyze"&&h.recordedAt>d.recordedAt),l=d.inputs??{report:ti(e,await No(n,e)).split(Fb).join("/"),changeHistory:!0,currentDiff:!1,maxPacketBytes:ei.maxPacketBytes},u=await jn(e),p=await Eu({reportPath:Co(e,l.report),...l.framework===void 0?{}:{framework:l.framework},workspaceRoot:e,...u.kind==="read"?{gitRoot:u.status.gitRoot}:{},evidencePolicy:{...ei,maxPacketBytes:l.maxPacketBytes},includeChangeHistory:l.changeHistory,includeCurrentDiff:l.currentDiff,...l.probe===void 0?{}:{probePath:Co(e,l.probe)}},(d.clusters??[]).map(h=>h.clusterId));if(p.kind==="unreadable"||p.run.runId!==d.runId)return n.io.error(`The test report this analysis read (${l.report}) has changed or is gone, so its tests can't be shown. Run \`${r} analyze --html\` on the current report.`),q.failed;let f=$s(Ga({run:p.run,record:d,...p.detail===void 0?{}:{detail:p.detail},...c===void 0?{}:{repair:c},kwikqaVersion:Zs}));return await Zu(n,e,s.path,f)===void 0?q.usage:q.ok}async function nx(n,t){return n.io.interactive?Fn(n,async()=>{let e=await Cr(n.cwd),r=await Ju(e),s=t.retry?r.pendingRetry:void 0;if(t.retry&&s===void 0)return n.io.error("There is no failed validation to retry."),q.usage;let i=s===void 0?void 0:r.tickets?.[s.repairSessionId],a=await Yu(n,"repair",i);if("exit"in a)return Hb(n,a);let o=s===void 0?await No(n,e,t.report):void 0,d=o===void 0?void 0:await XO(e,r,o);d!==void 0&&n.io.print(`Using the evidence captured by \`analyze --capture\`: ${ti(e,d.reportPath)}`);let c=await Lu({reportPath:s===void 0?d?.reportPath??o??ze(e,"report.json"):ze(e,s.reportPath),...t.framework===void 0?{}:{framework:t.framework},...d?.probePath===void 0?{}:{probePath:d.probePath},workspaceRoot:e,evidencePolicy:Ku(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:{...Qu(n,a.destination,!1),confirmFailure:(m,g)=>zb(n,e,m,g,{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:s===void 0,proposeOnly:t.proposeOnly,...s===void 0?{}:{retryRepairSessionId:s.repairSessionId}}),l=c.record?.repair?.repairSessionId,u=a.ticket(),{pendingRetry:p,...f}=r;await Xu(e,{...s===void 0?r:f,...l===void 0||u===void 0?{}:{tickets:{...r.tickets,[l]:u}}});let h=Oo(n,c);return await Ys(n.io,a.client,a.status,Ab(c)),h}):(n.io.error("`kwikqa fix` needs a terminal: every request and patch is approved by a person."),q.usage)}async function a2(n,t){let e=Pb(t),r=e===void 0?void 0:await Zt(n.env);if(r===void 0)return;let s=new xt(Qt(n.env,r.apiUrl),r.token,n.fetch),i;try{i=await s.status()}catch{return}await Ys(n.io,s,i,e)}async function rx(n){let t=await Cr(n.cwd),e=await Fu({workspaceRoot:t,checkGroup:(i,a)=>zb(n,t,i,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?"})}),r=e.record?.repair;if(r?.retryAvailable===!0&&r.retryReportPath!==void 0){let i=await Ju(t);await Xu(t,{...i,pendingRetry:{repairSessionId:r.repairSessionId,reportPath:r.retryReportPath}})}let s=Oo(n,e);return await a2(n,e),s}import{createInterface as o2}from"node:readline/promises";function sx(){return{interactive:process.stdin.isTTY===!0,print:(n="")=>{process.stdout.write(`${n}
216
- `)},error:n=>{process.stderr.write(`${n}
217
- `)},confirm:async n=>{if(process.stdin.isTTY!==!0)return!1;let t=o2({input:process.stdin,output:process.stdout});try{let e=await t.question(`${n} [y/N] `);return/^y(?:es)?$/i.test(e.trim())}finally{t.close()}}}}var c2=`KwikQA turns failed Playwright, Cypress, and WebdriverIO runs into evidence-backed diagnoses and safe, validated test repairs.
217
+ `);let c=new Set((await Gy(n)).map(p=>p.framework)),l=p=>c.size===0||c.has(p),u=kt(t.env);return l("playwright")&&(t.io.print(""),t.io.print("Playwright: add a JSON reporter to playwright.config so KwikQA can read your runs:"),t.io.print(' reporter: [["list"], ["json", { outputFile: "test-results/kwikqa-report.json" }]],'),t.io.print(' use: { trace: "retain-on-failure" },')),l("cypress")&&(t.io.print(""),t.io.print(`Cypress: with kwikqa installed (${sp(t.env,"kwikqa")}), set KwikQA's reporter in cypress.config`),t.io.print("so every attempt and its code frame is kept:"),t.io.print(' reporter: "node_modules/kwikqa/dist/cypress-reporter.cjs",'),t.io.print(` Mochawesome and JUnit reports work too: ${u} analyze --report mochawesome-report`)),l("webdriverio")&&(t.io.print(""),t.io.print(`WebdriverIO: with kwikqa installed (${sp(t.env,"kwikqa")}), add KwikQA's reporter in wdio.conf:`),t.io.print(' import KwikqaReporter from "kwikqa/wdio-reporter";'),t.io.print(' reporters: ["spec", [KwikqaReporter, {}]],'),t.io.print(` @wdio/json-reporter and JUnit reports work too: ${u} analyze --report <directory>`)),(c.has("cypress")||c.has("webdriverio"))&&(t.io.print(""),t.io.print(`Then \`${u} analyze --capture\` re-runs failing specs and records each failure's page.`)),q.ok}async function bx(t,n){return Bn(t,async()=>{let e=await $r(t.cwd);if(n.output!==void 0&&n.html!==!0)return t.io.error("--output names where --html writes the report; add --html."),q.usage;let r=n.html===!0?await Un(e,n.output):void 0;if(r?.kind==="refused")return t.io.error(r.message),q.usage;let s=await Mo(t,e,n.report);if(n.capture===!0&&!t.io.interactive&&!n.yes)return t.io.error("Capturing re-runs your failing tests: run in a terminal, or pass --yes."),q.usage;let i=n.local?void 0:await up(t,"analysis");if(i!==void 0&&"exit"in i)return cx(t,i);if(i!==void 0&&!t.io.interactive&&!n.yes)return t.io.error("Sending evidence needs approval: run in a terminal, or pass --yes, or use --local."),q.usage;let a=n.capture===!0?await L2(t,e,s,{yes:n.yes,probe:n.probe!==!1,...n.framework===void 0?{}:{framework:n.framework}}):void 0,o=a?.reportPath??s,d=await Fn(e),c=await Ao({reportPath:o,...n.framework===void 0?{}:{framework:n.framework},...a?.probePath===void 0?{}:{probePath:a.probePath},workspaceRoot:e,...d.kind==="read"?{gitRoot:d.status.gitRoot}:{},evidencePolicy:op(i),includeChangeHistory:n.changes!==!1,...i===void 0?{}:{remote:i.diagnosis},interaction:pp(t,i?.destination??"",n.yes)}),l=Lo(t,c),u=r===void 0?l:await U2(t,e,r.path,c,l);return i!==void 0&&await ti(t.io,i.client,i.status,rp(c)),u})}async function H2(t,n,e,r){if(n)return{notDiagnosed:"--local analyzes without asking a model."};if(await en(t.env)===void 0)return{notDiagnosed:r?`${e==="gitlab"?"the merge request comes from a fork, whose pipeline gets none of this project's variables":e==="azure"?"the pull request comes from a fork, and Azure Pipelines gives a fork's build no secrets unless the pipeline allows it":"the pull request comes from a fork, and GitHub gives its workflows no secrets"}, so there is no KWIKQA_TOKEN.`:`there is no KwikQA token. Set KWIKQA_TOKEN${e==="azure"?", mapped in the step's env,":""} to a CI token from ${Nr}account/ to diagnose failures.`};try{let s=await up(t,"analysis");return"exit"in s?{notDiagnosed:s.messages.join(" ")}:{setup:s}}catch(s){if(s instanceof ft)return{notDiagnosed:s.message};throw s}}async function xx(t,n){return Bn(t,async()=>{let e=await $r(t.cwd),r=await Un(e,n.output);if(r.kind==="refused")return t.io.error(r.message),q.usage;let s=await Kc(t.env),i=s===void 0?Vo(t.env):void 0,a=s===void 0&&i===void 0?Yc(t.env):void 0,o=s??i??a,d=await Mo(t,e,n.report),c=await H2(t,n.local,s!==void 0?"github":i!==void 0?"azure":a!==void 0?"gitlab":void 0,o?.pullRequest?.fork===!0);c.notDiagnosed!==void 0&&t.io.print(`Not diagnosed: ${c.notDiagnosed} Analyzing locally.`);let l=await Fn(e),u=await Ao({reportPath:d,...n.framework===void 0?{}:{framework:n.framework},workspaceRoot:e,...l.kind==="read"?{gitRoot:l.status.gitRoot}:{},evidencePolicy:op(c.setup),includeChangeHistory:n.changes!==!1,...c.setup===void 0?{}:{remote:c.setup.diagnosis},interaction:pp(t,c.setup?.destination??"",!0)}),p=Lo(t,u,{ci:!0}),f=u.run===void 0||u.record===void 0?void 0:vx(u.run,u.record,u),h=f===void 0?void 0:await fp(t,e,r.path,Fr(f));c.setup!==void 0&&await ti(t.io,c.setup.client,c.setup.status,rp(u));let m=Zc({model:f,message:u.message,...c.notDiagnosed===void 0?{}:{notDiagnosed:c.notDiagnosed},...h===void 0?{}:{reportFile:h.split(ax).join("/")},...o?.runUrl===void 0?{}:{runUrl:o.runUrl}}),g=f?.run.counts.find(x=>x.label==="Failed")?.value??0,y=f===void 0||g>0;s!==void 0?await Wc(t.io,t.fetch,s,m,{failures:y}):i!==void 0?await zo(t.io,t.fetch,i,m,{failures:y}):a!==void 0?await Qc(t.io,t.fetch,a,m,{failures:y}):t.io.print("Not running in GitHub Actions, Azure Pipelines, or GitLab CI/CD, the CI systems supported so far: no summary or comment.");let w=Hc({model:f,message:u.message,...c.notDiagnosed===void 0?{}:{notDiagnosed:c.notDiagnosed},...o===void 0?{}:{run:o}});return await Uc(t.io,t.fetch,ux(t),t.env,w,{when:n.notify??"on-failure",failures:y}),p})}async function fp(t,n,e,r){let s=await Jo(e,r);if(s.kind==="refused"){t.io.error(s.message);return}let i=ii(n,e),a=i.startsWith("..")||ap(i)?e:i;return t.io.print(`Report: ${a}`),a}async function U2(t,n,e,r,s){if(r.run===void 0||r.record===void 0)return t.io.error("No failure report: the test report could not be read."),s;let i=Fr(vx(r.run,r.record,r));return await fp(t,n,e,i)===void 0?q.usage:s}function vx(t,n,e){return aa({run:t,record:n,...e.detail===void 0?{}:{detail:e.detail},kwikqaVersion:ri})}async function kx(t,n){let e=await $r(t.cwd),r=kt(t.env);if(n.run!==void 0&&!/^run_[a-f0-9]{24}$/.test(n.run))return t.io.error("--run takes a run id as named under .kwikqa/runs/, such as run_0123456789abcdef01234567."),q.usage;let s=await Un(e,n.output);if(s.kind==="refused")return t.io.error(s.message),q.usage;let i=n.run??await zu(e),a=i===void 0?[]:await Vu(e,i),o=h=>[...a].reverse().find(h),d=o(h=>h.command==="analyze")??o(h=>h.command==="fix"&&h.clusters!==void 0);if(d===void 0)return t.io.error(i===void 0?`No analysis is recorded here yet. Run \`${r} analyze\` first.`:`Run ${i} has no recorded analysis. Run \`${r} analyze\` first.`),q.usage;let c=o(h=>h.command!=="analyze"&&h.recordedAt>d.recordedAt),l=d.inputs??{report:ii(e,await Mo(t,e)).split(ax).join("/"),changeHistory:!0,currentDiff:!1,maxPacketBytes:si.maxPacketBytes},u=await Fn(e),p=await Hu({reportPath:Do(e,l.report),...l.framework===void 0?{}:{framework:l.framework},workspaceRoot:e,...u.kind==="read"?{gitRoot:u.status.gitRoot}:{},evidencePolicy:{...si,maxPacketBytes:l.maxPacketBytes},includeChangeHistory:l.changeHistory,includeCurrentDiff:l.currentDiff,...l.probe===void 0?{}:{probePath:Do(e,l.probe)}},(d.clusters??[]).map(h=>h.clusterId));if(p.kind==="unreadable"||p.run.runId!==d.runId)return t.io.error(`The test report this analysis read (${l.report}) has changed or is gone, so its tests can't be shown. Run \`${r} analyze --html\` on the current report.`),q.failed;let f=Fr(aa({run:p.run,record:d,...p.detail===void 0?{}:{detail:p.detail},...c===void 0?{}:{repair:c},kwikqaVersion:ri}));return await fp(t,e,s.path,f)===void 0?q.usage:q.ok}async function Rx(t,n){return t.io.interactive?Bn(t,async()=>{let e=await $r(t.cwd),r=await cp(e),s=n.retry?r.pendingRetry:void 0;if(n.retry&&s===void 0)return t.io.error("There is no failed validation to retry."),q.usage;let i=s===void 0?void 0:r.tickets?.[s.repairSessionId],a=await up(t,"repair",i);if("exit"in a)return cx(t,a);let o=s===void 0?await Mo(t,e,n.report):void 0,d=o===void 0?void 0:await M2(e,r,o);d!==void 0&&t.io.print(`Using the evidence captured by \`analyze --capture\`: ${ii(e,d.reportPath)}`);let c=await Xu({reportPath:s===void 0?d?.reportPath??o??He(e,"report.json"):He(e,s.reportPath),...n.framework===void 0?{}:{framework:n.framework},...d?.probePath===void 0?{}:{probePath:d.probePath},workspaceRoot:e,evidencePolicy:op(a),includeChangeHistory:n.changes!==!1,remote:a.diagnosis,repairModel:a.repairModel,repairCaps:a.repairCaps,...a.repairSession===void 0?{}:{repairSession:a.repairSession},...n.group===void 0?{}:{group:n.group},interaction:{...pp(t,a.destination,!1),confirmFailure:(m,g)=>lx(t,e,m,g,{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:s===void 0,proposeOnly:n.proposeOnly,...s===void 0?{}:{retryRepairSessionId:s.repairSessionId}}),l=c.record?.repair?.repairSessionId,u=a.ticket(),{pendingRetry:p,...f}=r;await lp(e,{...s===void 0?r:f,...l===void 0||u===void 0?{}:{tickets:{...r.tickets,[l]:u}}});let h=Lo(t,c);return await ti(t.io,a.client,a.status,Gb(c)),h}):(t.io.error("`kwikqa fix` needs a terminal: every request and patch is approved by a person."),q.usage)}async function q2(t,n){let e=Kb(n),r=e===void 0?void 0:await en(t.env);if(r===void 0)return;let s=new vt(Zt(t.env,r.apiUrl),r.token,t.fetch),i;try{i=await s.status()}catch{return}await ti(t.io,s,i,e)}async function Ix(t){let n=await $r(t.cwd),e=await Zu({workspaceRoot:n,checkGroup:(i,a)=>lx(t,n,i,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?"})}),r=e.record?.repair;if(r?.retryAvailable===!0&&r.retryReportPath!==void 0){let i=await cp(n);await lp(n,{...i,pendingRetry:{repairSessionId:r.repairSessionId,reportPath:r.retryReportPath}})}let s=Lo(t,e);return await q2(t,e),s}import{createInterface as G2}from"node:readline/promises";function Ax(t){let n=e=>e.replace(/##vso\[/gi,"##vso [");return{interactive:t.interactive,print:(e="")=>t.print(n(e)),error:e=>t.error(n(e)),confirm:e=>t.confirm(n(e)),command:e=>t.print(e)}}function Tx(){return{interactive:process.stdin.isTTY===!0,print:(t="")=>{process.stdout.write(`${t}
218
+ `)},error:t=>{process.stderr.write(`${t}
219
+ `)},confirm:async t=>{if(process.stdin.isTTY!==!0)return!1;let n=G2({input:process.stdin,output:process.stdout});try{let e=await n.question(`${t} [y/N] `);return/^y(?:es)?$/i.test(e.trim())}finally{n.close()}}}}var W2=`KwikQA turns failed Playwright, Cypress, and WebdriverIO runs into evidence-backed diagnoses and safe, validated test repairs.
218
220
 
219
221
  Usage:
220
222
  npx kwikqa init Create kwikqa.config.json and set up your reporter
@@ -248,8 +250,8 @@ Usage:
248
250
  npx kwikqa logout Sign out and revoke this machine's token
249
251
 
250
252
  Docs: https://kwikqa.com/docs/
251
- Dashboard: https://kwikqa.com/dashboard/`;function ix(n){let t=vt(n),e=" ".repeat(t.length-10);return c2.split(`
252
- `).map(r=>r.startsWith(" npx kwikqa ")?r.replace("npx kwikqa",t):/^ +\[/.test(r)?`${e}${r}`:r).join(`
253
- `)}async function l2(n,t){let[e,...r]=n,s;try{s=d2({args:[...r],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"},html:{type:"boolean",default:!1},output:{type:"string"},notify:{type:"string"},run:{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(c){return t.io.error(c.message),q.usage}let i=s.values;if(i.help||e===void 0||e==="help"||e==="--help")return t.io.print(ix(t.env)),q.ok;if(i.framework!==void 0&&!ft.includes(i.framework))return t.io.error(`--framework must be one of: ${ft.join(", ")}`),q.usage;let a=i.framework;if(i.notify!==void 0&&!Ka.includes(i.notify))return t.io.error(`--notify must be one of: ${Ka.join(", ")}`),q.usage;let o=i.notify,d=i.group===void 0?void 0:Number(i.group);if(d!==void 0&&!(Number.isInteger(d)&&d>=1))return t.io.error("--group takes a failure group's number as analyze printed it: 1, 2, ..."),q.usage;switch(e){case"--version":case"version":return t.io.print(Zs),q.ok;case"init":return Yb(t);case"login":return qb(t);case"logout":return Gb(t);case"status":return Kb(t);case"upgrade":return Jb(t,s.positionals[0],{annual:i.annual,...i.seats===void 0?{}:{seats:i.seats}});case"billing":return Xb(t);case"analyze":return Qb(t,{...i.report===void 0?{}:{report:i.report},...a===void 0?{}:{framework:a},local:i.local,yes:i.yes,capture:i.capture,probe:!i["no-probe"],changes:!i["no-changes"],html:i.html,...i.output===void 0?{}:{output:i.output}});case"ci":return Zb(t,{...i.report===void 0?{}:{report:i.report},...a===void 0?{}:{framework:a},local:i.local,changes:!i["no-changes"],...i.output===void 0?{}:{output:i.output},...o===void 0?{}:{notify:o}});case"report":return tx(t,{...i.run===void 0?{}:{run:i.run},...i.output===void 0?{}:{output:i.output}});case"fix":return nx(t,{...i.report===void 0?{}:{report:i.report},...a===void 0?{}:{framework:a},retry:i.retry,proposeOnly:i["propose-only"],changes:!i["no-changes"],...d===void 0?{}:{group:d}});case"validate":return rx(t);default:return t.io.error(`Unknown command: ${e}
253
+ Dashboard: https://kwikqa.com/dashboard/`;function Px(t){let n=kt(t),e=" ".repeat(n.length-10);return W2.split(`
254
+ `).map(r=>r.startsWith(" npx kwikqa ")?r.replace("npx kwikqa",n):/^ +\[/.test(r)?`${e}${r}`:r).join(`
255
+ `)}async function J2(t,n){let e=n.env.TF_BUILD==="True"?{...n,env:Bo(n.env),io:Ax(n.io)}:n,[r,...s]=t,i;try{i=K2({args:[...s],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"},html:{type:"boolean",default:!1},output:{type:"string"},notify:{type:"string"},run:{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(l){return e.io.error(l.message),q.usage}let a=i.values;if(a.help||r===void 0||r==="help"||r==="--help")return e.io.print(Px(e.env)),q.ok;if(a.framework!==void 0&&!ht.includes(a.framework))return e.io.error(`--framework must be one of: ${ht.join(", ")}`),q.usage;let o=a.framework;if(a.notify!==void 0&&!oa.includes(a.notify))return e.io.error(`--notify must be one of: ${oa.join(", ")}`),q.usage;let d=a.notify,c=a.group===void 0?void 0:Number(a.group);if(c!==void 0&&!(Number.isInteger(c)&&c>=1))return e.io.error("--group takes a failure group's number as analyze printed it: 1, 2, ..."),q.usage;switch(r){case"--version":case"version":return e.io.print(ri),q.ok;case"init":return wx(e);case"login":return px(e);case"logout":return fx(e);case"status":return hx(e);case"upgrade":return yx(e,i.positionals[0],{annual:a.annual,...a.seats===void 0?{}:{seats:a.seats}});case"billing":return gx(e);case"analyze":return bx(e,{...a.report===void 0?{}:{report:a.report},...o===void 0?{}:{framework:o},local:a.local,yes:a.yes,capture:a.capture,probe:!a["no-probe"],changes:!a["no-changes"],html:a.html,...a.output===void 0?{}:{output:a.output}});case"ci":return xx(e,{...a.report===void 0?{}:{report:a.report},...o===void 0?{}:{framework:o},local:a.local,changes:!a["no-changes"],...a.output===void 0?{}:{output:a.output},...d===void 0?{}:{notify:d}});case"report":return kx(e,{...a.run===void 0?{}:{run:a.run},...a.output===void 0?{}:{output:a.output}});case"fix":return Rx(e,{...a.report===void 0?{}:{report:a.report},...o===void 0?{}:{framework:o},retry:a.retry,proposeOnly:a["propose-only"],changes:!a["no-changes"],...c===void 0?{}:{group:c}});case"validate":return Ix(e);default:return e.io.error(`Unknown command: ${r}
254
256
 
255
- ${ix(t.env)}`),q.usage}}async function ax(){let n=await l2(process.argv.slice(2),{cwd:process.cwd(),env:process.env,io:sx(),fetch});process.exitCode=n}await ax();
257
+ ${Px(e.env)}`),q.usage}}async function Sx(){let t=await J2(process.argv.slice(2),{cwd:process.cwd(),env:process.env,io:Tx(),fetch});process.exitCode=t}await Sx();