kwikqa 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/kwikqa.mjs +14 -14
- package/package.json +1 -1
package/dist/kwikqa.mjs
CHANGED
|
@@ -7,7 +7,7 @@ var dx=Object.create;var np=Object.defineProperty;var cx=Object.getOwnPropertyDe
|
|
|
7
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=dR[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=_k(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 pR(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&&pR(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}},fR=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(hR(n,f,t,e)){c+=t.slice(u,e);break}if(f===92){c+=t.slice(u,e);let h=mR(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
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 hR(n,t,e,r){return n==="template"?t===96||t===36&&e.charCodeAt(r+1)===123:t===(n==="double"?34:39)}function mR(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
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:fR(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 yR=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(lR(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(yR.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 gR(){return new Jn(3)}function wR(){return new $i(1)}function bR(){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 xR(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 vR(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 kR(n){return n==="in"||n==="out"}var RR=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):kR(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 xR(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":vR(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 zk(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 Uk(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):AR(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 IR(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 AR(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)||PR(n,t)||r==="TemplateLiteral"&&n.expressions.length===0||IR(n))}function Gf(n,t){return t?n.type==="Literal"&&(typeof n.value=="number"||"bigint"in n):n.type==="NumericLiteral"||n.type==="BigIntLiteral"}function PR(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."}),SR=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)}},TR=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 ER(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:$k,jsx:uR,flow:oR,typescript:RR,v8intrinsic:TR,placeholders:SR},CR=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)),jk(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(Bk(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,qk(t)?e-1:e)}parseHackPipeBody(){var t;let{startLoc:e}=this.state,r=this.parseMaybeAssign();return Ak.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(Hk(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(;Vk(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(bR()),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(wR());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=Lk(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||!tR(t))return;if(r&&Qk(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},NR={kind:2},OR=/[\uD800-\uDFFF]/u,ld=/in(?:stanceof)?/y;function $R(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=$R(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(NR),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=Fk(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(gR()),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=OR.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=Nk(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 DR(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 MR(n,t){let e=Gr(t,n);return e.options.strictMode&&(e.state.strict=!0),e.getExpression()}function LR(n){let t={};for(let e of Object.keys(n))t[e]=It(n[e]);return t}var _R=LR(Mk);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||{})}ER(r),e=jR(r)}return new e(n,t,r)}var Df=new Map;function jR(n){let t=[];for(let s of CR)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=DR;Yr.parseExpression=MR;Yr.tokTypes=_R});import{parseArgs as d2}from"node:util";import{createHash as Mb}from"node:crypto";import{access as qO,appendFile as GO,mkdir as KO,readdir as WO,readFile as Eo,realpath as Cr,stat as Lb,writeFile as Fb}from"node:fs/promises";import{isAbsolute as Gu,join as ze,relative as ti,resolve as Co,sep as Bb}from"node:path";import{mkdir as iE,writeFile as aE}from"node:fs/promises";import{join as lg}from"node:path";import{lstat as mx,readFile as rp,realpath as Lo}from"node:fs/promises";import{dirname as $o,isAbsolute as yx,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"},gx={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===""||!yx(e)&&e!==".."&&!e.startsWith(`..${sp}`)}async function oi(n){return(await mx(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=gx[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 wx(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(wx).join("|"),r=dp("sha256").update(e,"utf8").digest("hex");return`${n}_${r.slice(0,24)}`}import{isAbsolute as cp,relative as bx,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 xx(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 vx(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=bx(n,t);if(!(cp(e)||e===".."||e.startsWith(`..${lp}`)))return e.split(lp).join("/")}function kx(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 Rx(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)=>xx(a,s,o)),annotations:n.annotations.map(fp),...n.errorLocation===void 0?{}:{errorLocation:Bo(n.errorLocation)}}}function Ix(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=kx(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=vx(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)=>Rx(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:Ix(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 Ax(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 Ax(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 Px(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"]),Sx=new Set(["expected","unexpected","flaky","skipped"]);function Tx(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`,Px),annotations:Z(e.annotations??[],`${t}.annotations`,wp),...s===void 0?{}:{errorLocation:s}}}function Ex(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`,Tx),status:nn(e.status,`${t}.status`,Sx)}}function Cx(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`,Ex),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`,Cx)}}function Nx(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",Nx),...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 Ox=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 $x(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=Ox.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=$x(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 eI}from"node:crypto";import{readdir as tI,readFile as nI,stat as rI}from"node:fs/promises";import{basename as sI,dirname as iI,join as aI}from"node:path";import{resolve as Ux}from"node:path";import{readdir as Dx,stat as Mx}from"node:fs/promises";import{join as Rp}from"node:path";var Pp=/\.(?:java|kt|groovy|scala)$/,Lx=/^at (?:([\w.$-]+)\/\/?)?([\w$]+(?:\.[\w$]+)*)\.([\w$<>-]+)\(([\w$-]+\.(?:java|kt|groovy|scala)):(\d+)\)\s*$/,_x=/^(?: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)\./,jx=["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"],Fx=["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=Lx.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"||_x.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 Mx(n)).isFile()}catch{return!1}}async function Bx(n){return(await Dx(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)?Fx:jx;this.modules??=Bx(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 Vx=/(?:\(|\bat\s+|^)((?:webpack:\/\/[^\s()]*|file:\/\/[^\s()]*|(?:[A-Za-z]:)?[^():\s][^():]*?)):(\d+):(\d+)\)?\s*$/,Hx=/^File "([^"]+\.py)", line (\d+)/,zx=/^((?:[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=Hx.exec(r)??zx.exec(r),a=i===null?Vx.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 qx="1",Gx="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 Kx={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(`
|
|
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=Lk(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||!tR(t))return;if(r&&Qk(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},NR={kind:2},OR=/[\uD800-\uDFFF]/u,ld=/in(?:stanceof)?/y;function $R(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=$R(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(NR),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=Fk(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(gR()),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=OR.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=Nk(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 DR(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 MR(n,t){let e=Gr(t,n);return e.options.strictMode&&(e.state.strict=!0),e.getExpression()}function LR(n){let t={};for(let e of Object.keys(n))t[e]=It(n[e]);return t}var _R=LR(Mk);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||{})}ER(r),e=jR(r)}return new e(n,t,r)}var Df=new Map;function jR(n){let t=[];for(let s of CR)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=DR;Yr.parseExpression=MR;Yr.tokTypes=_R});import{parseArgs as c2}from"node:util";import{createHash as Mb}from"node:crypto";import{access as GO,appendFile as KO,mkdir as WO,readdir as JO,readFile as Eo,realpath as Cr,stat as Lb,writeFile as Fb}from"node:fs/promises";import{isAbsolute as Gu,join as ze,relative as ti,resolve as Co,sep as Bb}from"node:path";import{mkdir as iE,writeFile as aE}from"node:fs/promises";import{join as lg}from"node:path";import{lstat as mx,readFile as rp,realpath as Lo}from"node:fs/promises";import{dirname as $o,isAbsolute as yx,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"},gx={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===""||!yx(e)&&e!==".."&&!e.startsWith(`..${sp}`)}async function oi(n){return(await mx(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=gx[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 wx(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(wx).join("|"),r=dp("sha256").update(e,"utf8").digest("hex");return`${n}_${r.slice(0,24)}`}import{isAbsolute as cp,relative as bx,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 xx(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 vx(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=bx(n,t);if(!(cp(e)||e===".."||e.startsWith(`..${lp}`)))return e.split(lp).join("/")}function kx(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 Rx(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)=>xx(a,s,o)),annotations:n.annotations.map(fp),...n.errorLocation===void 0?{}:{errorLocation:Bo(n.errorLocation)}}}function Ix(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=kx(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=vx(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)=>Rx(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:Ix(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 Ax(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 Ax(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 Px(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"]),Sx=new Set(["expected","unexpected","flaky","skipped"]);function Tx(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`,Px),annotations:Z(e.annotations??[],`${t}.annotations`,wp),...s===void 0?{}:{errorLocation:s}}}function Ex(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`,Tx),status:nn(e.status,`${t}.status`,Sx)}}function Cx(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`,Ex),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`,Cx)}}function Nx(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",Nx),...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 Ox=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 $x(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=Ox.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=$x(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 eI}from"node:crypto";import{readdir as tI,readFile as nI,stat as rI}from"node:fs/promises";import{basename as sI,dirname as iI,join as aI}from"node:path";import{resolve as Ux}from"node:path";import{readdir as Dx,stat as Mx}from"node:fs/promises";import{join as Rp}from"node:path";var Pp=/\.(?:java|kt|groovy|scala)$/,Lx=/^at (?:([\w.$-]+)\/\/?)?([\w$]+(?:\.[\w$]+)*)\.([\w$<>-]+)\(([\w$-]+\.(?:java|kt|groovy|scala)):(\d+)\)\s*$/,_x=/^(?: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)\./,jx=["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"],Fx=["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=Lx.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"||_x.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 Mx(n)).isFile()}catch{return!1}}async function Bx(n){return(await Dx(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)?Fx:jx;this.modules??=Bx(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 Vx=/(?:\(|\bat\s+|^)((?:webpack:\/\/[^\s()]*|file:\/\/[^\s()]*|(?:[A-Za-z]:)?[^():\s][^():]*?)):(\d+):(\d+)\)?\s*$/,Hx=/^File "([^"]+\.py)", line (\d+)/,zx=/^((?:[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=Hx.exec(r)??zx.exec(r),a=i===null?Vx.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 qx="1",Gx="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 Kx={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
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===Gx?"application/zip":r.type??"",path:t===void 0?r.source:Ux(t,r.source)}]),...(n.steps??[]).flatMap(r=>Mp(r,t))]}function Wx(n){return n.replace(/^\[/,"").replace(/\]$/,"").split("]/[").map(t=>{let e=t.indexOf(":");return{type:t.slice(0,e),value:t.slice(e+1)}})}function Jx(n){let t=Rt(n,"junit.platform.uniqueid")??n.parameters?.find(a=>a.name==="UniqueId")?.value;if(t===void 0)return;let e=Wx(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 Xx(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 Yx(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)}:Xx((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}=Yx(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=>Kx[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 Jx(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:qx,...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 Qx="1",Zx=["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 ev=[...ft,..._o];function tv(n){let t=n?.trim().toLowerCase()??"";return ev.includes(t)?t:"unknown"}var nv={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 rv(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 sv(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:rv(n,r);return{status:t,retry:e,...i===void 0?{}:{startTime:i},duration:d>=0?d:0,errors:c===void 0?[]:[c],attachments:sv(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 iv(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=tv(t.results.tool?.name),r=t.results.tool?.version?.trim()||void 0,s=[],i=t.specVersion??"";Zx.includes(i)||s.push(`unverified-ctrf-spec-version:${i===""?"unrecorded":i}`);let a=0,o=0,d=!1,c=m=>{let g=nv[m.status??""];return g===void 0&&(a+=1),g??"skipped"},l=t.results.tests.map(m=>{let g=m.filePath??"",y=iv(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:Qx,...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 av="1";function ov(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Qo(n){return Array.isArray(n)&&n.length>0&&n.every(t=>ov(t)&&typeof t.uri=="string"&&typeof t.keyword=="string"&&Array.isArray(t.elements))}function dv(n){return n.startsWith("classpath:")?n.slice(10).replace(/^\/+/,""):n}var zp=new Set(["undefined","ambiguous","pending"]),cv=1e6;function Hp(n){let t=n.result?.duration;return typeof t=="number"&&t>0?t/cv:0}function lv(n,t){return t!==void 0?`${t} hook`:`${(n.keyword??"").trim()} ${n.name??""}`.trim()}function uv(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 pv(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
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 fv(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 hv(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=uv(l,c.hook),p=lv(l,u),f=pv(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(...fv(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 mv(...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=dv(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:mv(s.tags,l.tags),attempts:[hv(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:av,...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 yv}from"node:path";var wi="kwikqa-test-report",Zo="1.0",gv="1",wv=new Set(["cypress","webdriverio"]),bv=new Set(["passed","failed","timedOut","skipped","interrupted"]);function qp(n,t){let e=t.replaceAll("\\","/");return/^(?:[A-Za-z]:\/|\/|file:\/\/)/.test(e)?t:yv(n,e.replace(/^(?:\.\/)+/,""))}function xv(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 vv(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",vv,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
13
|
Received: ${c??"(not recorded)"}`},...u===void 0?{}:{location:u}}}function kv(n,t,e){let r=ne(n,t),s=fe(r.startTime,`${t}.startTime`);return{status:nn(r.status,`${t}.status`,bv),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 Rv(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)=>kv(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",wv),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:gv,...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",Rv),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(xv),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 Tv,dirname as Ev,isAbsolute as Cv,resolve as Nv}from"node:path";var bi=class extends Error{constructor(t){super(t),this.name="XmlError"}},Iv=64,Av=5e5,Pv=/^[A-Za-z_:][\w.:-]*/,Sv={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=Sv[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=Pv.exec(r.slice(t,t+256));return c===null?s("Expected a name"):(t+=c[0].length,c[0])},o=c=>{c>Iv&&s("XML nests too deeply"),e+=1,e>Av&&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",Ov=/(?:^|[\\/])cypress[\\/]|\.cy\.[cm]?[jt]sx?$/,$v=/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 Dv(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 Mv(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 Lv=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/;function _v(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)&&Lv.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 jv(n,t){let e=Mv(n);if(e!==void 0)return e;if(_v(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=>Ov.test(o.attributes.file??""));return i&&a||$v.test(t)?"cypress":i?"mocha":Dv(n,r)?"playwright":"unknown"}function dn(n){let t=Number.parseFloat(n??"");return Number.isFinite(t)&&t>=0?Math.round(t*1e3):0}function Fv(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=>Fv(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(`
|
|
@@ -19,7 +19,7 @@ Received: ${c??"(not recorded)"}`},...u===void 0?{}:{location:u}}}function kv(n,
|
|
|
19
19
|
`);return e===""?[]:[e]}var rk={PASS:"passed",FAIL:"failed",SKIP:"skipped"};function sk(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":rk[r.attributes.status??""]??"skipped",retry:t,...s===void 0?{}:{startTime:s},duration:Number.isFinite(i)&&i>=0?i:0,errors:ek(r,e),attachments:[],stdout:nk(r),stderr:[],steps:[]}}function ik(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=tk(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)=>sk(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=>ik(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:Zv,...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 lk,isAbsolute as uk,join as pk}from"node:path";import{isAbsolute as Ii,relative as ak,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=ak(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 ok(n,t){let e=Vr(t),r=Fr==="\\"?e.replaceAll("/","\\"):e;return Ii(r)||n===void 0?r:`${n}${Fr}${r.replace(/^(?:\.[/\\])+/,"")}`}function dk(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 ck(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:ok(t.rootDir,k.path)},...k.body===void 0?{}:{bodyBase64:k.body}})),annotations:[],...D===void 0?{}:{errorLocation:D}}}),M=dk(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:ck(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 fk="1",hk=/\.(?: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 mk(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;hk.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 uk(i)||t===void 0?i:pk(t,i)})}function yk(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 gk(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:lk(t.reportPath),a=t.framework??yk(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=gk(R,x,y);if(R.isHook===!0){ff(R)!=="passed"&&d.push(...N);return}let E=mk(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:fk,...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 wk="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 bk(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:bk(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:wk,...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 FR,readFile as BR,realpath as Jf}from"node:fs/promises";import{isAbsolute as Xf,relative as VR,resolve as HR,sep as zR}from"node:path";var UR=2*1024*1024,qR=new Set(["it","test","specify","xit","fit","xtest","xspecify"]),GR=new Set(["describe","context","suite","xdescribe","fdescribe","xcontext"]),KR=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 WR(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=>!KR.has(i)).at(-1);if(s!==void 0){if(GR.has(s))return"suite";if(qR.has(s))return"test"}}function JR(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 XR(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=WR(o.callee),l=o.arguments,u=JR(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 YR(n,t){let e=VR(n,t);return e===""||!Xf(e)&&e!==".."&&!e.startsWith(`..${zR}`)}async function QR(n,t){if(!(Xf(t)||t.split("/").includes("..")))try{let e=await Jf(n),r=await Jf(HR(e,t));if(!YR(e,r))return;let s=await FR(r);return!s.isFile()||s.size>UR?void 0:await BR(r,"utf8")}catch{return}}function ZR(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 QR(n.workspace.root,s);e.set(s,i===void 0?[]:XR(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=>ZR(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,oI=["kwikqa-json","playwright-json","mochawesome-json","wdio-json","allure-json","ctrf-json","testng-xml","cucumber-json","junit-xml"],dI=new TextDecoder("utf-8",{fatal:!0});function cI(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 lI(n){if(n.bytes.byteLength===0)return{kind:"unreadable",diagnostic:{reasonCode:"empty-input",message:"The report is empty."}};let t;try{t=dI.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":cI(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 uI(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 pI(n){if(n.length===1&&n[0]!==void 0)return Ee(n[0].bytes);let t=n.map(e=>`${sI(e.path??"")}\0${Ee(e.bytes)}`).sort();return eI("sha256").update(t.join(`
|
|
20
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=pI(n),s=[],i;for(let y of n){let w=lI(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=oI.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:iI(y.file.path)}}))):Jp(o.map(y=>uI(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 fI(n){return(await tI(n,{withFileTypes:!0})).filter(e=>e.isFile()&&/\.(?:json|xml|log)$/i.test(e.name)).map(e=>aI(n,e.name)).sort()}async function at(n,t){let e;try{e=await rI(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 fI(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 nI(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 hI(a.run))}}async function hI(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 oS,realpath as dS}from"node:fs/promises";import{createRequire as cS}from"node:module";import{delimiter as lS,dirname as jm,isAbsolute as uS,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"]},mI=["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 mI){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 yI={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"},gI={button:"button",submit:"button",reset:"button",checkbox:"checkbox",radio:"radio",range:"slider",text:"textbox",search:"searchbox",email:"textbox",tel:"textbox",url:"textbox",password:"textbox"},wI=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||wI.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"?gI[(t.type??"text").toLowerCase()]:yI[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 bI=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&&bI.has(r))continue;t.push(Pt(e))}return t.join(" ").replace(/\s+/g," ").trim()}function xI(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=xI(t.root,s);i!==void 0&&r.push(i)}return r}var vI=`"((?:[^"\\\\]|\\\\.)*)"|'((?:[^'\\\\]|\\\\.)*)'`;function kI(n){return n.replace(/\\(.)/g,"$1")}function ji(n){let t=new RegExp(`^(?:${vI})([is])?$`).exec(n.trim());if(t===null)return;let e=t[1]??t[2];if(e!==void 0)return{value:kI(e),caseSensitive:t[3]!=="i"}}function RI(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 II(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 RI(t)}function AI(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 PI(n){let t=n.trim(),e=/^internal:([\w-]+)=([\s\S]+)$/.exec(t);if(e!==null)return II(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 AI(t)}function SI(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 TI(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=SI(t).flatMap(TI);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=PI(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 EI=/\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001B]*(?:\u0007|\u001B\\))/g;function wt(n){return n.replace(EI,"")}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 CI=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&&CI.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 NI(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 NI(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,OI=200,$I={__playwright_value_:"value",__playwright_checked_:"checked",__playwright_selected_:"selected"},DI=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"],MI=new Set(["internal","role","testid","data","name","text","label","attr","has","nth","visible","true","false","exact","css","xpath","and","the"]);function LI(n){let t=[];for(let[e,r]of Object.entries(Le(n))){let s=$I[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 _I(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=LI(c),h=Gd(f,p,e.sensitiveNames),m=qd(be(_I(c),OI),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
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&&!MI.has(e));return[...new Set(t)]}function jI(n){return/(?:^|>>\s*)(?:internal:)?role=([\w-]+)/.exec(n)?.[1]?.toLowerCase()}function FI(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=jI(t),d=FI(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&&DI.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 zI}from"node:fs/promises";import{realpath as ph,stat as BI}from"node:fs/promises";import{isAbsolute as mh,relative as VI,resolve as HI,sep as fh}from"node:path";function hh(n,t){let e=VI(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:HI(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 BI(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 zI(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 UI}from"module";var qI=UI("/"),nr,GI,KI;try{nr=qI("worker_threads"),GI=nr.Worker,KI=nr.isMarkedAsUntransferable}catch{}var Oe=Uint8Array,Zn=Uint16Array,WI=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]),JI=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 WI(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,XI=nr.r;bh[28]=258,XI[258]=28;var xh=wh(gh,0),YI=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 QI=as(ds,9,1);var ZI=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)},eA=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 tA=["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||tA[n]);if(r.code=n,Error.captureStackTrace&&Error.captureStackTrace(r,Pe),!e)throw r;return r},nA=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=QI,h=ZI,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[JI[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=eA(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=YI[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 rA=(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=nA(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,sA=0;try{Qd.decode(is,{stream:!0}),sA=1}catch{}var iA=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 aA(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=iA(n),i=s.s,e=s.r;return e.length&&Pe(8),i}}var oA=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 dA=(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 rA(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:dA},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=aA(c.subarray(o+30,o+=30+S),!x),P=oA(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 cA(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,cA(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 lA(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 uA(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=uA(s),a=V(s.frameId)??V(s.pageId)??"unknown-frame",o=`${t}
|
|
22
|
+
`),redactions:y,nodes:g.length,truncated:v}}import{open as zI}from"node:fs/promises";import{realpath as ph,stat as BI}from"node:fs/promises";import{isAbsolute as mh,relative as VI,resolve as HI,sep as fh}from"node:path";function hh(n,t){let e=VI(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:HI(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 BI(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 zI(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 UI}from"module";var qI=UI("/"),nr,GI,KI;try{nr=qI("worker_threads"),GI=nr.Worker,KI=nr.isMarkedAsUntransferable}catch{}var Oe=Uint8Array,Zn=Uint16Array,WI=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]),JI=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 WI(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,XI=nr.r;bh[28]=258,XI[258]=28;var xh=wh(gh,0),YI=xh.b,MD=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 QI=as(ds,9,1);var ZI=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)},eA=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 tA=["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||tA[n]);if(r.code=n,Error.captureStackTrace&&Error.captureStackTrace(r,Pe),!e)throw r;return r},nA=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=QI,h=ZI,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[JI[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=eA(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=YI[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 rA=(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=nA(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,sA=0;try{Qd.decode(is,{stream:!0}),sA=1}catch{}var iA=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 aA(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=iA(n),i=s.s,e=s.r;return e.length&&Pe(8),i}}var oA=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 dA=(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 rA(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:dA},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=aA(c.subarray(o+30,o+=30+S),!x),P=oA(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 cA(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,cA(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 lA(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 uA(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=uA(s),a=V(s.frameId)??V(s.pageId)??"unknown-frame",o=`${t}
|
|
23
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
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(lA(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,pA=2,nc=5e4,rc=25,fA=new Set(["screencast-frame","object","resource","input"]),re={failure:5,failedCall:4,significant:3,context:2,ordinary:1,afterFailure:0};function hA(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 mA(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 yA(n){let t=me(n?.params);return V(t?.selector)}function gA(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 wA(n){return Ae(n.startTime)??Ae(n.endTime)??Ae(n.time)}function bA(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=wA(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=mA(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(fA.has(c))continue;let p=V(d.callId),f=p===void 0?void 0:`${t}
|
|
25
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=gA(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 xA(n){let t=[];for(let e of n.actions.values()){let r=yA(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 vA(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 kA(n,t){let e=vA(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}:
|
|
@@ -171,7 +171,7 @@ footer{margin-top:40px;padding-bottom:40px;color:var(--muted);font-size:13px;bor
|
|
|
171
171
|
`)}</section>`,e,s,yE(n),gE(n),wE(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
172
|
`)}var Va="kwikqa-report.html",xg=4096;async function RE(n){let t=await vE(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=kE(n,t??Va),r=await bE(e).catch(s=>{if(s.code!=="ENOENT")throw s});return r===void 0?{kind:"writable",path:e}:r.isFile()?(await RE(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 xE(bg(n),{recursive:!0}),await ye(n,t,{mode:420,replace:!0})),e}import{basename as qE}from"node:path";var IE=[[/\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
173
|
`).replace(/(?:file:\/\/)?(?:[A-Za-z]:)?(?:\/[\w.@+-]+){2,}/g,r=>Ds(r));for(let[r,s]of IE)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 AE(n,t,e){return n.evidence.filter(r=>t.includes(r.kind)&&e.some(s=>s.test(r.observation)))}var PE=[/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/],SE=[/\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 \[/],TE=[/expected:.{0,80}received:/s,/received:.{0,80}expected:/s],EE=[/uncaught \w*error/,/\bpageerror\b/,/unhandled (?:promise )?rejection/,/uncaught page error/,/originated from your application code/],CE=[/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/],NE=[/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/],OE=[/cy\.request\(\) failed/,/response we received from your web server was/,/request failed with status code/],$E=[/"(?: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: /],DE=[/^(?: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,PE)},{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,SE);return t.length>0?t:Dt(n,gr,TE)}},{ruleId:"page-exception/uncaught-error",category:"page-exception",description:"An uncaught page error or unhandled rejection was observed.",match:n=>Dt(n,[...gr,...Cl],EE)},{ruleId:"navigation-failure/net-error",category:"navigation-failure",description:"Navigation reported a network-level or navigation timeout error.",match:n=>Dt(n,[...gr,...Cl],CE)},{ruleId:"http-failure/error-status",category:"http-failure",description:"A recorded request returned a 4xx or 5xx status, or reported a failure.",match:n=>AE(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,OE)},{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],NE)},{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,$E)},{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,DE)}];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"},ME=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 LE(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 _E(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 jE(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 FE(n,t,e){let r=Pg(t),s=r===void 0?void 0:Ha(r.observation),i=jE(n,t),a=LE(t),o=_E(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=FE(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(!ME.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 BE=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 VE(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=>BE.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=VE(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 HE=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})),HE.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 zE=/\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(zE)){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 UE(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:UE(s.flatMap(i=>i.findings))}}var Ng=50,Og=24,Lg="<absent>",GE={"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"},KE={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"},WE={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"},JE={"symptom-category":"Symptom","action-api":"Action","error-fingerprint":"Error","network-endpoint":"Request","support-location":"Support code","target-locator":"Locator","failing-source-location":"Failing line"},XE={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 YE(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 QE="1970-01-01T00:00:00.000Z";function ZE(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!==qE(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:XE[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 eC(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 tC(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 nC(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=tC(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 rC(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 sC(n){return[...n.hypotheses].sort((t,e)=>t.rank-e.rank)[0]}function iC(n){let t=n?.diagnosis;if(n===void 0||t===void 0)return{owner:"not-diagnosed"};let e=sC(t);return n.outcome!=="diagnosed"||e===void 0?{owner:"inconclusive"}:{owner:e.probableOwner,grade:e.evidenceGrade}}function aC(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 oC(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 dC(n){let t=oC(n);return{evidenceId:n.evidenceId,label:GE[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 cC(n){return[...[...n.hypotheses].sort((t,e)=>t.rank-e.rank).flatMap(t=>[...t.supportingEvidenceIds,...t.contradictingEvidenceIds]),...n.ownershipEvidenceIds]}function lC(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 uC(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,cC(r))}else s=lC(n,e);return{evidence:s.slice(0,Og).map(dC),evidenceCut:Math.max(0,s.length-Og)}}function pC(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=eC(t,r),o=jg(n,t.logicalTestIds),d=iC(e),c=e===void 0?void 0:aC(e),l=nC(t,a,r),u=t.logicalTestIds.length,p=rC(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:JE[f.kind]??f.kind,value:f.value})),commonCause:{supported:t.commonCauseSupported,rationale:t.commonCauseRationale},...d,status:pC(e,i),tests:o.slice(0,Ng),testsCut:Math.max(0,o.length-Ng),...c===void 0?{}:{diagnosis:c},...uC(t,e,r)}}function fC(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 hC(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)??fC(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 mC(n){return Vg(n).map(({group:t,audit:e})=>({group:t,purpose:e.purpose,model:Hg(e),zeroDataRetention:e.model.zeroDataRetention===!0,packetHash:ZE(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 yC(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 gC(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 wC(n){let{run:t}=n,e=t.logicalTests.filter(s=>s.status==="flaky").map(s=>Fl(t,s)),r=jg(t,gC(n)).map(s=>({...s,status:"passed when fix re-ran it"}));return[...e,...r]}function bC(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 xC(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=hC(n),l=new Map;for(let p of r?.packet.omissions??[]){let f=WE[p.reason]??p.reason;l.set(f,(l.get(f)??0)+1)}let u=xC(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:YE(t.stats.duration),...e.inputs===void 0?{}:{report:e.inputs.report},createdAt:t.createdAt===QE?"not recorded in the report":Dg(t.createdAt),diagnosedBy:yC(n),outcome:`${e.outcome} (${e.reasonCode})`,message:e.message},groups:c,flaky:wC(n),notAnalyzed:bC(n),coverage:(r?.packet.accounting??[]).map(p=>({channel:KE[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:mC(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,vC=3e4,kC=2e3,RC=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?.repository===void 0?void 0:`${e.repository}${e.branch===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){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function qg(n){let t=e=>({type:"plain_text",text:e,emoji:!1});return{text:n.headline,blocks:[{type:"header",text:t(wr(n.headline,150))},...n.source===void 0&&n.links.length===0?[]:[{type:"context",elements:[...n.source===void 0?[]:[t(n.source)],...n.links.map(e=>({type:"mrkdwn",text:`<${Ug(e.url).replace(/\|/g,"%7C")}|${Ug(e.label)}>`}))]}],{type:"section",text:t(n.lines.join(`
|
|
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 nC(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=tC(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 rC(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 sC(n){return[...n.hypotheses].sort((t,e)=>t.rank-e.rank)[0]}function iC(n){let t=n?.diagnosis;if(n===void 0||t===void 0)return{owner:"not-diagnosed"};let e=sC(t);return n.outcome!=="diagnosed"||e===void 0?{owner:"inconclusive"}:{owner:e.probableOwner,grade:e.evidenceGrade}}function aC(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 oC(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 dC(n){let t=oC(n);return{evidenceId:n.evidenceId,label:GE[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 cC(n){return[...[...n.hypotheses].sort((t,e)=>t.rank-e.rank).flatMap(t=>[...t.supportingEvidenceIds,...t.contradictingEvidenceIds]),...n.ownershipEvidenceIds]}function lC(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 uC(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,cC(r))}else s=lC(n,e);return{evidence:s.slice(0,Og).map(dC),evidenceCut:Math.max(0,s.length-Og)}}function pC(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=eC(t,r),o=jg(n,t.logicalTestIds),d=iC(e),c=e===void 0?void 0:aC(e),l=nC(t,a,r),u=t.logicalTestIds.length,p=rC(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:JE[f.kind]??f.kind,value:f.value})),commonCause:{supported:t.commonCauseSupported,rationale:t.commonCauseRationale},...d,status:pC(e,i),tests:o.slice(0,Ng),testsCut:Math.max(0,o.length-Ng),...c===void 0?{}:{diagnosis:c},...uC(t,e,r)}}function fC(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 hC(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)??fC(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 mC(n){return Vg(n).map(({group:t,audit:e})=>({group:t,purpose:e.purpose,model:Hg(e),zeroDataRetention:e.model.zeroDataRetention===!0,packetHash:ZE(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 yC(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 gC(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 wC(n){let{run:t}=n,e=t.logicalTests.filter(s=>s.status==="flaky").map(s=>Fl(t,s)),r=jg(t,gC(n)).map(s=>({...s,status:"passed when fix re-ran it"}));return[...e,...r]}function bC(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 xC(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=hC(n),l=new Map;for(let p of r?.packet.omissions??[]){let f=WE[p.reason]??p.reason;l.set(f,(l.get(f)??0)+1)}let u=xC(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:YE(t.stats.duration),...e.inputs===void 0?{}:{report:e.inputs.report},createdAt:t.createdAt===QE?"not recorded in the report":Dg(t.createdAt),diagnosedBy:yC(n),outcome:`${e.outcome} (${e.reasonCode})`,message:e.message},groups:c,flaky:wC(n),notAnalyzed:bC(n),coverage:(r?.packet.accounting??[]).map(p=>({channel:KE[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:mC(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,vC=3e4,kC=2e3,RC=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){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function qg(n){let t=r=>({type:"plain_text",text:r,emoji:!1}),e=n.links.map(r=>`<${Ug(r.url).replace(/\|/g,"%7C")}|${Ug(r.label)}>`).join(" \xB7 ");return{text:n.headline,blocks:[{type:"header",text:t(wr(n.headline,150))},...n.source===void 0&&n.links.length===0?[]:[{type:"context",elements:[...n.source===void 0?[]:[t(n.source)],...e===""?[]:[{type:"mrkdwn",text:n.source===void 0?e:`\xB7 ${e}`}]]}],{type:"section",text:t(n.lines.join(`
|
|
175
175
|
`).slice(0,3e3))}]}}function Gg(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 IC(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 AC(n){let t=Number(n?.headers.get("retry-after"));return Number.isFinite(t)&&t>0?Math.min(t*1e3,RC):kC}async function PC(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(vC)})}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(AC(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:qg},{name:"Teams",variable:"KWIKQA_TEAMS_WEBHOOK_URL",message:Gg}];for(let o of a){let d=r[o.variable];if(d===void 0||d.trim()==="")continue;let c=IC(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 PC(n,t,e,o.name,c,o.message(s))}}import{appendFile as SC,readFile as TC}from"node:fs/promises";var EC=30,Kg=100,CC=3e4,NC=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;function Wg(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 OC(n){if(n===void 0||n==="")return{};try{let t=JSON.parse(await TC(n,"utf8"));return typeof t=="object"&&t!==null?t:{}}catch{return{}}}async function Ul(n){if(n.GITHUB_ACTIONS!=="true")return;let t=NC.test(n.GITHUB_REPOSITORY??"")?n.GITHUB_REPOSITORY:void 0,e=Wg(n.GITHUB_API_URL,"https://api.github.com"),r=Wg(n.GITHUB_SERVER_URL,"https://github.com"),s=/^\d+$/.test(n.GITHUB_RUN_ID??"")?n.GITHUB_RUN_ID:void 0,i=(await OC(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 Jg(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(CC)})}},br=class extends Error{};async function $C(n,t,e){for(let r=1;r<=EC;r+=1){let s=await n.call("GET",`${t}/comments?per_page=${Kg}&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<Kg)return}}async function DC(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=Jg(e),l={body:`${c}
|
|
176
176
|
${r}`};try{let u=await $C(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 SC(e.summaryPath,`${r}
|
|
177
177
|
`),n.print("Job summary: written.")}catch(i){n.error(`No job summary: ${i.message}`)}await DC(n,t,e,r,s.failures)}var MC=20,Xg=10,LC=100;function xr(n,t){return`${n} ${t}${n===1?"":"s"}`}function Yg(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=Yg(n,LC)||"(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 Yg(n,1e3).replace(/[\\`*_{}[\]()#+!|<>~&]/g,"\\$&")}function _C(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 jC(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
|
|
@@ -201,17 +201,17 @@ You have no tools, filesystem, shell, repository access, commands, or external l
|
|
|
201
201
|
`,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=O1(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 Aw(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 Pw(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 Sw=ri(Qr(),1),$1=/\.([cm]?[jt]sx?)$/i;function vu(n,t){let e=n.match($1)?.[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,Sw.parse)(t,{sourceType:"unambiguous",errorRecovery:!1,plugins:r}),!0}catch{return!1}}var D1=[{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 Tw(n){return Us(n,/\bexpect\s*\(/g)+Us(n,/\bassert(?:\.|\s*\()/g)+Us(n,/\.(?:should|and)\s*\(/g)}function Ew(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 M1(n,t){let e=Ew(t);return[...Ew(n)].filter(([r,s])=>(e.get(r)??0)<s).map(([r])=>r).sort()}function Cw(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=M1(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){Tw(s.newText)<Tw(s.oldText)&&t.push({code:"forbidden-edit",message:"The proposal removes or weakens assertion coverage.",path:e.path});for(let i of D1){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 L1=/^(?:\.\/)?[A-Za-z0-9_./-]+$/,_1=/^[A-Z][A-Z0-9_]*$/,j1=/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTH)/i,F1=new Set(["focused","affected","static"]);function Nw(n){return n.length>0&&!n.includes("\0")&&!n.includes("\\")&&!n.startsWith("/")&&!/^[A-Za-z]:/.test(n)&&!n.split("/").some(t=>t===".."||t==="")}var B1=new Set(["page-object","fixture","test-data","test-helper","playwright-config","framework-config"]);function V1(n){let t=Object.entries(n.environment);return n.id.trim().length>0&&L1.test(n.executable)&&Nw(n.executable.replace(/^\.\//,""))&&!n.args.some(e=>e.includes("\0"))&&(n.workingDirectory==="."||Nw(n.workingDirectory))&&F1.has(n.scope)&&t.every(([e,r])=>_1.test(e)&&!j1.test(e)&&!r.includes("\0"))&&Number.isInteger(n.timeoutMs)&&n.timeoutMs>0&&n.reason.trim().length>0}function Ow(n,t){let e=t.some(i=>B1.has(i)),r=[...n.validation].sort((i,a)=>i.id.localeCompare(a.id));if(r.some(i=>!V1(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 H1(n){let{packetHash:t,...e}=n;return Yn(e)===t}function z1(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(!H1(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=Pw(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=z1(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=Cw(a.targets);if(o.length>0)return nt(o);let d=xu(a.targets),c=Aw(d,t.config.budgets);if(c.length>0)return nt(c);let l=Ow(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 tN,realpath as qw}from"node:fs/promises";import{join as nN,relative as rN,sep as sN}from"node:path";var U1=new Set(["failed","timedOut","interrupted"]);function q1(n){return n.status==="unexpected"||n.status==="flaky"}function Mw(n){return[...n.clusters].sort((t,e)=>e.logicalTestIds.length-t.logicalTestIds.length||t.clusterId.localeCompare(e.clusterId)).slice(0,6)}function G1(n){return n.attachments.reduce((t,e)=>t+(e.name==="trace"||e.contentType==="application/zip"?10:e.path===void 0?0:1),0)}function Lw(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=>U1.has(a.status));return{test:s,score:Math.max(0,...i.map(G1)),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 _w(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:[]}))}:q1(s)?{...s,attempts:[]}:s)}}function jw(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 Fw(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 Bw}from"node:crypto";import{readdir as Vw,readFile as K1,realpath as W1}from"node:fs/promises";import{join as Ar,relative as J1,sep as X1}from"node:path";var Au=/^run_[a-f0-9]{24}$/,Pu=/^rec_[a-f0-9]{24}$/;function ho(){return`rec_${Bw().replaceAll("-","").slice(0,24)}`}function Pr(){return`auth_${Bw().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)}
|
|
202
202
|
`,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}),J1(await W1(n),i).split(X1).join("/")}var Y1=new Set(["analyze","fix","validate"]),Q1=["analysis","proposal","application","validation"];function Z1(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"&&Y1.has(e.command)&&typeof e.recordedAt=="string"&&typeof e.outcome=="string"&&typeof e.reasonCode=="string"&&typeof e.message=="string"&&Q1.every(r=>typeof e[r]=="object"&&e[r]!==null)}async function Hw(n,t){try{let e=JSON.parse(await K1(n,"utf8"));return Z1(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 Vw(e).catch(()=>[]);return(await Promise.all(r.filter(i=>Pu.test(i.replace(/\.json$/,""))&&i.endsWith(".json")).map(i=>Hw(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 Vw(t).catch(()=>[])).filter(s=>Au.test(s)),r;for(let s of e){let i=await Hw(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"]),iN={"test-support":"test-support-owned",application:"application-owned",environment:"environment-owned",undetermined:"owner-undetermined"};function aN(n){return n.logicalTests.filter(t=>t.status==="unexpected"||t.status==="flaky").map(t=>t.logicalTestId).sort()}function oN(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 zw(n,t){let e=await qw(t).catch(()=>t);return rN(n,e).split(sN).join("/")}async function dN(n,t){return{report:await zw(t,n.reportPath),...n.framework===void 0?{}:{framework:n.framework},...n.probePath===void 0?{}:{probe:await zw(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 iN[t?.probableOwner??"undetermined"]??"owner-undetermined"}function cN(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=aN(r),i=await dN(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=oN(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 mN(n,r,l,t),m=pN(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: ${lN(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 lN(n){return n.find(e=>e.result.reasonCode==="cluster-not-requested")?.result.message??"at most 6 groups are sent per analysis."}var uN={strong:3,moderate:2,weak:1,insufficient:0};function Uw(n){let[t]=[...n.result.diagnosis?.hypotheses??[]].sort((e,r)=>e.rank-r.rank);return uN[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)=>Uw(e.item)-Uw(t.item)||e.item.cluster.logicalTestIds.length-t.item.cluster.logicalTestIds.length||t.index-e.index).map(({item:t})=>t)}function pN(n){let t=n.filter(e=>e.result.outcome==="diagnosed");return wo(n)[0]??t[0]??n[0]}var fN=new Set(["provider-refusal","malformed-response","schema-invalid","citation-or-grading-invalid"]);async function Gw(n,t,e,r){let s=Lw(t,r);if(s===void 0)return;let i=_w(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:jw(r,o,e)}}var hN={approveDiagnosis:async()=>!1};async function Eu(n,t){let e=await Ks({...n,interaction:hN,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 Gw(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 mN(n,t,e,r){let s=n.remote;if(s===void 0)return[];let i=Mw(e),a=[],o=[];for(let g of i){let y=await Gw(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 gN(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 Fw(f,3,async y=>{let w=await Kw(n,y.prepared,s.transport,r),v=s.escalation;if(v===void 0||!fN.has(w.reasonCode))return Xt(y.item,w);let x=await yN(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 Kw(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 yN(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 Kw(n,i.prepared,r,s)}async function gN(n,t,e,r){if(/^run_[a-f0-9]{24}$/.test(t))try{let s=await qw(n),i=JSON.parse(await tN(nN(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 wN(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:cN(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(wN)},...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 bN(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:bN(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 jN}from"node:crypto";import{relative as FN,resolve as BN,sep as VN}from"node:path";import{createHash as Ww}from"node:crypto";import{lstat as xN,readFile as vN,realpath as ko}from"node:fs/promises";import{isAbsolute as kN,join as RN,relative as IN,resolve as AN,sep as PN}from"node:path";var Yt=/^[a-f0-9]{64}$/,Xw=/^vld_[a-f0-9]{24}$/,SN=Ht,TN=4*1024*1024,EN=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 CN(n,t){let e=IN(n,t);return e===""||!kN(e)&&e!==".."&&!e.startsWith(`..${PN}`)}function NN(n){return typeof n=="string"&&n.length>0&&Number.isFinite(Date.parse(n))}function Jw(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 Yw(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"||!Xw.test(t.validationRunId)||!SN.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)||!NN(t.startedAt)||!Number.isInteger(t.durationMs)||t.durationMs<0||!Ws(t.termination)||t.termination.kind!=="exit"||t.termination.exitCode!==0||!Jw(t.stdout)||!Jw(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 ON(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)Yw(e);return t}async function Qw(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 Zw(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 eb(n){return Yt.test(n.planHash)&&Xw.test(n.validationRunId)}async function Ro(n,t,e){let r=AN(n,t);if(!CN(n,r))throw new Error("Validation record path escapes its run.");let s=await xN(r);if(!s.isFile()||s.isSymbolicLink()||s.size>e)throw new Error("Validation record path is unsafe or unbounded.");return vN(r)}async function $N(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`,EN),o=Yw(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||Ww("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||Ww("sha256").update(c).digest("hex")!==d.sha256)return!1}}return!0}async function Ou(n){if(!eb(n))return{kind:"rejected",reasons:[_n("Validation identity is invalid.")]};let t=n.now??new Date().toISOString(),e;try{let r=await Qw(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 Zw(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(!eb(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 Qw(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 Zw(r,n.context,s))return{kind:"rejected",reasons:[_n("Transaction is not validating this exact approved run.")],transaction:Se(s)};let o=RN(s.directory,"validation",n.validationRunId),d=await Ro(o,"manifest.json",TN),c=ON(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 $N(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 DN}from"node:path";var tb="1.0",MN=/^rps_[a-f0-9]{24}$/,LN=8*1024*1024;function _N(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 nb(n){if(!MN.test(n))throw new Error("Repair session id is invalid.");return[".kwikqa","repairs",n]}async function rb(n,t){let e=await He(n,nb(t.repairSessionId));await ye(DN(e,`attempt-${t.attempt}.json`),`${pe(t)}
|
|
203
203
|
`,{mode:384,replace:!1})}async function sb(n,t,e){let r=await He(n,nb(t)),s=await Rn(r,`attempt-${e}.json`,LN),i=Ln(s.config);if(s.schemaVersion!==tb||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=_N(s.group);return{schemaVersion:tb,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 ib,resolve as ab}from"node:path";function Sr(n,t){return{kind:"configuration",path:n.relativePath,sha256:n.sha256,detail:t}}async function ob(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:ib(ab(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:ib(ab(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 HN=600*1e3,db=1e6,zN={maxFiles:5e3,maxFileBytes:1024*1024,maxTotalBytes:64*1024*1024,maxImportEdges:5e4,maxImportDepth:20},UN={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 qN(n){return Io(n.run,n.diagnosis,n.packet,n.representativeId)}function cb(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 GN(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 KN={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};async function WN(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(KN[e]);a!==void 0&&(i[e]=a);for(let o of new Set(r)){if(o==="kwikqa-babel")continue;let d=await s(UN[o]);d!==void 0&&(i[o]=d)}return i}async function lb(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=qN(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:zN}),p=u.scope==="focused"&&u.projectIds.length===0&&l!==void 0&&l.name!==""?{...u,projectIds:[l.name]}:u,f=await WN(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 ob({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??HN,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:db},R={sessionId:`kwikqa-${jN()}`},S=tl({proposal:s,context:x,payloadManifests:[...n.diagnosisAudit===void 0?[]:cb(n.diagnosisAudit),...cb(n.repairAudit)],costBounds:GN(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 rb(i.workspaceRoot,{schemaVersion:"1.0",repairSessionId:v,attempt:w,transactionId:C,plan:y,workspace:x.workspace,config:n.config,maxTargetBytes:db,...P.length===0?{}:{group:{reportPath:FN(i.workspaceRoot,BN(i.workspaceRoot,t.reportPath)).split(VN).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 JN}from"node:child_process";import{realpath as Js}from"node:fs/promises";import{isAbsolute as XN,relative as YN,resolve as Du,sep as ub}from"node:path";import{promisify as QN}from"node:util";var ZN=QN(JN),eO=3e4,tO=16*1024*1024;async function Ao(n,t){return(await ZN("git",["-C",n,"--no-optional-locks",...t],{timeout:eO,maxBuffer:tO,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}function pb(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 nO(n,t,e){let r=YN(n,Du(t,e));if(!(r===""||XN(r)||r===".."||r.startsWith(`..${ub}`)))return r.split(ub).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(`
|
|
204
|
-
`)[0]??"";return{kind:"unavailable",message:`Repository status could not be read: ${d===""?"git failed.":d}`}}let s=pb(r),i=[...new Set(s.map(a=>nO(t,e,a)).filter(a=>a!==void 0))].sort();return{kind:"read",status:{workspaceRoot:t,gitRoot:e,dirtyPaths:i,pristine:s.length===0}}}var rO="kwikqa.config.json",sO=256*1024;async function iO(n,t){let e=await Q(n,t,sO);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 aO(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 iO(r,n.configPath??rO);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=pO(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):fb(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=uO(l,g),{packet:w}=y,{diagnosis:v,grading:x}=g.result;if(!(w===void 0||v===void 0||x===void 0)){if(m=await fb(n,y,{packet:w,diagnosis:v,grading:x},d,t,p(y,h),u),!cO(m))return m;h.push(`Failure group ${lO(l,g)}: ${m.message}`)}}return m??p(l)(l.result)}finally{await n.repairSession?.close()}}var oO=3,dO=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 cO(n){return n.outcome==="abstained-from-repair"?dO.has(n.reasonCode):n.outcome==="validation-unavailable"&&n.record?.application.status==="not-run"}function lO(n,t){return(n.clusterStages??[]).indexOf(t)+1}function uO(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 pO(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:oO;return{groups:r.slice(0,s)}}async function fO(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 fb(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:aO(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 fO(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}):lb({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 hO}from"node:crypto";import{realpath as mO}from"node:fs/promises";import{join as yO,relative as gO,sep as _u}from"node:path";var wO={maxStreamBytes:4*1024*1024,maxTotalStreamBytes:16*1024*1024,terminationGraceMs:5e3},bO=32*1024*1024,xO=new Set(["applied","validating"]);function vO(){return`vld_${hO().replaceAll("-","").slice(0,24)}`}function kO(n){return{config:n.config,snapshot:{workspaceRoot:n.workspace.workspaceRoot,gitRoot:n.workspace.gitRoot,dirtyPaths:[],validation:[]},workspace:n.workspace,maxTargetBytes:n.maxTargetBytes}}function RO(n,t,e){let r=s=>gO(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 IO(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(yO(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 mO(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=>xO.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 sb(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=kO(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=vO();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:wO,...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:bO,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 IO(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?RO(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 AO=1200*1e3,PO=10,SO=1e3,TO=15e3,EO=3e3,CO=6e4,hb=3e4,NO=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:{}}catch{return{}}}function yb(n){return typeof n=="number"&&Number.isFinite(n)?Math.min(TO,Math.max(SO,n)):EO}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===NO)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",CO,{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 mb(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=yb(a.pollAfterMs),l=0;for(;;){if(e()>(this.options.maxWaitMs??AO))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}`,hb)}catch{u=new Response(null,{status:599})}if(u.status>=500){if(l+=1,l>PO)return r("network-error","Lost contact with the KwikQA service while the model was working. If it answered, it is given back unused.");continue}l=0;let p=await mb(u);if(u.status===404)return"interrupted";if(!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.status==="running"){this.options.onProgress?.(e()),c=yb(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}`,hb)}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 gb(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 wb(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=wb(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=wb(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 bb}from"node:os";import{join as Xs}from"node:path";function xb(n){return n.KWIKQA_CONFIG_DIR!==void 0&&n.KWIKQA_CONFIG_DIR!==""?n.KWIKQA_CONFIG_DIR:process.platform==="win32"?Xs(n.APPDATA??Xs(bb(),"AppData","Roaming"),"kwikqa"):Xs(n.XDG_CONFIG_HOME??Xs(bb(),".config"),"kwikqa")}function Hu(n){return Xs(xb(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 vb(n,t){await DO(xb(n),{recursive:!0,mode:448}),await _O(Hu(n),`${JSON.stringify(t)}
|
|
205
|
-
`,{mode:384})}async function kb(n){await
|
|
206
|
-
`),"","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=` ${
|
|
207
|
-
`)}var Zs="0.2.
|
|
208
|
-
`,{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 _b)if(await Er(ze(t,r)))return ze(t,r);return ze(t,_b[0]??"report.json")}async function Hb(n){try{if((await Lb(n)).isDirectory()){let t=Mb("sha256");for(let e of(await WO(n)).sort()){let r=ze(n,e);(await Lb(r)).isFile()&&t.update(`${e}\0`).update(await Eo(r))}return t.digest("hex")}return Mb("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 Hb(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 Hb(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 jb(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=gb(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:jb(n.env.KWIKQA_DIAGNOSIS_MODEL,a.models.diagnosis),caps:a.caps.diagnosis,transport:x,...u===void 0?{}:{session:u}},repairModel:jb(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 zb(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 Cb(s,i))n.io.print(a);return n.io.confirm("Apply this patch?")}}}async function Ub(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=$b("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 Nb(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=Db("run"in t?t.run:void 0,s);i!==void 0&&n.io.print(i);let a=Ob(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 qb(n){return n.sleep??(t=>new Promise(e=>setTimeout(e,t)))}async function Gb(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=qb(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 vb(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 Kb(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 kb(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 Wb(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 Jb(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 Xb(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 Jb(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 Yb(n){return Fn(n,async()=>{let t=await Jb(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 Qb(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(`
|
|
209
|
-
`))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 Fb(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
|
|
204
|
+
`)[0]??"";return{kind:"unavailable",message:`Repository status could not be read: ${d===""?"git failed.":d}`}}let s=pb(r),i=[...new Set(s.map(a=>nO(t,e,a)).filter(a=>a!==void 0))].sort();return{kind:"read",status:{workspaceRoot:t,gitRoot:e,dirtyPaths:i,pristine:s.length===0}}}var rO="kwikqa.config.json",sO=256*1024;async function iO(n,t){let e=await Q(n,t,sO);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 aO(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 iO(r,n.configPath??rO);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=pO(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):fb(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=uO(l,g),{packet:w}=y,{diagnosis:v,grading:x}=g.result;if(!(w===void 0||v===void 0||x===void 0)){if(m=await fb(n,y,{packet:w,diagnosis:v,grading:x},d,t,p(y,h),u),!cO(m))return m;h.push(`Failure group ${lO(l,g)}: ${m.message}`)}}return m??p(l)(l.result)}finally{await n.repairSession?.close()}}var oO=3,dO=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 cO(n){return n.outcome==="abstained-from-repair"?dO.has(n.reasonCode):n.outcome==="validation-unavailable"&&n.record?.application.status==="not-run"}function lO(n,t){return(n.clusterStages??[]).indexOf(t)+1}function uO(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 pO(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:oO;return{groups:r.slice(0,s)}}async function fO(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 fb(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:aO(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 fO(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}):lb({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 hO}from"node:crypto";import{realpath as mO}from"node:fs/promises";import{join as yO,relative as gO,sep as _u}from"node:path";var wO={maxStreamBytes:4*1024*1024,maxTotalStreamBytes:16*1024*1024,terminationGraceMs:5e3},bO=32*1024*1024,xO=new Set(["applied","validating"]);function vO(){return`vld_${hO().replaceAll("-","").slice(0,24)}`}function kO(n){return{config:n.config,snapshot:{workspaceRoot:n.workspace.workspaceRoot,gitRoot:n.workspace.gitRoot,dirtyPaths:[],validation:[]},workspace:n.workspace,maxTargetBytes:n.maxTargetBytes}}function RO(n,t,e){let r=s=>gO(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 IO(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(yO(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 mO(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=>xO.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 sb(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=kO(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=vO();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:wO,...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:bO,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 IO(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?RO(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 AO=1200*1e3,PO=10,SO=1e3,TO=15e3,EO=3e3,CO=6e4,hb=3e4,NO=2;function Vu(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}async function yb(n){try{let t=await n.json();return Vu(t)?t:void 0}catch{return}}async function OO(n){return await yb(n)??{}}function mb(n){return typeof n=="number"&&Number.isFinite(n)?Math.min(TO,Math.max(SO,n)):EO}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===NO)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",CO,{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 OO(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=mb(a.pollAfterMs),l=0;for(;;){if(e()>(this.options.maxWaitMs??AO))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}`,hb)}catch{u=new Response(null,{status:599})}let p=u.status>=500?void 0:await yb(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>PO)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 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}`,hb)}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 $O="https://api.kwikqa.com",Tr="https://kwikqa.com/dashboard/";function gb(n){return n.hosted??!(n.plan==="byo"||n.plan==="byo-team")}function DO(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===""?$O:t)).replace(/\/+$/,"")}function wb(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=wb(i),o=DO(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=wb(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 MO,readFile as LO,rm as _O,writeFile as jO}from"node:fs/promises";import{homedir as bb}from"node:os";import{join as Xs}from"node:path";function xb(n){return n.KWIKQA_CONFIG_DIR!==void 0&&n.KWIKQA_CONFIG_DIR!==""?n.KWIKQA_CONFIG_DIR:process.platform==="win32"?Xs(n.APPDATA??Xs(bb(),"AppData","Roaming"),"kwikqa"):Xs(n.XDG_CONFIG_HOME??Xs(bb(),".config"),"kwikqa")}function Hu(n){return Xs(xb(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 LO(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 vb(n,t){await MO(xb(n),{recursive:!0,mode:448}),await jO(Hu(n),`${JSON.stringify(t)}
|
|
205
|
+
`,{mode:384})}async function kb(n){await _O(Hu(n),{force:!0})}import{createHash as FO}from"node:crypto";import{basename as BO}from"node:path";var VO=100;function Rb(n){return FO("sha256").update(n).digest("hex")}function Ib(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!==BO(r));return{key:Rb([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 Ab(n){return n===void 0?void 0:Rb(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,VO).map(r=>({...Ib(t,r),status:r.status==="flaky"?"flaky":"failed"}));return{kind:"analysis",outcome:n.outcome,reasonCode:n.reasonCode,framework:t.framework,tests:e}}function Pb(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=Ab(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:Ib(n.run,e)},...t?.repairProposal===void 0?{}:{changedFiles:t.repairProposal.changedFiles,changedLines:t.repairProposal.changedLines}}}function Sb(n){let t=n.record?.repair,e=Ab(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 HO={npm:"npx",pnpm:"pnpm exec",yarn:"yarn",bun:"bunx"},zO={npm:"npm i -D",pnpm:"pnpm add -D",yarn:"yarn add -D",bun:"bun add -d"};function Tb(n){let t=(n.npm_config_user_agent??"").split("/")[0];return t==="pnpm"||t==="yarn"||t==="bun"?t:"npm"}function vt(n){return`${HO[Tb(n)]} kwikqa`}function Uu(n,t){return`${zO[Tb(n)]} ${t}`}import{basename as UO}from"node:path";function en(n,t){return`${n} ${t}${n===1?"":"s"}`}function Eb(n){return`$${n.toFixed(n<.1?4:2)}`}function qO(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`,...qO(t),` Estimate: at most ${t.estimate.estimatedInputTokens.toLocaleString("en-US")} input + ${t.estimate.estimatedOutputTokens.toLocaleString("en-US")} output tokens, at most ${Eb(t.estimate.estimatedDollars)}`,` Caps: ${Eb(t.caps.request.maxDollars)} per request`,` Payload: ${t.payloadManifestHash.slice(0,16)}... (exactly this redacted payload is sent)`]}function Cb(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(`
|
|
206
|
+
`),"","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=` ${UO(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 Nb(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 Ob(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 $b(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 Db(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(`
|
|
207
|
+
`)}var Zs="0.2.1";var q={ok:0,failed:1,usage:2,account:3},ei=(()=>{let{workspaceRoot:n,...t}=zd;return{...t,maxPacketBytes:6e5}})(),XO=.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*XO))}}var _b=["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"],Vb=ze(".kwikqa","cli-state.json");function Wu(n){return`Not signed in. Run \`${vt(n.env)} login\` first.`}async function Er(n){return GO(n).then(()=>!0,()=>!1)}async function Ju(n){try{return JSON.parse(await Eo(ze(n,Vb),"utf8"))}catch{return{}}}async function Xu(n,t){await WO(ze(n,".kwikqa"),{recursive:!0,mode:448}),await Fb(ze(n,Vb),`${JSON.stringify(t)}
|
|
208
|
+
`,{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 _b)if(await Er(ze(t,r)))return ze(t,r);return ze(t,_b[0]??"report.json")}async function Hb(n){try{if((await Lb(n)).isDirectory()){let t=Mb("sha256");for(let e of(await JO(n)).sort()){let r=ze(n,e);(await Lb(r)).isFile()&&t.update(`${e}\0`).update(await Eo(r))}return t.digest("hex")}return Mb("sha256").update(await Eo(n)).digest("hex")}catch{return}}async function YO(n,t,e){let r=t.capture;if(r===void 0)return;let s=ze(n,r.reportPath);if(await Hb(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 QO(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 Hb(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 jb(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=gb(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:jb(n.env.KWIKQA_DIAGNOSIS_MODEL,a.models.diagnosis),caps:a.caps.diagnosis,transport:x,...u===void 0?{}:{session:u}},repairModel:jb(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:t2(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 zb(n,t){for(let e of t.messages)n.io.error(e);return t.exit}var ZO=3e4;function e2(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 t2(n){let t=0;return e=>{let r=Math.floor(e/ZO);r<=t||(t=r,n.io.print(` The model is still working (${e2(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 Cb(s,i))n.io.print(a);return n.io.confirm("Apply this patch?")}}}async function Ub(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 n2(n){return n==="repair-failed"||n==="validation-unavailable"||n==="operation-failed"?q.failed:q.ok}function Oo(n,t){n.io.print("");let e=$b("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 Nb(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=Db("run"in t?t.run:void 0,s);i!==void 0&&n.io.print(i);let a=Ob(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}`),n2(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 qb(n){return n.sleep??(t=>new Promise(e=>setTimeout(e,t)))}async function Gb(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=qb(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 vb(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 Kb(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 kb(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 r2(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 Wb(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} ${r2(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 Jb(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 s2(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 Xb(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}=s2(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 Jb(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 Yb(n){return Fn(n,async()=>{let t=await Jb(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 Qb(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(`
|
|
209
|
+
`))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 Fb(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 KO(r,`
|
|
210
210
|
${o.map(p=>p.entry).join(`
|
|
211
211
|
`)}
|
|
212
|
-
`);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 Zb(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 zb(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
|
|
212
|
+
`);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 Zb(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 zb(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 QO(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 a2(n,e,r.path,c,l);return i!==void 0&&await Ys(n.io,i.client,i.status,zu(c)),u})}async function i2(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 ex(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 i2(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:tx(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(Bb).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,qb(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 a2(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(tx(r.run,r.record,r));return await Zu(n,t,e,i)===void 0?q.usage:s}function tx(n,t,e){return Ga({run:n,record:t,...e.detail===void 0?{}:{detail:e.detail},kwikqaVersion:Zs})}async function nx(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(Bb).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 rx(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 zb(n,a);let o=s===void 0?await No(n,e,t.report):void 0,d=o===void 0?void 0:await YO(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)=>Ub(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,Pb(c)),h}):(n.io.error("`kwikqa fix` needs a terminal: every request and patch is approved by a person."),q.usage)}async function o2(n,t){let e=Sb(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 sx(n){let t=await Cr(n.cwd),e=await Fu({workspaceRoot:t,checkGroup:(i,a)=>Ub(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 o2(n,e),s}import{createInterface as d2}from"node:readline/promises";function ix(){return{interactive:process.stdin.isTTY===!0,print:(n="")=>{process.stdout.write(`${n}
|
|
213
213
|
`)},error:n=>{process.stderr.write(`${n}
|
|
214
|
-
`)},confirm:async n=>{if(process.stdin.isTTY!==!0)return!1;let t=
|
|
214
|
+
`)},confirm:async n=>{if(process.stdin.isTTY!==!0)return!1;let t=d2({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 l2=`KwikQA turns failed Playwright, Cypress, and WebdriverIO runs into evidence-backed diagnoses and safe, validated test repairs.
|
|
215
215
|
|
|
216
216
|
Usage:
|
|
217
217
|
npx kwikqa init Create kwikqa.config.json and set up your reporter
|
|
@@ -245,8 +245,8 @@ Usage:
|
|
|
245
245
|
npx kwikqa logout Sign out and revoke this machine's token
|
|
246
246
|
|
|
247
247
|
Docs: https://kwikqa.com/docs/
|
|
248
|
-
Dashboard: https://kwikqa.com/dashboard/`;function ax(n){let t=vt(n),e=" ".repeat(t.length-10);return
|
|
248
|
+
Dashboard: https://kwikqa.com/dashboard/`;function ax(n){let t=vt(n),e=" ".repeat(t.length-10);return l2.split(`
|
|
249
249
|
`).map(r=>r.startsWith(" npx kwikqa ")?r.replace("npx kwikqa",t):/^ +\[/.test(r)?`${e}${r}`:r).join(`
|
|
250
|
-
`)}async function
|
|
250
|
+
`)}async function u2(n,t){let[e,...r]=n,s;try{s=c2({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(ax(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 Qb(t);case"login":return Gb(t);case"logout":return Kb(t);case"status":return Wb(t);case"upgrade":return Xb(t,s.positionals[0],{annual:i.annual,...i.seats===void 0?{}:{seats:i.seats}});case"billing":return Yb(t);case"analyze":return Zb(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 ex(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 nx(t,{...i.run===void 0?{}:{run:i.run},...i.output===void 0?{}:{output:i.output}});case"fix":return rx(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 sx(t);default:return t.io.error(`Unknown command: ${e}
|
|
251
251
|
|
|
252
|
-
${ax(t.env)}`),q.usage}}async function ox(){let n=await
|
|
252
|
+
${ax(t.env)}`),q.usage}}async function ox(){let n=await u2(process.argv.slice(2),{cwd:process.cwd(),env:process.env,io:ix(),fetch});process.exitCode=n}await ox();
|