kwikqa 0.10.0 → 0.10.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/CHANGELOG.md +6 -0
- package/LICENSE +2 -2
- package/README.md +3 -4
- package/dist/kwikqa.mjs +20 -20
- package/package.json +2 -2
package/dist/kwikqa.mjs
CHANGED
|
@@ -7,7 +7,7 @@ var RC=Object.create;var Ob=Object.defineProperty;var xC=Object.getOwnPropertyDe
|
|
|
7
7
|
`):s=String.fromCharCode(r),++this.state.curLine,this.state.lineStart=this.state.pos,s}jsxReadString(n){let r="",s=++this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(_.UnterminatedString,this.state.startLoc);let o=this.input.charCodeAt(this.state.pos);if(o===n)break;o===38?(r+=this.input.slice(s,this.state.pos),r+=this.jsxReadEntity(),s=this.state.pos):gs(o)?(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 n=++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 o=this.input.slice(n,this.state.pos),a=VO[o];if(++this.state.pos,a)return a}}return this.state.pos=n,"&"}jsxReadWord(){let n,r=this.state.pos;do n=this.input.charCodeAt(++this.state.pos);while(ni(n)||n===45);this.finishToken(141,this.input.slice(r,this.state.pos))}jsxParseIdentifier(){let n=this.startNode();return this.match(141)?n.name=this.state.value:rm(this.state.type)?n.name=vr(this.state.type):this.unexpected(),this.next(),this.finishNode(n,"JSXIdentifier")}jsxParseNamespacedName(){let n=this.state.startLoc,r=this.jsxParseIdentifier();if(!this.eat(14))return r;let s=this.startNodeAt(n);return s.namespace=r,s.name=this.jsxParseIdentifier(),this.finishNode(s,"JSXNamespacedName")}jsxParseElementName(){let n=this.state.startLoc,r=this.jsxParseNamespacedName();if(r.type==="JSXNamespacedName")return r;for(;this.eat(16);){let s=this.startNodeAt(n);s.object=r,s.property=this.jsxParseIdentifier(),r=this.finishNode(s,"JSXMemberExpression")}return r}jsxParseAttributeValue(){let n;switch(this.state.type){case 5:return n=this.startNode(),this.setContext(he.brace),this.next(),n=this.jsxParseExpressionContainer(n,he.j_oTag),n.expression.type==="JSXEmptyExpression"&&this.raise(ei.AttributeIsEmpty,n),n;case 143:case 134:return this.parseExprAtom();default:throw this.raise(ei.UnsupportedJsxValue,this.state.startLoc)}}jsxParseEmptyExpression(){let n=this.startNodeAt(this.state.lastTokEndLoc);return this.finishNodeAt(n,"JSXEmptyExpression",this.state.startLoc)}jsxParseSpreadChild(n){return this.next(),n.expression=this.parseExpression(),this.setContext(he.j_expr),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(n,"JSXSpreadChild")}jsxParseExpressionContainer(n,r){if(this.match(8))n.expression=this.jsxParseEmptyExpression();else{let s=this.parseExpression();n.expression=s}return this.setContext(r),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(n,"JSXExpressionContainer")}jsxParseAttribute(){let n=this.startNode();return this.match(5)?(this.setContext(he.brace),this.next(),this.expect(21),n.argument=this.parseMaybeAssignAllowIn(),this.setContext(he.j_oTag),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(n,"JSXSpreadAttribute")):(n.name=this.jsxParseNamespacedName(),n.value=this.eat(29)?this.jsxParseAttributeValue():null,this.finishNode(n,"JSXAttribute"))}jsxParseOpeningElementAt(n){let r=this.startNodeAt(n);return this.eat(144)?this.finishNode(r,"JSXOpeningFragment"):(r.name=this.jsxParseElementName(),this.jsxParseOpeningElementAfterName(r))}jsxParseOpeningElementAfterName(n){let r=[];for(;!this.match(56)&&!this.match(144);)r.push(this.jsxParseAttribute());return n.attributes=r,n.selfClosing=this.eat(56),this.expect(144),this.finishNode(n,"JSXOpeningElement")}jsxParseClosingElementAt(n){let r=this.startNodeAt(n);return this.eat(144)?this.finishNode(r,"JSXClosingFragment"):(r.name=this.jsxParseElementName(),this.expect(144),this.finishNode(r,"JSXClosingElement"))}jsxParseElementAt(n){let r=this.startNodeAt(n),s=[],o=this.jsxParseOpeningElementAt(n),a=null;if(!o.selfClosing){e:for(;;)switch(this.state.type){case 143:if(n=this.state.startLoc,this.next(),this.eat(56)){a=this.jsxParseClosingElementAt(n);break e}s.push(this.jsxParseElementAt(n));break;case 142:s.push(this.parseLiteral(this.state.value,"JSXText"));break;case 5:{let d=this.startNode();this.setContext(he.brace),this.next(),this.match(21)?s.push(this.jsxParseSpreadChild(d)):s.push(this.jsxParseExpressionContainer(d,he.j_expr));break}default:this.unexpected()}br(o)&&!br(a)&&a!==null?this.raise(ei.MissingClosingTagFragment,a):!br(o)&&br(a)?this.raise(ei.MissingClosingTagElement,a,{openingTagName:hs(o.name)}):!br(o)&&!br(a)&&hs(a.name)!==hs(o.name)&&this.raise(ei.MissingClosingTagElement,a,{openingTagName:hs(o.name)})}if(br(o)?(r.openingFragment=o,r.closingFragment=a):(r.openingElement=o,r.closingElement=a),r.children=s,this.match(47))throw this.raise(ei.UnwrappedAdjacentJSXElements,this.state.startLoc);return br(o)?this.finishNode(r,"JSXFragment"):this.finishNode(r,"JSXElement")}jsxParseElement(){let n=this.state.startLoc;return this.next(),this.jsxParseElementAt(n)}setContext(n){let{context:r}=this.state;r[r.length-1]=n}parseExprAtom(n){return this.match(143)?this.jsxParseElement():this.match(47)&&this.input.charCodeAt(this.state.pos)!==33?(this.replaceToken(143),this.jsxParseElement()):super.parseExprAtom(n)}skipSpace(){this.curContext().preserveSpace||super.skipSpace()}getTokenFromCode(n){let r=this.curContext();if(r===he.j_expr){this.jsxReadToken();return}if(r===he.j_oTag||r===he.j_cTag){if(kn(n)){this.jsxReadWord();return}if(n===62){++this.state.pos,this.finishToken(144);return}if((n===34||n===39)&&r===he.j_oTag){this.jsxReadString(n);return}}if(n===60&&this.state.canStartJSXElement&&this.input.charCodeAt(this.state.pos+1)!==33){++this.state.pos,this.finishToken(143);return}super.getTokenFromCode(n)}updateContext(n){let{context:r,type:s}=this.state;if(s===56&&n===143)r.splice(-2,2,he.j_cTag),this.state.canStartJSXElement=!1;else if(s===143)r.push(he.j_oTag);else if(s===144){let o=r[r.length-1];o===he.j_oTag&&n===56||o===he.j_cTag?(r.pop(),this.state.canStartJSXElement=r[r.length-1]===he.j_expr):(this.setContext(he.j_expr),this.state.canStartJSXElement=!0)}else this.state.canStartJSXElement=gO(s)}},Of=class extends ra{constructor(...t){super(...t),this.tsNames=new Map}},$f=class extends ia{constructor(...t){super(...t),this.importsStack=[]}createScope(t){return this.importsStack.push(new Set),new Of(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,n){let r=this.importsStack.length;if(this.importsStack[r-1].has(t))return!0;if(!n&&r>1){for(let s=0;s<r-1;s++)if(this.importsStack[s].has(t))return!0}return!1}declareName(t,n,r){if(n&4096){this.hasImport(t,!0)&&this.parser.raise(_.VarRedeclaration,r,{identifierName:t}),this.importsStack[this.importsStack.length-1].add(t);return}let s=this.currentScope(),o=s.tsNames.get(t)||0;if(n&1024){this.maybeExportDefined(s,t),s.tsNames.set(t,o|16);return}super.declareName(t,n,r),n&2&&(n&1||(this.checkRedeclarationInScope(s,t,n,r),this.maybeExportDefined(s,t)),o=o|1),n&256&&(o=o|2),n&512&&(o=o|4),n&128&&(o=o|8),o&&s.tsNames.set(t,o)}isRedeclaredInScope(t,n,r){let s=t.tsNames.get(n);if((s&2)>0){if(r&256){let o=!!(r&512),a=(s&4)>0;return o!==a}return!0}return r&128&&(s&8)>0?t.names.get(n)&2?!!(r&1):!1:r&2&&(s&1)>0?!0:super.isRedeclaredInScope(t,n,r)}checkLocalExport(t){let{name:n}=t;if(this.hasImport(n))return;let r=this.scopeStack.length;for(let s=r-1;s>=0;s--){let a=this.scopeStack[s].tsNames.get(n);if((a&1)>0||(a&16)>0)return}super.checkLocalExport(t)}},Mf=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 Ol(e,t){return(e?2:0)|(t?1:0)}var Lf=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[n,r]=t;if(!this.hasPlugin(n))return!1;let s=this.plugins.get(n);for(let o of Object.keys(r))if(s?.[o]!==r[o])return!1;return!0}}getPluginOption(t,n){var r;return(r=this.plugins.get(t))==null?void 0:r[n]}};function vk(e,t){e.trailingComments===void 0?e.trailingComments=t:e.trailingComments.unshift(...t)}function qO(e,t){e.leadingComments===void 0?e.leadingComments=t:e.leadingComments.unshift(...t)}function sa(e,t){e.innerComments===void 0?e.innerComments=t:e.innerComments.unshift(...t)}function Xt(e,t,n){let r=null,s=t.length;for(;r===null&&s>0;)r=t[--s];r===null||r.start>n.start?sa(e,n.comments):vk(r,n.comments)}var Df=class extends Lf{addComment(t){this.filename&&(t.loc.filename=this.filename);let{commentsLen:n}=this.state;this.comments.length!==n&&(this.comments.length=n),this.comments.push(t),this.state.commentsLen++}processComment(t){let{commentStack:n}=this.state,r=n.length;if(r===0)return;let s=r-1,o=n[s];o.start===t.end&&(o.leadingNode=t,s--);let{start:a}=t;for(;s>=0;s--){let d=n[s],l=d.end;if(l>a)d.containingNode=t,this.finalizeComment(d),n.splice(s,1);else{l===a&&(d.trailingNode=t);break}}}finalizeComment(t){var n;let{comments:r}=t;if(t.leadingNode!==null||t.trailingNode!==null)t.leadingNode!==null&&vk(t.leadingNode,r),t.trailingNode!==null&&qO(t.trailingNode,r);else{let s=t.containingNode,o=t.start;if(this.input.charCodeAt(this.offsetToSourcePos(o)-1)===44)switch(s.type){case"ObjectExpression":case"ObjectPattern":Xt(s,s.properties,t);break;case"CallExpression":case"NewExpression":case"OptionalCallExpression":Xt(s,s.arguments,t);break;case"ImportExpression":Xt(s,[s.source,(n=s.options)!=null?n:null],t);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":case"ObjectMethod":case"ClassMethod":case"ClassPrivateMethod":case"TSTypeParameterDeclaration":Xt(s,s.params,t);break;case"ArrayExpression":case"ArrayPattern":Xt(s,s.elements,t);break;case"ExportNamedDeclaration":case"ImportDeclaration":Xt(s,s.specifiers,t);break;case"TSEnumDeclaration":Xt(s,s.members,t);break;case"TSEnumBody":Xt(s,s.members,t);break;case"TSInterfaceBody":Xt(s,s.body,t);break;default:{if(s.type==="RecordExpression"){Xt(s,s.properties,t);break}if(s.type==="TupleExpression"){Xt(s,s.elements,t);break}sa(s,r)}}else sa(s,r)}}finalizeRemainingComments(){let{commentStack:t}=this.state;for(let n=t.length-1;n>=0;n--)this.finalizeComment(t[n]);this.state.commentStack=[]}resetPreviousNodeTrailingComments(t){let{commentStack:n}=this.state,{length:r}=n;if(r===0)return;let s=n[r-1];s.leadingNode===t&&(s.leadingNode=null)}takeSurroundingComments(t,n,r){let{commentStack:s}=this.state,o=s.length;if(o===0)return;let a=o-1;for(;a>=0;a--){let d=s[a],l=d.end;if(d.start===r)d.leadingNode=t;else if(l===n)d.trailingNode=t;else if(l<n)break}}},Ff=class e{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=[he.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:n,startIndex:r,startLine:s,startColumn:o}){this.strict=t===!1?!1:t===!0?!0:n==="module",this.startIndex=r,this.curLine=s,this.lineStart=-o,this.startLoc=this.endLoc=new Rn(s,o,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 Rn(this.curLine,this.pos-this.lineStart,this.pos+this.startIndex)}clone(){let t=new e;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}},GO=function(t){return t>=48&&t<=57},sk={decBinOct:new Set([46,66,69,79,95,98,101,111]),hex:new Set([46,88,95,120])},El={bin:e=>e===48||e===49,oct:e=>e>=48&&e<=55,dec:e=>e>=48&&e<=57,hex:e=>e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102};function ok(e,t,n,r,s,o){let a=n,d=r,l=s,c="",u=null,p=n,{length:f}=t;for(;;){if(n>=f){o.unterminated(a,d,l),c+=t.slice(p,n);break}let m=t.charCodeAt(n);if(KO(e,m,t,n)){c+=t.slice(p,n);break}if(m===92){c+=t.slice(p,n);let h=WO(t,n,r,s,e==="template",o);h.ch===null&&!u?u={pos:n,lineStart:r,curLine:s}:c+=h.ch,{pos:n,lineStart:r,curLine:s}=h,p=n}else m===8232||m===8233?(++n,++s,r=n):m===10||m===13?e==="template"?(c+=t.slice(p,n)+`
|
|
8
8
|
`,++n,m===13&&t.charCodeAt(n)===10&&++n,++s,p=r=n):o.unterminated(a,d,l):++n}return{pos:n,str:c,firstInvalidLoc:u,lineStart:r,curLine:s,containsInvalid:!!u}}function KO(e,t,n,r){return e==="template"?t===96||t===36&&n.charCodeAt(r+1)===123:t===(e==="double"?34:39)}function WO(e,t,n,r,s,o){let a=!s;t++;let d=c=>({pos:t,ch:c,lineStart:n,curLine:r}),l=e.charCodeAt(t++);switch(l){case 110:return d(`
|
|
9
9
|
`);case 114:return d("\r");case 120:{let c;return{code:c,pos:t}=jf(e,t,n,r,2,!1,a,o),d(c===null?null:String.fromCharCode(c))}case 117:{let c;return{code:c,pos:t}=Rk(e,t,n,r,a,o),d(c===null?null:String.fromCodePoint(c))}case 116:return d(" ");case 98:return d("\b");case 118:return d("\v");case 102:return d("\f");case 13:e.charCodeAt(t)===10&&++t;case 10:n=t,++r;case 8232:case 8233:return d("");case 56:case 57:if(s)return d(null);o.strictNumericEscape(t-1,n,r);default:if(l>=48&&l<=55){let c=t-1,p=/^[0-7]+/.exec(e.slice(c,t+2))[0],f=parseInt(p,8);f>255&&(p=p.slice(0,-1),f=parseInt(p,8)),t+=p.length-1;let m=e.charCodeAt(t);if(p!=="0"||m===56||m===57){if(s)return d(null);o.strictNumericEscape(c,n,r)}return d(String.fromCharCode(f))}return d(String.fromCharCode(l))}}function jf(e,t,n,r,s,o,a,d){let l=t,c;return{n:c,pos:t}=kk(e,t,n,r,16,s,o,!1,d,!a),c===null&&(a?d.invalidEscapeSequence(l,n,r):t=l-1),{code:c,pos:t}}function kk(e,t,n,r,s,o,a,d,l,c){let u=t,p=s===16?sk.hex:sk.decBinOct,f=s===16?El.hex:s===10?El.dec:s===8?El.oct:El.bin,m=!1,h=0;for(let g=0,y=o??1/0;g<y;++g){let w=e.charCodeAt(t),b;if(w===95&&d!=="bail"){let v=e.charCodeAt(t-1),R=e.charCodeAt(t+1);if(d){if(Number.isNaN(R)||!f(R)||p.has(v)||p.has(R)){if(c)return{n:null,pos:t};l.unexpectedNumericSeparator(t,n,r)}}else{if(c)return{n:null,pos:t};l.numericSeparatorInEscapeSequence(t,n,r)}++t;continue}if(w>=97?b=w-97+10:w>=65?b=w-65+10:GO(w)?b=w-48:b=1/0,b>=s){if(b<=9&&c)return{n:null,pos:t};if(b<=9&&l.invalidDigit(t,n,r,s))b=0;else if(a)b=0,m=!0;else break}++t,h=h*s+b}return t===u||o!=null&&t-u!==o||m?{n:null,pos:t}:{n:h,pos:t}}function Rk(e,t,n,r,s,o){let a=e.charCodeAt(t),d;if(a===123){if(++t,{code:d,pos:t}=jf(e,t,n,r,e.indexOf("}",t)-t,!0,s,o),++t,d!==null&&d>1114111)if(s)o.invalidCodePoint(t,n,r);else return{code:null,pos:t}}else({code:d,pos:t}=jf(e,t,n,r,4,!1,s,o));return{code:d,pos:t}}function Zo(e,t,n){return new Rn(n,e-t,e)}var JO=new Set([103,109,115,105,121,117,100,118]),vn=class{constructor(t){let n=t.startIndex||0;this.type=t.type,this.value=t.value,this.start=n+t.start,this.end=n+t.end,this.loc=new ws(t.startLoc,t.endLoc)}},Bf=class extends Df{constructor(t,n){super(),this.isLookahead=void 0,this.tokens=[],this.errorHandlers_readInt={invalidDigit:(r,s,o,a)=>this.optionFlags&2048?(this.raise(_.InvalidDigit,Zo(r,s,o),{radix:a}),!0):!1,numericSeparatorInEscapeSequence:this.errorBuilder(_.NumericSeparatorInEscapeSequence),unexpectedNumericSeparator:this.errorBuilder(_.UnexpectedNumericSeparator)},this.errorHandlers_readCodePoint=Object.assign({},this.errorHandlers_readInt,{invalidEscapeSequence:this.errorBuilder(_.InvalidEscapeSequence),invalidCodePoint:this.errorBuilder(_.InvalidCodePoint)}),this.errorHandlers_readStringContents_string=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:(r,s,o)=>{this.recordStrictModeErrors(_.StrictNumericEscape,Zo(r,s,o))},unterminated:(r,s,o)=>{throw this.raise(_.UnterminatedString,Zo(r-1,s,o))}}),this.errorHandlers_readStringContents_template=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:this.errorBuilder(_.StrictNumericEscape),unterminated:(r,s,o)=>{throw this.raise(_.UnterminatedTemplate,Zo(r,s,o))}}),this.state=new Ff,this.state.init(t),this.input=n,this.length=n.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 vn(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 n=this.state;return this.state=t,n}nextTokenStart(){return this.nextTokenStartSince(this.state.pos)}nextTokenStartSince(t){return If.lastIndex=t,If.test(this.input)?If.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 Sf.lastIndex=t,Sf.test(this.input)?Sf.lastIndex:t}lookaheadInLineCharCode(){return this.input.charCodeAt(this.nextTokenInLineStart())}codePointAtPos(t){let n=this.input.charCodeAt(t);if((n&64512)===55296&&++t<this.input.length){let r=this.input.charCodeAt(t);(r&64512)===56320&&(n=65536+((n&1023)<<10)+(r&1023))}return n}setStrict(t){this.state.strict=t,t&&(this.state.strictErrors.forEach(([n,r])=>this.raise(n,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 n;this.isLookahead||(n=this.state.curPosition());let r=this.state.pos,s=this.input.indexOf(t,r+2);if(s===-1)throw this.raise(_.UnterminatedComment,this.state.curPosition());for(this.state.pos=s+t.length,Pl.lastIndex=r+2;Pl.test(this.input)&&Pl.lastIndex<=s;)++this.state.curLine,this.state.lineStart=Pl.lastIndex;if(this.isLookahead)return;let o={type:"CommentBlock",value:this.input.slice(r+2,s),start:this.sourceToOffsetPos(r),end:this.sourceToOffsetPos(s+t.length),loc:new ws(n,this.state.curPosition())};return this.optionFlags&256&&this.pushToken(o),o}skipLineComment(t){let n=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(;!gs(s)&&++this.state.pos<this.length;)s=this.input.charCodeAt(this.state.pos);if(this.isLookahead)return;let o=this.state.pos,d={type:"CommentLine",value:this.input.slice(n+t,o),start:this.sourceToOffsetPos(n),end:this.sourceToOffsetPos(o),loc:new ws(r,this.state.curPosition())};return this.optionFlags&256&&this.pushToken(d),d}skipSpace(){let t=this.state.pos,n=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),n?.push(s));break}case 47:{let s=this.skipLineComment(2);s!==void 0&&(this.addComment(s),n?.push(s));break}default:break e}break;default:if(HO(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 o=this.skipLineComment(3);o!==void 0&&(this.addComment(o),n?.push(o))}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 o=this.skipLineComment(4);o!==void 0&&(this.addComment(o),n?.push(o))}else break e}else break e}}if(n?.length>0){let r=this.state.pos,s={start:this.sourceToOffsetPos(t),end:this.sourceToOffsetPos(r),comments:n,leadingNode:null,trailingNode:null,containingNode:null};this.state.commentStack.push(s)}}finishToken(t,n){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();let r=this.state.type;this.state.type=t,this.state.value=n,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,n=this.codePointAtPos(t);if(n>=48&&n<=57)throw this.raise(_.UnexpectedDigitAfterHash,this.state.curPosition());if(n===123||n===91&&this.hasPlugin("recordAndTuple")){if(this.expectPlugin("recordAndTuple"),this.getPluginOption("recordAndTuple","syntaxType")==="bar")throw this.raise(n===123?_.RecordExpressionHashIncorrectStartSyntaxType:_.TupleExpressionHashIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,n===123?this.finishToken(7):this.finishToken(1)}else kn(n)?(++this.state.pos,this.finishToken(139,this.readWord1(n))):n===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 n=this.state.pos;for(this.state.pos+=1;!gs(t)&&++this.state.pos<this.length;)t=this.input.charCodeAt(this.state.pos);let r=this.input.slice(n+2,this.state.pos);return this.finishToken(28,r),!0}readToken_mult_modulo(t){let n=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),n=57),s===61&&!this.state.inType&&(r++,n=t===37?33:30),this.finishOp(n,r)}readToken_pipe_amp(t){let n=this.input.charCodeAt(this.state.pos+1);if(n===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(n===62){this.finishOp(39,2);return}if(this.hasPlugin("recordAndTuple")&&n===125){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(_.RecordExpressionBarIncorrectEndSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(9);return}if(this.hasPlugin("recordAndTuple")&&n===93){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(_.TupleExpressionBarIncorrectEndSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(4);return}}if(n===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 n=this.input.charCodeAt(this.state.pos+1);if(n===t){this.finishOp(34,2);return}n===61?this.finishOp(30,2):this.finishOp(53,1)}readToken_lt(){let{pos:t}=this.state,n=this.input.charCodeAt(t+1);if(n===60){if(this.input.charCodeAt(t+2)===61){this.finishOp(30,3);return}this.finishOp(51,2);return}if(n===61){this.finishOp(49,2);return}this.finishOp(47,1)}readToken_gt(){let{pos:t}=this.state,n=this.input.charCodeAt(t+1);if(n===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(n===61){this.finishOp(49,2);return}this.finishOp(48,1)}readToken_eq_excl(t){let n=this.input.charCodeAt(this.state.pos+1);if(n===61){this.finishOp(46,this.input.charCodeAt(this.state.pos+2)===61?3:2);return}if(t===61&&n===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),n=this.input.charCodeAt(this.state.pos+2);t===63?n===61?this.finishOp(30,3):this.finishOp(40,2):t===46&&!(n>=48&&n<=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(_.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(_.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 n=this.input.charCodeAt(this.state.pos+1);if(n===120||n===88){this.readRadixNumber(16);return}if(n===111||n===79){this.readRadixNumber(8);return}if(n===98||n===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(kn(t)){this.readWord(t);return}}throw this.raise(_.InvalidOrUnexpectedToken,this.state.curPosition(),{unexpected:String.fromCodePoint(t)})}finishOp(t,n){let r=this.input.slice(this.state.pos,this.state.pos+n);this.state.pos+=n,this.finishToken(t,r)}readRegexp(){let t=this.state.startLoc,n=this.state.start+1,r,s,{pos:o}=this.state;for(;;++o){if(o>=this.length)throw this.raise(_.UnterminatedRegExp,dt(t,1));let c=this.input.charCodeAt(o);if(gs(c))throw this.raise(_.UnterminatedRegExp,dt(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(n,o);++o;let d="",l=()=>dt(t,o+2-n);for(;o<this.length;){let c=this.codePointAtPos(o),u=String.fromCharCode(c);if(JO.has(c))c===118?d.includes("u")&&this.raise(_.IncompatibleRegExpUVFlags,l()):c===117&&d.includes("v")&&this.raise(_.IncompatibleRegExpUVFlags,l()),d.includes(u)&&this.raise(_.DuplicateRegExpFlags,l());else if(ni(c)||c===92)this.raise(_.MalformedRegExpFlags,l());else break;++o,d+=u}this.state.pos=o,this.finishToken(138,{pattern:a,flags:d})}readInt(t,n,r=!1,s=!0){let{n:o,pos:a}=kk(this.input,this.state.pos,this.state.lineStart,this.state.curLine,t,n,r,s,this.errorHandlers_readInt,!1);return this.state.pos=a,o}readRadixNumber(t){let n=this.state.pos,r=this.state.curPosition(),s=!1;this.state.pos+=2;let o=this.readInt(t);o==null&&this.raise(_.InvalidDigit,dt(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(_.InvalidDecimal,r);if(kn(this.codePointAtPos(this.state.pos)))throw this.raise(_.NumberIdentifier,this.state.curPosition());if(s){let d=this.input.slice(n,this.state.pos).replace(/[_n]/g,"");this.finishToken(136,d);return}this.finishToken(135,o)}readNumber(t){let n=this.state.pos,r=this.state.curPosition(),s=!1,o=!1,a=!1,d=!1;!t&&this.readInt(10)===null&&this.raise(_.InvalidNumber,this.state.curPosition());let l=this.state.pos-n>=2&&this.input.charCodeAt(n)===48;if(l){let m=this.input.slice(n,this.state.pos);if(this.recordStrictModeErrors(_.StrictOctalLiteral,r),!this.state.strict){let h=m.indexOf("_");h>0&&this.raise(_.ZeroDigitNumericSeparator,dt(r,h))}d=l&&!/[89]/.test(m)}let c=this.input.charCodeAt(this.state.pos);if(c===46&&!d&&(++this.state.pos,this.readInt(10),s=!0,c=this.input.charCodeAt(this.state.pos)),(c===69||c===101)&&!d&&(c=this.input.charCodeAt(++this.state.pos),(c===43||c===45)&&++this.state.pos,this.readInt(10)===null&&this.raise(_.InvalidOrMissingExponent,r),s=!0,a=!0,c=this.input.charCodeAt(this.state.pos)),c===110&&((s||l)&&this.raise(_.InvalidBigIntLiteral,r),++this.state.pos,o=!0),c===109){this.expectPlugin("decimal",this.state.curPosition()),(a||l)&&this.raise(_.InvalidDecimal,r),++this.state.pos;var u=!0}if(kn(this.codePointAtPos(this.state.pos)))throw this.raise(_.NumberIdentifier,this.state.curPosition());let p=this.input.slice(n,this.state.pos).replace(/[_mn]/g,"");if(o){this.finishToken(136,p);return}if(u){this.finishToken(137,p);return}let f=d?parseInt(p,8):parseFloat(p);this.finishToken(135,f)}readCodePoint(t){let{code:n,pos:r}=Rk(this.input,this.state.pos,this.state.lineStart,this.state.curLine,t,this.errorHandlers_readCodePoint);return this.state.pos=r,n}readString(t){let{str:n,pos:r,curLine:s,lineStart:o}=ok(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=o,this.state.curLine=s,this.finishToken(134,n)}readTemplateContinuation(){this.match(8)||this.unexpected(null,8),this.state.pos--,this.readTemplateToken()}readTemplateToken(){let t=this.input[this.state.pos],{str:n,firstInvalidLoc:r,pos:s,curLine:o,lineStart:a}=ok("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=o,r&&(this.state.firstInvalidTemplateEscapePos=new Rn(r.curLine,r.pos-r.lineStart,this.sourceToOffsetPos(r.pos))),this.input.codePointAt(s)===96?this.finishToken(24,r?null:t+n+"`"):(this.state.pos++,this.finishToken(25,r?null:t+n+"${"))}recordStrictModeErrors(t,n){let r=n.index;this.state.strict&&!this.state.strictErrors.has(r)?this.raise(t,n):this.state.strictErrors.set(r,[t,n])}readWord1(t){this.state.containsEsc=!1;let n="",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 o=this.codePointAtPos(this.state.pos);if(ni(o))this.state.pos+=o<=65535?1:2;else if(o===92){this.state.containsEsc=!0,n+=this.input.slice(s,this.state.pos);let a=this.state.curPosition(),d=this.state.pos===r?kn:ni;if(this.input.charCodeAt(++this.state.pos)!==117){this.raise(_.MissingUnicodeEscape,this.state.curPosition()),s=this.state.pos-1;continue}++this.state.pos;let l=this.readCodePoint(!0);l!==null&&(d(l)||this.raise(_.EscapedCharNotAnIdentifier,a),n+=String.fromCodePoint(l)),s=this.state.pos}else break}return n+this.input.slice(s,this.state.pos)}readWord(t){let n=this.readWord1(t),r=Xf.get(n);r!==void 0?this.finishToken(r,vr(r)):this.finishToken(132,n)}checkKeywordEscapes(){let{type:t}=this.state;rm(t)&&this.state.containsEsc&&this.raise(_.InvalidEscapedReservedWord,this.state.startLoc,{reservedWord:vr(t)})}raise(t,n,r={}){let s=n instanceof Rn?n:n.loc.start,o=t(s,r);if(!(this.optionFlags&2048))throw o;return this.isLookahead||this.state.errors.push(o),o}raiseOverwrite(t,n,r={}){let s=n instanceof Rn?n:n.loc.start,o=s.index,a=this.state.errors;for(let d=a.length-1;d>=0;d--){let l=a[d];if(l.loc.index===o)return a[d]=t(s,r);if(l.loc.index<o)break}return this.raise(t,n,r)}updateContext(t){}unexpected(t,n){throw this.raise(_.UnexpectedToken,t??this.state.startLoc,{expected:n?vr(n):null})}expectPlugin(t,n){if(this.hasPlugin(t))return!0;throw this.raise(_.MissingPlugin,n??this.state.startLoc,{missingPlugin:[t]})}expectOnePlugin(t){if(!t.some(n=>this.hasPlugin(n)))throw this.raise(_.MissingOneOfPlugins,this.state.startLoc,{missingPlugin:t})}errorBuilder(t){return(n,r,s)=>{this.raise(t,Zo(n,r,s))}}},Vf=class{constructor(){this.privateNames=new Set,this.loneAccessors=new Map,this.undefinedPrivateNames=new Map}},Uf=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 Vf)}exit(){let t=this.stack.pop(),n=this.current();for(let[r,s]of Array.from(t.undefinedPrivateNames))n?n.undefinedPrivateNames.has(r)||n.undefinedPrivateNames.set(r,s):this.parser.raise(_.InvalidPrivateFieldResolution,s,{identifierName:r})}declarePrivateName(t,n,r){let{privateNames:s,loneAccessors:o,undefinedPrivateNames:a}=this.current(),d=s.has(t);if(n&3){let l=d&&o.get(t);if(l){let c=l&4,u=n&4,p=l&3,f=n&3;d=p===f||c!==u,d||o.delete(t)}else d||o.set(t,n)}d&&this.parser.raise(_.PrivateNameRedeclaration,r,{identifierName:t}),s.add(t),a.delete(t)}usePrivateName(t,n){let r;for(r of this.stack)if(r.privateNames.has(t))return;r?r.undefinedPrivateNames.set(t,n):this.parser.raise(_.InvalidPrivateFieldResolution,n,{identifierName:t})}},bs=class{constructor(t=0){this.type=t}canBeArrowParameterDeclaration(){return this.type===2||this.type===1}isCertainlyParameterDeclaration(){return this.type===3}},Ll=class extends bs{constructor(t){super(t),this.declarationErrors=new Map}recordDeclarationError(t,n){let r=n.index;this.declarationErrors.set(r,[t,n])}clearDeclarationError(t){this.declarationErrors.delete(t)}iterateErrors(t){this.declarationErrors.forEach(t)}},Hf=class{constructor(t){this.parser=void 0,this.stack=[new bs],this.parser=t}enter(t){this.stack.push(t)}exit(){this.stack.pop()}recordParameterInitializerError(t,n){let r=n.loc.start,{stack:s}=this,o=s.length-1,a=s[o];for(;!a.isCertainlyParameterDeclaration();){if(a.canBeArrowParameterDeclaration())a.recordDeclarationError(t,r);else return;a=s[--o]}this.parser.raise(t,r)}recordArrowParameterBindingError(t,n){let{stack:r}=this,s=r[r.length-1],o=n.loc.start;if(s.isCertainlyParameterDeclaration())this.parser.raise(t,o);else if(s.canBeArrowParameterDeclaration())s.recordDeclarationError(t,o);else return}recordAsyncArrowParametersError(t){let{stack:n}=this,r=n.length-1,s=n[r];for(;s.canBeArrowParameterDeclaration();)s.type===2&&s.recordDeclarationError(_.AwaitBindingIdentifier,t),s=n[--r]}validateAsPattern(){let{stack:t}=this,n=t[t.length-1];n.canBeArrowParameterDeclaration()&&n.iterateErrors(([r,s])=>{this.parser.raise(r,s);let o=t.length-2,a=t[o];for(;a.canBeArrowParameterDeclaration();)a.clearDeclarationError(s.index),a=t[--o]})}};function YO(){return new bs(3)}function XO(){return new Ll(1)}function QO(){return new Ll(2)}function xk(){return new bs}var zf=class extends Bf{addExtra(t,n,r,s=!0){if(!t)return;let{extra:o}=t;o==null&&(o={},t.extra=o),s?o[n]=r:Object.defineProperty(o,n,{enumerable:s,value:r})}isContextual(t){return this.state.type===t&&!this.state.containsEsc}isUnparsedContextual(t,n){if(this.input.startsWith(n,t)){let r=this.input.charCodeAt(t+n.length);return!(ni(r)||(r&64512)===55296)}return!1}isLookaheadContextual(t){let n=this.nextTokenStart();return this.isUnparsedContextual(n,t)}eatContextual(t){return this.isContextual(t)?(this.next(),!0):!1}expectContextual(t,n){if(!this.eatContextual(t)){if(n!=null)throw this.raise(n,this.state.startLoc);this.unexpected(null,t)}}canInsertSemicolon(){return this.match(140)||this.match(8)||this.hasPrecedingLineBreak()}hasPrecedingLineBreak(){return ik(this.input,this.offsetToSourcePos(this.state.lastTokEndLoc.index),this.state.start)}hasFollowingLineBreak(){return ik(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(_.MissingSemicolon,this.state.lastTokEndLoc)}expect(t,n){this.eat(t)||this.unexpected(n,t)}tryParse(t,n=this.state.clone()){let r={node:null};try{let s=t((o=null)=>{throw r.node=o,r});if(this.state.errors.length>n.errors.length){let o=this.state;return this.state=n,this.state.tokensLength=o.tokensLength,{node:s,error:o.errors[n.errors.length],thrown:!1,aborted:!1,failState:o}}return{node:s,error:null,thrown:!1,aborted:!1,failState:null}}catch(s){let o=this.state;if(this.state=n,s instanceof SyntaxError)return{node:null,error:s,thrown:!0,aborted:!1,failState:o};if(s===r)return{node:r.node,error:null,thrown:!1,aborted:!0,failState:o};throw s}}checkExpressionErrors(t,n){if(!t)return!1;let{shorthandAssignLoc:r,doubleProtoLoc:s,privateKeyLoc:o,optionalParametersLoc:a,voidPatternLoc:d}=t,l=!!r||!!s||!!a||!!o||!!d;if(!n)return l;r!=null&&this.raise(_.InvalidCoverInitializedName,r),s!=null&&this.raise(_.DuplicateProto,s),o!=null&&this.raise(_.UnexpectedPrivateField,o),a!=null&&this.unexpected(a),d!=null&&this.raise(_.InvalidCoverDiscardElement,d)}isLiteralPropertyName(){return fk(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 n=this.state.labels;this.state.labels=[];let r=this.exportedIdentifiers;this.exportedIdentifiers=new Set;let s=this.inModule;this.inModule=t;let o=this.scope,a=this.getScopeHandler();this.scope=new a(this,t);let d=this.prodParam;this.prodParam=new Mf;let l=this.classScope;this.classScope=new Uf(this);let c=this.expressionScope;return this.expressionScope=new Hf(this),()=>{this.state.labels=n,this.exportedIdentifiers=r,this.inModule=s,this.scope=o,this.prodParam=d,this.classScope=l,this.expressionScope=c}}enterInitialScopes(){let t=0;(this.inModule||this.optionFlags&1)&&(t|=2),this.optionFlags&32&&(t|=1);let n=!this.inModule&&this.options.sourceType==="commonjs";(n||this.optionFlags&2)&&(t|=4),this.prodParam.enter(t);let r=n?514:1;this.optionFlags&4&&(r|=512),this.scope.enter(r)}checkDestructuringPrivate(t){let{privateKeyLoc:n}=t;n!==null&&this.expectPlugin("destructuringPrivate",n)}},ys=class{constructor(){this.shorthandAssignLoc=null,this.doubleProtoLoc=null,this.privateKeyLoc=null,this.optionalParametersLoc=null,this.voidPatternLoc=null}},vs=class{constructor(t,n,r){this.type="",this.start=n,this.end=0,this.loc=new ws(r),t?.optionFlags&128&&(this.range=[n,0]),t!=null&&t.filename&&(this.loc.filename=t.filename)}},qf=vs.prototype;qf.__clone=function(){let e=new vs(void 0,this.start,this.loc.start),t=Object.keys(this);for(let n=0,r=t.length;n<r;n++){let s=t[n];s!=="leadingComments"&&s!=="trailingComments"&&s!=="innerComments"&&(e[s]=this[s])}return e};var Gf=class extends zf{startNode(){let t=this.state.startLoc;return new vs(this,t.index,t)}startNodeAt(t){return new vs(this,t.index,t)}startNodeAtNode(t){return this.startNodeAt(t.loc.start)}finishNode(t,n){return this.finishNodeAt(t,n,this.state.lastTokEndLoc)}finishNodeAt(t,n,r){return t.type=n,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,n){t.start=n.index,t.loc.start=n,this.optionFlags&128&&(t.range[0]=n.index)}resetEndLocation(t,n=this.state.lastTokEndLoc){t.end=n.index,t.loc.end=n,this.optionFlags&128&&(t.range[1]=n.index)}resetStartLocationFromNode(t,n){this.resetStartLocation(t,n.loc.start)}castNodeTo(t,n){return t.type=n,t}cloneIdentifier(t){let{type:n,start:r,end:s,loc:o,range:a,name:d}=t,l=Object.create(qf);return l.type=n,l.start=r,l.end=s,l.loc=o,l.range=a,l.name=d,t.extra&&(l.extra=t.extra),l}cloneStringLiteral(t){let{type:n,start:r,end:s,loc:o,range:a,extra:d}=t,l=Object.create(qf);return l.type=n,l.start=r,l.end=s,l.loc=o,l.range=a,l.extra=d,l.value=t.value,l}},Kf=e=>e.type==="ParenthesizedExpression"?Kf(e.expression):e,Wf=class extends Gf{toAssignable(t,n=!1){var r,s;let o;switch((t.type==="ParenthesizedExpression"||(r=t.extra)!=null&&r.parenthesized)&&(o=Kf(t),n?o.type==="Identifier"?this.expressionScope.recordArrowParameterBindingError(_.InvalidParenthesizedAssignment,t):o.type!=="CallExpression"&&o.type!=="MemberExpression"&&!this.isOptionalMemberExpression(o)&&this.raise(_.InvalidParenthesizedAssignment,t):this.raise(_.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 d=0,l=t.properties.length,c=l-1;d<l;d++){var a;let u=t.properties[d],p=d===c;this.toAssignableObjectExpressionProp(u,p,n),p&&u.type==="RestElement"&&(a=t.extra)!=null&&a.trailingCommaLoc&&this.raise(_.RestTrailingComma,t.extra.trailingCommaLoc)}break;case"ObjectProperty":{let{key:d,value:l}=t;this.isPrivateName(d)&&this.classScope.usePrivateName(this.getPrivateNameSV(d),d.loc.start),this.toAssignable(l,n);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,n);break;case"AssignmentExpression":t.operator!=="="&&this.raise(_.MissingEqInAssignment,t.left.loc.end),this.castNodeTo(t,"AssignmentPattern"),delete t.operator,t.left.type==="VoidPattern"&&this.raise(_.VoidPatternInitializer,t.left),this.toAssignable(t.left,n);break;case"ParenthesizedExpression":this.toAssignable(o,n);break}}toAssignableObjectExpressionProp(t,n,r){if(t.type==="ObjectMethod")this.raise(t.kind==="get"||t.kind==="set"?_.PatternHasAccessor:_.PatternHasMethod,t.key);else if(t.type==="SpreadElement"){this.castNodeTo(t,"RestElement");let s=t.argument;this.checkToRestConversion(s,!1),this.toAssignable(s,r),n||this.raise(_.RestTrailingComma,t)}else this.toAssignable(t,r)}toAssignableList(t,n,r){let s=t.length-1;for(let o=0;o<=s;o++){let a=t[o];a&&(this.toAssignableListItem(t,o,r),a.type==="RestElement"&&(o<s?this.raise(_.RestTrailingComma,a):n&&this.raise(_.RestTrailingComma,n)))}}toAssignableListItem(t,n,r){let s=t[n];if(s.type==="SpreadElement"){this.castNodeTo(s,"RestElement");let o=s.argument;this.checkToRestConversion(o,!0),this.toAssignable(o,r)}else this.toAssignable(s,r)}isAssignable(t,n){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,o)=>s.type!=="ObjectMethod"&&(o===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!n;default:return!1}}toReferencedList(t,n){return t}toReferencedListDeep(t,n){this.toReferencedList(t,n);for(let r of t)r?.type==="ArrayExpression"&&this.toReferencedListDeep(r.elements)}parseSpread(t){let n=this.startNode();return this.next(),n.argument=this.parseMaybeAssignAllowIn(t,void 0),this.finishNode(n,"SpreadElement")}parseRestBinding(){let t=this.startNode();this.next();let n=this.parseBindingAtom();return n.type==="VoidPattern"&&this.raise(_.UnexpectedVoidPattern,n),t.argument=n,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,n,r){let s=r&1,o=[],a=!0;for(;!this.eat(t);)if(a?a=!1:this.expect(12),s&&this.match(12))o.push(null);else{if(this.eat(t))break;if(this.match(21)){let d=this.parseRestBinding();if((this.hasPlugin("flow")||r&2)&&(d=this.parseFunctionParamType(d)),o.push(d),!this.checkCommaAfterRest(n)){this.expect(t);break}}else{let d=[];if(r&2)for(this.match(26)&&this.hasPlugin("decorators")&&this.raise(_.UnsupportedParameterDecorator,this.state.startLoc);this.match(26);)d.push(this.parseDecorator());o.push(this.parseBindingElement(r,d))}}return o}parseBindingRestProperty(t){return this.next(),this.hasPlugin("discardBinding")&&this.match(88)?(t.argument=this.parseVoidPattern(null),this.raise(_.UnexpectedVoidPattern,t.argument)):t.argument=this.parseIdentifier(),this.checkCommaAfterRest(125),this.finishNode(t,"RestElement")}parseBindingProperty(){let{type:t,startLoc:n}=this.state;if(t===21)return this.parseBindingRestProperty(this.startNode());let r=this.startNode();return t===139?(this.expectPlugin("destructuringPrivate",n),this.classScope.usePrivateName(this.state.value,n),r.key=this.parsePrivateName()):this.parsePropertyName(r),r.method=!1,this.parseObjPropValue(r,n,!1,!1,!0,!1)}parseBindingElement(t,n){let r=this.parseMaybeDefault();return(this.hasPlugin("flow")||t&2)&&this.parseFunctionParamType(r),n.length&&(r.decorators=n,this.resetStartLocationFromNode(r,n[0])),this.parseMaybeDefault(r.loc.start,r)}parseFunctionParamType(t){return t}parseMaybeDefault(t,n){if(t??(t=this.state.startLoc),n=n??this.parseBindingAtom(),!this.eat(29))return n;let r=this.startNodeAt(t);return n.type==="VoidPattern"&&this.raise(_.VoidPatternInitializer,n),r.left=n,r.right=this.parseMaybeAssignAllowIn(),this.finishNode(r,"AssignmentPattern")}isValidLVal(t,n,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(!n&&!this.state.strict&&this.optionFlags&8192)return!0}return!1}isOptionalMemberExpression(t){return t.type==="OptionalMemberExpression"}checkLVal(t,n,r=64,s=!1,o=!1,a=!1,d=!1){var l;let c=t.type;if(this.isObjectMethod(t))return;let u=this.isOptionalMemberExpression(t);if(u||c==="MemberExpression"){u&&(this.expectPlugin("optionalChainingAssign",t.loc.start),n.type!=="AssignmentExpression"&&this.raise(_.InvalidLhsOptionalChaining,t,{ancestor:n})),r!==64&&this.raise(_.InvalidPropertyBindingPattern,t);return}if(c==="Identifier"){this.checkIdentifier(t,r,o);let{name:w}=t;s&&(s.has(w)?this.raise(_.ParamDupe,t):s.add(w));return}else c==="VoidPattern"&&n.type==="CatchClause"&&this.raise(_.VoidPatternCatchClauseParam,t);let p=Kf(t);d||(d=p.type==="CallExpression"&&(p.callee.type==="Import"||p.callee.type==="Super"));let f=this.isValidLVal(c,d,!(a||(l=t.extra)!=null&&l.parenthesized)&&n.type==="AssignmentExpression",r);if(f===!0)return;if(f===!1){let w=r===64?_.InvalidLhs:_.InvalidLhsBinding;this.raise(w,t,{ancestor:n});return}let m,h;typeof f=="string"?(m=f,h=c==="ParenthesizedExpression"):[m,h]=f;let g=c==="ArrayPattern"||c==="ObjectPattern"?{type:c}:n,y=t[m];if(Array.isArray(y))for(let w of y)w&&this.checkLVal(w,g,r,s,o,h,!0);else y&&this.checkLVal(y,g,r,s,o,h,d)}checkIdentifier(t,n,r=!1){this.state.strict&&(r?bk(t.name,this.inModule):wk(t.name))&&(n===64?this.raise(_.StrictEvalArguments,t,{referenceName:t.name}):this.raise(_.StrictEvalArgumentsBinding,t,{bindingName:t.name})),n&8192&&t.name==="let"&&this.raise(_.LetInLexicalBinding,t),n&64||this.declareNameFromIdentifier(t,n)}declareNameFromIdentifier(t,n){this.scope.declareName(t.name,n,t.loc.start)}checkToRestConversion(t,n){switch(t.type){case"ParenthesizedExpression":this.checkToRestConversion(t.expression,n);break;case"Identifier":case"MemberExpression":break;case"ArrayExpression":case"ObjectExpression":if(n)break;default:this.raise(_.InvalidRestAssignmentPattern,t)}}checkCommaAfterRest(t){return this.match(12)?(this.raise(this.lookaheadCharCode()===t?_.RestTrailingComma:_.ElementAfterRest,this.state.startLoc),!0):!1}},Tf=/in(?:stanceof)?|as|satisfies/y;function ZO(e){if(e==null)throw new Error(`Unexpected ${e} value.`);return e}function ak(e){if(!e)throw new Error("Assert fail")}var K=Qt`typescript`({AbstractMethodHasImplementation:({methodName:e})=>`Method '${e}' cannot have an implementation because it is marked abstract.`,AbstractPropertyHasInitializer:({propertyName:e})=>`Property '${e}' 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:e})=>`'declare' is not allowed in ${e}ters.`,DeclareClassFieldHasInitializer:"Initializers are not allowed in ambient contexts.",DeclareFunctionHasImplementation:"An implementation cannot be declared in ambient contexts.",DuplicateAccessibilityModifier:({modifier:e})=>`Accessibility modifier already seen: '${e}'.`,DuplicateModifier:({modifier:e})=>`Duplicate modifier: '${e}'.`,EmptyHeritageClauseType:({token:e})=>`'${e}' 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:e})=>`'${e[0]}' modifier cannot be used with '${e[1]}' modifier.`,IndexSignatureHasAbstract:"Index signatures cannot have the 'abstract' modifier.",IndexSignatureHasAccessibility:({modifier:e})=>`Index signatures cannot have an accessibility modifier ('${e}').`,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:e})=>`'${e}' list can only include identifiers or qualified-names with optional type arguments.`,InvalidModifierOnAwaitUsingDeclaration:e=>`'${e}' modifier cannot appear on an await using declaration.`,InvalidModifierOnTypeMember:({modifier:e})=>`'${e}' modifier cannot appear on a type member.`,InvalidModifierOnTypeParameter:({modifier:e})=>`'${e}' modifier cannot appear on a type parameter.`,InvalidModifierOnTypeParameterPositions:({modifier:e})=>`'${e}' modifier can only appear on a type parameter of a class, interface or type alias.`,InvalidModifierOnUsingDeclaration:e=>`'${e}' modifier cannot appear on a using declaration.`,InvalidModifiersOrder:({orderedModifiers:e})=>`'${e[0]}' modifier must precede '${e[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:e})=>`Private elements cannot have an accessibility modifier ('${e}').`,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:e})=>`Single type parameter ${e} should have a trailing comma. Example usage: <${e},>.`,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:e})=>`Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${e}.`,UsingDeclarationInAmbientContext:e=>`'${e}' declarations are not allowed in ambient contexts.`});function e$(e){switch(e){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 dk(e){return e==="private"||e==="public"||e==="protected"}function t$(e){return e==="in"||e==="out"}var n$=e=>class extends e{constructor(...n){super(...n),this.tsParseInOutModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out"],disallowedModifiers:["const","public","private","protected","readonly","declare","abstract","override"],errorTemplate:K.InvalidModifierOnTypeParameter}),this.tsParseConstModifier=this.tsParseModifiers.bind(this,{allowedModifiers:["const"],disallowedModifiers:["in","out"],errorTemplate:K.InvalidModifierOnTypeParameterPositions}),this.tsParseInOutConstModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out","const"],disallowedModifiers:["public","private","protected","readonly","declare","abstract","override"],errorTemplate:K.InvalidModifierOnTypeParameter})}getScopeHandler(){return $f}tsIsIdentifier(){return ye(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(n,r,s){if(!ye(this.state.type)&&this.state.type!==58&&this.state.type!==75)return;let o=this.state.value;if(n.includes(o)){if(s&&this.match(106)||r&&this.tsIsStartOfStaticBlocks())return;if(this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this)))return o}}tsParseModifiers({allowedModifiers:n,disallowedModifiers:r,stopOnStartOfClassStaticBlock:s,errorTemplate:o=K.InvalidModifierOnTypeMember},a){let d=(c,u,p,f)=>{u===p&&a[f]&&this.raise(K.InvalidModifiersOrder,c,{orderedModifiers:[p,f]})},l=(c,u,p,f)=>{(a[p]&&u===f||a[f]&&u===p)&&this.raise(K.IncompatibleModifiers,c,{modifiers:[p,f]})};for(;;){let{startLoc:c}=this.state,u=this.tsParseModifier(n.concat(r??[]),s,a.static);if(!u)break;dk(u)?a.accessibility?this.raise(K.DuplicateAccessibilityModifier,c,{modifier:u}):(d(c,u,u,"override"),d(c,u,u,"static"),d(c,u,u,"readonly"),a.accessibility=u):t$(u)?(a[u]&&this.raise(K.DuplicateModifier,c,{modifier:u}),a[u]=!0,d(c,u,"in","out")):(hasOwnProperty.call(a,u)?this.raise(K.DuplicateModifier,c,{modifier:u}):(d(c,u,"static","readonly"),d(c,u,"static","override"),d(c,u,"override","readonly"),d(c,u,"abstract","override"),l(c,u,"declare","override"),l(c,u,"static","abstract")),a[u]=!0),r!=null&&r.includes(u)&&this.raise(o,c,{modifier:u})}}tsIsListTerminator(n){switch(n){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(n,r){let s=[];for(;!this.tsIsListTerminator(n);)s.push(r());return s}tsParseDelimitedList(n,r,s){return ZO(this.tsParseDelimitedListWorker(n,r,!0,s))}tsParseDelimitedListWorker(n,r,s,o){let a=[],d=-1;for(;!this.tsIsListTerminator(n);){d=-1;let l=r();if(l==null)return;if(a.push(l),this.eat(12)){d=this.state.lastTokStartLoc.index;continue}if(this.tsIsListTerminator(n))break;s&&this.expect(12);return}return o&&(o.value=d),a}tsParseBracketedList(n,r,s,o,a){o||(s?this.expect(0):this.expect(47));let d=this.tsParseDelimitedList(n,r,a);return s?this.expect(3):this.expect(48),d}tsParseImportType(){let n=this.startNode();return this.expect(83),this.expect(10),this.match(134)?n.argument=this.parseStringLiteral(this.state.value):(this.raise(K.UnsupportedImportTypeArgument,this.state.startLoc),n.argument=super.parseExprAtom()),this.eat(12)?n.options=this.tsParseImportTypeOptions():n.options=null,this.expect(11),this.eat(16)&&(n.qualifier=this.tsParseEntityName(3)),this.match(47)&&(n.typeParameters=this.tsParseTypeArguments()),this.finishNode(n,"TSImportType")}tsParseImportTypeOptions(){let n=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(),n.properties=[this.finishObjectProperty(r)],this.eat(12),this.expect(8),this.finishNode(n,"ObjectExpression")}tsParseImportTypeWithPropertyValue(){let n=this.startNode(),r=[];for(this.expect(5);!this.match(8);){let s=this.state.type;ye(s)||s===134?r.push(super.parsePropertyDefinition(null)):this.unexpected(),this.eat(12)}return n.properties=r,this.next(),this.finishNode(n,"ObjectExpression")}tsParseEntityName(n){let r;if(n&1&&this.match(78))if(n&2)r=this.parseIdentifier(!0);else{let s=this.startNode();this.next(),r=this.finishNode(s,"ThisExpression")}else r=this.parseIdentifier(!!(n&1));for(;this.eat(16);){let s=this.startNodeAtNode(r);s.left=r,s.right=this.parseIdentifier(!!(n&1)),r=this.finishNode(s,"TSQualifiedName")}return r}tsParseTypeReference(){let n=this.startNode();return n.typeName=this.tsParseEntityName(1),!this.hasPrecedingLineBreak()&&this.match(47)&&(n.typeParameters=this.tsParseTypeArguments()),this.finishNode(n,"TSTypeReference")}tsParseThisTypePredicate(n){this.next();let r=this.startNodeAtNode(n);return r.parameterName=n,r.typeAnnotation=this.tsParseTypeAnnotation(!1),r.asserts=!1,this.finishNode(r,"TSTypePredicate")}tsParseThisTypeNode(){let n=this.startNode();return this.next(),this.finishNode(n,"TSThisType")}tsParseTypeQuery(){let n=this.startNode();return this.expect(87),this.match(83)?n.exprName=this.tsParseImportType():n.exprName=this.tsParseEntityName(3),!this.hasPrecedingLineBreak()&&this.match(47)&&(n.typeParameters=this.tsParseTypeArguments()),this.finishNode(n,"TSTypeQuery")}tsParseTypeParameter(n){let r=this.startNode();return n(r),r.name=this.tsParseTypeParameterName(),r.constraint=this.tsEatThenParseType(81),r.default=this.tsEatThenParseType(29),this.finishNode(r,"TSTypeParameter")}tsTryParseTypeParameters(n){if(this.match(47))return this.tsParseTypeParameters(n)}tsParseTypeParameters(n){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,n),!1,!0,s),r.params.length===0&&this.raise(K.EmptyTypeParameters,r),s.value!==-1&&this.addExtra(r,"trailingComma",s.value),this.finishNode(r,"TSTypeParameterDeclaration")}tsFillSignature(n,r){let s=n===19,o="parameters",a="typeAnnotation";r.typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier),this.expect(10),r[o]=this.tsParseBindingListForSignature(),s?r[a]=this.tsParseTypeOrTypePredicateAnnotation(n):this.match(n)&&(r[a]=this.tsParseTypeOrTypePredicateAnnotation(n))}tsParseBindingListForSignature(){let n=super.parseBindingList(11,41,2);for(let r of n){let{type:s}=r;(s==="AssignmentPattern"||s==="TSParameterProperty")&&this.raise(K.UnsupportedSignatureParameterKind,r,{type:s})}return n}tsParseTypeMemberSemicolon(){!this.eat(12)&&!this.isLineTerminator()&&this.expect(13)}tsParseSignatureMember(n,r){return this.tsFillSignature(14,r),this.tsParseTypeMemberSemicolon(),this.finishNode(r,n)}tsIsUnambiguouslyIndexSignature(){return this.next(),ye(this.state.type)?(this.next(),this.match(14)):!1}tsTryParseIndexSignature(n){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),n.parameters=[r];let s=this.tsTryParseTypeAnnotation();return s&&(n.typeAnnotation=s),this.tsParseTypeMemberSemicolon(),this.finishNode(n,"TSIndexSignature")}tsParsePropertyOrMethodSignature(n,r){if(this.eat(17)&&(n.optional=!0),this.match(10)||this.match(47)){r&&this.raise(K.ReadonlyForMethodSignature,n);let s=n;s.kind&&this.match(47)&&this.raise(K.AccessorCannotHaveTypeParameters,this.state.curPosition()),this.tsFillSignature(14,s),this.tsParseTypeMemberSemicolon();let o="parameters",a="typeAnnotation";if(s.kind==="get")s[o].length>0&&(this.raise(_.BadGetterArity,this.state.curPosition()),this.isThisParam(s[o][0])&&this.raise(K.AccessorCannotDeclareThisParameter,this.state.curPosition()));else if(s.kind==="set"){if(s[o].length!==1)this.raise(_.BadSetterArity,this.state.curPosition());else{let d=s[o][0];this.isThisParam(d)&&this.raise(K.AccessorCannotDeclareThisParameter,this.state.curPosition()),d.type==="Identifier"&&d.optional&&this.raise(K.SetAccessorCannotHaveOptionalParameter,this.state.curPosition()),d.type==="RestElement"&&this.raise(K.SetAccessorCannotHaveRestParameter,this.state.curPosition())}s[a]&&this.raise(K.SetAccessorCannotHaveReturnType,s[a])}else s.kind="method";return this.finishNode(s,"TSMethodSignature")}else{let s=n;r&&(s.readonly=!0);let o=this.tsTryParseTypeAnnotation();return o&&(s.typeAnnotation=o),this.tsParseTypeMemberSemicolon(),this.finishNode(s,"TSPropertySignature")}}tsParseTypeMember(){let n=this.startNode();if(this.match(10)||this.match(47))return this.tsParseSignatureMember("TSCallSignatureDeclaration",n);if(this.match(77)){let s=this.startNode();return this.next(),this.match(10)||this.match(47)?this.tsParseSignatureMember("TSConstructSignatureDeclaration",n):(n.key=this.createIdentifier(s,"new"),this.tsParsePropertyOrMethodSignature(n,!1))}this.tsParseModifiers({allowedModifiers:["readonly"],disallowedModifiers:["declare","abstract","private","protected","public","static","override"]},n);let r=this.tsTryParseIndexSignature(n);return r||(super.parsePropertyName(n),!n.computed&&n.key.type==="Identifier"&&(n.key.name==="get"||n.key.name==="set")&&this.tsTokenCanFollowModifier()&&(n.kind=n.key.name,super.parsePropertyName(n),!this.match(10)&&!this.match(47)&&this.unexpected(null,10)),this.tsParsePropertyOrMethodSignature(n,!!n.readonly))}tsParseTypeLiteral(){let n=this.startNode();return n.members=this.tsParseObjectTypeMembers(),this.finishNode(n,"TSTypeLiteral")}tsParseObjectTypeMembers(){this.expect(5);let n=this.tsParseList("TypeMembers",this.tsParseTypeMember.bind(this));return this.expect(8),n}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 n=this.startNode();this.expect(5),this.match(53)?(n.readonly=this.state.value,this.next(),this.expectContextual(122)):this.eatContextual(122)&&(n.readonly=!0),this.expect(0);let r=this.startNode();return r.name=this.tsParseTypeParameterName(),r.constraint=this.tsExpectThenParseType(58),n.typeParameter=this.finishNode(r,"TSTypeParameter"),n.nameType=this.eatContextual(93)?this.tsParseType():null,this.expect(3),this.match(53)?(n.optional=this.state.value,this.next(),this.expect(17)):this.eat(17)&&(n.optional=!0),n.typeAnnotation=this.tsTryParseType(),this.semicolon(),this.expect(8),this.finishNode(n,"TSMappedType")}tsParseTupleType(){let n=this.startNode();n.elementTypes=this.tsParseBracketedList("TupleElementTypes",this.tsParseTupleElementType.bind(this),!0,!1);let r=!1;return n.elementTypes.forEach(s=>{let{type:o}=s;r&&o!=="TSRestType"&&o!=="TSOptionalType"&&!(o==="TSNamedTupleMember"&&s.optional)&&this.raise(K.OptionalTypeBeforeRequired,s),r||(r=o==="TSNamedTupleMember"&&s.optional||o==="TSOptionalType")}),this.finishNode(n,"TSTupleType")}tsParseTupleElementType(){let n=this.state.startLoc,r=this.eat(21),{startLoc:s}=this.state,o,a,d,l,u=Zt(this.state.type)?this.lookaheadCharCode():null;if(u===58)o=!0,d=!1,a=this.parseIdentifier(!0),this.expect(14),l=this.tsParseType();else if(u===63){d=!0;let p=this.state.value,f=this.tsParseNonArrayType();this.lookaheadCharCode()===58?(o=!0,a=this.createIdentifier(this.startNodeAt(s),p),this.expect(17),this.expect(14),l=this.tsParseType()):(o=!1,l=f,this.expect(17))}else l=this.tsParseType(),d=this.eat(17),o=this.eat(14);if(o){let p;a?(p=this.startNodeAt(s),p.optional=d,p.label=a,p.elementType=l,this.eat(17)&&(p.optional=!0,this.raise(K.TupleOptionalAfterType,this.state.lastTokStartLoc))):(p=this.startNodeAt(s),p.optional=d,this.raise(K.InvalidTupleMemberLabel,l),p.label=l,p.elementType=this.tsParseType()),l=this.finishNode(p,"TSNamedTupleMember")}else if(d){let p=this.startNodeAt(s);p.typeAnnotation=l,l=this.finishNode(p,"TSOptionalType")}if(r){let p=this.startNodeAt(n);p.typeAnnotation=l,l=this.finishNode(p,"TSRestType")}return l}tsParseParenthesizedType(){let n=this.startNode();return this.expect(10),n.typeAnnotation=this.tsParseType(),this.expect(11),this.finishNode(n,"TSParenthesizedType")}tsParseFunctionOrConstructorType(n,r){let s=this.startNode();return n==="TSConstructorType"&&(s.abstract=!!r,r&&this.next(),this.next()),this.tsInAllowConditionalTypesContext(()=>this.tsFillSignature(19,s)),this.finishNode(s,n)}tsParseLiteralTypeNode(){let n=this.startNode();switch(this.state.type){case 135:case 136:case 134:case 85:case 86:n.literal=super.parseExprAtom();break;default:this.unexpected()}return this.finishNode(n,"TSLiteralType")}tsParseTemplateLiteralType(){let n=this.startNode();return n.literal=super.parseTemplate(!1),this.finishNode(n,"TSLiteralType")}parseTemplateSubstitution(){return this.state.inType?this.tsParseType():super.parseTemplateSubstitution()}tsParseThisTypeOrThisTypePredicate(){let n=this.tsParseThisTypeNode();return this.isContextual(116)&&!this.hasPrecedingLineBreak()?this.tsParseThisTypePredicate(n):n}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 n=this.startNode(),r=this.lookahead();return r.type!==135&&r.type!==136&&this.unexpected(),n.literal=this.parseMaybeUnary(),this.finishNode(n,"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:n}=this.state;if(ye(n)||n===88||n===84){let r=n===88?"TSVoidKeyword":n===84?"TSNullKeyword":e$(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:n}=this.state,r=this.tsParseNonArrayType();for(;!this.hasPrecedingLineBreak()&&this.eat(0);)if(this.match(3)){let s=this.startNodeAt(n);s.elementType=r,this.expect(3),r=this.finishNode(s,"TSArrayType")}else{let s=this.startNodeAt(n);s.objectType=r,s.indexType=this.tsParseType(),this.expect(3),r=this.finishNode(s,"TSIndexedAccessType")}return r}tsParseTypeOperator(){let n=this.startNode(),r=this.state.value;return this.next(),n.operator=r,n.typeAnnotation=this.tsParseTypeOperatorOrHigher(),r==="readonly"&&this.tsCheckTypeAnnotationForReadOnly(n),this.finishNode(n,"TSTypeOperator")}tsCheckTypeAnnotationForReadOnly(n){switch(n.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(K.UnexpectedReadonly,n)}}tsParseInferType(){let n=this.startNode();this.expectContextual(115);let r=this.startNode();return r.name=this.tsParseTypeParameterName(),r.constraint=this.tsTryParse(()=>this.tsParseConstraintForInferType()),n.typeParameter=this.finishNode(r,"TSTypeParameter"),this.finishNode(n,"TSInferType")}tsParseConstraintForInferType(){if(this.eat(81)){let n=this.tsInDisallowConditionalTypesContext(()=>this.tsParseType());if(this.state.inDisallowConditionalTypesContext||!this.match(17))return n}}tsParseTypeOperatorOrHigher(){return RO(this.state.type)&&!this.state.containsEsc?this.tsParseTypeOperator():this.isContextual(115)?this.tsParseInferType():this.tsInAllowConditionalTypesContext(()=>this.tsParseArrayTypeOrHigher())}tsParseUnionOrIntersectionType(n,r,s){let o=this.startNode(),a=this.eat(s),d=[];do d.push(r());while(this.eat(s));return d.length===1&&!a?d[0]:(o.types=d,this.finishNode(o,n))}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(ye(this.state.type)||this.match(78))return this.next(),!0;if(this.match(5)){let{errors:n}=this.state,r=n.length;try{return this.parseObjectLike(8,!0),n.length===r}catch{return!1}}if(this.match(0)){this.next();let{errors:n}=this.state,r=n.length;try{return super.parseBindingList(3,93,1),n.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(n){return this.tsInType(()=>{let r=this.startNode();this.expect(n);let s=this.startNode(),o=!!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));if(o&&this.match(78)){let l=this.tsParseThisTypeOrThisTypePredicate();return l.type==="TSThisType"?(s.parameterName=l,s.asserts=!0,s.typeAnnotation=null,l=this.finishNode(s,"TSTypePredicate")):(this.resetStartLocationFromNode(l,s),l.asserts=!0),r.typeAnnotation=l,this.finishNode(r,"TSTypeAnnotation")}let a=this.tsIsIdentifier()&&this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));if(!a)return o?(s.parameterName=this.parseIdentifier(),s.asserts=o,s.typeAnnotation=null,r.typeAnnotation=this.finishNode(s,"TSTypePredicate"),this.finishNode(r,"TSTypeAnnotation")):this.tsParseTypeAnnotation(!1,r);let d=this.tsParseTypeAnnotation(!1);return s.parameterName=a,s.typeAnnotation=d,s.asserts=o,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 n=this.parseIdentifier();if(this.isContextual(116)&&!this.hasPrecedingLineBreak())return this.next(),n}tsParseTypePredicateAsserts(){if(this.state.type!==109)return!1;let n=this.state.containsEsc;return this.next(),!ye(this.state.type)&&!this.match(78)?!1:(n&&this.raise(_.InvalidEscapedReservedWord,this.state.lastTokStartLoc,{reservedWord:"asserts"}),!0)}tsParseTypeAnnotation(n=!0,r=this.startNode()){return this.tsInType(()=>{n&&this.expect(14),r.typeAnnotation=this.tsParseType()}),this.finishNode(r,"TSTypeAnnotation")}tsParseType(){ak(this.state.inType);let n=this.tsParseNonConditionalType();if(this.state.inDisallowConditionalTypesContext||this.hasPrecedingLineBreak()||!this.eat(81))return n;let r=this.startNodeAtNode(n);return r.checkType=n,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(K.ReservedTypeAssertion,this.state.startLoc);let n=this.startNode();return n.typeAnnotation=this.tsInType(()=>(this.next(),this.match(75)?this.tsParseTypeReference():this.tsParseType())),this.expect(48),n.expression=this.parseMaybeUnary(),this.finishNode(n,"TSTypeAssertion")}tsParseHeritageClause(n){let r=this.state.startLoc,s=this.tsParseDelimitedList("HeritageClauseElement",()=>{let o=this.startNode();return o.expression=this.tsParseEntityName(3),this.match(47)&&(o.typeParameters=this.tsParseTypeArguments()),this.finishNode(o,"TSExpressionWithTypeArguments")});return s.length||this.raise(K.EmptyHeritageClauseType,r,{token:n}),s}tsParseInterfaceDeclaration(n,r={}){if(this.hasFollowingLineBreak())return null;this.expectContextual(129),r.declare&&(n.declare=!0),ye(this.state.type)?(n.id=this.parseIdentifier(),this.checkIdentifier(n.id,130)):(n.id=null,this.raise(K.MissingInterfaceName,this.state.startLoc)),n.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers),this.eat(81)&&(n.extends=this.tsParseHeritageClause("extends"));let s=this.startNode();return s.body=this.tsInType(this.tsParseObjectTypeMembers.bind(this)),n.body=this.finishNode(s,"TSInterfaceBody"),this.finishNode(n,"TSInterfaceDeclaration")}tsParseTypeAliasDeclaration(n){return n.id=this.parseIdentifier(),this.checkIdentifier(n.id,2),n.typeAnnotation=this.tsInType(()=>{if(n.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(n,"TSTypeAliasDeclaration")}tsInTopLevelContext(n){if(this.curContext()!==he.brace){let r=this.state.context;this.state.context=[r[0]];try{return n()}finally{this.state.context=r}}else return n()}tsInType(n){let r=this.state.inType;this.state.inType=!0;try{return n()}finally{this.state.inType=r}}tsInDisallowConditionalTypesContext(n){let r=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!0;try{return n()}finally{this.state.inDisallowConditionalTypesContext=r}}tsInAllowConditionalTypesContext(n){let r=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!1;try{return n()}finally{this.state.inDisallowConditionalTypesContext=r}}tsEatThenParseType(n){if(this.match(n))return this.tsNextThenParseType()}tsExpectThenParseType(n){return this.tsInType(()=>(this.expect(n),this.tsParseType()))}tsNextThenParseType(){return this.tsInType(()=>(this.next(),this.tsParseType()))}tsParseEnumMember(){let n=this.startNode();return n.id=this.match(134)?super.parseStringLiteral(this.state.value):this.parseIdentifier(!0),this.eat(29)&&(n.initializer=super.parseMaybeAssignAllowIn()),this.finishNode(n,"TSEnumMember")}tsParseEnumDeclaration(n,r={}){return r.const&&(n.const=!0),r.declare&&(n.declare=!0),this.expectContextual(126),n.id=this.parseIdentifier(),this.checkIdentifier(n.id,n.const?8971:8459),this.expect(5),n.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(8),this.finishNode(n,"TSEnumDeclaration")}tsParseEnumBody(){let n=this.startNode();return this.expect(5),n.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(8),this.finishNode(n,"TSEnumBody")}tsParseModuleBlock(){let n=this.startNode();return this.scope.enter(0),this.expect(5),super.parseBlockOrModuleBlockBody(n.body=[],void 0,!0,8),this.scope.exit(),this.finishNode(n,"TSModuleBlock")}tsParseModuleOrNamespaceDeclaration(n,r=!1){if(n.id=this.parseIdentifier(),r||this.checkIdentifier(n.id,1024),this.eat(16)){let s=this.startNode();this.tsParseModuleOrNamespaceDeclaration(s,!0),n.body=s}else this.scope.enter(1024),this.prodParam.enter(0),n.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit();return this.finishNode(n,"TSModuleDeclaration")}tsParseAmbientExternalModuleDeclaration(n){return this.isContextual(112)?(n.kind="global",n.global=!0,n.id=this.parseIdentifier()):this.match(134)?(n.kind="module",n.id=super.parseStringLiteral(this.state.value)):this.unexpected(),this.match(5)?(this.scope.enter(1024),this.prodParam.enter(0),n.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit()):this.semicolon(),this.finishNode(n,"TSModuleDeclaration")}tsParseImportEqualsDeclaration(n,r,s){n.isExport=s||!1,n.id=r||this.parseIdentifier(),this.checkIdentifier(n.id,4096),this.expect(29);let o=this.tsParseModuleReference();return n.importKind==="type"&&o.type!=="TSExternalModuleReference"&&this.raise(K.ImportAliasHasImportType,o),n.moduleReference=o,this.semicolon(),this.finishNode(n,"TSImportEqualsDeclaration")}tsIsExternalModuleReference(){return this.isContextual(119)&&this.lookaheadCharCode()===40}tsParseModuleReference(){return this.tsIsExternalModuleReference()?this.tsParseExternalModuleReference():this.tsParseEntityName(0)}tsParseExternalModuleReference(){let n=this.startNode();return this.expectContextual(119),this.expect(10),this.match(134)||this.unexpected(),n.expression=super.parseExprAtom(),this.expect(11),this.sawUnambiguousESM=!0,this.finishNode(n,"TSExternalModuleReference")}tsLookAhead(n){let r=this.state.clone(),s=n();return this.state=r,s}tsTryParseAndCatch(n){let r=this.tryParse(s=>n()||s());if(!(r.aborted||!r.node))return r.error&&(this.state=r.failState),r.node}tsTryParse(n){let r=this.state.clone(),s=n();if(s!==void 0&&s!==!1)return s;this.state=r}tsTryParseDeclare(n){if(this.isLineTerminator())return;let r=this.state.type;return this.tsInAmbientContext(()=>{switch(r){case 68:return n.declare=!0,super.parseFunctionStatement(n,!1,!1);case 80:return n.declare=!0,this.parseClass(n,!0,!1);case 126:return this.tsParseEnumDeclaration(n,{declare:!0});case 112:return this.tsParseAmbientExternalModuleDeclaration(n);case 100:if(this.state.containsEsc)return;case 75:case 74:return!this.match(75)||!this.isLookaheadContextual("enum")?(n.declare=!0,this.parseVarStatement(n,this.state.value,!0)):(this.expect(75),this.tsParseEnumDeclaration(n,{const:!0,declare:!0}));case 107:if(this.isUsing())return this.raise(K.InvalidModifierOnUsingDeclaration,this.state.startLoc,"declare"),n.declare=!0,this.parseVarStatement(n,"using",!0);break;case 96:if(this.isAwaitUsing())return this.raise(K.InvalidModifierOnAwaitUsingDeclaration,this.state.startLoc,"declare"),n.declare=!0,this.next(),this.parseVarStatement(n,"await using",!0);break;case 129:{let s=this.tsParseInterfaceDeclaration(n,{declare:!0});if(s)return s}default:if(ye(r))return this.tsParseDeclaration(n,this.state.type,!0,null)}})}tsTryParseExportDeclaration(){return this.tsParseDeclaration(this.startNode(),this.state.type,!0,null)}tsParseDeclaration(n,r,s,o){switch(r){case 124:if(this.tsCheckLineTerminator(s)&&(this.match(80)||ye(this.state.type)))return this.tsParseAbstractDeclaration(n,o);break;case 127:if(this.tsCheckLineTerminator(s)){if(this.match(134))return this.tsParseAmbientExternalModuleDeclaration(n);if(ye(this.state.type))return n.kind="module",this.tsParseModuleOrNamespaceDeclaration(n)}break;case 128:if(this.tsCheckLineTerminator(s)&&ye(this.state.type))return n.kind="namespace",this.tsParseModuleOrNamespaceDeclaration(n);break;case 130:if(this.tsCheckLineTerminator(s)&&ye(this.state.type))return this.tsParseTypeAliasDeclaration(n);break}}tsCheckLineTerminator(n){return n?this.hasFollowingLineBreak()?!1:(this.next(),!0):!this.isLineTerminator()}tsTryParseGenericAsyncArrowFunction(n){if(!this.match(47))return;let r=this.state.maybeInArrowParameters;this.state.maybeInArrowParameters=!0;let s=this.tsTryParseAndCatch(()=>{let o=this.startNodeAt(n);return o.typeParameters=this.tsParseTypeParameters(this.tsParseConstModifier),super.parseFunctionParams(o),o.returnType=this.tsTryParseTypeOrTypePredicateAnnotation(),this.expect(19),o});if(this.state.maybeInArrowParameters=r,!!s)return super.parseArrowExpression(s,null,!0)}tsParseTypeArgumentsInExpression(){if(this.reScan_lt()===47)return this.tsParseTypeArguments()}tsParseTypeArguments(){let n=this.startNode();return n.params=this.tsInType(()=>this.tsInTopLevelContext(()=>(this.expect(47),this.tsParseDelimitedList("TypeParametersOrArguments",this.tsParseType.bind(this))))),n.params.length===0?this.raise(K.EmptyTypeArguments,n):!this.state.inType&&this.curContext()===he.brace&&this.reScan_lt_gt(),this.expect(48),this.finishNode(n,"TSTypeParameterInstantiation")}tsIsDeclarationStart(){return xO(this.state.type)}isExportDefaultSpecifier(){return this.tsIsDeclarationStart()?!1:super.isExportDefaultSpecifier()}parseBindingElement(n,r){let s=r.length?r[0].loc.start:this.state.startLoc,o={};this.tsParseModifiers({allowedModifiers:["public","private","protected","override","readonly"]},o);let a=o.accessibility,d=o.override,l=o.readonly;!(n&4)&&(a||l||d)&&this.raise(K.UnexpectedParameterModifier,s);let c=this.parseMaybeDefault();n&2&&this.parseFunctionParamType(c);let u=this.parseMaybeDefault(c.loc.start,c);if(a||l||d){let p=this.startNodeAt(s);return r.length&&(p.decorators=r),a&&(p.accessibility=a),l&&(p.readonly=l),d&&(p.override=d),u.type!=="Identifier"&&u.type!=="AssignmentPattern"&&this.raise(K.UnsupportedParameterPropertyKind,p),p.parameter=u,this.finishNode(p,"TSParameterProperty")}return r.length&&(c.decorators=r),u}isSimpleParameter(n){return n.type==="TSParameterProperty"&&super.isSimpleParameter(n.parameter)||super.isSimpleParameter(n)}tsDisallowOptionalPattern(n){for(let r of n.params)r.type!=="Identifier"&&r.optional&&!this.state.isAmbientContext&&this.raise(K.PatternIsOptional,r)}setArrowFunctionParameters(n,r,s){super.setArrowFunctionParameters(n,r,s),this.tsDisallowOptionalPattern(n)}parseFunctionBodyAndFinish(n,r,s=!1){this.match(14)&&(n.returnType=this.tsParseTypeOrTypePredicateAnnotation(14));let o=r==="FunctionDeclaration"?"TSDeclareFunction":r==="ClassMethod"||r==="ClassPrivateMethod"?"TSDeclareMethod":void 0;return o&&!this.match(5)&&this.isLineTerminator()?this.finishNode(n,o):o==="TSDeclareFunction"&&this.state.isAmbientContext&&(this.raise(K.DeclareFunctionHasImplementation,n),n.declare)?super.parseFunctionBodyAndFinish(n,o,s):(this.tsDisallowOptionalPattern(n),super.parseFunctionBodyAndFinish(n,r,s))}registerFunctionStatementId(n){!n.body&&n.id?this.checkIdentifier(n.id,1024):super.registerFunctionStatementId(n)}tsCheckForInvalidTypeCasts(n){n.forEach(r=>{r?.type==="TSTypeCastExpression"&&this.raise(K.UnexpectedTypeAnnotation,r.typeAnnotation)})}toReferencedList(n,r){return this.tsCheckForInvalidTypeCasts(n),n}parseArrayLike(n,r,s){let o=super.parseArrayLike(n,r,s);return o.type==="ArrayExpression"&&this.tsCheckForInvalidTypeCasts(o.elements),o}parseSubscript(n,r,s,o){if(!this.hasPrecedingLineBreak()&&this.match(35)){this.state.canStartJSXElement=!1,this.next();let d=this.startNodeAt(r);return d.expression=n,this.finishNode(d,"TSNonNullExpression")}let a=!1;if(this.match(18)&&this.lookaheadCharCode()===60){if(s)return o.stop=!0,n;o.optionalChainMember=a=!0,this.next()}if(this.match(47)||this.match(51)){let d,l=this.tsTryParseAndCatch(()=>{if(!s&&this.atPossibleAsyncArrow(n)){let f=this.tsTryParseGenericAsyncArrowFunction(r);if(f)return o.stop=!0,f}let c=this.tsParseTypeArgumentsInExpression();if(!c)return;if(a&&!this.match(10)){d=this.state.curPosition();return}if(Ml(this.state.type)){let f=super.parseTaggedTemplateExpression(n,r,o);return f.typeParameters=c,f}if(!s&&this.eat(10)){let f=this.startNodeAt(r);return f.callee=n,f.arguments=this.parseCallExpressionArguments(),this.tsCheckForInvalidTypeCasts(f.arguments),f.typeParameters=c,o.optionalChainMember&&(f.optional=a),this.finishCallExpression(f,o.optionalChainMember)}let u=this.state.type;if(u===48||u===52||u!==10&&u!==93&&u!==120&&ea(u)&&!this.hasPrecedingLineBreak())return;let p=this.startNodeAt(r);return p.expression=n,p.typeParameters=c,this.finishNode(p,"TSInstantiationExpression")});if(d&&this.unexpected(d,10),l)return l.type==="TSInstantiationExpression"&&((this.match(16)||this.match(18)&&this.lookaheadCharCode()!==40)&&this.raise(K.InvalidPropertyAccessAfterInstantiationExpression,this.state.startLoc),!this.match(16)&&!this.match(18)&&(l.expression=super.stopParseSubscript(n,o))),l}return super.parseSubscript(n,r,s,o)}parseNewCallee(n){var r;super.parseNewCallee(n);let{callee:s}=n;s.type==="TSInstantiationExpression"&&!((r=s.extra)!=null&&r.parenthesized)&&(n.typeParameters=s.typeParameters,n.callee=s.expression)}parseExprOp(n,r,s){let o;if(Nl(58)>s&&!this.hasPrecedingLineBreak()&&(this.isContextual(93)||(o=this.isContextual(120)))){let a=this.startNodeAt(r);return a.expression=n,a.typeAnnotation=this.tsInType(()=>(this.next(),this.match(75)?(o&&this.raise(_.UnexpectedKeyword,this.state.startLoc,{keyword:"const"}),this.tsParseTypeReference()):this.tsParseType())),this.finishNode(a,o?"TSSatisfiesExpression":"TSAsExpression"),this.reScan_lt_gt(),this.parseExprOp(a,r,s)}return super.parseExprOp(n,r,s)}checkReservedWord(n,r,s,o){this.state.isAmbientContext||super.checkReservedWord(n,r,s,o)}checkImportReflection(n){super.checkImportReflection(n),n.module&&n.importKind!=="value"&&this.raise(K.ImportReflectionHasImportType,n.specifiers[0].loc.start)}checkDuplicateExports(){}isPotentialImportPhase(n){if(super.isPotentialImportPhase(n))return!0;if(this.isContextual(130)){let r=this.lookaheadCharCode();return n?r===123||r===42:r!==61}return!n&&this.isContextual(87)}applyImportPhase(n,r,s,o){super.applyImportPhase(n,r,s,o),r?n.exportKind=s==="type"?"type":"value":n.importKind=s==="type"||s==="typeof"?s:"value"}parseImport(n){if(this.match(134))return n.importKind="value",super.parseImport(n);let r;if(ye(this.state.type)&&this.lookaheadCharCode()===61)return n.importKind="value",this.tsParseImportEqualsDeclaration(n);if(this.isContextual(130)){let s=this.parseMaybeImportPhase(n,!1);if(this.lookaheadCharCode()===61)return this.tsParseImportEqualsDeclaration(n,s);r=super.parseImportSpecifiersAndAfter(n,s)}else r=super.parseImport(n);return r.importKind==="type"&&r.specifiers.length>1&&r.specifiers[0].type==="ImportDefaultSpecifier"&&this.raise(K.TypeImportCannotSpecifyDefaultAndNamed,r),r}parseExport(n,r){if(this.match(83)){let s=n;this.next();let o=null;return this.isContextual(130)&&this.isPotentialImportPhase(!1)?o=this.parseMaybeImportPhase(s,!1):s.importKind="value",this.tsParseImportEqualsDeclaration(s,o,!0)}else if(this.eat(29)){let s=n;return s.expression=super.parseExpression(),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(s,"TSExportAssignment")}else if(this.eatContextual(93)){let s=n;return this.expectContextual(128),s.id=this.parseIdentifier(),this.semicolon(),this.finishNode(s,"TSNamespaceExportDeclaration")}else return super.parseExport(n,r)}isAbstractClass(){return this.isContextual(124)&&this.isLookaheadContextual("class")}parseExportDefaultExpression(){if(this.isAbstractClass()){let n=this.startNode();return this.next(),n.abstract=!0,this.parseClass(n,!0,!0)}if(this.match(129)){let n=this.tsParseInterfaceDeclaration(this.startNode());if(n)return n}return super.parseExportDefaultExpression()}parseVarStatement(n,r,s=!1){let{isAmbientContext:o}=this.state,a=super.parseVarStatement(n,r,s||o);if(!o)return a;if(!n.declare&&(r==="using"||r==="await using"))return this.raiseOverwrite(K.UsingDeclarationInAmbientContext,n,r),a;for(let{id:d,init:l}of a.declarations)l&&(r==="var"||r==="let"||d.typeAnnotation?this.raise(K.InitializerNotAllowedInAmbientContext,l):i$(l,this.hasPlugin("estree"))||this.raise(K.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference,l));return a}parseStatementContent(n,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,o=this.startNode();this.next();let a=s===125?this.tsTryParseDeclare(o):this.tsParseAbstractDeclaration(o,r);return a?(s===125&&(a.declare=!0),a):(o.expression=this.createIdentifier(this.startNodeAt(o.loc.start),s===125?"declare":"abstract"),this.semicolon(!1),this.finishNode(o,"ExpressionStatement"))}break}case 126:return this.tsParseEnumDeclaration(this.startNode());case 112:{if(this.lookaheadCharCode()===123){let o=this.startNode();return this.tsParseAmbientExternalModuleDeclaration(o)}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(n,r)}parseAccessModifier(){return this.tsParseModifier(["public","protected","private"])}tsHasSomeModifiers(n,r){return r.some(s=>dk(s)?n.accessibility===s:!!n[s])}tsIsStartOfStaticBlocks(){return this.isContextual(106)&&this.lookaheadCharCode()===123}parseClassMember(n,r,s){let o=["declare","private","public","protected","override","abstract","readonly","static"];this.tsParseModifiers({allowedModifiers:o,disallowedModifiers:["in","out"],stopOnStartOfClassStaticBlock:!0,errorTemplate:K.InvalidModifierOnTypeParameterPositions},r);let a=()=>{this.tsIsStartOfStaticBlocks()?(this.next(),this.next(),this.tsHasSomeModifiers(r,o)&&this.raise(K.StaticBlockCannotHaveModifier,this.state.curPosition()),super.parseClassStaticBlock(n,r)):this.parseClassMemberWithIsStatic(n,r,s,!!r.static)};r.declare?this.tsInAmbientContext(a):a()}parseClassMemberWithIsStatic(n,r,s,o){let a=this.tsTryParseIndexSignature(r);if(a){n.body.push(a),r.abstract&&this.raise(K.IndexSignatureHasAbstract,r),r.accessibility&&this.raise(K.IndexSignatureHasAccessibility,r,{modifier:r.accessibility}),r.declare&&this.raise(K.IndexSignatureHasDeclare,r),r.override&&this.raise(K.IndexSignatureHasOverride,r);return}!this.state.inAbstractClass&&r.abstract&&this.raise(K.NonAbstractClassHasAbstractMethod,r),r.override&&(s.hadSuperClass||this.raise(K.OverrideNotInSubClass,r)),super.parseClassMemberWithIsStatic(n,r,s,o)}parsePostMemberNameModifiers(n){this.eat(17)&&(n.optional=!0),n.readonly&&this.match(10)&&this.raise(K.ClassMethodHasReadonly,n),n.declare&&this.match(10)&&this.raise(K.ClassMethodHasDeclare,n)}shouldParseExportDeclaration(){return this.tsIsDeclarationStart()?!0:super.shouldParseExportDeclaration()}parseConditional(n,r,s){if(!this.match(17))return n;if(this.state.maybeInArrowParameters){let o=this.lookaheadCharCode();if(o===44||o===61||o===58||o===41)return this.setOptionalParametersError(s),n}return super.parseConditional(n,r,s)}parseParenItem(n,r){let s=super.parseParenItem(n,r);if(this.eat(17)&&(s.optional=!0,this.resetEndLocation(n)),this.match(14)){let o=this.startNodeAt(r);return o.expression=n,o.typeAnnotation=this.tsParseTypeAnnotation(),this.finishNode(o,"TSTypeCastExpression")}return n}parseExportDeclaration(n){if(!this.state.isAmbientContext&&this.isContextual(125))return this.tsInAmbientContext(()=>this.parseExportDeclaration(n));let r=this.state.startLoc,s=this.eatContextual(125);if(s&&(this.isContextual(125)||!this.shouldParseExportDeclaration()))throw this.raise(K.ExpectedAmbientAfterExportDeclare,this.state.startLoc);let a=ye(this.state.type)&&this.tsTryParseExportDeclaration()||super.parseExportDeclaration(n);return a?((a.type==="TSInterfaceDeclaration"||a.type==="TSTypeAliasDeclaration"||s)&&(n.exportKind="type"),s&&a.type!=="TSImportEqualsDeclaration"&&(this.resetStartLocation(a,r),a.declare=!0),a):null}parseClassId(n,r,s,o){if((!r||s)&&this.isContextual(113))return;super.parseClassId(n,r,s,n.declare?1024:8331);let a=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);a&&(n.typeParameters=a)}parseClassPropertyAnnotation(n){n.optional||(this.eat(35)?n.definite=!0:this.eat(17)&&(n.optional=!0));let r=this.tsTryParseTypeAnnotation();r&&(n.typeAnnotation=r)}parseClassProperty(n){if(this.parseClassPropertyAnnotation(n),this.state.isAmbientContext&&!(n.readonly&&!n.typeAnnotation)&&this.match(29)&&this.raise(K.DeclareClassFieldHasInitializer,this.state.startLoc),n.abstract&&this.match(29)){let{key:r}=n;this.raise(K.AbstractPropertyHasInitializer,this.state.startLoc,{propertyName:r.type==="Identifier"&&!n.computed?r.name:`[${this.input.slice(this.offsetToSourcePos(r.start),this.offsetToSourcePos(r.end))}]`})}return super.parseClassProperty(n)}parseClassPrivateProperty(n){return n.abstract&&this.raise(K.PrivateElementHasAbstract,n),n.accessibility&&this.raise(K.PrivateElementHasAccessibility,n,{modifier:n.accessibility}),this.parseClassPropertyAnnotation(n),super.parseClassPrivateProperty(n)}parseClassAccessorProperty(n){return this.parseClassPropertyAnnotation(n),n.optional&&this.raise(K.AccessorCannotBeOptional,n),super.parseClassAccessorProperty(n)}pushClassMethod(n,r,s,o,a,d){let l=this.tsTryParseTypeParameters(this.tsParseConstModifier);l&&a&&this.raise(K.ConstructorHasTypeParameters,l);let{declare:c=!1,kind:u}=r;c&&(u==="get"||u==="set")&&this.raise(K.DeclareAccessor,r,{kind:u}),l&&(r.typeParameters=l),super.pushClassMethod(n,r,s,o,a,d)}pushClassPrivateMethod(n,r,s,o){let a=this.tsTryParseTypeParameters(this.tsParseConstModifier);a&&(r.typeParameters=a),super.pushClassPrivateMethod(n,r,s,o)}declareClassPrivateMethodInScope(n,r){n.type!=="TSDeclareMethod"&&(n.type==="MethodDefinition"&&n.value.body==null||super.declareClassPrivateMethodInScope(n,r))}parseClassSuper(n){if(super.parseClassSuper(n),n.superClass)if(n.superClass.type==="TSInstantiationExpression"){let r=n.superClass,s=r.expression;this.takeSurroundingComments(s,s.start,s.end);let o=r.typeParameters;this.takeSurroundingComments(o,o.start,o.end),n.superClass=s,n.superTypeParameters=o}else(this.match(47)||this.match(51))&&(n.superTypeParameters=this.tsParseTypeArgumentsInExpression());this.eatContextual(113)&&(n.implements=this.tsParseHeritageClause("implements"))}parseObjPropValue(n,r,s,o,a,d,l){let c=this.tsTryParseTypeParameters(this.tsParseConstModifier);return c&&(n.typeParameters=c),super.parseObjPropValue(n,r,s,o,a,d,l)}parseFunctionParams(n,r){let s=this.tsTryParseTypeParameters(this.tsParseConstModifier);s&&(n.typeParameters=s),super.parseFunctionParams(n,r)}parseVarId(n,r){super.parseVarId(n,r),n.id.type==="Identifier"&&!this.hasPrecedingLineBreak()&&this.eat(35)&&(n.definite=!0);let s=this.tsTryParseTypeAnnotation();s&&(n.id.typeAnnotation=s,this.resetEndLocation(n.id))}parseAsyncArrowFromCallExpression(n,r){return this.match(14)&&(n.returnType=this.tsParseTypeAnnotation()),super.parseAsyncArrowFromCallExpression(n,r)}parseMaybeAssign(n,r){var s,o,a,d,l;let c,u,p;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){if(c=this.state.clone(),u=this.tryParse(()=>super.parseMaybeAssign(n,r),c),!u.error)return u.node;let{context:h}=this.state,g=h[h.length-1];(g===he.j_oTag||g===he.j_expr)&&h.pop()}if(!((s=u)!=null&&s.error)&&!this.match(47))return super.parseMaybeAssign(n,r);(!c||c===this.state)&&(c=this.state.clone());let f,m=this.tryParse(h=>{var g,y;f=this.tsParseTypeParameters(this.tsParseConstModifier);let w=super.parseMaybeAssign(n,r);return(w.type!=="ArrowFunctionExpression"||(g=w.extra)!=null&&g.parenthesized)&&h(),((y=f)==null?void 0:y.params.length)!==0&&this.resetStartLocationFromNode(w,f),w.typeParameters=f,w},c);if(!m.error&&!m.aborted)return f&&this.reportReservedArrowTypeParam(f),m.node;if(!u&&(ak(!this.hasPlugin("jsx")),p=this.tryParse(()=>super.parseMaybeAssign(n,r),c),!p.error))return p.node;if((o=u)!=null&&o.node)return this.state=u.failState,u.node;if(m.node)return this.state=m.failState,f&&this.reportReservedArrowTypeParam(f),m.node;if((a=p)!=null&&a.node)return this.state=p.failState,p.node;throw((d=u)==null?void 0:d.error)||m.error||((l=p)==null?void 0:l.error)}reportReservedArrowTypeParam(n){var r;n.params.length===1&&!n.params[0].constraint&&!((r=n.extra)!=null&&r.trailingComma)&&this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(K.ReservedArrowTypeParam,n)}parseMaybeUnary(n,r){return!this.hasPlugin("jsx")&&this.match(47)?this.tsParseTypeAssertion():super.parseMaybeUnary(n,r)}parseArrow(n){if(this.match(14)){let r=this.tryParse(s=>{let o=this.tsParseTypeOrTypePredicateAnnotation(14);return(this.canInsertSemicolon()||!this.match(19))&&s(),o});if(r.aborted)return;r.thrown||(r.error&&(this.state=r.failState),n.returnType=r.node)}return super.parseArrow(n)}parseFunctionParamType(n){this.eat(17)&&(n.optional=!0);let r=this.tsTryParseTypeAnnotation();return r&&(n.typeAnnotation=r),this.resetEndLocation(n),n}isAssignable(n,r){switch(n.type){case"TSTypeCastExpression":return this.isAssignable(n.expression,r);case"TSParameterProperty":return!0;default:return super.isAssignable(n,r)}}toAssignable(n,r=!1){switch(n.type){case"ParenthesizedExpression":this.toAssignableParenthesizedExpression(n,r);break;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":r?this.expressionScope.recordArrowParameterBindingError(K.UnexpectedTypeCastInParameter,n):this.raise(K.UnexpectedTypeCastInParameter,n),this.toAssignable(n.expression,r);break;case"AssignmentExpression":!r&&n.left.type==="TSTypeCastExpression"&&(n.left=this.typeCastToParameter(n.left));default:super.toAssignable(n,r)}}toAssignableParenthesizedExpression(n,r){switch(n.expression.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":case"ParenthesizedExpression":this.toAssignable(n.expression,r);break;default:super.toAssignable(n,r)}}checkToRestConversion(n,r){switch(n.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":this.checkToRestConversion(n.expression,!1);break;default:super.checkToRestConversion(n,r)}}isValidLVal(n,r,s,o){switch(n){case"TSTypeCastExpression":return!0;case"TSParameterProperty":return"parameter";case"TSNonNullExpression":return"expression";case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":return(o!==64||!s)&&["expression",!0];default:return super.isValidLVal(n,r,s,o)}}parseBindingAtom(){return this.state.type===78?this.parseIdentifier(!0):super.parseBindingAtom()}parseMaybeDecoratorArguments(n,r){if(this.match(47)||this.match(51)){let s=this.tsParseTypeArgumentsInExpression();if(this.match(10)){let o=super.parseMaybeDecoratorArguments(n,r);return o.typeParameters=s,o}this.unexpected(null,10)}return super.parseMaybeDecoratorArguments(n,r)}checkCommaAfterRest(n){return this.state.isAmbientContext&&this.match(12)&&this.lookaheadCharCode()===n?(this.next(),!1):super.checkCommaAfterRest(n)}isClassMethod(){return this.match(47)||super.isClassMethod()}isClassProperty(){return this.match(35)||this.match(14)||super.isClassProperty()}parseMaybeDefault(n,r){let s=super.parseMaybeDefault(n,r);return s.type==="AssignmentPattern"&&s.typeAnnotation&&s.right.start<s.typeAnnotation.start&&this.raise(K.TypeAnnotationAfterAssign,s.typeAnnotation),s}getTokenFromCode(n){if(this.state.inType){if(n===62){this.finishOp(48,1);return}if(n===60){this.finishOp(47,1);return}}super.getTokenFromCode(n)}reScan_lt_gt(){let{type:n}=this.state;n===47?(this.state.pos-=1,this.readToken_lt()):n===48&&(this.state.pos-=1,this.readToken_gt())}reScan_lt(){let{type:n}=this.state;return n===51?(this.state.pos-=2,this.finishOp(47,1),47):n}toAssignableListItem(n,r,s){let o=n[r];o.type==="TSTypeCastExpression"&&(n[r]=this.typeCastToParameter(o)),super.toAssignableListItem(n,r,s)}typeCastToParameter(n){return n.expression.typeAnnotation=n.typeAnnotation,this.resetEndLocation(n.expression,n.typeAnnotation.loc.end),n.expression}shouldParseArrow(n){return this.match(14)?n.every(r=>this.isAssignable(r,!0)):super.shouldParseArrow(n)}shouldParseAsyncArrow(){return this.match(14)||super.shouldParseAsyncArrow()}canHaveLeadingDecorator(){return super.canHaveLeadingDecorator()||this.isAbstractClass()}jsxParseOpeningElementAfterName(n){if(this.match(47)||this.match(51)){let r=this.tsTryParseAndCatch(()=>this.tsParseTypeArgumentsInExpression());r&&(n.typeParameters=r)}return super.jsxParseOpeningElementAfterName(n)}getGetterSetterExpectedParamCount(n){let r=super.getGetterSetterExpectedParamCount(n),o=this.getObjectOrClassMethodParams(n)[0];return o&&this.isThisParam(o)?r+1:r}parseCatchClauseParam(){let n=super.parseCatchClauseParam(),r=this.tsTryParseTypeAnnotation();return r&&(n.typeAnnotation=r,this.resetEndLocation(n)),n}tsInAmbientContext(n){let{isAmbientContext:r,strict:s}=this.state;this.state.isAmbientContext=!0,this.state.strict=!1;try{return n()}finally{this.state.isAmbientContext=r,this.state.strict=s}}parseClass(n,r,s){let o=this.state.inAbstractClass;this.state.inAbstractClass=!!n.abstract;try{return super.parseClass(n,r,s)}finally{this.state.inAbstractClass=o}}tsParseAbstractDeclaration(n,r){if(this.match(80))return n.abstract=!0,this.maybeTakeDecorators(r,this.parseClass(n,!0,!1));if(this.isContextual(129))return this.hasFollowingLineBreak()?null:(n.abstract=!0,this.raise(K.NonClassMethodPropertyHasAbstractModifier,n),this.tsParseInterfaceDeclaration(n));throw this.unexpected(null,80)}parseMethod(n,r,s,o,a,d,l){let c=super.parseMethod(n,r,s,o,a,d,l);if((c.abstract||c.type==="TSAbstractMethodDefinition")&&(this.hasPlugin("estree")?c.value:c).body){let{key:f}=c;this.raise(K.AbstractMethodHasImplementation,c,{methodName:f.type==="Identifier"&&!c.computed?f.name:`[${this.input.slice(this.offsetToSourcePos(f.start),this.offsetToSourcePos(f.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(n,r,s,o){return!r&&o?(this.parseTypeOnlyImportExportSpecifier(n,!1,s),this.finishNode(n,"ExportSpecifier")):(n.exportKind="value",super.parseExportSpecifier(n,r,s,o))}parseImportSpecifier(n,r,s,o,a){return!r&&o?(this.parseTypeOnlyImportExportSpecifier(n,!0,s),this.finishNode(n,"ImportSpecifier")):(n.importKind="value",super.parseImportSpecifier(n,r,s,o,s?4098:4096))}parseTypeOnlyImportExportSpecifier(n,r,s){let o=r?"imported":"local",a=r?"local":"exported",d=n[o],l,c=!1,u=!0,p=d.loc.start;if(this.isContextual(93)){let m=this.parseIdentifier();if(this.isContextual(93)){let h=this.parseIdentifier();Zt(this.state.type)?(c=!0,d=m,l=r?this.parseIdentifier():this.parseModuleExportName(),u=!1):(l=h,u=!1)}else Zt(this.state.type)?(u=!1,l=r?this.parseIdentifier():this.parseModuleExportName()):(c=!0,d=m)}else Zt(this.state.type)&&(c=!0,r?(d=this.parseIdentifier(!0),this.isContextual(93)||this.checkReservedWord(d.name,d.loc.start,!0,!0)):d=this.parseModuleExportName());c&&s&&this.raise(r?K.TypeModifierIsUsedInTypeImports:K.TypeModifierIsUsedInTypeExports,p),n[o]=d,n[a]=l;let f=r?"importKind":"exportKind";n[f]=c?"type":"value",u&&this.eatContextual(93)&&(n[a]=r?this.parseIdentifier():this.parseModuleExportName()),n[a]||(n[a]=this.cloneIdentifier(n[o])),r&&this.checkIdentifier(n[a],c?4098:4096)}fillOptionalPropertiesForTSESLint(n){var r,s,o,a,d,l,c,u,p,f,m,h,g,y,w,b,v,R,x,T,N,U,F,I,C,A,M,$,j,O,P,E,L,B,Z,te,D,ne,Ae,vt,fn,Et,Bn,$e,qt,Ct,_o,Cb,Nb;switch(n.type){case"ImportDeclaration":(r=n.phase)!=null||(n.phase=null);return;case"ExpressionStatement":(s=n.directive)!=null||(n.directive=void 0);return;case"RestElement":n.value=void 0;case"Identifier":case"ArrayPattern":case"AssignmentPattern":case"ObjectPattern":(o=n.decorators)!=null||(n.decorators=[]),(a=n.optional)!=null||(n.optional=!1),(d=n.typeAnnotation)!=null||(n.typeAnnotation=void 0);return;case"TSParameterProperty":(l=n.accessibility)!=null||(n.accessibility=void 0),(c=n.decorators)!=null||(n.decorators=[]),(u=n.override)!=null||(n.override=!1),(p=n.readonly)!=null||(n.readonly=!1),(f=n.static)!=null||(n.static=!1);return;case"TSEmptyBodyFunctionExpression":n.body=null;case"TSDeclareFunction":case"FunctionDeclaration":case"FunctionExpression":case"ClassMethod":case"ClassPrivateMethod":(m=n.declare)!=null||(n.declare=!1),(h=n.returnType)!=null||(n.returnType=void 0),(g=n.typeParameters)!=null||(n.typeParameters=void 0);return;case"Property":(y=n.optional)!=null||(n.optional=!1);return;case"TSMethodSignature":case"TSPropertySignature":(w=n.optional)!=null||(n.optional=!1);case"TSIndexSignature":(b=n.accessibility)!=null||(n.accessibility=void 0),(v=n.readonly)!=null||(n.readonly=!1),(R=n.static)!=null||(n.static=!1);return;case"TSAbstractPropertyDefinition":case"PropertyDefinition":case"TSAbstractAccessorProperty":case"AccessorProperty":(x=n.declare)!=null||(n.declare=!1),(T=n.definite)!=null||(n.definite=!1),(N=n.readonly)!=null||(n.readonly=!1),(U=n.typeAnnotation)!=null||(n.typeAnnotation=void 0);case"TSAbstractMethodDefinition":case"MethodDefinition":(F=n.accessibility)!=null||(n.accessibility=void 0),(I=n.decorators)!=null||(n.decorators=[]),(C=n.override)!=null||(n.override=!1),(A=n.optional)!=null||(n.optional=!1);return;case"ClassExpression":(M=n.id)!=null||(n.id=null);case"ClassDeclaration":($=n.abstract)!=null||(n.abstract=!1),(j=n.declare)!=null||(n.declare=!1),(O=n.decorators)!=null||(n.decorators=[]),(P=n.implements)!=null||(n.implements=[]),(E=n.superTypeArguments)!=null||(n.superTypeArguments=void 0),(L=n.typeParameters)!=null||(n.typeParameters=void 0);return;case"TSTypeAliasDeclaration":case"VariableDeclaration":(B=n.declare)!=null||(n.declare=!1);return;case"VariableDeclarator":(Z=n.definite)!=null||(n.definite=!1);return;case"TSEnumDeclaration":(te=n.const)!=null||(n.const=!1),(D=n.declare)!=null||(n.declare=!1);return;case"TSEnumMember":(ne=n.computed)!=null||(n.computed=!1);return;case"TSImportType":(Ae=n.qualifier)!=null||(n.qualifier=null),(vt=n.options)!=null||(n.options=null);return;case"TSInterfaceDeclaration":(fn=n.declare)!=null||(n.declare=!1),(Et=n.extends)!=null||(n.extends=[]);return;case"TSMappedType":(Bn=n.optional)!=null||(n.optional=!1),($e=n.readonly)!=null||(n.readonly=void 0);return;case"TSModuleDeclaration":(qt=n.declare)!=null||(n.declare=!1),(Ct=n.global)!=null||(n.global=n.kind==="global");return;case"TSTypeParameter":(_o=n.const)!=null||(n.const=!1),(Cb=n.in)!=null||(n.in=!1),(Nb=n.out)!=null||(n.out=!1);return}}chStartsBindingIdentifierAndNotRelationalOperator(n,r){if(kn(n)){if(Tf.lastIndex=r,Tf.test(this.input)){let s=this.codePointAtPos(Tf.lastIndex);if(!ni(s)&&s!==92)return!1}return!0}else return n===92}nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine(){let n=this.nextTokenInLineStart(),r=this.codePointAtPos(n);return this.chStartsBindingIdentifierAndNotRelationalOperator(r,n)}nextTokenIsIdentifierOrStringLiteralOnSameLine(){let n=this.nextTokenInLineStart(),r=this.codePointAtPos(n);return this.chStartsBindingIdentifier(r,n)||r===34||r===39}};function r$(e){if(e.type!=="MemberExpression")return!1;let{computed:t,property:n}=e;return t&&n.type!=="StringLiteral"&&(n.type!=="TemplateLiteral"||n.expressions.length>0)?!1:Ik(e.object)}function i$(e,t){var n;let{type:r}=e;if((n=e.extra)!=null&&n.parenthesized)return!1;if(t){if(r==="Literal"){let{value:s}=e;if(typeof s=="string"||typeof s=="boolean")return!0}}else if(r==="StringLiteral"||r==="BooleanLiteral")return!0;return!!(_k(e,t)||s$(e,t)||r==="TemplateLiteral"&&e.expressions.length===0||r$(e))}function _k(e,t){return t?e.type==="Literal"&&(typeof e.value=="number"||"bigint"in e):e.type==="NumericLiteral"||e.type==="BigIntLiteral"}function s$(e,t){if(e.type==="UnaryExpression"){let{operator:n,argument:r}=e;if(n==="-"&&_k(r,t))return!0}return!1}function Ik(e){return e.type==="Identifier"?!0:e.type!=="MemberExpression"||e.computed?!1:Ik(e.object)}var lk=Qt`placeholders`({ClassNameIsRequired:"A class name is required.",UnexpectedSpace:"Unexpected space in placeholder."}),o$=e=>class extends e{parsePlaceholder(n){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,n)}}finishPlaceholder(n,r){let s=n;return(!s.expectedNode||!s.type)&&(s=this.finishNode(s,"Placeholder")),s.expectedNode=r,s}getTokenFromCode(n){n===37&&this.input.charCodeAt(this.state.pos+1)===37?this.finishOp(133,2):super.getTokenFromCode(n)}parseExprAtom(n){return this.parsePlaceholder("Expression")||super.parseExprAtom(n)}parseIdentifier(n){return this.parsePlaceholder("Identifier")||super.parseIdentifier(n)}checkReservedWord(n,r,s,o){n!==void 0&&super.checkReservedWord(n,r,s,o)}cloneIdentifier(n){let r=super.cloneIdentifier(n);return r.type==="Placeholder"&&(r.expectedNode=n.expectedNode),r}cloneStringLiteral(n){return n.type==="Placeholder"?this.cloneIdentifier(n):super.cloneStringLiteral(n)}parseBindingAtom(){return this.parsePlaceholder("Pattern")||super.parseBindingAtom()}isValidLVal(n,r,s,o){return n==="Placeholder"||super.isValidLVal(n,r,s,o)}toAssignable(n,r){n&&n.type==="Placeholder"&&n.expectedNode==="Expression"?n.expectedNode="Pattern":super.toAssignable(n,r)}chStartsBindingIdentifier(n,r){if(super.chStartsBindingIdentifier(n,r))return!0;let s=this.nextTokenStart();return this.input.charCodeAt(s)===37&&this.input.charCodeAt(s+1)===37}verifyBreakContinue(n,r){var s;((s=n.label)==null?void 0:s.type)!=="Placeholder"&&super.verifyBreakContinue(n,r)}parseExpressionStatement(n,r){var s;if(r.type!=="Placeholder"||(s=r.extra)!=null&&s.parenthesized)return super.parseExpressionStatement(n,r);if(this.match(14)){let a=n;return a.label=this.finishPlaceholder(r,"Identifier"),this.next(),a.body=super.parseStatementOrSloppyAnnexBFunctionDeclaration(),this.finishNode(a,"LabeledStatement")}this.semicolon();let o=n;return o.name=r.name,this.finishPlaceholder(o,"Statement")}parseBlock(n,r,s){return this.parsePlaceholder("BlockStatement")||super.parseBlock(n,r,s)}parseFunctionId(n){return this.parsePlaceholder("Identifier")||super.parseFunctionId(n)}parseClass(n,r,s){let o=r?"ClassDeclaration":"ClassExpression";this.next();let a=this.state.strict,d=this.parsePlaceholder("Identifier");if(d)if(this.match(81)||this.match(133)||this.match(5))n.id=d;else{if(s||!r)return n.id=null,n.body=this.finishPlaceholder(d,"ClassBody"),this.finishNode(n,o);throw this.raise(lk.ClassNameIsRequired,this.state.startLoc)}else this.parseClassId(n,r,s);return super.parseClassSuper(n),n.body=this.parsePlaceholder("ClassBody")||super.parseClassBody(!!n.superClass,a),this.finishNode(n,o)}parseExport(n,r){let s=this.parsePlaceholder("Identifier");if(!s)return super.parseExport(n,r);let o=n;if(!this.isContextual(98)&&!this.match(12))return o.specifiers=[],o.source=null,o.declaration=this.finishPlaceholder(s,"Declaration"),this.finishNode(o,"ExportNamedDeclaration");this.expectPlugin("exportDefaultFrom");let a=this.startNode();return a.exported=s,o.specifiers=[this.finishNode(a,"ExportDefaultSpecifier")],super.parseExport(o,r)}isExportDefaultSpecifier(){if(this.match(65)){let n=this.nextTokenStart();if(this.isUnparsedContextual(n,"from")&&this.input.startsWith(vr(133),this.nextTokenStartSince(n+4)))return!0}return super.isExportDefaultSpecifier()}maybeParseExportDefaultSpecifier(n,r){var s;return(s=n.specifiers)!=null&&s.length?!0:super.maybeParseExportDefaultSpecifier(n,r)}checkExport(n){let{specifiers:r}=n;r!=null&&r.length&&(n.specifiers=r.filter(s=>s.exported.type==="Placeholder")),super.checkExport(n),n.specifiers=r}parseImport(n){let r=this.parsePlaceholder("Identifier");if(!r)return super.parseImport(n);if(n.specifiers=[],!this.isContextual(98)&&!this.match(12))return n.source=this.finishPlaceholder(r,"StringLiteral"),this.semicolon(),this.finishNode(n,"ImportDeclaration");let s=this.startNodeAtNode(r);return s.local=r,n.specifiers.push(this.finishNode(s,"ImportDefaultSpecifier")),this.eat(12)&&(this.maybeParseStarImportSpecifier(n)||this.parseNamedImportSpecifiers(n)),this.expectContextual(98),n.source=this.parseImportSource(),this.semicolon(),this.finishNode(n,"ImportDeclaration")}parseImportSource(){return this.parsePlaceholder("StringLiteral")||super.parseImportSource()}assertNoSpace(){this.state.start>this.offsetToSourcePos(this.state.lastTokEndLoc.index)&&this.raise(lk.UnexpectedSpace,this.state.lastTokEndLoc)}},a$=e=>class extends e{parseV8Intrinsic(){if(this.match(54)){let n=this.state.startLoc,r=this.startNode();if(this.next(),ye(this.state.type)){let s=this.parseIdentifierName(),o=this.createIdentifier(r,s);if(this.castNodeTo(o,"V8IntrinsicIdentifier"),this.match(10))return o}this.unexpected(n)}}parseExprAtom(n){return this.parseV8Intrinsic()||super.parseExprAtom(n)}},ck=["minimal","fsharp","hack","smart"],uk=["^^","@@","^","%","#"];function d$(e){if(e.has("decorators")){if(e.has("decorators-legacy"))throw new Error("Cannot use the decorators and decorators-legacy plugin together");let r=e.get("decorators").decoratorsBeforeExport;if(r!=null&&typeof r!="boolean")throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");let s=e.get("decorators").allowCallParenthesized;if(s!=null&&typeof s!="boolean")throw new Error("'allowCallParenthesized' must be a boolean.")}if(e.has("flow")&&e.has("typescript"))throw new Error("Cannot combine flow and typescript plugins.");if(e.has("placeholders")&&e.has("v8intrinsic"))throw new Error("Cannot combine placeholders and v8intrinsic plugins.");if(e.has("pipelineOperator")){var t;let r=e.get("pipelineOperator").proposal;if(!ck.includes(r)){let s=ck.map(o=>`"${o}"`).join(", ");throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${s}.`)}if(r==="hack"){var n;if(e.has("placeholders"))throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");if(e.has("v8intrinsic"))throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");let s=e.get("pipelineOperator").topicToken;if(!uk.includes(s)){let o=uk.map(a=>`"${a}"`).join(", ");throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${o}.`)}if(s==="#"&&((n=e.get("recordAndTuple"))==null?void 0:n.syntaxType)==="hash")throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple",e.get("recordAndTuple")])}\`.`)}else if(r==="smart"&&((t=e.get("recordAndTuple"))==null?void 0:t.syntaxType)==="hash")throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple",e.get("recordAndTuple")])}\`.`)}if(e.has("moduleAttributes")){if(e.has("deprecatedImportAssert")||e.has("importAssertions"))throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.");if(e.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(e.has("importAssertions")&&e.has("deprecatedImportAssert"))throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins.");if(e.has("deprecatedImportAssert")||e.has("importAttributes")&&e.get("importAttributes").deprecatedAssertSyntax&&e.set("deprecatedImportAssert",{}),e.has("recordAndTuple")){let r=e.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(o=>`'${o}'`).join(", "))}}if(e.has("asyncDoExpressions")&&!e.has("doExpressions")){let r=new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");throw r.missingPlugins="doExpressions",r}if(e.has("optionalChainingAssign")&&e.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(e.has("discardBinding")&&e.get("discardBinding").syntaxType!=="void")throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'.")}var Sk={estree:pO,jsx:zO,flow:BO,typescript:n$,v8intrinsic:a$,placeholders:o$},l$=Object.keys(Sk),Jf=class extends Wf{checkProto(t,n,r,s){if(t.type==="SpreadElement"||this.isObjectMethod(t)||t.computed||t.shorthand)return r;let o=t.key;return(o.type==="Identifier"?o.name:o.value)==="__proto__"?n?(this.raise(_.RecordNoProto,o),!0):(r&&(s?s.doubleProtoLoc===null&&(s.doubleProtoLoc=o.loc.start):this.raise(_.DuplicateProto,o)),!0):r}shouldExitDescending(t,n){return t.type==="ArrowFunctionExpression"&&this.offsetToSourcePos(t.start)===n}getExpression(){if(this.enterInitialScopes(),this.nextToken(),this.match(140))throw this.raise(_.ParseExpressionEmptyInput,this.state.startLoc);let t=this.parseExpression();if(!this.match(140))throw this.raise(_.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,n){return t?this.disallowInAnd(()=>this.parseExpressionBase(n)):this.allowInAnd(()=>this.parseExpressionBase(n))}parseExpressionBase(t){let n=this.state.startLoc,r=this.parseMaybeAssign(t);if(this.match(12)){let s=this.startNodeAt(n);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,n){return this.disallowInAnd(()=>this.parseMaybeAssign(t,n))}parseMaybeAssignAllowIn(t,n){return this.allowInAnd(()=>this.parseMaybeAssign(t,n))}setOptionalParametersError(t){t.optionalParametersLoc=this.state.startLoc}parseMaybeAssign(t,n){let r=this.state.startLoc,s=this.isContextual(108);if(s&&this.prodParam.hasYield){this.next();let l=this.parseYield(r);return n&&(l=n.call(this,l,r)),l}let o;t?o=!1:(t=new ys,o=!0);let{type:a}=this.state;(a===10||ye(a))&&(this.state.potentialArrowAt=this.state.start);let d=this.parseMaybeConditional(t);if(n&&(d=n.call(this,d,r)),yO(this.state.type)){let l=this.startNodeAt(r),c=this.state.value;if(l.operator=c,this.match(29)){this.toAssignable(d,!0),l.left=d;let u=r.index;t.doubleProtoLoc!=null&&t.doubleProtoLoc.index>=u&&(t.doubleProtoLoc=null),t.shorthandAssignLoc!=null&&t.shorthandAssignLoc.index>=u&&(t.shorthandAssignLoc=null),t.privateKeyLoc!=null&&t.privateKeyLoc.index>=u&&(this.checkDestructuringPrivate(t),t.privateKeyLoc=null),t.voidPatternLoc!=null&&t.voidPatternLoc.index>=u&&(t.voidPatternLoc=null)}else l.left=d;return this.next(),l.right=this.parseMaybeAssign(),this.checkLVal(d,this.finishNode(l,"AssignmentExpression"),void 0,void 0,void 0,void 0,c==="||="||c==="&&="||c==="??="),l}else o&&this.checkExpressionErrors(t,!0);if(s){let{type:l}=this.state;if((this.hasPlugin("v8intrinsic")?ea(l):ea(l)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(_.YieldNotInGeneratorFunction,r),this.parseYield(r)}return d}parseMaybeConditional(t){let n=this.state.startLoc,r=this.state.potentialArrowAt,s=this.parseExprOps(t);return this.shouldExitDescending(s,r)?s:this.parseConditional(s,n,t)}parseConditional(t,n,r){if(this.eat(17)){let s=this.startNodeAt(n);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 n=this.state.startLoc,r=this.state.potentialArrowAt,s=this.parseMaybeUnaryOrPrivate(t);return this.shouldExitDescending(s,r)?s:this.parseExprOp(s,n,-1)}parseExprOp(t,n,r){if(this.isPrivateName(t)){let o=this.getPrivateNameSV(t);(r>=Nl(58)||!this.prodParam.hasIn||!this.match(58))&&this.raise(_.PrivateInExpectedIn,t,{identifierName:o}),this.classScope.usePrivateName(o,t.loc.start)}let s=this.state.type;if(bO(s)&&(this.prodParam.hasIn||!this.match(58))){let o=Nl(s);if(o>r){if(s===39){if(this.expectPlugin("pipelineOperator"),this.state.inFSharpPipelineDirectBody)return t;this.checkPipelineAtInfixOperator(t,n)}let a=this.startNodeAt(n);a.left=t,a.operator=this.state.value;let d=s===41||s===42,l=s===40;if(l&&(o=Nl(42)),this.next(),s===39&&this.hasPlugin(["pipelineOperator",{proposal:"minimal"}])&&this.state.type===96&&this.prodParam.hasAwait)throw this.raise(_.UnexpectedAwaitAfterPipelineBody,this.state.startLoc);a.right=this.parseExprOpRightExpr(s,o);let c=this.finishNode(a,d||l?"LogicalExpression":"BinaryExpression"),u=this.state.type;if(l&&(u===41||u===42)||d&&u===40)throw this.raise(_.MixingCoalesceWithLogical,this.state.startLoc);return this.parseExprOp(c,n,r)}}return t}parseExprOpRightExpr(t,n){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(n))}if(this.getPluginOption("pipelineOperator","proposal")==="smart")return this.withTopicBindingContext(()=>{if(this.prodParam.hasYield&&this.isContextual(108))throw this.raise(_.PipeBodyIsTighter,this.state.startLoc);return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(t,n),r)});default:return this.parseExprOpBaseRightExpr(t,n)}}parseExprOpBaseRightExpr(t,n){let r=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnaryOrPrivate(),r,_O(t)?n-1:n)}parseHackPipeBody(){var t;let{startLoc:n}=this.state,r=this.parseMaybeAssign();return iO.has(r.type)&&!((t=r.extra)!=null&&t.parenthesized)&&this.raise(_.PipeUnparenthesizedBody,n,{type:r.type}),this.topicReferenceWasUsedInCurrentContext()||this.raise(_.PipeTopicUnused,n),r}checkExponentialAfterUnary(t){this.match(57)&&this.raise(_.UnexpectedTokenUnaryExponentiation,t.argument)}parseMaybeUnary(t,n){let r=this.state.startLoc,s=this.isContextual(96);if(s&&this.recordAwaitIfAllowed()){this.next();let l=this.parseAwait(r);return n||this.checkExponentialAfterUnary(l),l}let o=this.match(34),a=this.startNode();if(kO(this.state.type)){a.operator=this.state.value,a.prefix=!0,this.match(72)&&this.expectPlugin("throwExpressions");let l=this.match(89);if(this.next(),a.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(t,!0),this.state.strict&&l){let c=a.argument;c.type==="Identifier"?this.raise(_.StrictDelete,a):this.hasPropertyAsPrivateName(c)&&this.raise(_.DeletePrivateField,a)}if(!o)return n||this.checkExponentialAfterUnary(a),this.finishNode(a,"UnaryExpression")}let d=this.parseUpdate(a,o,t);if(s){let{type:l}=this.state;if((this.hasPlugin("v8intrinsic")?ea(l):ea(l)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(_.AwaitNotInAsyncContext,r),this.parseAwait(r)}return d}parseUpdate(t,n,r){if(n){let a=t;return this.checkLVal(a.argument,this.finishNode(a,"UpdateExpression")),t}let s=this.state.startLoc,o=this.parseExprSubscripts(r);if(this.checkExpressionErrors(r,!1))return o;for(;vO(this.state.type)&&!this.canInsertSemicolon();){let a=this.startNodeAt(s);a.operator=this.state.value,a.prefix=!1,a.argument=o,this.next(),this.checkLVal(o,o=this.finishNode(a,"UpdateExpression"))}return o}parseExprSubscripts(t){let n=this.state.startLoc,r=this.state.potentialArrowAt,s=this.parseExprAtom(t);return this.shouldExitDescending(s,r)?s:this.parseSubscripts(s,n)}parseSubscripts(t,n,r){let s={optionalChainMember:!1,maybeAsyncArrow:this.atPossibleAsyncArrow(t),stop:!1};do t=this.parseSubscript(t,n,r,s),s.maybeAsyncArrow=!1;while(!s.stop);return t}parseSubscript(t,n,r,s){let{type:o}=this.state;if(!r&&o===15)return this.parseBind(t,n,s);if(Ml(o))return this.parseTaggedTemplateExpression(t,n,s);let a=!1;if(o===18){if(r&&(this.raise(_.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,n,s,a);{let d=this.eat(0);return d||a||this.eat(16)?this.parseMember(t,n,s,d,a):this.stopParseSubscript(t,s)}}stopParseSubscript(t,n){return n.stop=!0,t}parseMember(t,n,r,s,o){let a=this.startNodeAt(n);return a.object=t,a.computed=s,s?(a.property=this.parseExpression(),this.expect(3)):this.match(139)?(t.type==="Super"&&this.raise(_.SuperPrivateField,n),this.classScope.usePrivateName(this.state.value,this.state.startLoc),a.property=this.parsePrivateName()):a.property=this.parseIdentifier(!0),r.optionalChainMember?(a.optional=o,this.finishNode(a,"OptionalMemberExpression")):this.finishNode(a,"MemberExpression")}parseBind(t,n,r){let s=this.startNodeAt(n);s.object=t,this.next();let o=this.match(83),a=this.parseNoCallExpr();if(a.type==="Super"||o&&a.type==="ImportExpression"||a.type==="Import")throw this.raise(_.UnsupportedBindRHS,a);return s.callee=a,r.stop=!0,this.parseSubscripts(this.finishNode(s,"BindExpression"),n,!1)}parseCoverCallAndAsyncArrowHead(t,n,r,s){let o=this.state.maybeInArrowParameters,a=null;this.state.maybeInArrowParameters=!0,this.next();let d=this.startNodeAt(n);d.callee=t;let{maybeAsyncArrow:l,optionalChainMember:c}=r;l&&(this.expressionScope.enter(QO()),a=new ys),c&&(d.optional=s),s?d.arguments=this.parseCallExpressionArguments():d.arguments=this.parseCallExpressionArguments(t.type!=="Super",d,a);let u=this.finishCallExpression(d,c);return l&&this.shouldParseAsyncArrow()&&!s?(r.stop=!0,this.checkDestructuringPrivate(a),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),u=this.parseAsyncArrowFromCallExpression(this.startNodeAt(n),u)):(l&&(this.checkExpressionErrors(a,!0),this.expressionScope.exit()),this.toReferencedArguments(u)),this.state.maybeInArrowParameters=o,u}toReferencedArguments(t,n){this.toReferencedListDeep(t.arguments,n)}parseTaggedTemplateExpression(t,n,r){let s=this.startNodeAt(n);return s.tag=t,s.quasi=this.parseTemplate(!0),r.optionalChainMember&&this.raise(_.OptionalChainingNoTemplate,n),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,n){if(t.callee.type==="Import")if(t.arguments.length===0||t.arguments.length>2)this.raise(_.ImportCallArity,t);else for(let r of t.arguments)r.type==="SpreadElement"&&this.raise(_.ImportCallSpreadArgument,r);return this.finishNode(t,n?"OptionalCallExpression":"CallExpression")}parseCallExpressionArguments(t,n,r){let s=[],o=!0,a=this.state.inFSharpPipelineDirectBody;for(this.state.inFSharpPipelineDirectBody=!1;!this.eat(11);){if(o)o=!1;else if(this.expect(12),this.match(11)){n&&this.addTrailingCommaExtraToNode(n),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,n){var r;return this.resetPreviousNodeTrailingComments(n),this.expect(19),this.parseArrowExpression(t,n.arguments,!0,(r=n.extra)==null?void 0:r.trailingCommaLoc),n.innerComments&&sa(t,n.innerComments),n.callee.trailingComments&&sa(t,n.callee.trailingComments),t}parseNoCallExpr(){let t=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),t,!0)}parseExprAtom(t){let n,r=null,{type:s}=this.state;switch(s){case 79:return this.parseSuper();case 83:return n=this.startNode(),this.next(),this.match(16)?this.parseImportMetaPropertyOrPhaseCall(n):this.match(10)?this.optionFlags&512?this.parseImportCall(n):this.finishNode(n,"Import"):(this.raise(_.UnsupportedImport,this.state.lastTokStartLoc),this.finishNode(n,"Import"));case 78:return n=this.startNode(),this.next(),this.finishNode(n,"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 o=this.state.potentialArrowAt===this.state.start;return this.parseParenAndDistinguishExpression(o)}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:{n=this.startNode(),this.next(),n.object=null;let o=n.callee=this.parseNoCallExpr();if(o.type==="MemberExpression")return this.finishNode(n,"BindExpression");throw this.raise(_.UnsupportedBind,o)}case 139:return this.raise(_.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 o=this.getPluginOption("pipelineOperator","proposal");if(o)return this.parseTopicReference(o);throw this.unexpected()}case 47:{let o=this.input.codePointAt(this.nextTokenStart());throw kn(o)||o===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(ye(s)){if(this.isContextual(127)&&this.lookaheadInLineCharCode()===123)return this.parseModuleExpression();let o=this.state.potentialArrowAt===this.state.start,a=this.state.containsEsc,d=this.parseIdentifier();if(!a&&d.name==="async"&&!this.canInsertSemicolon()){let{type:l}=this.state;if(l===68)return this.resetPreviousNodeTrailingComments(d),this.next(),this.parseAsyncFunctionExpression(this.startNodeAtNode(d));if(ye(l))return o&&this.lookaheadCharCode()===61?this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(d)):d;if(l===90)return this.resetPreviousNodeTrailingComments(d),this.parseDo(this.startNodeAtNode(d),!0)}return o&&this.match(19)&&!this.canInsertSemicolon()?(this.next(),this.parseArrowExpression(this.startNodeAtNode(d),[d],!1)):d}else throw this.unexpected()}}parseTopicReferenceThenEqualsSign(t,n){let r=this.getPluginOption("pipelineOperator","proposal");if(r)return this.state.type=t,this.state.value=n,this.state.pos--,this.state.end--,this.state.endLoc=dt(this.state.endLoc,-1),this.parseTopicReference(r);throw this.unexpected()}parseTopicReference(t){let n=this.startNode(),r=this.state.startLoc,s=this.state.type;return this.next(),this.finishTopicReference(n,r,t,s)}finishTopicReference(t,n,r,s){if(this.testTopicReferenceConfiguration(r,n,s))return r==="hack"?(this.topicReferenceIsAllowedInCurrentContext()||this.raise(_.PipeTopicUnbound,n),this.registerTopicReference(),this.finishNode(t,"TopicReference")):(this.topicReferenceIsAllowedInCurrentContext()||this.raise(_.PrimaryTopicNotAllowed,n),this.registerTopicReference(),this.finishNode(t,"PipelinePrimaryTopicReference"));throw this.raise(_.PipeTopicUnconfiguredToken,n,{token:vr(s)})}testTopicReferenceConfiguration(t,n,r){switch(t){case"hack":return this.hasPlugin(["pipelineOperator",{topicToken:vr(r)}]);case"smart":return r===27;default:throw this.raise(_.PipeTopicRequiresHackPipes,n)}}parseAsyncArrowUnaryFunction(t){this.prodParam.enter(Ol(!0,this.prodParam.hasYield));let n=[this.parseIdentifier()];return this.prodParam.exit(),this.hasPrecedingLineBreak()&&this.raise(_.LineTerminatorBeforeArrow,this.state.curPosition()),this.expect(19),this.parseArrowExpression(t,n,!0)}parseDo(t,n){this.expectPlugin("doExpressions"),n&&this.expectPlugin("asyncDoExpressions"),t.async=n,this.next();let r=this.state.labels;return this.state.labels=[],n?(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(_.SuperNotAllowed,t):this.scope.allowSuper||this.optionFlags&16||this.raise(_.UnexpectedSuper,t),!this.match(10)&&!this.match(0)&&!this.match(16)&&this.raise(_.UnsupportedSuper,t),this.finishNode(t,"Super")}parsePrivateName(){let t=this.startNode(),n=this.startNodeAt(dt(this.state.startLoc,1)),r=this.state.value;return this.next(),t.id=this.createIdentifier(n,r),this.finishNode(t,"PrivateName")}parseFunctionOrFunctionSent(){let t=this.startNode();if(this.next(),this.prodParam.hasYield&&this.match(16)){let n=this.createIdentifier(this.startNodeAtNode(t),"function");return this.next(),this.match(103)?this.expectPlugin("functionSent"):this.hasPlugin("functionSent")||this.unexpected(),this.parseMetaProperty(t,n,"sent")}return this.parseFunction(t)}parseMetaProperty(t,n,r){t.meta=n;let s=this.state.containsEsc;return t.property=this.parseIdentifier(!0),(t.property.name!==r||s)&&this.raise(_.UnsupportedMetaProperty,t.property,{target:n.name,onlyValidPropertyName:r}),this.finishNode(t,"MetaProperty")}parseImportMetaPropertyOrPhaseCall(t){if(this.next(),this.isContextual(105)||this.isContextual(97)){let n=this.isContextual(105);return this.expectPlugin(n?"sourcePhaseImports":"deferredImportEvaluation"),this.next(),t.phase=n?"source":"defer",this.parseImportCall(t)}else{let n=this.createIdentifierAt(this.startNodeAtNode(t),"import",this.state.lastTokStartLoc);return this.isContextual(101)&&(this.inModule||this.raise(_.ImportMetaOutsideModule,n),this.sawUnambiguousESM=!0),this.parseMetaProperty(t,n,"meta")}}parseLiteralAtNode(t,n,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,n)}parseLiteral(t,n){let r=this.startNode();return this.parseLiteralAtNode(t,n,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 n=this.startNode();return this.addExtra(n,"raw",this.input.slice(this.offsetToSourcePos(n.start),this.state.end)),n.pattern=t.pattern,n.flags=t.flags,this.next(),this.finishNode(n,"RegExpLiteral")}parseBooleanLiteral(t){let n=this.startNode();return n.value=t,this.next(),this.finishNode(n,"BooleanLiteral")}parseNullLiteral(){let t=this.startNode();return this.next(),this.finishNode(t,"NullLiteral")}parseParenAndDistinguishExpression(t){let n=this.state.startLoc,r;this.next(),this.expressionScope.enter(XO());let s=this.state.maybeInArrowParameters,o=this.state.inFSharpPipelineDirectBody;this.state.maybeInArrowParameters=!0,this.state.inFSharpPipelineDirectBody=!1;let a=this.state.startLoc,d=[],l=new ys,c=!0,u,p;for(;!this.match(11);){if(c)c=!1;else if(this.expect(12,l.optionalParametersLoc===null?null:l.optionalParametersLoc),this.match(11)){p=this.state.startLoc;break}if(this.match(21)){let h=this.state.startLoc;if(u=this.state.startLoc,d.push(this.parseParenItem(this.parseRestBinding(),h)),!this.checkCommaAfterRest(41))break}else d.push(this.parseMaybeAssignAllowInOrVoidPattern(11,l,this.parseParenItem))}let f=this.state.lastTokEndLoc;this.expect(11),this.state.maybeInArrowParameters=s,this.state.inFSharpPipelineDirectBody=o;let m=this.startNodeAt(n);return t&&this.shouldParseArrow(d)&&(m=this.parseArrow(m))?(this.checkDestructuringPrivate(l),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),this.parseArrowExpression(m,d,!1),m):(this.expressionScope.exit(),d.length||this.unexpected(this.state.lastTokStartLoc),p&&this.unexpected(p),u&&this.unexpected(u),this.checkExpressionErrors(l,!0),this.toReferencedListDeep(d,!0),d.length>1?(r=this.startNodeAt(a),r.expressions=d,this.finishNode(r,"SequenceExpression"),this.resetEndLocation(r,f)):r=d[0],this.wrapParenthesis(n,r))}wrapParenthesis(t,n){if(!(this.optionFlags&1024))return this.addExtra(n,"parenthesized",!0),this.addExtra(n,"parenStart",t.index),this.takeSurroundingComments(n,t.index,this.state.lastTokEndLoc.index),n;let r=this.startNodeAt(t);return r.expression=n,this.finishNode(r,"ParenthesizedExpression")}shouldParseArrow(t){return!this.canInsertSemicolon()}parseArrow(t){if(this.eat(19))return t}parseParenItem(t,n){return t}parseNewOrNewTarget(){let t=this.startNode();if(this.next(),this.match(16)){let n=this.createIdentifier(this.startNodeAtNode(t),"new");this.next();let r=this.parseMetaProperty(t,n,"target");return this.scope.allowNewTarget||this.raise(_.UnexpectedNewTarget,r),r}return this.parseNew(t)}parseNew(t){if(this.parseNewCallee(t),this.eat(10)){let n=this.parseExprList(11);this.toReferencedList(n),t.arguments=n}else t.arguments=[];return this.finishNode(t,"NewExpression")}parseNewCallee(t){let n=this.match(83),r=this.parseNoCallExpr();t.callee=r,(n&&r.type==="ImportExpression"||r.type==="Import")&&this.raise(_.ImportCallNotNewExpression,r),r.type==="Super"&&this.raise(_.SuperCallNotNewExpression,r)}parseTemplateElement(t){let{start:n,startLoc:r,end:s,value:o}=this.state,a=n+1,d=this.startNodeAt(dt(r,1));o===null&&(t||this.raise(_.InvalidEscapeSequenceTemplate,dt(this.state.firstInvalidTemplateEscapePos,1)));let l=this.match(24),c=l?-1:-2,u=s+c;d.value={raw:this.input.slice(a,u).replace(/\r\n?/g,`
|
|
10
|
-
`),cooked:o===null?null:o.slice(1,c)},d.tail=l,this.next();let p=this.finishNode(d,"TemplateElement");return this.resetEndLocation(p,dt(this.state.lastTokEndLoc,c)),p}parseTemplate(t){let n=this.startNode(),r=this.parseTemplateElement(t),s=[r],o=[];for(;!r.tail;)o.push(this.parseTemplateSubstitution()),this.readTemplateContinuation(),s.push(r=this.parseTemplateElement(t));return n.expressions=o,n.quasis=s,this.finishNode(n,"TemplateLiteral")}parseTemplateSubstitution(){return this.parseExpression()}parseObjectLike(t,n,r,s){r&&this.expectPlugin("recordAndTuple");let o=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let a=!1,d=!0,l=this.startNode();for(l.properties=[],this.next();!this.match(t);){if(d)d=!1;else if(this.expect(12),this.match(t)){this.addTrailingCommaExtraToNode(l);break}let u;n?u=this.parseBindingProperty():(u=this.parsePropertyDefinition(s),a=this.checkProto(u,r,a,s)),r&&!this.isObjectProperty(u)&&u.type!=="SpreadElement"&&this.raise(_.InvalidRecordProperty,u),u.shorthand&&this.addExtra(u,"shorthand",!0),l.properties.push(u)}this.next(),this.state.inFSharpPipelineDirectBody=o;let c="ObjectExpression";return n?c="ObjectPattern":r&&(c="RecordExpression"),this.finishNode(l,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 n=[];if(this.match(26))for(this.hasPlugin("decorators")&&this.raise(_.UnsupportedPropertyDecorator,this.state.startLoc);this.match(26);)n.push(this.parseDecorator());let r=this.startNode(),s=!1,o=!1,a;if(this.match(21))return n.length&&this.unexpected(),this.parseSpread();n.length&&(r.decorators=n,n=[]),r.method=!1,t&&(a=this.state.startLoc);let d=this.eat(55);this.parsePropertyNamePrefixOperator(r);let l=this.state.containsEsc;if(this.parsePropertyName(r,t),!d&&!l&&this.maybeAsyncOrAccessorProp(r)){let{key:c}=r,u=c.name;u==="async"&&!this.hasPrecedingLineBreak()&&(s=!0,this.resetPreviousNodeTrailingComments(c),d=this.eat(55),this.parsePropertyName(r)),(u==="get"||u==="set")&&(o=!0,this.resetPreviousNodeTrailingComments(c),r.kind=u,this.match(55)&&(d=!0,this.raise(_.AccessorIsGenerator,this.state.curPosition(),{kind:u}),this.next()),this.parsePropertyName(r))}return this.parseObjPropValue(r,a,d,s,!1,o,t)}getGetterSetterExpectedParamCount(t){return t.kind==="get"?0:1}getObjectOrClassMethodParams(t){return t.params}checkGetterSetterParams(t){var n;let r=this.getGetterSetterExpectedParamCount(t),s=this.getObjectOrClassMethodParams(t);s.length!==r&&this.raise(t.kind==="get"?_.BadGetterArity:_.BadSetterArity,t),t.kind==="set"&&((n=s[s.length-1])==null?void 0:n.type)==="RestElement"&&this.raise(_.BadSetterRestParameter,t)}parseObjectMethod(t,n,r,s,o){if(o){let a=this.parseMethod(t,n,!1,!1,!1,"ObjectMethod");return this.checkGetterSetterParams(a),a}if(r||n||this.match(10))return s&&this.unexpected(),t.kind="method",t.method=!0,this.parseMethod(t,n,r,!1,!1,"ObjectMethod")}parseObjectProperty(t,n,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(n,this.cloneIdentifier(t.key));else if(this.match(29)){let o=this.state.startLoc;s!=null?s.shorthandAssignLoc===null&&(s.shorthandAssignLoc=o):this.raise(_.InvalidCoverInitializedName,o),t.value=this.parseMaybeDefault(n,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,n,r,s,o,a,d){let l=this.parseObjectMethod(t,r,s,o,a)||this.parseObjectProperty(t,n,o,d);return l||this.unexpected(),l}parsePropertyName(t,n){if(this.eat(0))t.computed=!0,t.key=this.parseMaybeAssignAllowIn(),this.expect(3);else{let{type:r,value:s}=this.state,o;if(Zt(r))o=this.parseIdentifier(!0);else switch(r){case 135:o=this.parseNumericLiteral(s);break;case 134:o=this.parseStringLiteral(s);break;case 136:o=this.parseBigIntLiteral(s);break;case 139:{let a=this.state.startLoc;n!=null?n.privateKeyLoc===null&&(n.privateKeyLoc=a):this.raise(_.UnexpectedPrivateField,a),o=this.parsePrivateName();break}default:if(r===137){o=this.parseDecimalLiteral(s);break}this.unexpected()}t.key=o,r!==139&&(t.computed=!1)}}initFunction(t,n){t.id=null,t.generator=!1,t.async=n}parseMethod(t,n,r,s,o,a,d=!1){this.initFunction(t,r),t.generator=n,this.scope.enter(530|(d?576:0)|(o?32:0)),this.prodParam.enter(Ol(r,t.generator)),this.parseFunctionParams(t,s);let l=this.parseFunctionBodyAndFinish(t,a,!0);return this.prodParam.exit(),this.scope.exit(),l}parseArrayLike(t,n,r){n&&this.expectPlugin("recordAndTuple");let s=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let o=this.startNode();return this.next(),o.elements=this.parseExprList(t,!n,r,o),this.state.inFSharpPipelineDirectBody=s,this.finishNode(o,n?"TupleExpression":"ArrayExpression")}parseArrowExpression(t,n,r,s){this.scope.enter(518);let o=Ol(r,!1);!this.match(5)&&this.prodParam.hasIn&&(o|=8),this.prodParam.enter(o),this.initFunction(t,r);let a=this.state.maybeInArrowParameters;return n&&(this.state.maybeInArrowParameters=!0,this.setArrowFunctionParameters(t,n,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,n,r){this.toAssignableList(n,r,!1),t.params=n}parseFunctionBodyAndFinish(t,n,r=!1){return this.parseFunctionBody(t,!1,r),this.finishNode(t,n)}parseFunctionBody(t,n,r=!1){let s=n&&!this.match(5);if(this.expressionScope.enter(xk()),s)t.body=this.parseMaybeAssign(),this.checkParams(t,!1,n,!1);else{let o=this.state.strict,a=this.state.labels;this.state.labels=[],this.prodParam.enter(this.prodParam.currentFlags()|4),t.body=this.parseBlock(!0,!1,d=>{let l=!this.isSimpleParamList(t.params);d&&l&&this.raise(_.IllegalLanguageModeDirective,(t.kind==="method"||t.kind==="constructor")&&t.key?t.key.loc.end:t);let c=!o&&this.state.strict;this.checkParams(t,!this.state.strict&&!n&&!r&&!l,n,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 n=0,r=t.length;n<r;n++)if(!this.isSimpleParameter(t[n]))return!1;return!0}checkParams(t,n,r,s=!0){let o=!n&&new Set,a={type:"FormalParameters"};for(let d of t.params)this.checkLVal(d,a,5,o,s)}parseExprList(t,n,r,s){let o=[],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}o.push(this.parseExprListItem(t,n,r))}return o}parseExprListItem(t,n,r,s){let o;if(this.match(12))n||this.raise(_.UnexpectedToken,this.state.curPosition(),{unexpected:","}),o=null;else if(this.match(21)){let a=this.state.startLoc;o=this.parseParenItem(this.parseSpread(r),a)}else if(this.match(17)){this.expectPlugin("partialApplication"),s||this.raise(_.UnexpectedArgumentPlaceholder,this.state.startLoc);let a=this.startNode();this.next(),o=this.finishNode(a,"ArgumentPlaceholder")}else o=this.parseMaybeAssignAllowInOrVoidPattern(t,r,this.parseParenItem);return o}parseIdentifier(t){let n=this.startNode(),r=this.parseIdentifierName(t);return this.createIdentifier(n,r)}createIdentifier(t,n){return t.name=n,t.loc.identifierName=n,this.finishNode(t,"Identifier")}createIdentifierAt(t,n,r){return t.name=n,t.loc.identifierName=n,this.finishNodeAt(t,"Identifier",r)}parseIdentifierName(t){let n,{startLoc:r,type:s}=this.state;Zt(s)?n=this.state.value:this.unexpected();let o=hO(s);return t?o&&this.replaceToken(132):this.checkReservedWord(n,r,o,!1),this.next(),n}checkReservedWord(t,n,r,s){if(t.length>10||!$O(t))return;if(r&&CO(t)){this.raise(_.UnexpectedKeyword,n,{keyword:t});return}if((this.state.strict?s?bk:yk:gk)(t,this.inModule)){this.raise(_.UnexpectedReservedWord,n,{reservedWord:t});return}else if(t==="yield"){if(this.prodParam.hasYield){this.raise(_.YieldBindingIdentifier,n);return}}else if(t==="await"){if(this.prodParam.hasAwait){this.raise(_.AwaitBindingIdentifier,n);return}if(this.scope.inStaticBlock){this.raise(_.AwaitBindingIdentifierInStaticBlock,n);return}this.expressionScope.recordAsyncArrowParametersError(n)}else if(t==="arguments"&&this.scope.inClassAndNotInNonArrowFunction){this.raise(_.ArgumentsInClass,n);return}}recordAwaitIfAllowed(){let t=this.prodParam.hasAwait;return t&&!this.scope.inFunction&&(this.state.hasTopLevelAwait=!0),t}parseAwait(t){let n=this.startNodeAt(t);return this.expressionScope.recordParameterInitializerError(_.AwaitExpressionFormalParameter,n),this.eat(55)&&this.raise(_.ObsoleteAwaitStar,n),!this.scope.inFunction&&!(this.optionFlags&1)&&(this.isAmbiguousPrefixOrIdentifier()?this.ambiguousScriptDifferentAst=!0:this.sawUnambiguousESM=!0),this.state.soloAwait||(n.argument=this.parseMaybeUnary(null,!0)),this.finishNode(n,"AwaitExpression")}isAmbiguousPrefixOrIdentifier(){if(this.hasPrecedingLineBreak())return!0;let{type:t}=this.state;return t===53||t===10||t===0||Ml(t)||t===102&&!this.state.containsEsc||t===138||t===56||this.hasPlugin("v8intrinsic")&&t===54}parseYield(t){let n=this.startNodeAt(t);this.expressionScope.recordParameterInitializerError(_.YieldInParameter,n);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 n.delegate=r,n.argument=s,this.finishNode(n,"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(_.ImportCallArity,t)}}return this.expect(11),this.finishNode(t,"ImportExpression")}checkPipelineAtInfixOperator(t,n){this.hasPlugin(["pipelineOperator",{proposal:"smart"}])&&t.type==="SequenceExpression"&&this.raise(_.PipelineHeadSequenceExpression,n)}parseSmartPipelineBodyInStyle(t,n){if(this.isSimpleReference(t)){let r=this.startNodeAt(n);return r.callee=t,this.finishNode(r,"PipelineBareFunction")}else{let r=this.startNodeAt(n);return this.checkSmartPipeTopicBodyEarlyErrors(n),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(_.PipelineBodyNoArrow,this.state.startLoc);this.topicReferenceWasUsedInCurrentContext()||this.raise(_.PipelineTopicUnused,t)}withTopicBindingContext(t){let n=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:1,maxTopicIndex:null};try{return t()}finally{this.state.topicContext=n}}withSmartMixTopicForbiddingContext(t){if(this.hasPlugin(["pipelineOperator",{proposal:"smart"}])){let n=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null};try{return t()}finally{this.state.topicContext=n}}else return t()}withSoloAwaitPermittingContext(t){let n=this.state.soloAwait;this.state.soloAwait=!0;try{return t()}finally{this.state.soloAwait=n}}allowInAnd(t){let n=this.prodParam.currentFlags();if(8&~n){this.prodParam.enter(n|8);try{return t()}finally{this.prodParam.exit()}}return t()}disallowInAnd(t){let n=this.prodParam.currentFlags();if(8&n){this.prodParam.enter(n&-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 n=this.state.startLoc;this.state.potentialArrowAt=this.state.start;let r=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!0;let s=this.parseExprOp(this.parseMaybeUnaryOrPrivate(),n,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 n=this.startNodeAt(this.state.endLoc);this.next();let r=this.initializeScopes(!0);this.enterInitialScopes();try{t.body=this.parseProgram(n,8,"module")}finally{r()}return this.finishNode(t,"ModuleExpression")}parseVoidPattern(t){this.expectPlugin("discardBinding");let n=this.startNode();return t!=null&&(t.voidPatternLoc=this.state.startLoc),this.next(),this.finishNode(n,"VoidPattern")}parseMaybeAssignAllowInOrVoidPattern(t,n,r){if(n!=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(n))}return this.parseMaybeAssignAllowIn(n,r)}parsePropertyNamePrefixOperator(t){}},Af={kind:1},c$={kind:2},u$=/[\uD800-\uDFFF]/u,Pf=/in(?:stanceof)?/y;function p$(e,t,n){for(let r=0;r<e.length;r++){let s=e[r],{type:o}=s;if(typeof o=="number"){if(o===139){let{loc:a,start:d,value:l,end:c}=s,u=d+1,p=dt(a.start,1);e.splice(r,1,new vn({type:Jn(27),value:"#",start:d,end:u,startLoc:a.start,endLoc:p}),new vn({type:Jn(132),value:l,start:u,end:c,startLoc:p,endLoc:a.end})),r++;continue}if(Ml(o)){let{loc:a,start:d,value:l,end:c}=s,u=d+1,p=dt(a.start,1),f;t.charCodeAt(d-n)===96?f=new vn({type:Jn(22),value:"`",start:d,end:u,startLoc:a.start,endLoc:p}):f=new vn({type:Jn(8),value:"}",start:d,end:u,startLoc:a.start,endLoc:p});let m,h,g,y;o===24?(h=c-1,g=dt(a.end,-1),m=l===null?null:l.slice(1,-1),y=new vn({type:Jn(22),value:"`",start:h,end:c,startLoc:g,endLoc:a.end})):(h=c-2,g=dt(a.end,-2),m=l===null?null:l.slice(1,-2),y=new vn({type:Jn(23),value:"${",start:h,end:c,startLoc:g,endLoc:a.end})),e.splice(r,1,f,new vn({type:Jn(20),value:m,start:u,end:h,startLoc:p,endLoc:g}),y),r+=2;continue}s.type=Jn(o)}}return e}var Yf=class extends Jf{parseTopLevel(t,n){return t.program=this.parseProgram(n,140,this.options.sourceType==="module"?"module":"script"),t.comments=this.comments,this.optionFlags&256&&(t.tokens=p$(this.tokens,this.input,this.startIndex)),this.finishNode(t,"File")}parseProgram(t,n,r){if(t.sourceType=r,t.interpreter=this.parseInterpreterDirective(),this.parseBlockBody(t,!0,!0,n),this.inModule){if(!(this.optionFlags&64)&&this.scope.undefinedExports.size>0)for(let[o,a]of Array.from(this.scope.undefinedExports))this.raise(_.ModuleExportUndefined,a,{localName:o});this.addExtra(t,"topLevelAwait",this.state.hasTopLevelAwait)}let s;return n===140?s=this.finishNode(t,"Program"):s=this.finishNodeAt(t,"Program",dt(this.state.startLoc,-1)),s}stmtToDirective(t){let n=this.castNodeTo(t,"Directive"),r=this.castNodeTo(t.expression,"DirectiveLiteral"),s=r.value,o=this.input.slice(this.offsetToSourcePos(r.start),this.offsetToSourcePos(r.end)),a=r.value=o.slice(1,-1);return this.addExtra(r,"raw",o),this.addExtra(r,"rawValue",a),this.addExtra(r,"expressionValue",s),n.value=r,delete t.expression,n}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(),n=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(n,t)||this.isUnparsedContextual(t,"void"))}nextTokenIsIdentifierOnSameLine(){let t=this.nextTokenInLineStart(),n=this.codePointAtPos(t);return this.chStartsBindingIdentifier(n,t)}isAwaitUsing(){if(!this.isContextual(96))return!1;let t=this.nextTokenInLineStart();if(this.isUnparsedContextual(t,"using")){t=this.nextTokenInLineStartSince(t+5);let n=this.codePointAtPos(t);if(this.chStartsBindingIdentifier(n,t))return!0}return!1}chStartsBindingIdentifier(t,n){if(kn(t)){if(Pf.lastIndex=n,Pf.test(this.input)){let r=this.codePointAtPos(Pf.lastIndex);if(!ni(r)&&r!==92)return!1}return!0}else return t===92}chStartsBindingPattern(t){return t===91||t===123}hasFollowingBindingAtom(){let t=this.nextTokenStart(),n=this.codePointAtPos(t);return this.chStartsBindingPattern(n)||this.chStartsBindingIdentifier(n,t)}hasInLineFollowingBindingIdentifierOrBrace(){let t=this.nextTokenInLineStart(),n=this.codePointAtPos(t);return n===123||this.chStartsBindingIdentifier(n,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 n=0;return this.options.annexB&&!this.state.strict&&(n|=4,t&&(n|=8)),this.parseStatementLike(n)}parseStatement(){return this.parseStatementLike(0)}parseStatementLike(t){let n=null;return this.match(26)&&(n=this.parseDecorators(!0)),this.parseStatementContent(t,n)}parseStatementContent(t,n){let r=this.state.type,s=this.startNode(),o=!!(t&2),a=!!(t&4),d=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?_.StrictFunction:this.options.annexB?_.SloppyFunctionAnnexB:_.SloppyFunction,this.state.startLoc),this.parseFunctionStatement(s,!1,!o&&a);case 80:return o||this.unexpected(),this.parseClass(this.maybeTakeDecorators(n,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()?o?this.recordAwaitIfAllowed()||this.raise(_.AwaitUsingNotInAsyncContext,s):this.raise(_.UnexpectedLexicalDeclaration,s):this.raise(_.UnexpectedUsingDeclaration,s),this.next(),this.parseVarStatement(s,"await using");break;case 107:if(this.state.containsEsc||!this.hasInLineFollowingBindingIdentifierOrBrace())break;return this.allowsUsing()?o||this.raise(_.UnexpectedLexicalDeclaration,this.state.startLoc):this.raise(_.UnexpectedUsingDeclaration,this.state.startLoc),this.parseVarStatement(s,"using");case 100:{if(this.state.containsEsc)break;let u=this.nextTokenStart(),p=this.codePointAtPos(u);if(p!==91&&(!o&&this.hasFollowingLineBreak()||!this.chStartsBindingIdentifier(p,u)&&p!==123))break}case 75:o||this.raise(_.UnexpectedLexicalDeclaration,this.state.startLoc);case 74:{let u=this.state.value;return this.parseVarStatement(s,u)}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 u=this.lookaheadCharCode();if(u===40||u===46)break}case 82:{!(this.optionFlags&8)&&!d&&this.raise(_.UnexpectedImportExport,this.state.startLoc),this.next();let u;return r===83?u=this.parseImport(s):u=this.parseExport(s,n),this.assertModuleNodeAllowed(u),u}default:if(this.isAsyncFunction())return o||this.raise(_.AsyncFunctionInSingleStatementContext,this.state.startLoc),this.next(),this.parseFunctionStatement(s,!0,!o&&a)}let l=this.state.value,c=this.parseExpression();return ye(r)&&c.type==="Identifier"&&this.eat(14)?this.parseLabeledStatement(s,l,c,t):this.parseExpressionStatement(s,c,n)}assertModuleNodeAllowed(t){!(this.optionFlags&8)&&!this.inModule&&this.raise(_.ImportOutsideModule,t)}decoratorsEnabledBeforeExport(){return this.hasPlugin("decorators-legacy")?!0:this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")!==!1}maybeTakeDecorators(t,n,r){if(t){var s;(s=n.decorators)!=null&&s.length?(typeof this.getPluginOption("decorators","decoratorsBeforeExport")!="boolean"&&this.raise(_.DecoratorsBeforeAfterExport,n.decorators[0]),n.decorators.unshift(...t)):n.decorators=t,this.resetStartLocationFromNode(n,t[0]),r&&this.resetStartLocationFromNode(r,n)}return n}canHaveLeadingDecorator(){return this.match(80)}parseDecorators(t){let n=[];do n.push(this.parseDecorator());while(this.match(26));if(this.match(82))t||this.unexpected(),this.decoratorsEnabledBeforeExport()||this.raise(_.DecoratorExportClass,this.state.startLoc);else if(!this.canHaveLeadingDecorator())throw this.raise(_.UnexpectedLeadingDecorator,this.state.startLoc);return n}parseDecorator(){this.expectOnePlugin(["decorators","decorators-legacy"]);let t=this.startNode();if(this.next(),this.hasPlugin("decorators")){let n=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 o=this.state.startLoc;t.expression=this.parseMaybeDecoratorArguments(r,s),this.getPluginOption("decorators","allowCallParenthesized")===!1&&t.expression!==r&&this.raise(_.DecoratorArgumentsOutsideParentheses,o)}else{for(r=this.parseIdentifier(!1);this.eat(16);){let s=this.startNodeAt(n);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,n)}}else t.expression=this.parseExprSubscripts();return this.finishNode(t,"Decorator")}parseMaybeDecoratorArguments(t,n){if(this.eat(10)){let r=this.startNodeAt(n);return r.callee=t,r.arguments=this.parseCallExpressionArguments(),this.toReferencedList(r.arguments),this.finishNode(r,"CallExpression")}return t}parseBreakContinueStatement(t,n){return this.next(),this.isLineTerminator()?t.label=null:(t.label=this.parseIdentifier(),this.semicolon()),this.verifyBreakContinue(t,n),this.finishNode(t,n?"BreakStatement":"ContinueStatement")}verifyBreakContinue(t,n){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&&(n||s.kind===1)||t.label&&n))break}if(r===this.state.labels.length){let s=n?"BreakStatement":"ContinueStatement";this.raise(_.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(Af),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(Af);let n=null;if(this.isContextual(96)&&this.recordAwaitIfAllowed()&&(n=this.state.startLoc,this.next()),this.scope.enter(0),this.expect(10),this.match(13))return n!==null&&this.unexpected(n),this.parseFor(t,null);let r=this.isContextual(100);{let l=this.isAwaitUsing(),c=l||this.isForUsing(),u=r&&this.hasFollowingBindingAtom()||c;if(this.match(74)||this.match(75)||u){let p=this.startNode(),f;l?(f="await using",this.recordAwaitIfAllowed()||this.raise(_.AwaitUsingNotInAsyncContext,this.state.startLoc),this.next()):f=this.state.value,this.next(),this.parseVar(p,!0,f);let m=this.finishNode(p,"VariableDeclaration"),h=this.match(58);return h&&c&&this.raise(_.ForInUsing,m),(h||this.isContextual(102))&&m.declarations.length===1?this.parseForIn(t,m,n):(n!==null&&this.unexpected(n),this.parseFor(t,m))}}let s=this.isContextual(95),o=new ys,a=this.parseExpression(!0,o),d=this.isContextual(102);if(d&&(r&&this.raise(_.ForOfLet,a),n===null&&s&&a.type==="Identifier"&&this.raise(_.ForOfAsync,a)),d||this.match(58)){this.checkDestructuringPrivate(o),this.toAssignable(a,!0);let l=d?"ForOfStatement":"ForInStatement";return this.checkLVal(a,{type:l}),this.parseForIn(t,a,n)}else this.checkExpressionErrors(o,!0);return n!==null&&this.unexpected(n),this.parseFor(t,a)}parseFunctionStatement(t,n,r){return this.next(),this.parseFunction(t,1|(r?2:0)|(n?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(_.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 n=t.cases=[];this.expect(5),this.state.labels.push(c$),this.scope.enter(256);let r;for(let s;!this.match(8);)if(this.match(61)||this.match(65)){let o=this.match(61);r&&this.finishNode(r,"SwitchCase"),n.push(r=this.startNode()),r.consequent=[],this.next(),o?r.test=this.parseExpression():(s&&this.raise(_.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(_.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 n=this.startNode();this.next(),this.match(10)?(this.expect(10),n.param=this.parseCatchClauseParam(),this.expect(11)):(n.param=null,this.scope.enter(0)),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseBlock(!1,!1)),this.scope.exit(),t.handler=this.finishNode(n,"CatchClause")}return t.finalizer=this.eat(67)?this.parseBlock():null,!t.handler&&!t.finalizer&&this.raise(_.NoCatchOrFinally,t),this.finishNode(t,"TryStatement")}parseVarStatement(t,n,r=!1){return this.next(),this.parseVar(t,!1,n,r),this.semicolon(),this.finishNode(t,"VariableDeclaration")}parseWhileStatement(t){return this.next(),t.test=this.parseHeaderExpression(),this.state.labels.push(Af),t.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.state.labels.pop(),this.finishNode(t,"WhileStatement")}parseWithStatement(t){return this.state.strict&&this.raise(_.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,n,r,s){for(let a of this.state.labels)a.name===n&&this.raise(_.LabelRedeclaration,r,{labelName:n});let o=wO(this.state.type)?1:this.match(71)?2:null;for(let a=this.state.labels.length-1;a>=0;a--){let d=this.state.labels[a];if(d.statementStart===t.start)d.statementStart=this.sourceToOffsetPos(this.state.start),d.kind=o;else break}return this.state.labels.push({name:n,kind:o,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,n,r){return t.expression=n,this.semicolon(),this.finishNode(t,"ExpressionStatement")}parseBlock(t=!1,n=!0,r){let s=this.startNode();return t&&this.state.strictErrors.clear(),this.expect(5),n&&this.scope.enter(0),this.parseBlockBody(s,t,!1,8,r),n&&this.scope.exit(),this.finishNode(s,"BlockStatement")}isValidDirective(t){return t.type==="ExpressionStatement"&&t.expression.type==="StringLiteral"&&!t.expression.extra.parenthesized}parseBlockBody(t,n,r,s,o){let a=t.body=[],d=t.directives=[];this.parseBlockOrModuleBlockBody(a,n?d:void 0,r,s,o)}parseBlockOrModuleBlockBody(t,n,r,s,o){let a=this.state.strict,d=!1,l=!1;for(;!this.match(s);){let c=r?this.parseModuleItem():this.parseStatementListItem();if(n&&!l){if(this.isValidDirective(c)){let u=this.stmtToDirective(c);n.push(u),!d&&u.value.value==="use strict"&&(d=!0,this.setStrict(!0));continue}l=!0,this.state.strictErrors.clear()}t.push(c)}o?.call(this,d),a||this.setStrict(!1),this.next()}parseFor(t,n){return t.init=n,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,n,r){let s=this.match(58);return this.next(),s?r!==null&&this.unexpected(r):t.await=r!==null,n.type==="VariableDeclaration"&&n.declarations[0].init!=null&&(!s||!this.options.annexB||this.state.strict||n.kind!=="var"||n.declarations[0].id.type!=="Identifier")&&this.raise(_.ForInOfLoopInitializer,n,{type:s?"ForInStatement":"ForOfStatement"}),n.type==="AssignmentPattern"&&this.raise(_.InvalidLhs,n,{ancestor:{type:"ForStatement"}}),t.left=n,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,n,r,s=!1){let o=t.declarations=[];for(t.kind=r;;){let a=this.startNode();if(this.parseVarId(a,r),a.init=this.eat(29)?n?this.parseMaybeAssignDisallowIn():this.parseMaybeAssignAllowIn():null,a.init===null&&!s&&(a.id.type!=="Identifier"&&!(n&&(this.match(58)||this.isContextual(102)))?this.raise(_.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:"destructuring"}):(r==="const"||r==="using"||r==="await using")&&!(this.match(58)||this.isContextual(102))&&this.raise(_.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:r})),o.push(this.finishNode(a,"VariableDeclarator")),!this.eat(12))break}return t}parseVarId(t,n){let r=this.parseBindingAtom();n==="using"||n==="await using"?(r.type==="ArrayPattern"||r.type==="ObjectPattern")&&this.raise(_.UsingDeclarationHasBindingPattern,r.loc.start):r.type==="VoidPattern"&&this.raise(_.UnexpectedVoidPattern,r.loc.start),this.checkLVal(r,{type:"VariableDeclarator"},n==="var"?5:8201),t.id=r}parseAsyncFunctionExpression(t){return this.parseFunction(t,8)}parseFunction(t,n=0){let r=n&2,s=!!(n&1),o=s&&!(n&4),a=!!(n&8);this.initFunction(t,a),this.match(55)&&(r&&this.raise(_.GeneratorInSingleStatementContext,this.state.startLoc),this.next(),t.generator=!0),s&&(t.id=this.parseFunctionId(o));let d=this.state.maybeInArrowParameters;return this.state.maybeInArrowParameters=!1,this.scope.enter(514),this.prodParam.enter(Ol(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=d,t}parseFunctionId(t){return t||ye(this.state.type)?this.parseIdentifier():null}parseFunctionParams(t,n){this.expect(10),this.expressionScope.enter(YO()),t.params=this.parseBindingList(11,41,2|(n?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,n,r){this.next();let s=this.state.strict;return this.state.strict=!0,this.parseClassId(t,n,r),this.parseClassSuper(t),t.body=this.parseClassBody(!!t.superClass,s),this.finishNode(t,n?"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,n){this.classScope.enter();let r={hadConstructor:!1,hadSuperClass:t},s=[],o=this.startNode();if(o.body=[],this.expect(5),this.withSmartMixTopicForbiddingContext(()=>{for(;!this.match(8);){if(this.eat(13)){if(s.length>0)throw this.raise(_.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(o,a,r),a.kind==="constructor"&&a.decorators&&a.decorators.length>0&&this.raise(_.DecoratorConstructor,a)}}),this.state.strict=n,this.next(),s.length)throw this.raise(_.TrailingDecorator,this.state.startLoc);return this.classScope.exit(),this.finishNode(o,"ClassBody")}parseClassMemberFromModifier(t,n){let r=this.parseIdentifier(!0);if(this.isClassMethod()){let s=n;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=n;return s.computed=!1,s.key=r,s.static=!1,t.body.push(this.parseClassProperty(s)),!0}return this.resetPreviousNodeTrailingComments(r),!1}parseClassMember(t,n,r){let s=this.isContextual(106);if(s){if(this.parseClassMemberFromModifier(t,n))return;if(this.eat(5)){this.parseClassStaticBlock(t,n);return}}this.parseClassMemberWithIsStatic(t,n,r,s)}parseClassMemberWithIsStatic(t,n,r,s){let o=n,a=n,d=n,l=n,c=n,u=o,p=o;if(n.static=s,this.parsePropertyNamePrefixOperator(n),this.eat(55)){u.kind="method";let w=this.match(139);if(this.parseClassElementName(u),this.parsePostMemberNameModifiers(u),w){this.pushClassPrivateMethod(t,a,!0,!1);return}this.isNonstaticConstructor(o)&&this.raise(_.ConstructorIsGenerator,o.key),this.pushClassMethod(t,o,!0,!1,!1,!1);return}let f=!this.state.containsEsc&&ye(this.state.type),m=this.parseClassElementName(n),h=f?m.name:null,g=this.isPrivateName(m),y=this.state.startLoc;if(this.parsePostMemberNameModifiers(p),this.isClassMethod()){if(u.kind="method",g){this.pushClassPrivateMethod(t,a,!1,!1);return}let w=this.isNonstaticConstructor(o),b=!1;w&&(o.kind="constructor",r.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(_.DuplicateConstructor,m),w&&this.hasPlugin("typescript")&&n.override&&this.raise(_.OverrideOnConstructor,m),r.hadConstructor=!0,b=r.hadSuperClass),this.pushClassMethod(t,o,!1,!1,w,b)}else if(this.isClassProperty())g?this.pushClassPrivateProperty(t,l):this.pushClassProperty(t,d);else if(h==="async"&&!this.isLineTerminator()){this.resetPreviousNodeTrailingComments(m);let w=this.eat(55);p.optional&&this.unexpected(y),u.kind="method";let b=this.match(139);this.parseClassElementName(u),this.parsePostMemberNameModifiers(p),b?this.pushClassPrivateMethod(t,a,w,!0):(this.isNonstaticConstructor(o)&&this.raise(_.ConstructorIsAsync,o.key),this.pushClassMethod(t,o,w,!0,!1,!1))}else if((h==="get"||h==="set")&&!(this.match(55)&&this.isLineTerminator())){this.resetPreviousNodeTrailingComments(m),u.kind=h;let w=this.match(139);this.parseClassElementName(o),w?this.pushClassPrivateMethod(t,a,!1,!1):(this.isNonstaticConstructor(o)&&this.raise(_.ConstructorIsAccessor,o.key),this.pushClassMethod(t,o,!1,!1,!1,!1)),this.checkGetterSetterParams(o)}else if(h==="accessor"&&!this.isLineTerminator()){this.expectPlugin("decoratorAutoAccessors"),this.resetPreviousNodeTrailingComments(m);let w=this.match(139);this.parseClassElementName(d),this.pushClassAccessorProperty(t,c,w)}else this.isLineTerminator()?g?this.pushClassPrivateProperty(t,l):this.pushClassProperty(t,d):this.unexpected()}parseClassElementName(t){let{type:n,value:r}=this.state;if((n===132||n===134)&&t.static&&r==="prototype"&&this.raise(_.StaticPrototype,this.state.startLoc),n===139){r==="constructor"&&this.raise(_.ConstructorClassPrivateField,this.state.startLoc);let s=this.parsePrivateName();return t.key=s,s}return this.parsePropertyName(t),t.key}parseClassStaticBlock(t,n){var r;this.scope.enter(720);let s=this.state.labels;this.state.labels=[],this.prodParam.enter(0);let o=n.body=[];this.parseBlockOrModuleBlockBody(o,void 0,!1,8),this.prodParam.exit(),this.scope.exit(),this.state.labels=s,t.body.push(this.finishNode(n,"StaticBlock")),(r=n.decorators)!=null&&r.length&&this.raise(_.DecoratorStaticBlock,n)}pushClassProperty(t,n){!n.computed&&this.nameIsConstructor(n.key)&&this.raise(_.ConstructorClassField,n.key),t.body.push(this.parseClassProperty(n))}pushClassPrivateProperty(t,n){let r=this.parseClassPrivateProperty(n);t.body.push(r),this.classScope.declarePrivateName(this.getPrivateNameSV(r.key),0,r.key.loc.start)}pushClassAccessorProperty(t,n,r){!r&&!n.computed&&this.nameIsConstructor(n.key)&&this.raise(_.ConstructorClassField,n.key);let s=this.parseClassAccessorProperty(n);t.body.push(s),r&&this.classScope.declarePrivateName(this.getPrivateNameSV(s.key),0,s.key.loc.start)}pushClassMethod(t,n,r,s,o,a){t.body.push(this.parseMethod(n,r,s,o,a,"ClassMethod",!0))}pushClassPrivateMethod(t,n,r,s){let o=this.parseMethod(n,r,s,!1,!1,"ClassPrivateMethod",!0);t.body.push(o);let a=o.kind==="get"?o.static?6:2:o.kind==="set"?o.static?5:1:0;this.declareClassPrivateMethodInScope(o,a)}declareClassPrivateMethodInScope(t,n){this.classScope.declarePrivateName(this.getPrivateNameSV(t.key),n,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(xk()),this.prodParam.enter(0),t.value=this.eat(29)?this.parseMaybeAssignAllowIn():null,this.expressionScope.exit(),this.prodParam.exit(),this.scope.exit()}parseClassId(t,n,r,s=8331){if(ye(this.state.type))t.id=this.parseIdentifier(),n&&this.declareNameFromIdentifier(t.id,s);else if(r||!n)t.id=null;else throw this.raise(_.MissingClassName,this.state.startLoc)}parseClassSuper(t){t.superClass=this.eat(81)?this.parseExprSubscripts():null}parseExport(t,n){let r=this.parseMaybeImportPhase(t,!0),s=this.maybeParseExportDefaultSpecifier(t,r),o=!s||this.eat(12),a=o&&this.eatExportStar(t),d=a&&this.maybeParseExportNamespaceSpecifier(t),l=o&&(!d||this.eat(12)),c=s||a;if(a&&!d){if(s&&this.unexpected(),n)throw this.raise(_.UnsupportedDecoratorExport,t);return this.parseExportFrom(t,!0),this.sawUnambiguousESM=!0,this.finishNode(t,"ExportAllDeclaration")}let u=this.maybeParseExportNamedSpecifiers(t);s&&o&&!a&&!u&&this.unexpected(null,5),d&&l&&this.unexpected(null,98);let p;if(c||u){if(p=!1,n)throw this.raise(_.UnsupportedDecoratorExport,t);this.parseExportFrom(t,c)}else p=this.maybeParseExportDeclaration(t);if(c||u||p){var f;let m=t;if(this.checkExport(m,!0,!1,!!m.source),((f=m.declaration)==null?void 0:f.type)==="ClassDeclaration")this.maybeTakeDecorators(n,m.declaration,m);else if(n)throw this.raise(_.UnsupportedDecoratorExport,t);return this.sawUnambiguousESM=!0,this.finishNode(m,"ExportNamedDeclaration")}if(this.eat(65)){let m=t,h=this.parseExportDefaultExpression();if(m.declaration=h,h.type==="ClassDeclaration")this.maybeTakeDecorators(n,h,m);else if(n)throw this.raise(_.UnsupportedDecoratorExport,t);return this.checkExport(m,!0,!0),this.sawUnambiguousESM=!0,this.finishNode(m,"ExportDefaultDeclaration")}throw this.unexpected(null,5)}eatExportStar(t){return this.eat(55)}maybeParseExportDefaultSpecifier(t,n){if(n||this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom",n?.loc.start);let r=n||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 n,r;(r=(n=t).specifiers)!=null||(n.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 n=t;n.specifiers||(n.specifiers=[]);let r=n.exportKind==="type";return n.specifiers.push(...this.parseExportSpecifiers(r)),n.source=null,this.hasPlugin("importAssertions")?n.assertions=[]:n.attributes=[],n.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(_.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(_.UnsupportedDefaultExport,this.state.startLoc);let n=this.parseMaybeAssignAllowIn();return this.semicolon(),n}parseExportDeclaration(t){return this.match(80)?this.parseClass(this.startNode(),!0,!1):this.parseStatementListItem()}isExportDefaultSpecifier(){let{type:t}=this.state;if(ye(t)){if(t===95&&!this.state.containsEsc||t===100)return!1;if((t===130||t===129)&&!this.state.containsEsc){let s=this.nextTokenStart(),o=this.input.charCodeAt(s);if(o===123||this.chStartsBindingIdentifier(o,s)&&!this.input.startsWith("from",s))return this.expectOnePlugin(["flow","typescript"]),!1}}else if(!this.match(65))return!1;let n=this.nextTokenStart(),r=this.isUnparsedContextual(n,"from");if(this.input.charCodeAt(n)===44||ye(this.state.type)&&r)return!0;if(this.match(65)&&r){let s=this.input.charCodeAt(this.nextTokenStartSince(n+4));return s===34||s===39}return!1}parseExportFrom(t,n){this.eatContextual(98)?(t.source=this.parseImportSource(),this.checkExport(t),this.maybeParseImportAttributes(t),this.checkJSONModuleImport(t)):n&&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(_.DecoratorBeforeExport,this.state.startLoc),!0):this.isUsing()?(this.raise(_.UsingDeclarationExport,this.state.startLoc),!0):this.isAwaitUsing()?(this.raise(_.UsingDeclarationExport,this.state.startLoc),!0):t===74||t===75||t===68||t===80||this.isLet()||this.isAsyncFunction()}checkExport(t,n,r,s){if(n){var o;if(r){if(this.checkDuplicateExports(t,"default"),this.hasPlugin("exportDefaultFrom")){var a;let d=t.declaration;d.type==="Identifier"&&d.name==="from"&&d.end-d.start===4&&!((a=d.extra)!=null&&a.parenthesized)&&this.raise(_.ExportDefaultFromAsIdentifier,d)}}else if((o=t.specifiers)!=null&&o.length)for(let d of t.specifiers){let{exported:l}=d,c=l.type==="Identifier"?l.name:l.value;if(this.checkDuplicateExports(d,c),!s&&d.local){let{local:u}=d;u.type!=="Identifier"?this.raise(_.ExportBindingIsString,d,{localName:u.value,exportName:c}):(this.checkReservedWord(u.name,u.loc.start,!0,!1),this.scope.checkLocalExport(u))}}else if(t.declaration){let d=t.declaration;if(d.type==="FunctionDeclaration"||d.type==="ClassDeclaration"){let{id:l}=d;if(!l)throw new Error("Assertion failure");this.checkDuplicateExports(t,l.name)}else if(d.type==="VariableDeclaration")for(let l of d.declarations)this.checkDeclaration(l.id)}}}checkDeclaration(t){if(t.type==="Identifier")this.checkDuplicateExports(t,t.name);else if(t.type==="ObjectPattern")for(let n of t.properties)this.checkDeclaration(n);else if(t.type==="ArrayPattern")for(let n of t.elements)n&&this.checkDeclaration(n);else t.type==="ObjectProperty"?this.checkDeclaration(t.value):t.type==="RestElement"?this.checkDeclaration(t.argument):t.type==="AssignmentPattern"&&this.checkDeclaration(t.left)}checkDuplicateExports(t,n){this.exportedIdentifiers.has(n)&&(n==="default"?this.raise(_.DuplicateDefaultExport,t):this.raise(_.DuplicateExport,t,{exportName:n})),this.exportedIdentifiers.add(n)}parseExportSpecifiers(t){let n=[],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),o=this.match(134),a=this.startNode();a.local=this.parseModuleExportName(),n.push(this.parseExportSpecifier(a,o,t,s))}return n}parseExportSpecifier(t,n,r,s){return this.eatContextual(93)?t.exported=this.parseModuleExportName():n?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),n=u$.exec(t.value);return n&&this.raise(_.ModuleExportNameHasLoneSurrogate,t,{surrogateCharCode:n[0].charCodeAt(0)}),t}return this.parseIdentifier(!0)}isJSONModuleImport(t){return t.assertions!=null?t.assertions.some(({key:n,value:r})=>r.value==="json"&&(n.type==="Identifier"?n.name==="type":n.value==="type")):!1}checkImportReflection(t){let{specifiers:n}=t,r=n.length===1?n[0].type:null;if(t.phase==="source")r!=="ImportDefaultSpecifier"&&this.raise(_.SourcePhaseImportRequiresDefault,n[0].loc.start);else if(t.phase==="defer")r!=="ImportNamespaceSpecifier"&&this.raise(_.DeferImportRequiresNamespace,n[0].loc.start);else if(t.module){var s;r!=="ImportDefaultSpecifier"&&this.raise(_.ImportReflectionNotBinding,n[0].loc.start),((s=t.assertions)==null?void 0:s.length)>0&&this.raise(_.ImportReflectionHasAssertion,n[0].loc.start)}}checkJSONModuleImport(t){if(this.isJSONModuleImport(t)&&t.type!=="ExportAllDeclaration"){let{specifiers:n}=t;if(n!=null){let r=n.find(s=>{let o;if(s.type==="ExportSpecifier"?o=s.local:s.type==="ImportSpecifier"&&(o=s.imported),o!==void 0)return o.type==="Identifier"?o.name!=="default":o.value!=="default"});r!==void 0&&this.raise(_.ImportJSONBindingNotDefault,r.loc.start)}}}isPotentialImportPhase(t){return t?!1:this.isContextual(105)||this.isContextual(97)||this.isContextual(127)}applyImportPhase(t,n,r,s){n||(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,n){if(!this.isPotentialImportPhase(n))return this.applyImportPhase(t,n,null),null;let r=this.startNode(),s=this.parseIdentifierName(!0),{type:o}=this.state;return(Zt(o)?o!==98||this.lookaheadCharCode()===102:o!==12)?(this.applyImportPhase(t,n,s,r.loc.start),null):(this.applyImportPhase(t,n,null),this.createIdentifier(r,s))}isPrecedingIdImportPhase(t){let{type:n}=this.state;return ye(n)?n!==98||this.lookaheadCharCode()===102:n!==12}parseImport(t){return this.match(134)?this.parseImportSourceAndAttributes(t):this.parseImportSpecifiersAndAfter(t,this.parseMaybeImportPhase(t,!1))}parseImportSpecifiersAndAfter(t,n){t.specifiers=[];let s=!this.maybeParseDefaultImportSpecifier(t,n)||this.eat(12),o=s&&this.maybeParseStarImportSpecifier(t);return s&&!o&&this.parseNamedImportSpecifiers(t),this.expectContextual(98),this.parseImportSourceAndAttributes(t)}parseImportSourceAndAttributes(t){var n;return(n=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,n,r){n.local=this.parseIdentifier(),t.specifiers.push(this.finishImportSpecifier(n,r))}finishImportSpecifier(t,n,r=8201){return this.checkLVal(t.local,{type:n},r),this.finishNode(t,n)}parseImportAttributes(){this.expect(5);let t=[],n=new Set;do{if(this.match(8))break;let r=this.startNode(),s=this.state.value;if(n.has(s)&&this.raise(_.ModuleAttributesWithDuplicateKeys,this.state.startLoc,{key:s}),n.add(s),this.match(134)?r.key=this.parseStringLiteral(s):r.key=this.parseIdentifier(!0),this.expect(14),!this.match(134))throw this.raise(_.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=[],n=new Set;do{let r=this.startNode();if(r.key=this.parseIdentifier(!0),r.key.name!=="type"&&this.raise(_.ModuleAttributeDifferentFromType,r.key),n.has(r.key.name)&&this.raise(_.ModuleAttributesWithDuplicateKeys,r.key,{key:r.key.name}),n.add(r.key.name),this.expect(14),!this.match(134))throw this.raise(_.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 n;var r=!1;if(this.match(76)){if(this.hasPrecedingLineBreak()&&this.lookaheadCharCode()===40)return;this.next(),this.hasPlugin("moduleAttributes")?(n=this.parseModuleAttributes(),this.addExtra(t,"deprecatedWithLegacySyntax",!0)):n=this.parseImportAttributes(),r=!0}else this.isContextual(94)&&!this.hasPrecedingLineBreak()?(!this.hasPlugin("deprecatedImportAssert")&&!this.hasPlugin("importAssertions")&&this.raise(_.ImportAttributesUseAssert,this.state.startLoc),this.hasPlugin("importAssertions")||this.addExtra(t,"deprecatedAssertSyntax",!0),this.next(),n=this.parseImportAttributes()):n=[];!r&&this.hasPlugin("importAssertions")?t.assertions=n:t.attributes=n}maybeParseDefaultImportSpecifier(t,n){if(n){let r=this.startNodeAtNode(n);return r.local=n,t.specifiers.push(this.finishImportSpecifier(r,"ImportDefaultSpecifier")),!0}else if(Zt(this.state.type))return this.parseImportSpecifierLocal(t,this.startNode(),"ImportDefaultSpecifier"),!0;return!1}maybeParseStarImportSpecifier(t){if(this.match(55)){let n=this.startNode();return this.next(),this.expectContextual(93),this.parseImportSpecifierLocal(t,n,"ImportNamespaceSpecifier"),!0}return!1}parseNamedImportSpecifiers(t){let n=!0;for(this.expect(5);!this.eat(8);){if(n)n=!1;else{if(this.eat(14))throw this.raise(_.DestructureNamedImport,this.state.startLoc);if(this.expect(12),this.eat(8))break}let r=this.startNode(),s=this.match(134),o=this.isContextual(130);r.imported=this.parseModuleExportName();let a=this.parseImportSpecifier(r,s,t.importKind==="type"||t.importKind==="typeof",o,void 0);t.specifiers.push(a)}}parseImportSpecifier(t,n,r,s,o){if(this.eatContextual(93))t.local=this.parseIdentifier();else{let{imported:a}=t;if(n)throw this.raise(_.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",o)}isThisParam(t){return t.type==="Identifier"&&t.name==="this"}},Dl=class extends Yf{constructor(t,n,r){let s=cO(t);super(s,n),this.options=s,this.initializeScopes(),this.plugins=r,this.filename=s.sourceFilename,this.startIndex=s.startIndex;let o=0;s.allowAwaitOutsideFunction&&(o|=1),s.allowReturnOutsideFunction&&(o|=2),s.allowImportExportEverywhere&&(o|=8),s.allowSuperOutsideMethod&&(o|=16),s.allowUndeclaredExports&&(o|=64),s.allowNewTargetOutsideFunction&&(o|=4),s.allowYieldOutsideFunction&&(o|=32),s.ranges&&(o|=128),s.tokens&&(o|=256),s.createImportExpressions&&(o|=512),s.createParenthesizedExpressions&&(o|=1024),s.errorRecovery&&(o|=2048),s.attachComment&&(o|=4096),s.annexB&&(o|=8192),this.optionFlags=o}getScopeHandler(){return ia}parse(){this.enterInitialScopes();let t=this.startNode(),n=this.startNode();this.nextToken(),t.errors=null;let r=this.parseTopLevel(t,n);return r.errors=this.state.errors,r.comments.length=this.state.commentsLen,r}};function f$(e,t){var n;if(((n=t)==null?void 0:n.sourceType)==="unambiguous"){t=Object.assign({},t);try{t.sourceType="module";let r=ta(t,e),s=r.parse();if(r.sawUnambiguousESM)return s;if(r.ambiguousScriptDifferentAst)try{return t.sourceType="script",ta(t,e).parse()}catch{}else s.program.sourceType="script";return s}catch(r){try{return t.sourceType="script",ta(t,e).parse()}catch{}throw r}}else return ta(t,e).parse()}function m$(e,t){let n=ta(t,e);return n.options.strictMode&&(n.state.strict=!0),n.getExpression()}function h$(e){let t={};for(let n of Object.keys(e))t[n]=Jn(e[n]);return t}var g$=h$(mO);function ta(e,t){let n=Dl,r=new Map;if(e!=null&&e.plugins){for(let s of e.plugins){let o,a;typeof s=="string"?o=s:[o,a]=s,r.has(o)||r.set(o,a||{})}d$(r),n=y$(r)}return new n(e,t,r)}var pk=new Map;function y$(e){let t=[];for(let s of l$)e.has(s)&&t.push(s);let n=t.join("|"),r=pk.get(n);if(!r){r=Dl;for(let s of t)r=Sk[s](r);pk.set(n,r)}return r}oa.parse=f$;oa.parseExpression=m$;oa.tokTypes=g$});import{parseArgs as _J}from"node:util";import{writeFile as PC}from"node:fs/promises";import{join as EC}from"node:path";function $b(e,t){try{let n=new URL(e);return t.includes(n.protocol)&&n.username===""&&n.password===""&&n.search===""&&n.hash===""?n.href.replace(/\/+$/,""):void 0}catch{return}}function Gt(e,t=""){return $b(e===void 0||e===""?t:e,["https:"])}function Mp(e){return $b(e??"",["https:","http:"])}var CC=3e4,NC="7.1",Mb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Db="KwikQA.Ci",OC=4,Fb=/^\$\([\w.-]+\)$/;function jp(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t===void 0||!Fb.test(t.trim())))}function $C(e){if(!(e===void 0||e===""))try{let t=new URL(e);return t.username="",t.password="",Gt(t.href)}catch{return}}function Lp(e){let t=Number(e);return/^\d+$/.test(e??"")&&Number.isSafeInteger(t)&&t>0?t:void 0}function Lb(e){if(!(e===void 0||e===""||e.startsWith("refs/pull/")))return e.replace(/^refs\/(?:heads|tags)\//,"")}function zr(e){if(e.TF_BUILD!=="True")return;let t=Gt(e.SYSTEM_COLLECTIONURI),n=e.SYSTEM_TEAMPROJECT??"",r=Lp(e.BUILD_BUILDID),s=e.BUILD_REPOSITORY_PROVIDER??"",o=s==="GitHub"||s==="GitHubEnterprise",a=s==="TfsGit"?"pullrequest":o?"pull":void 0,d=a===void 0?void 0:$C(e.BUILD_REPOSITORY_URI),l=Lp((o?e.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER:void 0)||e.SYSTEM_PULLREQUEST_PULLREQUESTID),c=/^[0-9a-f]{40}$/i.test(e.BUILD_SOURCEVERSION??"")?e.BUILD_SOURCEVERSION:void 0,u=Lb(e.SYSTEM_PULLREQUEST_SOURCEBRANCH)??Lb(e.BUILD_SOURCEBRANCH),p=(e.SYSTEM_ACCESSTOKEN??"").trim(),f=Lp(e.SYSTEM_JOBATTEMPT),m=/^refs\/[^\s\0]+$/.test(e.BUILD_SOURCEBRANCH??"")?e.BUILD_SOURCEBRANCH:void 0,h=e.SYSTEM_PULLREQUEST_SOURCEBRANCH?.startsWith("refs/heads/")?e.SYSTEM_PULLREQUEST_SOURCEBRANCH.slice(11):void 0,g=/^[0-9a-f]{40}$/i.test(e.SYSTEM_PULLREQUEST_SOURCECOMMITID??"")?e.SYSTEM_PULLREQUEST_SOURCECOMMITID?.toLowerCase():void 0,y=Mb.test(e.SYSTEM_TEAMPROJECTID??"")?e.SYSTEM_TEAMPROJECTID:void 0,w=Mb.test(e.BUILD_REPOSITORY_ID??"")?e.BUILD_REPOSITORY_ID:void 0;return{...t===void 0?{}:{collectionUrl:t},...y===void 0?{}:{projectId:y},...w===void 0?{}:{repositoryId:w},provider:s,...e.BUILD_REPOSITORY_NAME?{repository:e.BUILD_REPOSITORY_NAME}:{},...t===void 0||n===""||r===void 0?{}:{runUrl:`${t}/${encodeURIComponent(n)}/_build/results?buildId=${r}`},pipeline:e.SYSTEM_DEFINITIONID||e.BUILD_DEFINITIONNAME||"",job:[e.SYSTEM_STAGENAME,e.SYSTEM_JOBNAME].filter(Boolean).join("."),...u===void 0?{}:{branch:u},...c===void 0?{}:{commit:{sha:c,...d===void 0?{}:{url:`${d}/commit/${c}`}}},...e.AGENT_TEMPDIRECTORY?{tempDirectory:e.AGENT_TEMPDIRECTORY}:{},...p===""||Fb.test(p)?{}:{token:p},...r===void 0?{}:{buildId:String(r)},...f===void 0?{}:{jobAttempt:f},...m===void 0?{}:{ref:m},...l!==void 0&&h!==void 0&&g!==void 0?{pullRequestHead:{ref:h,sha:g}}:{},...l===void 0?{}:{pullRequest:{number:l,...d===void 0?{}:{url:`${d}/${a}/${l}`},fork:e.SYSTEM_PULLREQUEST_ISFORK==="True"}}}}function MC(e,t="ci"){return`kwikqa-${t} pipeline=${encodeURIComponent(e.pipeline)} job=${encodeURIComponent(e.job)}`}function LC(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function mn(e){return e.ok&&e.status!==203}async function Zd(e){let t=await e.json().catch(()=>{});return typeof t?.message=="string"?t.message.replace(/\s+/g," ").trim().slice(0,200):void 0}async function Dp(e){if(e.status===429)return"Azure DevOps's rate limit was reached";if(e.status===401||e.status===203)return"Azure DevOps refused the token";if(e.status===403){let n=await Zd(e);return`the build service can't comment on this pull request; give it "Contribute to pull requests" on the repository${n===void 0?"":` (${n})`}`}if(e.status===404)return"Azure DevOps found no such pull request with this token";let t=await Zd(e);return`Azure DevOps answered ${e.status}${t===void 0?"":`: ${t}`}`}var Fp=class{constructor(t,n,r){this.send=t;this.base=n;this.token=r}send;base;token;call(t,n,r){return this.send(`${this.base}${n}?api-version=${NC}`,{method:t,headers:{Accept:"application/json",Authorization:`Bearer ${this.token}`,...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error",signal:AbortSignal.timeout(CC)})}},rs=class extends Error{};function DC(e){if(typeof e=="string")return e;let t=typeof e=="object"&&e!==null?e:{};return typeof t.$value=="string"?t.$value:void 0}async function FC(e,t){let n=await e.call("GET","/threads");if(!mn(n))throw new rs(await Dp(n));let r=(await n.json()).value??[];for(let s of r){if(s.isDeleted===!0||DC(s.properties?.[Db])!==t)continue;let o=s.comments?.find(a=>a.parentCommentId===0&&a.isDeleted!==!0);if(typeof s.id=="number"&&typeof o?.id=="number")return{thread:s.id,comment:o.id}}}async function Bp(e,t,n,r,s){let o=n.noun??"pull-request comment",a=`${o.charAt(0).toUpperCase()}${o.slice(1)}`,d=new Fp(t,`${n.collectionUrl}/${n.projectId}/_apis/git/repositories/${n.repositoryId}/pullRequests/${n.pullRequest}`,n.token);try{let l=await FC(d,n.marker);if(l!==void 0){let u=await d.call("PATCH",`/threads/${l.thread}/comments/${l.comment}`,{content:r});if(mn(u))return e.print(`${a}: updated.`);if(u.status!==403&&u.status!==404)throw new rs(await Dp(u))}if(l===void 0&&!s)return e.print(`No ${o}: nothing failed, and there is no earlier comment to update.`);let c=await d.call("POST","/threads",{comments:[{parentCommentId:0,content:r,commentType:1}],status:OC,properties:{[Db]:{$type:"System.String",$value:n.marker}}});if(!mn(c))throw new rs(await Dp(c));e.print(`${a}: posted.`)}catch(l){let c=l instanceof rs?l.message:`Azure DevOps couldn't be reached (${l instanceof Error?l.message:String(l)})`;e.error(`No ${o}: ${c}.`)}}async function jC(e,t,n,r,s,o){let a=l=>e.print(`No pull-request comment: ${l}.`),d=n.pullRequest;if(d===void 0)return a("this run isn't for a pull request");if(n.provider!=="TfsGit")return a(`the repository is on ${n.provider||"another host"}, and KwikQA comments from Azure Pipelines only on Azure Repos pull requests`);if(d.fork)return a("the pull request comes from a fork, and its build gets no secrets by default");if(n.token===void 0)return a("SYSTEM_ACCESSTOKEN isn't set; add `SYSTEM_ACCESSTOKEN: $(System.AccessToken)` to the step's env");if(n.collectionUrl===void 0||n.projectId===void 0||n.repositoryId===void 0)return a("System.CollectionUri, System.TeamProjectId, or Build.Repository.ID isn't what Azure Pipelines sets");await Bp(e,t,{collectionUrl:n.collectionUrl,projectId:n.projectId,repositoryId:n.repositoryId,pullRequest:d.number,token:n.token,marker:MC(n,o)},r,s)}async function Io(e,t,n,r,s){if(n.tempDirectory===void 0)e.print("No build summary: AGENT_TEMPDIRECTORY isn't set.");else{let o=EC(n.tempDirectory,"kwikqa-summary.md");try{await PC(o,r);let a=`##vso[task.addattachment type=Distributedtask.Core.Summary;name=KwikQA;]${LC(o)}`;e.command===void 0?e.print(a):e.command(a),e.print("Build summary: written.")}catch(a){e.error(`No build summary: ${a.message}`)}}await jC(e,t,n,r,s.failures,s.command??"ci")}import{createHash as pT}from"node:crypto";import{readFile as z6,stat as q6}from"node:fs/promises";import{join as G6,relative as K6,sep as W6}from"node:path";import{randomUUID as Ix}from"node:crypto";import{realpath as ND}from"node:fs/promises";import{join as Sx}from"node:path";import{open as zC}from"node:fs/promises";import{createHash as jb}from"node:crypto";function BC(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function Ce(e){return jb("sha256").update(e).digest("hex")}function Y(e,t){let n=t.map(BC).join("|"),r=jb("sha256").update(n,"utf8").digest("hex");return`${e}_${r.slice(0,24)}`}import{realpath as Bb,stat as VC}from"node:fs/promises";import{isAbsolute as Hb,relative as UC,resolve as HC,sep as Vb}from"node:path";function Ub(e,t){let n=UC(e,t);if(n==="")return"";if(!(n===".."||n.startsWith(`..${Vb}`)||Hb(n)))return n.split(Vb).join("/")}async function Kt(e,t){if(t.includes("\0"))return{kind:"unauthorized",message:"Path contains a NUL byte."};let n;try{n=await Bb(e)}catch{return{kind:"unreadable",message:"Authorized root could not be resolved."}}let r=Hb(t)?t:HC(n,t);if(Ub(n,r)===void 0)return{kind:"unauthorized",message:"Path escapes the authorized root."};let s;try{s=await Bb(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 o=Ub(n,s);if(o===void 0)return{kind:"unauthorized",message:"Resolved path escapes the authorized root."};try{if(!(await VC(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:o}}function Vp(e){return e.length===0||e.includes("\0")||e.includes("\\")||e.startsWith("/")||/^[A-Za-z]:/.test(e)?!1:e.split("/").every(n=>n!==".."&&n!==".")}async function G(e,t,n){let r=await Kt(e,t);if(r.kind!=="authorized")return r;let s;try{s=await zC(r.absolutePath,"r");let o=await s.stat();if(o.size>n)return{kind:"over-budget",message:`Artifact exceeds the ${n}-byte limit.`,relativePath:r.relativePath};let a=new Uint8Array(o.size),d=0;for(;d<a.byteLength;){let l=await s.read(a,d,a.byteLength-d,d);if(l.bytesRead===0)break;d+=l.bytesRead}return d!==a.byteLength?{kind:"unreadable",message:"Artifact changed or ended while it was being read.",relativePath:r.relativePath}:{kind:"read",bytes:a,sha256:Ce(a),relativePath:r.relativePath}}catch{return{kind:"unreadable",message:"Authorized artifact could not be read.",relativePath:r.relativePath}}finally{await s?.close()}}import{createHash as qC}from"node:crypto";function Up(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError("canonical JSON cannot contain non-finite numbers");return e}if(Array.isArray(e))return e.map(n=>Up(n,t));if(typeof e!="object")throw new TypeError(`canonical JSON cannot contain ${typeof e}`);if(t.has(e))throw new TypeError("canonical JSON cannot contain cycles");t.add(e);try{let n=e,r={};for(let s of Object.keys(n).sort()){let o=n[s];if(o===void 0)throw new TypeError(`canonical JSON cannot contain undefined at ${JSON.stringify(s)}`);r[s]=Up(o,t)}return r}finally{t.delete(e)}}function le(e){return JSON.stringify(Up(e,new Set))}function V(e){return qC("sha256").update(le(e),"utf8").digest("hex")}import{createHash as GC,randomUUID as tl}from"node:crypto";import{constants as is}from"node:fs";import{chmod as KC,link as WC,lstat as Un,mkdir as Gb,open as el,readFile as Kb,realpath as Vn,rename as qp,rm as zb,unlink as Hp}from"node:fs/promises";import{dirname as zp,isAbsolute as JC,join as mr,relative as Wb,resolve as Gp,sep as Jb}from"node:path";var YC=/^txn_[a-f0-9]{24}$/;function qr(e,t){let n=Wb(e,t);return n===""||!JC(n)&&n!==".."&&!n.startsWith(`..${Jb}`)}async function ss(e){if(process.platform==="win32")return;let t=await el(e,"r");try{await t.sync()}finally{await t.close()}}function qb(e){return GC("sha256").update(e).digest("hex")}function Yb(){return`txn_${tl().replaceAll("-","").slice(0,24)}`}function Hn(e){return YC.test(e)}async function nl(e){let t=await Vn(e),n=Gp(t,".kwikqa","transactions");if(!qr(t,n))throw new Error("Transaction path escapes workspace.");return{root:t,transactionsDirectory:n}}async function ge(e,t){let n=await Vn(e),r=n;for(let s of t){if(!/^[A-Za-z0-9_.-]+$/.test(s)||s==="."||s==="..")throw new Error("Unsafe transaction directory segment.");let o=mr(r,s),a=await Un(o).catch(l=>{if(l.code!=="ENOENT")throw l});if(a===void 0)await Gb(o,{mode:448}),await ss(r);else if(!a.isDirectory()||a.isSymbolicLink())throw new Error("Transaction directory contains an unsafe path.");let d=await Vn(o);if(!qr(n,d))throw new Error("Transaction directory escapes workspace.");r=d}return r}async function Xb(e,t,n){if(!/^\.staging-[a-f0-9]{24}$/.test(t)||!Hn(n))throw new Error("Transaction publication name is invalid.");let r=await nl(e),s=await Vn(r.transactionsDirectory),o=mr(s,t),a=mr(s,n),d=await Un(o);if(!d.isDirectory()||d.isSymbolicLink())throw new Error("Transaction staging directory is unsafe.");if(await Un(a).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Transaction already exists.");await qp(o,a),await ss(s)}async function oe(e,t,n){let r=await Vn(zp(e)),s=Gp(r,e.slice(zp(e).length+1));if(!qr(r,s))throw new Error("Write target escapes its directory.");if(!n.replace&&await Un(s).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Durable record already exists.");let o=mr(r,`.kwikqa-${tl()}.tmp`),a=await el(o,"wx",n.mode),d=!1;try{await a.writeFile(t),await a.sync(),await a.close(),n.replace?await qp(o,s):(await WC(o,s),await Hp(o)),d=!0,await ss(r)}finally{await a.close().catch(()=>{}),d||await Hp(o).catch(()=>{})}}async function hr(e,t,n,r){let s=await Vn(e),o=Gp(s,t);if(!qr(s,o))throw new Error("Target escapes workspace.");let a=await Un(o);if(!a.isFile()||a.isSymbolicLink())throw new Error("Target is not a regular file.");let d=await Vn(zp(o)),l=await Vn(o);if(!qr(s,d)||!qr(s,l))throw new Error("Target escapes workspace.");if(Wb(s,l).split(Jb).join("/")!==t)throw new Error("Target canonical path changed during final authorization.");let u=await el(l,is.O_RDONLY|is.O_NOFOLLOW);try{let g=await u.stat();if(!g.isFile()||g.dev!==a.dev||g.ino!==a.ino)throw new Error("Target changed during final authorization.");let y=await u.readFile();if(qb(y)!==n)throw new Error("Target content changed during final authorization.")}finally{await u.close()}let p=mr(d,`.kwikqa-target-${tl()}.tmp`),f=a.mode&511,m=await el(p,is.O_CREAT|is.O_EXCL|is.O_WRONLY|is.O_NOFOLLOW,f),h=!1;try{await m.writeFile(r),await m.sync(),await m.close(),await KC(p,f);let g=await Vn(o);if(g!==l||!qr(s,g))throw new Error("Target path changed before replacement.");let y=await Kb(g),w=await Un(g);if(!w.isFile()||w.isSymbolicLink()||w.dev!==a.dev||w.ino!==a.ino||qb(y)!==n)throw new Error("Target changed before replacement.");await qp(p,g),h=!0,await ss(d)}finally{await m.close().catch(()=>{}),h||await Hp(p).catch(()=>{})}}async function Qe(e,t){let n=await ge(e,[".kwikqa","transactions"]),r=mr(n,".lock"),s=tl();await Gb(r,{mode:448});let o=await Un(r);try{await oe(mr(r,"owner.json"),`${JSON.stringify({...t,nonce:s})}
|
|
10
|
+
`),cooked:o===null?null:o.slice(1,c)},d.tail=l,this.next();let p=this.finishNode(d,"TemplateElement");return this.resetEndLocation(p,dt(this.state.lastTokEndLoc,c)),p}parseTemplate(t){let n=this.startNode(),r=this.parseTemplateElement(t),s=[r],o=[];for(;!r.tail;)o.push(this.parseTemplateSubstitution()),this.readTemplateContinuation(),s.push(r=this.parseTemplateElement(t));return n.expressions=o,n.quasis=s,this.finishNode(n,"TemplateLiteral")}parseTemplateSubstitution(){return this.parseExpression()}parseObjectLike(t,n,r,s){r&&this.expectPlugin("recordAndTuple");let o=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let a=!1,d=!0,l=this.startNode();for(l.properties=[],this.next();!this.match(t);){if(d)d=!1;else if(this.expect(12),this.match(t)){this.addTrailingCommaExtraToNode(l);break}let u;n?u=this.parseBindingProperty():(u=this.parsePropertyDefinition(s),a=this.checkProto(u,r,a,s)),r&&!this.isObjectProperty(u)&&u.type!=="SpreadElement"&&this.raise(_.InvalidRecordProperty,u),u.shorthand&&this.addExtra(u,"shorthand",!0),l.properties.push(u)}this.next(),this.state.inFSharpPipelineDirectBody=o;let c="ObjectExpression";return n?c="ObjectPattern":r&&(c="RecordExpression"),this.finishNode(l,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 n=[];if(this.match(26))for(this.hasPlugin("decorators")&&this.raise(_.UnsupportedPropertyDecorator,this.state.startLoc);this.match(26);)n.push(this.parseDecorator());let r=this.startNode(),s=!1,o=!1,a;if(this.match(21))return n.length&&this.unexpected(),this.parseSpread();n.length&&(r.decorators=n,n=[]),r.method=!1,t&&(a=this.state.startLoc);let d=this.eat(55);this.parsePropertyNamePrefixOperator(r);let l=this.state.containsEsc;if(this.parsePropertyName(r,t),!d&&!l&&this.maybeAsyncOrAccessorProp(r)){let{key:c}=r,u=c.name;u==="async"&&!this.hasPrecedingLineBreak()&&(s=!0,this.resetPreviousNodeTrailingComments(c),d=this.eat(55),this.parsePropertyName(r)),(u==="get"||u==="set")&&(o=!0,this.resetPreviousNodeTrailingComments(c),r.kind=u,this.match(55)&&(d=!0,this.raise(_.AccessorIsGenerator,this.state.curPosition(),{kind:u}),this.next()),this.parsePropertyName(r))}return this.parseObjPropValue(r,a,d,s,!1,o,t)}getGetterSetterExpectedParamCount(t){return t.kind==="get"?0:1}getObjectOrClassMethodParams(t){return t.params}checkGetterSetterParams(t){var n;let r=this.getGetterSetterExpectedParamCount(t),s=this.getObjectOrClassMethodParams(t);s.length!==r&&this.raise(t.kind==="get"?_.BadGetterArity:_.BadSetterArity,t),t.kind==="set"&&((n=s[s.length-1])==null?void 0:n.type)==="RestElement"&&this.raise(_.BadSetterRestParameter,t)}parseObjectMethod(t,n,r,s,o){if(o){let a=this.parseMethod(t,n,!1,!1,!1,"ObjectMethod");return this.checkGetterSetterParams(a),a}if(r||n||this.match(10))return s&&this.unexpected(),t.kind="method",t.method=!0,this.parseMethod(t,n,r,!1,!1,"ObjectMethod")}parseObjectProperty(t,n,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(n,this.cloneIdentifier(t.key));else if(this.match(29)){let o=this.state.startLoc;s!=null?s.shorthandAssignLoc===null&&(s.shorthandAssignLoc=o):this.raise(_.InvalidCoverInitializedName,o),t.value=this.parseMaybeDefault(n,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,n,r,s,o,a,d){let l=this.parseObjectMethod(t,r,s,o,a)||this.parseObjectProperty(t,n,o,d);return l||this.unexpected(),l}parsePropertyName(t,n){if(this.eat(0))t.computed=!0,t.key=this.parseMaybeAssignAllowIn(),this.expect(3);else{let{type:r,value:s}=this.state,o;if(Zt(r))o=this.parseIdentifier(!0);else switch(r){case 135:o=this.parseNumericLiteral(s);break;case 134:o=this.parseStringLiteral(s);break;case 136:o=this.parseBigIntLiteral(s);break;case 139:{let a=this.state.startLoc;n!=null?n.privateKeyLoc===null&&(n.privateKeyLoc=a):this.raise(_.UnexpectedPrivateField,a),o=this.parsePrivateName();break}default:if(r===137){o=this.parseDecimalLiteral(s);break}this.unexpected()}t.key=o,r!==139&&(t.computed=!1)}}initFunction(t,n){t.id=null,t.generator=!1,t.async=n}parseMethod(t,n,r,s,o,a,d=!1){this.initFunction(t,r),t.generator=n,this.scope.enter(530|(d?576:0)|(o?32:0)),this.prodParam.enter(Ol(r,t.generator)),this.parseFunctionParams(t,s);let l=this.parseFunctionBodyAndFinish(t,a,!0);return this.prodParam.exit(),this.scope.exit(),l}parseArrayLike(t,n,r){n&&this.expectPlugin("recordAndTuple");let s=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let o=this.startNode();return this.next(),o.elements=this.parseExprList(t,!n,r,o),this.state.inFSharpPipelineDirectBody=s,this.finishNode(o,n?"TupleExpression":"ArrayExpression")}parseArrowExpression(t,n,r,s){this.scope.enter(518);let o=Ol(r,!1);!this.match(5)&&this.prodParam.hasIn&&(o|=8),this.prodParam.enter(o),this.initFunction(t,r);let a=this.state.maybeInArrowParameters;return n&&(this.state.maybeInArrowParameters=!0,this.setArrowFunctionParameters(t,n,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,n,r){this.toAssignableList(n,r,!1),t.params=n}parseFunctionBodyAndFinish(t,n,r=!1){return this.parseFunctionBody(t,!1,r),this.finishNode(t,n)}parseFunctionBody(t,n,r=!1){let s=n&&!this.match(5);if(this.expressionScope.enter(xk()),s)t.body=this.parseMaybeAssign(),this.checkParams(t,!1,n,!1);else{let o=this.state.strict,a=this.state.labels;this.state.labels=[],this.prodParam.enter(this.prodParam.currentFlags()|4),t.body=this.parseBlock(!0,!1,d=>{let l=!this.isSimpleParamList(t.params);d&&l&&this.raise(_.IllegalLanguageModeDirective,(t.kind==="method"||t.kind==="constructor")&&t.key?t.key.loc.end:t);let c=!o&&this.state.strict;this.checkParams(t,!this.state.strict&&!n&&!r&&!l,n,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 n=0,r=t.length;n<r;n++)if(!this.isSimpleParameter(t[n]))return!1;return!0}checkParams(t,n,r,s=!0){let o=!n&&new Set,a={type:"FormalParameters"};for(let d of t.params)this.checkLVal(d,a,5,o,s)}parseExprList(t,n,r,s){let o=[],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}o.push(this.parseExprListItem(t,n,r))}return o}parseExprListItem(t,n,r,s){let o;if(this.match(12))n||this.raise(_.UnexpectedToken,this.state.curPosition(),{unexpected:","}),o=null;else if(this.match(21)){let a=this.state.startLoc;o=this.parseParenItem(this.parseSpread(r),a)}else if(this.match(17)){this.expectPlugin("partialApplication"),s||this.raise(_.UnexpectedArgumentPlaceholder,this.state.startLoc);let a=this.startNode();this.next(),o=this.finishNode(a,"ArgumentPlaceholder")}else o=this.parseMaybeAssignAllowInOrVoidPattern(t,r,this.parseParenItem);return o}parseIdentifier(t){let n=this.startNode(),r=this.parseIdentifierName(t);return this.createIdentifier(n,r)}createIdentifier(t,n){return t.name=n,t.loc.identifierName=n,this.finishNode(t,"Identifier")}createIdentifierAt(t,n,r){return t.name=n,t.loc.identifierName=n,this.finishNodeAt(t,"Identifier",r)}parseIdentifierName(t){let n,{startLoc:r,type:s}=this.state;Zt(s)?n=this.state.value:this.unexpected();let o=hO(s);return t?o&&this.replaceToken(132):this.checkReservedWord(n,r,o,!1),this.next(),n}checkReservedWord(t,n,r,s){if(t.length>10||!$O(t))return;if(r&&CO(t)){this.raise(_.UnexpectedKeyword,n,{keyword:t});return}if((this.state.strict?s?bk:yk:gk)(t,this.inModule)){this.raise(_.UnexpectedReservedWord,n,{reservedWord:t});return}else if(t==="yield"){if(this.prodParam.hasYield){this.raise(_.YieldBindingIdentifier,n);return}}else if(t==="await"){if(this.prodParam.hasAwait){this.raise(_.AwaitBindingIdentifier,n);return}if(this.scope.inStaticBlock){this.raise(_.AwaitBindingIdentifierInStaticBlock,n);return}this.expressionScope.recordAsyncArrowParametersError(n)}else if(t==="arguments"&&this.scope.inClassAndNotInNonArrowFunction){this.raise(_.ArgumentsInClass,n);return}}recordAwaitIfAllowed(){let t=this.prodParam.hasAwait;return t&&!this.scope.inFunction&&(this.state.hasTopLevelAwait=!0),t}parseAwait(t){let n=this.startNodeAt(t);return this.expressionScope.recordParameterInitializerError(_.AwaitExpressionFormalParameter,n),this.eat(55)&&this.raise(_.ObsoleteAwaitStar,n),!this.scope.inFunction&&!(this.optionFlags&1)&&(this.isAmbiguousPrefixOrIdentifier()?this.ambiguousScriptDifferentAst=!0:this.sawUnambiguousESM=!0),this.state.soloAwait||(n.argument=this.parseMaybeUnary(null,!0)),this.finishNode(n,"AwaitExpression")}isAmbiguousPrefixOrIdentifier(){if(this.hasPrecedingLineBreak())return!0;let{type:t}=this.state;return t===53||t===10||t===0||Ml(t)||t===102&&!this.state.containsEsc||t===138||t===56||this.hasPlugin("v8intrinsic")&&t===54}parseYield(t){let n=this.startNodeAt(t);this.expressionScope.recordParameterInitializerError(_.YieldInParameter,n);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 n.delegate=r,n.argument=s,this.finishNode(n,"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(_.ImportCallArity,t)}}return this.expect(11),this.finishNode(t,"ImportExpression")}checkPipelineAtInfixOperator(t,n){this.hasPlugin(["pipelineOperator",{proposal:"smart"}])&&t.type==="SequenceExpression"&&this.raise(_.PipelineHeadSequenceExpression,n)}parseSmartPipelineBodyInStyle(t,n){if(this.isSimpleReference(t)){let r=this.startNodeAt(n);return r.callee=t,this.finishNode(r,"PipelineBareFunction")}else{let r=this.startNodeAt(n);return this.checkSmartPipeTopicBodyEarlyErrors(n),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(_.PipelineBodyNoArrow,this.state.startLoc);this.topicReferenceWasUsedInCurrentContext()||this.raise(_.PipelineTopicUnused,t)}withTopicBindingContext(t){let n=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:1,maxTopicIndex:null};try{return t()}finally{this.state.topicContext=n}}withSmartMixTopicForbiddingContext(t){if(this.hasPlugin(["pipelineOperator",{proposal:"smart"}])){let n=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null};try{return t()}finally{this.state.topicContext=n}}else return t()}withSoloAwaitPermittingContext(t){let n=this.state.soloAwait;this.state.soloAwait=!0;try{return t()}finally{this.state.soloAwait=n}}allowInAnd(t){let n=this.prodParam.currentFlags();if(8&~n){this.prodParam.enter(n|8);try{return t()}finally{this.prodParam.exit()}}return t()}disallowInAnd(t){let n=this.prodParam.currentFlags();if(8&n){this.prodParam.enter(n&-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 n=this.state.startLoc;this.state.potentialArrowAt=this.state.start;let r=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!0;let s=this.parseExprOp(this.parseMaybeUnaryOrPrivate(),n,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 n=this.startNodeAt(this.state.endLoc);this.next();let r=this.initializeScopes(!0);this.enterInitialScopes();try{t.body=this.parseProgram(n,8,"module")}finally{r()}return this.finishNode(t,"ModuleExpression")}parseVoidPattern(t){this.expectPlugin("discardBinding");let n=this.startNode();return t!=null&&(t.voidPatternLoc=this.state.startLoc),this.next(),this.finishNode(n,"VoidPattern")}parseMaybeAssignAllowInOrVoidPattern(t,n,r){if(n!=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(n))}return this.parseMaybeAssignAllowIn(n,r)}parsePropertyNamePrefixOperator(t){}},Af={kind:1},c$={kind:2},u$=/[\uD800-\uDFFF]/u,Pf=/in(?:stanceof)?/y;function p$(e,t,n){for(let r=0;r<e.length;r++){let s=e[r],{type:o}=s;if(typeof o=="number"){if(o===139){let{loc:a,start:d,value:l,end:c}=s,u=d+1,p=dt(a.start,1);e.splice(r,1,new vn({type:Jn(27),value:"#",start:d,end:u,startLoc:a.start,endLoc:p}),new vn({type:Jn(132),value:l,start:u,end:c,startLoc:p,endLoc:a.end})),r++;continue}if(Ml(o)){let{loc:a,start:d,value:l,end:c}=s,u=d+1,p=dt(a.start,1),f;t.charCodeAt(d-n)===96?f=new vn({type:Jn(22),value:"`",start:d,end:u,startLoc:a.start,endLoc:p}):f=new vn({type:Jn(8),value:"}",start:d,end:u,startLoc:a.start,endLoc:p});let m,h,g,y;o===24?(h=c-1,g=dt(a.end,-1),m=l===null?null:l.slice(1,-1),y=new vn({type:Jn(22),value:"`",start:h,end:c,startLoc:g,endLoc:a.end})):(h=c-2,g=dt(a.end,-2),m=l===null?null:l.slice(1,-2),y=new vn({type:Jn(23),value:"${",start:h,end:c,startLoc:g,endLoc:a.end})),e.splice(r,1,f,new vn({type:Jn(20),value:m,start:u,end:h,startLoc:p,endLoc:g}),y),r+=2;continue}s.type=Jn(o)}}return e}var Yf=class extends Jf{parseTopLevel(t,n){return t.program=this.parseProgram(n,140,this.options.sourceType==="module"?"module":"script"),t.comments=this.comments,this.optionFlags&256&&(t.tokens=p$(this.tokens,this.input,this.startIndex)),this.finishNode(t,"File")}parseProgram(t,n,r){if(t.sourceType=r,t.interpreter=this.parseInterpreterDirective(),this.parseBlockBody(t,!0,!0,n),this.inModule){if(!(this.optionFlags&64)&&this.scope.undefinedExports.size>0)for(let[o,a]of Array.from(this.scope.undefinedExports))this.raise(_.ModuleExportUndefined,a,{localName:o});this.addExtra(t,"topLevelAwait",this.state.hasTopLevelAwait)}let s;return n===140?s=this.finishNode(t,"Program"):s=this.finishNodeAt(t,"Program",dt(this.state.startLoc,-1)),s}stmtToDirective(t){let n=this.castNodeTo(t,"Directive"),r=this.castNodeTo(t.expression,"DirectiveLiteral"),s=r.value,o=this.input.slice(this.offsetToSourcePos(r.start),this.offsetToSourcePos(r.end)),a=r.value=o.slice(1,-1);return this.addExtra(r,"raw",o),this.addExtra(r,"rawValue",a),this.addExtra(r,"expressionValue",s),n.value=r,delete t.expression,n}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(),n=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(n,t)||this.isUnparsedContextual(t,"void"))}nextTokenIsIdentifierOnSameLine(){let t=this.nextTokenInLineStart(),n=this.codePointAtPos(t);return this.chStartsBindingIdentifier(n,t)}isAwaitUsing(){if(!this.isContextual(96))return!1;let t=this.nextTokenInLineStart();if(this.isUnparsedContextual(t,"using")){t=this.nextTokenInLineStartSince(t+5);let n=this.codePointAtPos(t);if(this.chStartsBindingIdentifier(n,t))return!0}return!1}chStartsBindingIdentifier(t,n){if(kn(t)){if(Pf.lastIndex=n,Pf.test(this.input)){let r=this.codePointAtPos(Pf.lastIndex);if(!ni(r)&&r!==92)return!1}return!0}else return t===92}chStartsBindingPattern(t){return t===91||t===123}hasFollowingBindingAtom(){let t=this.nextTokenStart(),n=this.codePointAtPos(t);return this.chStartsBindingPattern(n)||this.chStartsBindingIdentifier(n,t)}hasInLineFollowingBindingIdentifierOrBrace(){let t=this.nextTokenInLineStart(),n=this.codePointAtPos(t);return n===123||this.chStartsBindingIdentifier(n,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 n=0;return this.options.annexB&&!this.state.strict&&(n|=4,t&&(n|=8)),this.parseStatementLike(n)}parseStatement(){return this.parseStatementLike(0)}parseStatementLike(t){let n=null;return this.match(26)&&(n=this.parseDecorators(!0)),this.parseStatementContent(t,n)}parseStatementContent(t,n){let r=this.state.type,s=this.startNode(),o=!!(t&2),a=!!(t&4),d=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?_.StrictFunction:this.options.annexB?_.SloppyFunctionAnnexB:_.SloppyFunction,this.state.startLoc),this.parseFunctionStatement(s,!1,!o&&a);case 80:return o||this.unexpected(),this.parseClass(this.maybeTakeDecorators(n,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()?o?this.recordAwaitIfAllowed()||this.raise(_.AwaitUsingNotInAsyncContext,s):this.raise(_.UnexpectedLexicalDeclaration,s):this.raise(_.UnexpectedUsingDeclaration,s),this.next(),this.parseVarStatement(s,"await using");break;case 107:if(this.state.containsEsc||!this.hasInLineFollowingBindingIdentifierOrBrace())break;return this.allowsUsing()?o||this.raise(_.UnexpectedLexicalDeclaration,this.state.startLoc):this.raise(_.UnexpectedUsingDeclaration,this.state.startLoc),this.parseVarStatement(s,"using");case 100:{if(this.state.containsEsc)break;let u=this.nextTokenStart(),p=this.codePointAtPos(u);if(p!==91&&(!o&&this.hasFollowingLineBreak()||!this.chStartsBindingIdentifier(p,u)&&p!==123))break}case 75:o||this.raise(_.UnexpectedLexicalDeclaration,this.state.startLoc);case 74:{let u=this.state.value;return this.parseVarStatement(s,u)}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 u=this.lookaheadCharCode();if(u===40||u===46)break}case 82:{!(this.optionFlags&8)&&!d&&this.raise(_.UnexpectedImportExport,this.state.startLoc),this.next();let u;return r===83?u=this.parseImport(s):u=this.parseExport(s,n),this.assertModuleNodeAllowed(u),u}default:if(this.isAsyncFunction())return o||this.raise(_.AsyncFunctionInSingleStatementContext,this.state.startLoc),this.next(),this.parseFunctionStatement(s,!0,!o&&a)}let l=this.state.value,c=this.parseExpression();return ye(r)&&c.type==="Identifier"&&this.eat(14)?this.parseLabeledStatement(s,l,c,t):this.parseExpressionStatement(s,c,n)}assertModuleNodeAllowed(t){!(this.optionFlags&8)&&!this.inModule&&this.raise(_.ImportOutsideModule,t)}decoratorsEnabledBeforeExport(){return this.hasPlugin("decorators-legacy")?!0:this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")!==!1}maybeTakeDecorators(t,n,r){if(t){var s;(s=n.decorators)!=null&&s.length?(typeof this.getPluginOption("decorators","decoratorsBeforeExport")!="boolean"&&this.raise(_.DecoratorsBeforeAfterExport,n.decorators[0]),n.decorators.unshift(...t)):n.decorators=t,this.resetStartLocationFromNode(n,t[0]),r&&this.resetStartLocationFromNode(r,n)}return n}canHaveLeadingDecorator(){return this.match(80)}parseDecorators(t){let n=[];do n.push(this.parseDecorator());while(this.match(26));if(this.match(82))t||this.unexpected(),this.decoratorsEnabledBeforeExport()||this.raise(_.DecoratorExportClass,this.state.startLoc);else if(!this.canHaveLeadingDecorator())throw this.raise(_.UnexpectedLeadingDecorator,this.state.startLoc);return n}parseDecorator(){this.expectOnePlugin(["decorators","decorators-legacy"]);let t=this.startNode();if(this.next(),this.hasPlugin("decorators")){let n=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 o=this.state.startLoc;t.expression=this.parseMaybeDecoratorArguments(r,s),this.getPluginOption("decorators","allowCallParenthesized")===!1&&t.expression!==r&&this.raise(_.DecoratorArgumentsOutsideParentheses,o)}else{for(r=this.parseIdentifier(!1);this.eat(16);){let s=this.startNodeAt(n);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,n)}}else t.expression=this.parseExprSubscripts();return this.finishNode(t,"Decorator")}parseMaybeDecoratorArguments(t,n){if(this.eat(10)){let r=this.startNodeAt(n);return r.callee=t,r.arguments=this.parseCallExpressionArguments(),this.toReferencedList(r.arguments),this.finishNode(r,"CallExpression")}return t}parseBreakContinueStatement(t,n){return this.next(),this.isLineTerminator()?t.label=null:(t.label=this.parseIdentifier(),this.semicolon()),this.verifyBreakContinue(t,n),this.finishNode(t,n?"BreakStatement":"ContinueStatement")}verifyBreakContinue(t,n){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&&(n||s.kind===1)||t.label&&n))break}if(r===this.state.labels.length){let s=n?"BreakStatement":"ContinueStatement";this.raise(_.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(Af),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(Af);let n=null;if(this.isContextual(96)&&this.recordAwaitIfAllowed()&&(n=this.state.startLoc,this.next()),this.scope.enter(0),this.expect(10),this.match(13))return n!==null&&this.unexpected(n),this.parseFor(t,null);let r=this.isContextual(100);{let l=this.isAwaitUsing(),c=l||this.isForUsing(),u=r&&this.hasFollowingBindingAtom()||c;if(this.match(74)||this.match(75)||u){let p=this.startNode(),f;l?(f="await using",this.recordAwaitIfAllowed()||this.raise(_.AwaitUsingNotInAsyncContext,this.state.startLoc),this.next()):f=this.state.value,this.next(),this.parseVar(p,!0,f);let m=this.finishNode(p,"VariableDeclaration"),h=this.match(58);return h&&c&&this.raise(_.ForInUsing,m),(h||this.isContextual(102))&&m.declarations.length===1?this.parseForIn(t,m,n):(n!==null&&this.unexpected(n),this.parseFor(t,m))}}let s=this.isContextual(95),o=new ys,a=this.parseExpression(!0,o),d=this.isContextual(102);if(d&&(r&&this.raise(_.ForOfLet,a),n===null&&s&&a.type==="Identifier"&&this.raise(_.ForOfAsync,a)),d||this.match(58)){this.checkDestructuringPrivate(o),this.toAssignable(a,!0);let l=d?"ForOfStatement":"ForInStatement";return this.checkLVal(a,{type:l}),this.parseForIn(t,a,n)}else this.checkExpressionErrors(o,!0);return n!==null&&this.unexpected(n),this.parseFor(t,a)}parseFunctionStatement(t,n,r){return this.next(),this.parseFunction(t,1|(r?2:0)|(n?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(_.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 n=t.cases=[];this.expect(5),this.state.labels.push(c$),this.scope.enter(256);let r;for(let s;!this.match(8);)if(this.match(61)||this.match(65)){let o=this.match(61);r&&this.finishNode(r,"SwitchCase"),n.push(r=this.startNode()),r.consequent=[],this.next(),o?r.test=this.parseExpression():(s&&this.raise(_.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(_.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 n=this.startNode();this.next(),this.match(10)?(this.expect(10),n.param=this.parseCatchClauseParam(),this.expect(11)):(n.param=null,this.scope.enter(0)),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseBlock(!1,!1)),this.scope.exit(),t.handler=this.finishNode(n,"CatchClause")}return t.finalizer=this.eat(67)?this.parseBlock():null,!t.handler&&!t.finalizer&&this.raise(_.NoCatchOrFinally,t),this.finishNode(t,"TryStatement")}parseVarStatement(t,n,r=!1){return this.next(),this.parseVar(t,!1,n,r),this.semicolon(),this.finishNode(t,"VariableDeclaration")}parseWhileStatement(t){return this.next(),t.test=this.parseHeaderExpression(),this.state.labels.push(Af),t.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.state.labels.pop(),this.finishNode(t,"WhileStatement")}parseWithStatement(t){return this.state.strict&&this.raise(_.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,n,r,s){for(let a of this.state.labels)a.name===n&&this.raise(_.LabelRedeclaration,r,{labelName:n});let o=wO(this.state.type)?1:this.match(71)?2:null;for(let a=this.state.labels.length-1;a>=0;a--){let d=this.state.labels[a];if(d.statementStart===t.start)d.statementStart=this.sourceToOffsetPos(this.state.start),d.kind=o;else break}return this.state.labels.push({name:n,kind:o,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,n,r){return t.expression=n,this.semicolon(),this.finishNode(t,"ExpressionStatement")}parseBlock(t=!1,n=!0,r){let s=this.startNode();return t&&this.state.strictErrors.clear(),this.expect(5),n&&this.scope.enter(0),this.parseBlockBody(s,t,!1,8,r),n&&this.scope.exit(),this.finishNode(s,"BlockStatement")}isValidDirective(t){return t.type==="ExpressionStatement"&&t.expression.type==="StringLiteral"&&!t.expression.extra.parenthesized}parseBlockBody(t,n,r,s,o){let a=t.body=[],d=t.directives=[];this.parseBlockOrModuleBlockBody(a,n?d:void 0,r,s,o)}parseBlockOrModuleBlockBody(t,n,r,s,o){let a=this.state.strict,d=!1,l=!1;for(;!this.match(s);){let c=r?this.parseModuleItem():this.parseStatementListItem();if(n&&!l){if(this.isValidDirective(c)){let u=this.stmtToDirective(c);n.push(u),!d&&u.value.value==="use strict"&&(d=!0,this.setStrict(!0));continue}l=!0,this.state.strictErrors.clear()}t.push(c)}o?.call(this,d),a||this.setStrict(!1),this.next()}parseFor(t,n){return t.init=n,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,n,r){let s=this.match(58);return this.next(),s?r!==null&&this.unexpected(r):t.await=r!==null,n.type==="VariableDeclaration"&&n.declarations[0].init!=null&&(!s||!this.options.annexB||this.state.strict||n.kind!=="var"||n.declarations[0].id.type!=="Identifier")&&this.raise(_.ForInOfLoopInitializer,n,{type:s?"ForInStatement":"ForOfStatement"}),n.type==="AssignmentPattern"&&this.raise(_.InvalidLhs,n,{ancestor:{type:"ForStatement"}}),t.left=n,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,n,r,s=!1){let o=t.declarations=[];for(t.kind=r;;){let a=this.startNode();if(this.parseVarId(a,r),a.init=this.eat(29)?n?this.parseMaybeAssignDisallowIn():this.parseMaybeAssignAllowIn():null,a.init===null&&!s&&(a.id.type!=="Identifier"&&!(n&&(this.match(58)||this.isContextual(102)))?this.raise(_.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:"destructuring"}):(r==="const"||r==="using"||r==="await using")&&!(this.match(58)||this.isContextual(102))&&this.raise(_.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:r})),o.push(this.finishNode(a,"VariableDeclarator")),!this.eat(12))break}return t}parseVarId(t,n){let r=this.parseBindingAtom();n==="using"||n==="await using"?(r.type==="ArrayPattern"||r.type==="ObjectPattern")&&this.raise(_.UsingDeclarationHasBindingPattern,r.loc.start):r.type==="VoidPattern"&&this.raise(_.UnexpectedVoidPattern,r.loc.start),this.checkLVal(r,{type:"VariableDeclarator"},n==="var"?5:8201),t.id=r}parseAsyncFunctionExpression(t){return this.parseFunction(t,8)}parseFunction(t,n=0){let r=n&2,s=!!(n&1),o=s&&!(n&4),a=!!(n&8);this.initFunction(t,a),this.match(55)&&(r&&this.raise(_.GeneratorInSingleStatementContext,this.state.startLoc),this.next(),t.generator=!0),s&&(t.id=this.parseFunctionId(o));let d=this.state.maybeInArrowParameters;return this.state.maybeInArrowParameters=!1,this.scope.enter(514),this.prodParam.enter(Ol(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=d,t}parseFunctionId(t){return t||ye(this.state.type)?this.parseIdentifier():null}parseFunctionParams(t,n){this.expect(10),this.expressionScope.enter(YO()),t.params=this.parseBindingList(11,41,2|(n?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,n,r){this.next();let s=this.state.strict;return this.state.strict=!0,this.parseClassId(t,n,r),this.parseClassSuper(t),t.body=this.parseClassBody(!!t.superClass,s),this.finishNode(t,n?"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,n){this.classScope.enter();let r={hadConstructor:!1,hadSuperClass:t},s=[],o=this.startNode();if(o.body=[],this.expect(5),this.withSmartMixTopicForbiddingContext(()=>{for(;!this.match(8);){if(this.eat(13)){if(s.length>0)throw this.raise(_.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(o,a,r),a.kind==="constructor"&&a.decorators&&a.decorators.length>0&&this.raise(_.DecoratorConstructor,a)}}),this.state.strict=n,this.next(),s.length)throw this.raise(_.TrailingDecorator,this.state.startLoc);return this.classScope.exit(),this.finishNode(o,"ClassBody")}parseClassMemberFromModifier(t,n){let r=this.parseIdentifier(!0);if(this.isClassMethod()){let s=n;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=n;return s.computed=!1,s.key=r,s.static=!1,t.body.push(this.parseClassProperty(s)),!0}return this.resetPreviousNodeTrailingComments(r),!1}parseClassMember(t,n,r){let s=this.isContextual(106);if(s){if(this.parseClassMemberFromModifier(t,n))return;if(this.eat(5)){this.parseClassStaticBlock(t,n);return}}this.parseClassMemberWithIsStatic(t,n,r,s)}parseClassMemberWithIsStatic(t,n,r,s){let o=n,a=n,d=n,l=n,c=n,u=o,p=o;if(n.static=s,this.parsePropertyNamePrefixOperator(n),this.eat(55)){u.kind="method";let w=this.match(139);if(this.parseClassElementName(u),this.parsePostMemberNameModifiers(u),w){this.pushClassPrivateMethod(t,a,!0,!1);return}this.isNonstaticConstructor(o)&&this.raise(_.ConstructorIsGenerator,o.key),this.pushClassMethod(t,o,!0,!1,!1,!1);return}let f=!this.state.containsEsc&&ye(this.state.type),m=this.parseClassElementName(n),h=f?m.name:null,g=this.isPrivateName(m),y=this.state.startLoc;if(this.parsePostMemberNameModifiers(p),this.isClassMethod()){if(u.kind="method",g){this.pushClassPrivateMethod(t,a,!1,!1);return}let w=this.isNonstaticConstructor(o),b=!1;w&&(o.kind="constructor",r.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(_.DuplicateConstructor,m),w&&this.hasPlugin("typescript")&&n.override&&this.raise(_.OverrideOnConstructor,m),r.hadConstructor=!0,b=r.hadSuperClass),this.pushClassMethod(t,o,!1,!1,w,b)}else if(this.isClassProperty())g?this.pushClassPrivateProperty(t,l):this.pushClassProperty(t,d);else if(h==="async"&&!this.isLineTerminator()){this.resetPreviousNodeTrailingComments(m);let w=this.eat(55);p.optional&&this.unexpected(y),u.kind="method";let b=this.match(139);this.parseClassElementName(u),this.parsePostMemberNameModifiers(p),b?this.pushClassPrivateMethod(t,a,w,!0):(this.isNonstaticConstructor(o)&&this.raise(_.ConstructorIsAsync,o.key),this.pushClassMethod(t,o,w,!0,!1,!1))}else if((h==="get"||h==="set")&&!(this.match(55)&&this.isLineTerminator())){this.resetPreviousNodeTrailingComments(m),u.kind=h;let w=this.match(139);this.parseClassElementName(o),w?this.pushClassPrivateMethod(t,a,!1,!1):(this.isNonstaticConstructor(o)&&this.raise(_.ConstructorIsAccessor,o.key),this.pushClassMethod(t,o,!1,!1,!1,!1)),this.checkGetterSetterParams(o)}else if(h==="accessor"&&!this.isLineTerminator()){this.expectPlugin("decoratorAutoAccessors"),this.resetPreviousNodeTrailingComments(m);let w=this.match(139);this.parseClassElementName(d),this.pushClassAccessorProperty(t,c,w)}else this.isLineTerminator()?g?this.pushClassPrivateProperty(t,l):this.pushClassProperty(t,d):this.unexpected()}parseClassElementName(t){let{type:n,value:r}=this.state;if((n===132||n===134)&&t.static&&r==="prototype"&&this.raise(_.StaticPrototype,this.state.startLoc),n===139){r==="constructor"&&this.raise(_.ConstructorClassPrivateField,this.state.startLoc);let s=this.parsePrivateName();return t.key=s,s}return this.parsePropertyName(t),t.key}parseClassStaticBlock(t,n){var r;this.scope.enter(720);let s=this.state.labels;this.state.labels=[],this.prodParam.enter(0);let o=n.body=[];this.parseBlockOrModuleBlockBody(o,void 0,!1,8),this.prodParam.exit(),this.scope.exit(),this.state.labels=s,t.body.push(this.finishNode(n,"StaticBlock")),(r=n.decorators)!=null&&r.length&&this.raise(_.DecoratorStaticBlock,n)}pushClassProperty(t,n){!n.computed&&this.nameIsConstructor(n.key)&&this.raise(_.ConstructorClassField,n.key),t.body.push(this.parseClassProperty(n))}pushClassPrivateProperty(t,n){let r=this.parseClassPrivateProperty(n);t.body.push(r),this.classScope.declarePrivateName(this.getPrivateNameSV(r.key),0,r.key.loc.start)}pushClassAccessorProperty(t,n,r){!r&&!n.computed&&this.nameIsConstructor(n.key)&&this.raise(_.ConstructorClassField,n.key);let s=this.parseClassAccessorProperty(n);t.body.push(s),r&&this.classScope.declarePrivateName(this.getPrivateNameSV(s.key),0,s.key.loc.start)}pushClassMethod(t,n,r,s,o,a){t.body.push(this.parseMethod(n,r,s,o,a,"ClassMethod",!0))}pushClassPrivateMethod(t,n,r,s){let o=this.parseMethod(n,r,s,!1,!1,"ClassPrivateMethod",!0);t.body.push(o);let a=o.kind==="get"?o.static?6:2:o.kind==="set"?o.static?5:1:0;this.declareClassPrivateMethodInScope(o,a)}declareClassPrivateMethodInScope(t,n){this.classScope.declarePrivateName(this.getPrivateNameSV(t.key),n,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(xk()),this.prodParam.enter(0),t.value=this.eat(29)?this.parseMaybeAssignAllowIn():null,this.expressionScope.exit(),this.prodParam.exit(),this.scope.exit()}parseClassId(t,n,r,s=8331){if(ye(this.state.type))t.id=this.parseIdentifier(),n&&this.declareNameFromIdentifier(t.id,s);else if(r||!n)t.id=null;else throw this.raise(_.MissingClassName,this.state.startLoc)}parseClassSuper(t){t.superClass=this.eat(81)?this.parseExprSubscripts():null}parseExport(t,n){let r=this.parseMaybeImportPhase(t,!0),s=this.maybeParseExportDefaultSpecifier(t,r),o=!s||this.eat(12),a=o&&this.eatExportStar(t),d=a&&this.maybeParseExportNamespaceSpecifier(t),l=o&&(!d||this.eat(12)),c=s||a;if(a&&!d){if(s&&this.unexpected(),n)throw this.raise(_.UnsupportedDecoratorExport,t);return this.parseExportFrom(t,!0),this.sawUnambiguousESM=!0,this.finishNode(t,"ExportAllDeclaration")}let u=this.maybeParseExportNamedSpecifiers(t);s&&o&&!a&&!u&&this.unexpected(null,5),d&&l&&this.unexpected(null,98);let p;if(c||u){if(p=!1,n)throw this.raise(_.UnsupportedDecoratorExport,t);this.parseExportFrom(t,c)}else p=this.maybeParseExportDeclaration(t);if(c||u||p){var f;let m=t;if(this.checkExport(m,!0,!1,!!m.source),((f=m.declaration)==null?void 0:f.type)==="ClassDeclaration")this.maybeTakeDecorators(n,m.declaration,m);else if(n)throw this.raise(_.UnsupportedDecoratorExport,t);return this.sawUnambiguousESM=!0,this.finishNode(m,"ExportNamedDeclaration")}if(this.eat(65)){let m=t,h=this.parseExportDefaultExpression();if(m.declaration=h,h.type==="ClassDeclaration")this.maybeTakeDecorators(n,h,m);else if(n)throw this.raise(_.UnsupportedDecoratorExport,t);return this.checkExport(m,!0,!0),this.sawUnambiguousESM=!0,this.finishNode(m,"ExportDefaultDeclaration")}throw this.unexpected(null,5)}eatExportStar(t){return this.eat(55)}maybeParseExportDefaultSpecifier(t,n){if(n||this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom",n?.loc.start);let r=n||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 n,r;(r=(n=t).specifiers)!=null||(n.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 n=t;n.specifiers||(n.specifiers=[]);let r=n.exportKind==="type";return n.specifiers.push(...this.parseExportSpecifiers(r)),n.source=null,this.hasPlugin("importAssertions")?n.assertions=[]:n.attributes=[],n.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(_.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(_.UnsupportedDefaultExport,this.state.startLoc);let n=this.parseMaybeAssignAllowIn();return this.semicolon(),n}parseExportDeclaration(t){return this.match(80)?this.parseClass(this.startNode(),!0,!1):this.parseStatementListItem()}isExportDefaultSpecifier(){let{type:t}=this.state;if(ye(t)){if(t===95&&!this.state.containsEsc||t===100)return!1;if((t===130||t===129)&&!this.state.containsEsc){let s=this.nextTokenStart(),o=this.input.charCodeAt(s);if(o===123||this.chStartsBindingIdentifier(o,s)&&!this.input.startsWith("from",s))return this.expectOnePlugin(["flow","typescript"]),!1}}else if(!this.match(65))return!1;let n=this.nextTokenStart(),r=this.isUnparsedContextual(n,"from");if(this.input.charCodeAt(n)===44||ye(this.state.type)&&r)return!0;if(this.match(65)&&r){let s=this.input.charCodeAt(this.nextTokenStartSince(n+4));return s===34||s===39}return!1}parseExportFrom(t,n){this.eatContextual(98)?(t.source=this.parseImportSource(),this.checkExport(t),this.maybeParseImportAttributes(t),this.checkJSONModuleImport(t)):n&&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(_.DecoratorBeforeExport,this.state.startLoc),!0):this.isUsing()?(this.raise(_.UsingDeclarationExport,this.state.startLoc),!0):this.isAwaitUsing()?(this.raise(_.UsingDeclarationExport,this.state.startLoc),!0):t===74||t===75||t===68||t===80||this.isLet()||this.isAsyncFunction()}checkExport(t,n,r,s){if(n){var o;if(r){if(this.checkDuplicateExports(t,"default"),this.hasPlugin("exportDefaultFrom")){var a;let d=t.declaration;d.type==="Identifier"&&d.name==="from"&&d.end-d.start===4&&!((a=d.extra)!=null&&a.parenthesized)&&this.raise(_.ExportDefaultFromAsIdentifier,d)}}else if((o=t.specifiers)!=null&&o.length)for(let d of t.specifiers){let{exported:l}=d,c=l.type==="Identifier"?l.name:l.value;if(this.checkDuplicateExports(d,c),!s&&d.local){let{local:u}=d;u.type!=="Identifier"?this.raise(_.ExportBindingIsString,d,{localName:u.value,exportName:c}):(this.checkReservedWord(u.name,u.loc.start,!0,!1),this.scope.checkLocalExport(u))}}else if(t.declaration){let d=t.declaration;if(d.type==="FunctionDeclaration"||d.type==="ClassDeclaration"){let{id:l}=d;if(!l)throw new Error("Assertion failure");this.checkDuplicateExports(t,l.name)}else if(d.type==="VariableDeclaration")for(let l of d.declarations)this.checkDeclaration(l.id)}}}checkDeclaration(t){if(t.type==="Identifier")this.checkDuplicateExports(t,t.name);else if(t.type==="ObjectPattern")for(let n of t.properties)this.checkDeclaration(n);else if(t.type==="ArrayPattern")for(let n of t.elements)n&&this.checkDeclaration(n);else t.type==="ObjectProperty"?this.checkDeclaration(t.value):t.type==="RestElement"?this.checkDeclaration(t.argument):t.type==="AssignmentPattern"&&this.checkDeclaration(t.left)}checkDuplicateExports(t,n){this.exportedIdentifiers.has(n)&&(n==="default"?this.raise(_.DuplicateDefaultExport,t):this.raise(_.DuplicateExport,t,{exportName:n})),this.exportedIdentifiers.add(n)}parseExportSpecifiers(t){let n=[],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),o=this.match(134),a=this.startNode();a.local=this.parseModuleExportName(),n.push(this.parseExportSpecifier(a,o,t,s))}return n}parseExportSpecifier(t,n,r,s){return this.eatContextual(93)?t.exported=this.parseModuleExportName():n?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),n=u$.exec(t.value);return n&&this.raise(_.ModuleExportNameHasLoneSurrogate,t,{surrogateCharCode:n[0].charCodeAt(0)}),t}return this.parseIdentifier(!0)}isJSONModuleImport(t){return t.assertions!=null?t.assertions.some(({key:n,value:r})=>r.value==="json"&&(n.type==="Identifier"?n.name==="type":n.value==="type")):!1}checkImportReflection(t){let{specifiers:n}=t,r=n.length===1?n[0].type:null;if(t.phase==="source")r!=="ImportDefaultSpecifier"&&this.raise(_.SourcePhaseImportRequiresDefault,n[0].loc.start);else if(t.phase==="defer")r!=="ImportNamespaceSpecifier"&&this.raise(_.DeferImportRequiresNamespace,n[0].loc.start);else if(t.module){var s;r!=="ImportDefaultSpecifier"&&this.raise(_.ImportReflectionNotBinding,n[0].loc.start),((s=t.assertions)==null?void 0:s.length)>0&&this.raise(_.ImportReflectionHasAssertion,n[0].loc.start)}}checkJSONModuleImport(t){if(this.isJSONModuleImport(t)&&t.type!=="ExportAllDeclaration"){let{specifiers:n}=t;if(n!=null){let r=n.find(s=>{let o;if(s.type==="ExportSpecifier"?o=s.local:s.type==="ImportSpecifier"&&(o=s.imported),o!==void 0)return o.type==="Identifier"?o.name!=="default":o.value!=="default"});r!==void 0&&this.raise(_.ImportJSONBindingNotDefault,r.loc.start)}}}isPotentialImportPhase(t){return t?!1:this.isContextual(105)||this.isContextual(97)||this.isContextual(127)}applyImportPhase(t,n,r,s){n||(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,n){if(!this.isPotentialImportPhase(n))return this.applyImportPhase(t,n,null),null;let r=this.startNode(),s=this.parseIdentifierName(!0),{type:o}=this.state;return(Zt(o)?o!==98||this.lookaheadCharCode()===102:o!==12)?(this.applyImportPhase(t,n,s,r.loc.start),null):(this.applyImportPhase(t,n,null),this.createIdentifier(r,s))}isPrecedingIdImportPhase(t){let{type:n}=this.state;return ye(n)?n!==98||this.lookaheadCharCode()===102:n!==12}parseImport(t){return this.match(134)?this.parseImportSourceAndAttributes(t):this.parseImportSpecifiersAndAfter(t,this.parseMaybeImportPhase(t,!1))}parseImportSpecifiersAndAfter(t,n){t.specifiers=[];let s=!this.maybeParseDefaultImportSpecifier(t,n)||this.eat(12),o=s&&this.maybeParseStarImportSpecifier(t);return s&&!o&&this.parseNamedImportSpecifiers(t),this.expectContextual(98),this.parseImportSourceAndAttributes(t)}parseImportSourceAndAttributes(t){var n;return(n=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,n,r){n.local=this.parseIdentifier(),t.specifiers.push(this.finishImportSpecifier(n,r))}finishImportSpecifier(t,n,r=8201){return this.checkLVal(t.local,{type:n},r),this.finishNode(t,n)}parseImportAttributes(){this.expect(5);let t=[],n=new Set;do{if(this.match(8))break;let r=this.startNode(),s=this.state.value;if(n.has(s)&&this.raise(_.ModuleAttributesWithDuplicateKeys,this.state.startLoc,{key:s}),n.add(s),this.match(134)?r.key=this.parseStringLiteral(s):r.key=this.parseIdentifier(!0),this.expect(14),!this.match(134))throw this.raise(_.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=[],n=new Set;do{let r=this.startNode();if(r.key=this.parseIdentifier(!0),r.key.name!=="type"&&this.raise(_.ModuleAttributeDifferentFromType,r.key),n.has(r.key.name)&&this.raise(_.ModuleAttributesWithDuplicateKeys,r.key,{key:r.key.name}),n.add(r.key.name),this.expect(14),!this.match(134))throw this.raise(_.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 n;var r=!1;if(this.match(76)){if(this.hasPrecedingLineBreak()&&this.lookaheadCharCode()===40)return;this.next(),this.hasPlugin("moduleAttributes")?(n=this.parseModuleAttributes(),this.addExtra(t,"deprecatedWithLegacySyntax",!0)):n=this.parseImportAttributes(),r=!0}else this.isContextual(94)&&!this.hasPrecedingLineBreak()?(!this.hasPlugin("deprecatedImportAssert")&&!this.hasPlugin("importAssertions")&&this.raise(_.ImportAttributesUseAssert,this.state.startLoc),this.hasPlugin("importAssertions")||this.addExtra(t,"deprecatedAssertSyntax",!0),this.next(),n=this.parseImportAttributes()):n=[];!r&&this.hasPlugin("importAssertions")?t.assertions=n:t.attributes=n}maybeParseDefaultImportSpecifier(t,n){if(n){let r=this.startNodeAtNode(n);return r.local=n,t.specifiers.push(this.finishImportSpecifier(r,"ImportDefaultSpecifier")),!0}else if(Zt(this.state.type))return this.parseImportSpecifierLocal(t,this.startNode(),"ImportDefaultSpecifier"),!0;return!1}maybeParseStarImportSpecifier(t){if(this.match(55)){let n=this.startNode();return this.next(),this.expectContextual(93),this.parseImportSpecifierLocal(t,n,"ImportNamespaceSpecifier"),!0}return!1}parseNamedImportSpecifiers(t){let n=!0;for(this.expect(5);!this.eat(8);){if(n)n=!1;else{if(this.eat(14))throw this.raise(_.DestructureNamedImport,this.state.startLoc);if(this.expect(12),this.eat(8))break}let r=this.startNode(),s=this.match(134),o=this.isContextual(130);r.imported=this.parseModuleExportName();let a=this.parseImportSpecifier(r,s,t.importKind==="type"||t.importKind==="typeof",o,void 0);t.specifiers.push(a)}}parseImportSpecifier(t,n,r,s,o){if(this.eatContextual(93))t.local=this.parseIdentifier();else{let{imported:a}=t;if(n)throw this.raise(_.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",o)}isThisParam(t){return t.type==="Identifier"&&t.name==="this"}},Dl=class extends Yf{constructor(t,n,r){let s=cO(t);super(s,n),this.options=s,this.initializeScopes(),this.plugins=r,this.filename=s.sourceFilename,this.startIndex=s.startIndex;let o=0;s.allowAwaitOutsideFunction&&(o|=1),s.allowReturnOutsideFunction&&(o|=2),s.allowImportExportEverywhere&&(o|=8),s.allowSuperOutsideMethod&&(o|=16),s.allowUndeclaredExports&&(o|=64),s.allowNewTargetOutsideFunction&&(o|=4),s.allowYieldOutsideFunction&&(o|=32),s.ranges&&(o|=128),s.tokens&&(o|=256),s.createImportExpressions&&(o|=512),s.createParenthesizedExpressions&&(o|=1024),s.errorRecovery&&(o|=2048),s.attachComment&&(o|=4096),s.annexB&&(o|=8192),this.optionFlags=o}getScopeHandler(){return ia}parse(){this.enterInitialScopes();let t=this.startNode(),n=this.startNode();this.nextToken(),t.errors=null;let r=this.parseTopLevel(t,n);return r.errors=this.state.errors,r.comments.length=this.state.commentsLen,r}};function f$(e,t){var n;if(((n=t)==null?void 0:n.sourceType)==="unambiguous"){t=Object.assign({},t);try{t.sourceType="module";let r=ta(t,e),s=r.parse();if(r.sawUnambiguousESM)return s;if(r.ambiguousScriptDifferentAst)try{return t.sourceType="script",ta(t,e).parse()}catch{}else s.program.sourceType="script";return s}catch(r){try{return t.sourceType="script",ta(t,e).parse()}catch{}throw r}}else return ta(t,e).parse()}function m$(e,t){let n=ta(t,e);return n.options.strictMode&&(n.state.strict=!0),n.getExpression()}function h$(e){let t={};for(let n of Object.keys(e))t[n]=Jn(e[n]);return t}var g$=h$(mO);function ta(e,t){let n=Dl,r=new Map;if(e!=null&&e.plugins){for(let s of e.plugins){let o,a;typeof s=="string"?o=s:[o,a]=s,r.has(o)||r.set(o,a||{})}d$(r),n=y$(r)}return new n(e,t,r)}var pk=new Map;function y$(e){let t=[];for(let s of l$)e.has(s)&&t.push(s);let n=t.join("|"),r=pk.get(n);if(!r){r=Dl;for(let s of t)r=Sk[s](r);pk.set(n,r)}return r}oa.parse=f$;oa.parseExpression=m$;oa.tokTypes=g$});import{parseArgs as IJ}from"node:util";import{writeFile as PC}from"node:fs/promises";import{join as EC}from"node:path";function $b(e,t){try{let n=new URL(e);return t.includes(n.protocol)&&n.username===""&&n.password===""&&n.search===""&&n.hash===""?n.href.replace(/\/+$/,""):void 0}catch{return}}function Gt(e,t=""){return $b(e===void 0||e===""?t:e,["https:"])}function Mp(e){return $b(e??"",["https:","http:"])}var CC=3e4,NC="7.1",Mb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Db="KwikQA.Ci",OC=4,Fb=/^\$\([\w.-]+\)$/;function jp(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t===void 0||!Fb.test(t.trim())))}function $C(e){if(!(e===void 0||e===""))try{let t=new URL(e);return t.username="",t.password="",Gt(t.href)}catch{return}}function Lp(e){let t=Number(e);return/^\d+$/.test(e??"")&&Number.isSafeInteger(t)&&t>0?t:void 0}function Lb(e){if(!(e===void 0||e===""||e.startsWith("refs/pull/")))return e.replace(/^refs\/(?:heads|tags)\//,"")}function zr(e){if(e.TF_BUILD!=="True")return;let t=Gt(e.SYSTEM_COLLECTIONURI),n=e.SYSTEM_TEAMPROJECT??"",r=Lp(e.BUILD_BUILDID),s=e.BUILD_REPOSITORY_PROVIDER??"",o=s==="GitHub"||s==="GitHubEnterprise",a=s==="TfsGit"?"pullrequest":o?"pull":void 0,d=a===void 0?void 0:$C(e.BUILD_REPOSITORY_URI),l=Lp((o?e.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER:void 0)||e.SYSTEM_PULLREQUEST_PULLREQUESTID),c=/^[0-9a-f]{40}$/i.test(e.BUILD_SOURCEVERSION??"")?e.BUILD_SOURCEVERSION:void 0,u=Lb(e.SYSTEM_PULLREQUEST_SOURCEBRANCH)??Lb(e.BUILD_SOURCEBRANCH),p=(e.SYSTEM_ACCESSTOKEN??"").trim(),f=Lp(e.SYSTEM_JOBATTEMPT),m=/^refs\/[^\s\0]+$/.test(e.BUILD_SOURCEBRANCH??"")?e.BUILD_SOURCEBRANCH:void 0,h=e.SYSTEM_PULLREQUEST_SOURCEBRANCH?.startsWith("refs/heads/")?e.SYSTEM_PULLREQUEST_SOURCEBRANCH.slice(11):void 0,g=/^[0-9a-f]{40}$/i.test(e.SYSTEM_PULLREQUEST_SOURCECOMMITID??"")?e.SYSTEM_PULLREQUEST_SOURCECOMMITID?.toLowerCase():void 0,y=Mb.test(e.SYSTEM_TEAMPROJECTID??"")?e.SYSTEM_TEAMPROJECTID:void 0,w=Mb.test(e.BUILD_REPOSITORY_ID??"")?e.BUILD_REPOSITORY_ID:void 0;return{...t===void 0?{}:{collectionUrl:t},...y===void 0?{}:{projectId:y},...w===void 0?{}:{repositoryId:w},provider:s,...e.BUILD_REPOSITORY_NAME?{repository:e.BUILD_REPOSITORY_NAME}:{},...t===void 0||n===""||r===void 0?{}:{runUrl:`${t}/${encodeURIComponent(n)}/_build/results?buildId=${r}`},pipeline:e.SYSTEM_DEFINITIONID||e.BUILD_DEFINITIONNAME||"",job:[e.SYSTEM_STAGENAME,e.SYSTEM_JOBNAME].filter(Boolean).join("."),...u===void 0?{}:{branch:u},...c===void 0?{}:{commit:{sha:c,...d===void 0?{}:{url:`${d}/commit/${c}`}}},...e.AGENT_TEMPDIRECTORY?{tempDirectory:e.AGENT_TEMPDIRECTORY}:{},...p===""||Fb.test(p)?{}:{token:p},...r===void 0?{}:{buildId:String(r)},...f===void 0?{}:{jobAttempt:f},...m===void 0?{}:{ref:m},...l!==void 0&&h!==void 0&&g!==void 0?{pullRequestHead:{ref:h,sha:g}}:{},...l===void 0?{}:{pullRequest:{number:l,...d===void 0?{}:{url:`${d}/${a}/${l}`},fork:e.SYSTEM_PULLREQUEST_ISFORK==="True"}}}}function MC(e,t="ci"){return`kwikqa-${t} pipeline=${encodeURIComponent(e.pipeline)} job=${encodeURIComponent(e.job)}`}function LC(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function mn(e){return e.ok&&e.status!==203}async function Zd(e){let t=await e.json().catch(()=>{});return typeof t?.message=="string"?t.message.replace(/\s+/g," ").trim().slice(0,200):void 0}async function Dp(e){if(e.status===429)return"Azure DevOps's rate limit was reached";if(e.status===401||e.status===203)return"Azure DevOps refused the token";if(e.status===403){let n=await Zd(e);return`the build service can't comment on this pull request; give it "Contribute to pull requests" on the repository${n===void 0?"":` (${n})`}`}if(e.status===404)return"Azure DevOps found no such pull request with this token";let t=await Zd(e);return`Azure DevOps answered ${e.status}${t===void 0?"":`: ${t}`}`}var Fp=class{constructor(t,n,r){this.send=t;this.base=n;this.token=r}send;base;token;call(t,n,r){return this.send(`${this.base}${n}?api-version=${NC}`,{method:t,headers:{Accept:"application/json",Authorization:`Bearer ${this.token}`,...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error",signal:AbortSignal.timeout(CC)})}},rs=class extends Error{};function DC(e){if(typeof e=="string")return e;let t=typeof e=="object"&&e!==null?e:{};return typeof t.$value=="string"?t.$value:void 0}async function FC(e,t){let n=await e.call("GET","/threads");if(!mn(n))throw new rs(await Dp(n));let r=(await n.json()).value??[];for(let s of r){if(s.isDeleted===!0||DC(s.properties?.[Db])!==t)continue;let o=s.comments?.find(a=>a.parentCommentId===0&&a.isDeleted!==!0);if(typeof s.id=="number"&&typeof o?.id=="number")return{thread:s.id,comment:o.id}}}async function Bp(e,t,n,r,s){let o=n.noun??"pull-request comment",a=`${o.charAt(0).toUpperCase()}${o.slice(1)}`,d=new Fp(t,`${n.collectionUrl}/${n.projectId}/_apis/git/repositories/${n.repositoryId}/pullRequests/${n.pullRequest}`,n.token);try{let l=await FC(d,n.marker);if(l!==void 0){let u=await d.call("PATCH",`/threads/${l.thread}/comments/${l.comment}`,{content:r});if(mn(u))return e.print(`${a}: updated.`);if(u.status!==403&&u.status!==404)throw new rs(await Dp(u))}if(l===void 0&&!s)return e.print(`No ${o}: nothing failed, and there is no earlier comment to update.`);let c=await d.call("POST","/threads",{comments:[{parentCommentId:0,content:r,commentType:1}],status:OC,properties:{[Db]:{$type:"System.String",$value:n.marker}}});if(!mn(c))throw new rs(await Dp(c));e.print(`${a}: posted.`)}catch(l){let c=l instanceof rs?l.message:`Azure DevOps couldn't be reached (${l instanceof Error?l.message:String(l)})`;e.error(`No ${o}: ${c}.`)}}async function jC(e,t,n,r,s,o){let a=l=>e.print(`No pull-request comment: ${l}.`),d=n.pullRequest;if(d===void 0)return a("this run isn't for a pull request");if(n.provider!=="TfsGit")return a(`the repository is on ${n.provider||"another host"}, and KwikQA comments from Azure Pipelines only on Azure Repos pull requests`);if(d.fork)return a("the pull request comes from a fork, and its build gets no secrets by default");if(n.token===void 0)return a("SYSTEM_ACCESSTOKEN isn't set; add `SYSTEM_ACCESSTOKEN: $(System.AccessToken)` to the step's env");if(n.collectionUrl===void 0||n.projectId===void 0||n.repositoryId===void 0)return a("System.CollectionUri, System.TeamProjectId, or Build.Repository.ID isn't what Azure Pipelines sets");await Bp(e,t,{collectionUrl:n.collectionUrl,projectId:n.projectId,repositoryId:n.repositoryId,pullRequest:d.number,token:n.token,marker:MC(n,o)},r,s)}async function Io(e,t,n,r,s){if(n.tempDirectory===void 0)e.print("No build summary: AGENT_TEMPDIRECTORY isn't set.");else{let o=EC(n.tempDirectory,"kwikqa-summary.md");try{await PC(o,r);let a=`##vso[task.addattachment type=Distributedtask.Core.Summary;name=KwikQA;]${LC(o)}`;e.command===void 0?e.print(a):e.command(a),e.print("Build summary: written.")}catch(a){e.error(`No build summary: ${a.message}`)}}await jC(e,t,n,r,s.failures,s.command??"ci")}import{createHash as pT}from"node:crypto";import{readFile as z6,stat as q6}from"node:fs/promises";import{join as G6,relative as K6,sep as W6}from"node:path";import{randomUUID as Ix}from"node:crypto";import{realpath as ND}from"node:fs/promises";import{join as Sx}from"node:path";import{open as zC}from"node:fs/promises";import{createHash as jb}from"node:crypto";function BC(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function Ce(e){return jb("sha256").update(e).digest("hex")}function Y(e,t){let n=t.map(BC).join("|"),r=jb("sha256").update(n,"utf8").digest("hex");return`${e}_${r.slice(0,24)}`}import{realpath as Bb,stat as VC}from"node:fs/promises";import{isAbsolute as Hb,relative as UC,resolve as HC,sep as Vb}from"node:path";function Ub(e,t){let n=UC(e,t);if(n==="")return"";if(!(n===".."||n.startsWith(`..${Vb}`)||Hb(n)))return n.split(Vb).join("/")}async function Kt(e,t){if(t.includes("\0"))return{kind:"unauthorized",message:"Path contains a NUL byte."};let n;try{n=await Bb(e)}catch{return{kind:"unreadable",message:"Authorized root could not be resolved."}}let r=Hb(t)?t:HC(n,t);if(Ub(n,r)===void 0)return{kind:"unauthorized",message:"Path escapes the authorized root."};let s;try{s=await Bb(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 o=Ub(n,s);if(o===void 0)return{kind:"unauthorized",message:"Resolved path escapes the authorized root."};try{if(!(await VC(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:o}}function Vp(e){return e.length===0||e.includes("\0")||e.includes("\\")||e.startsWith("/")||/^[A-Za-z]:/.test(e)?!1:e.split("/").every(n=>n!==".."&&n!==".")}async function G(e,t,n){let r=await Kt(e,t);if(r.kind!=="authorized")return r;let s;try{s=await zC(r.absolutePath,"r");let o=await s.stat();if(o.size>n)return{kind:"over-budget",message:`Artifact exceeds the ${n}-byte limit.`,relativePath:r.relativePath};let a=new Uint8Array(o.size),d=0;for(;d<a.byteLength;){let l=await s.read(a,d,a.byteLength-d,d);if(l.bytesRead===0)break;d+=l.bytesRead}return d!==a.byteLength?{kind:"unreadable",message:"Artifact changed or ended while it was being read.",relativePath:r.relativePath}:{kind:"read",bytes:a,sha256:Ce(a),relativePath:r.relativePath}}catch{return{kind:"unreadable",message:"Authorized artifact could not be read.",relativePath:r.relativePath}}finally{await s?.close()}}import{createHash as qC}from"node:crypto";function Up(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError("canonical JSON cannot contain non-finite numbers");return e}if(Array.isArray(e))return e.map(n=>Up(n,t));if(typeof e!="object")throw new TypeError(`canonical JSON cannot contain ${typeof e}`);if(t.has(e))throw new TypeError("canonical JSON cannot contain cycles");t.add(e);try{let n=e,r={};for(let s of Object.keys(n).sort()){let o=n[s];if(o===void 0)throw new TypeError(`canonical JSON cannot contain undefined at ${JSON.stringify(s)}`);r[s]=Up(o,t)}return r}finally{t.delete(e)}}function le(e){return JSON.stringify(Up(e,new Set))}function V(e){return qC("sha256").update(le(e),"utf8").digest("hex")}import{createHash as GC,randomUUID as tl}from"node:crypto";import{constants as is}from"node:fs";import{chmod as KC,link as WC,lstat as Un,mkdir as Gb,open as el,readFile as Kb,realpath as Vn,rename as qp,rm as zb,unlink as Hp}from"node:fs/promises";import{dirname as zp,isAbsolute as JC,join as mr,relative as Wb,resolve as Gp,sep as Jb}from"node:path";var YC=/^txn_[a-f0-9]{24}$/;function qr(e,t){let n=Wb(e,t);return n===""||!JC(n)&&n!==".."&&!n.startsWith(`..${Jb}`)}async function ss(e){if(process.platform==="win32")return;let t=await el(e,"r");try{await t.sync()}finally{await t.close()}}function qb(e){return GC("sha256").update(e).digest("hex")}function Yb(){return`txn_${tl().replaceAll("-","").slice(0,24)}`}function Hn(e){return YC.test(e)}async function nl(e){let t=await Vn(e),n=Gp(t,".kwikqa","transactions");if(!qr(t,n))throw new Error("Transaction path escapes workspace.");return{root:t,transactionsDirectory:n}}async function ge(e,t){let n=await Vn(e),r=n;for(let s of t){if(!/^[A-Za-z0-9_.-]+$/.test(s)||s==="."||s==="..")throw new Error("Unsafe transaction directory segment.");let o=mr(r,s),a=await Un(o).catch(l=>{if(l.code!=="ENOENT")throw l});if(a===void 0)await Gb(o,{mode:448}),await ss(r);else if(!a.isDirectory()||a.isSymbolicLink())throw new Error("Transaction directory contains an unsafe path.");let d=await Vn(o);if(!qr(n,d))throw new Error("Transaction directory escapes workspace.");r=d}return r}async function Xb(e,t,n){if(!/^\.staging-[a-f0-9]{24}$/.test(t)||!Hn(n))throw new Error("Transaction publication name is invalid.");let r=await nl(e),s=await Vn(r.transactionsDirectory),o=mr(s,t),a=mr(s,n),d=await Un(o);if(!d.isDirectory()||d.isSymbolicLink())throw new Error("Transaction staging directory is unsafe.");if(await Un(a).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Transaction already exists.");await qp(o,a),await ss(s)}async function oe(e,t,n){let r=await Vn(zp(e)),s=Gp(r,e.slice(zp(e).length+1));if(!qr(r,s))throw new Error("Write target escapes its directory.");if(!n.replace&&await Un(s).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Durable record already exists.");let o=mr(r,`.kwikqa-${tl()}.tmp`),a=await el(o,"wx",n.mode),d=!1;try{await a.writeFile(t),await a.sync(),await a.close(),n.replace?await qp(o,s):(await WC(o,s),await Hp(o)),d=!0,await ss(r)}finally{await a.close().catch(()=>{}),d||await Hp(o).catch(()=>{})}}async function hr(e,t,n,r){let s=await Vn(e),o=Gp(s,t);if(!qr(s,o))throw new Error("Target escapes workspace.");let a=await Un(o);if(!a.isFile()||a.isSymbolicLink())throw new Error("Target is not a regular file.");let d=await Vn(zp(o)),l=await Vn(o);if(!qr(s,d)||!qr(s,l))throw new Error("Target escapes workspace.");if(Wb(s,l).split(Jb).join("/")!==t)throw new Error("Target canonical path changed during final authorization.");let u=await el(l,is.O_RDONLY|is.O_NOFOLLOW);try{let g=await u.stat();if(!g.isFile()||g.dev!==a.dev||g.ino!==a.ino)throw new Error("Target changed during final authorization.");let y=await u.readFile();if(qb(y)!==n)throw new Error("Target content changed during final authorization.")}finally{await u.close()}let p=mr(d,`.kwikqa-target-${tl()}.tmp`),f=a.mode&511,m=await el(p,is.O_CREAT|is.O_EXCL|is.O_WRONLY|is.O_NOFOLLOW,f),h=!1;try{await m.writeFile(r),await m.sync(),await m.close(),await KC(p,f);let g=await Vn(o);if(g!==l||!qr(s,g))throw new Error("Target path changed before replacement.");let y=await Kb(g),w=await Un(g);if(!w.isFile()||w.isSymbolicLink()||w.dev!==a.dev||w.ino!==a.ino||qb(y)!==n)throw new Error("Target changed before replacement.");await qp(p,g),h=!0,await ss(d)}finally{await m.close().catch(()=>{}),h||await Hp(p).catch(()=>{})}}async function Qe(e,t){let n=await ge(e,[".kwikqa","transactions"]),r=mr(n,".lock"),s=tl();await Gb(r,{mode:448});let o=await Un(r);try{await oe(mr(r,"owner.json"),`${JSON.stringify({...t,nonce:s})}
|
|
11
11
|
`,{mode:384,replace:!1})}catch(a){let d=await Un(r).catch(()=>{});throw d?.dev===o.dev&&d.ino===o.ino&&await zb(r,{recursive:!0,force:!0}).catch(()=>{}),a}return await ss(n),{release:async()=>{let a=await Un(r).catch(()=>{});if(a===void 0||a.dev!==o.dev||a.ino!==o.ino||a.isSymbolicLink())throw new Error("Workspace lock ownership changed before release.");if(JSON.parse(await Kb(mr(r,"owner.json"),"utf8")).nonce!==s)throw new Error("Workspace lock ownership changed before release.");await zb(r,{recursive:!0,force:!1}),await ss(n)}}}var Wt="kwikqa-init.gradle",rl="junit.xml",hn="cucumber.json",XC=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/,QC=/^[A-Za-z_$][\w$]*$/;function ZC(e){let t=e.split(/[([]/u,1)[0]??"";return t===""?void 0:t}var eN=/^(?:file|classpath):[^\s,\\\0]+$/u;function os(e){return eN.test(e)}function Kp(e){return XC.test(e.className)&&(e.methodName===void 0||QC.test(e.methodName))&&(e.feature===void 0||os(e.feature.uri)&&Number.isInteger(e.feature.line)&&e.feature.line>0)}function tN(e){return e.length>0&&!e.startsWith("-")&&!e.startsWith("/")&&!e.includes("\0")&&!e.includes("\\")&&!e.split("/").some(t=>t===""||t==="."||t==="..")}function Zb(e){if(e.length<2)return;let t=ZC(e.at(-1)??"");if(t===void 0)return;let n={className:e.slice(0,-1).join("$"),methodName:t};return Kp(n)?n:void 0}function nN(e){return e.methodName===void 0?e.className:`${e.className}#${e.methodName}`}function rN(e){return e.methodName===void 0?e.className:`${e.className}.${e.methodName}`}function Wp(e){return["-o","-B","-Dsurefire.rerunFailingTestsCount=0","-Dsurefire.failIfNoSpecifiedTests=false",`-Dtest=${e.selectors.map(nN).join(",")}`,"test"]}function Jp(e){return["-o","-B","-Dsurefire.rerunFailingTestsCount=0","-Dsurefire.failIfNoSpecifiedTests=false",`-Dtest=${e.runnerClass}`,...e.features.length===0?[]:[`-Dcucumber.features=${e.features.map(t=>`${t.uri}:${t.line}`).join(",")}`],`-Dcucumber.plugin=json:${e.reportPath}`,"test"]}function ev(e){return e.length>0&&!/[,:\0]/u.test(e)}var Yp=["-o","-B","test-compile"];function il(e){return["--offline","--no-daemon","--console=plain","--no-build-cache","--init-script",e.initScript,"test",...e.selectors.flatMap(t=>["--tests",rN(t)])]}function Xp(e){return il({selectors:[{className:e.runnerClass}],initScript:e.initScript})}var Qp=["--offline","--no-daemon","compileTestJava"];function Qb(e){return`'${e.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(`
|
|
12
12
|
`,"\\n").replaceAll("\r","\\r")}'`}function tv(e,t){return[...e,"gradle.projectsEvaluated {"," gradle.rootProject.allprojects { project ->"," project.plugins.withId('org.gradle.test-retry') {"," project.tasks.withType(Test).configureEach { test ->"," test.retry.maxRetries = 0"," }"," }"," project.tasks.withType(Test).configureEach { test ->"," test.outputs.cacheIf { false }"," test.outputs.upToDateWhen { false }"," test.filter.failOnNoMatchingTests = false",...t," }"," }","}",""].join(`
|
|
13
13
|
`)}function So(){return tv(["// Written by KwikQA for one validation command. It turns the test-retry plugin's retries off,","// and keeps the test task out of the build cache and never up to date, so every pass runs the tests. It","// lets a module with no matching test pass, since --tests applies to every module. It leaves each module's","// JUnit XML where that module's build writes it, which KwikQA collects after the run. It runs after the","// project's build scripts, so they cannot turn any of these back on."],[" test.reports.junitXml.required = true"])}function To(e){let t=Qb(`json:${e.reportPath}`),n=Qb(e.features.map(r=>`${r.uri}:${r.line}`).join(","));return tv(["// Written by KwikQA for one Cucumber-JVM validation command. Gradle passes no -D options to the","// test JVM, so this script passes Cucumber's JSON report and its scenarios as system properties. It turns","// the JUnit XML off, since the JSON is the only report KwikQA reads for this command. It also turns the","// test-retry plugin's retries off, keeps the test task out of the build cache and never up to date, and","// lets a module with no matching test pass. It runs after the project's build scripts, so they cannot turn","// any of these back on."],[" test.reports.junitXml.required = false",` test.systemProperty('cucumber.plugin', ${t})`,...e.features.length===0?[]:[` test.systemProperty('cucumber.features', ${n})`]])}function Zp(e,t){if(!(!tN(e)||t.length===0)&&!t.some(n=>n===""||n.includes("::")||n.includes("\0")))return`${e}::${t.join("::")}`}function ef(e){return["-m","pytest",...e.nodeIds,"-p","no:rerunfailures","-p","no:cacheprovider","-q",`--junitxml=${e.junitPath}`]}function nv(e){return e.every(t=>t.length>0&&!t.startsWith("-")&&!t.includes("\0"))}var ol="1.1",Po="1.0",Eo="1.2";var al="1.0",gr=/^[a-z][a-z0-9_-]{0,63}$/,as=32*1024*1024,Gr=16*1024*1024,Co="report.json",iv=["playwright-focused","playwright-affected","playwright-project","playwright-suite","cypress-focused","cypress-affected","cypress-project","cypress-suite","webdriverio-focused","webdriverio-affected","webdriverio-project","webdriverio-suite","maven-focused","maven-affected","gradle-focused","gradle-affected","pytest-focused","pytest-affected"],sv=["maven-focused","maven-affected","gradle-focused","gradle-affected","pytest-focused","pytest-affected"];function dl(e){return iv.includes(e)}function Kr(e){return sv.includes(e)}function Wr(e){return Kr(e)||e==="java-compile"}var He=/^[a-f0-9]{64}$/,No=gr;function Ke(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ov(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function Ao(e,t=!0){return ov(e)&&(t||e.length>0)&&e.every(n=>n.length>0&&!n.includes("\0"))&&new Set(e).size===e.length}function ze(e,t){let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((s,o)=>s===r[o])}function iN(e){if(!Ke(e))return!1;let t=["outputDirectory","maxArtifacts","maxArtifactBytes"];return e.reportFile!==void 0&&t.push("reportFile"),ze(e,t)&&typeof e.outputDirectory=="string"&&e.outputDirectory.length>0&&!e.outputDirectory.includes("\0")&&(e.reportFile===void 0||typeof e.reportFile=="string"&&e.reportFile.length>0&&!e.reportFile.includes("\0"))&&Number.isInteger(e.maxArtifacts)&&e.maxArtifacts>0&&Number.isInteger(e.maxArtifactBytes)&&e.maxArtifactBytes>0&&e.maxArtifactBytes<=as}function sN(e){return Ke(e)&&ze(e,["features"])&&Array.isArray(e.features)&&e.features.every(t=>Ke(t)&&ze(t,["uri","line"])&&typeof t.uri=="string"&&os(t.uri)&&Number.isInteger(t.line)&&t.line>0)}function oN(e){if(!Ke(e))return!1;let t=["kind","path","detail"];return e.sha256!==void 0&&t.push("sha256"),e.cucumber!==void 0&&t.push("cucumber"),ze(e,t)&&["package-root","package-manifest","package-entry","configuration","pnp-loader","source-graph","scope-escalation","build-executable","build-support","jdk-launcher","generated-init-script"].includes(String(e.kind))&&typeof e.path=="string"&&e.path.length>0&&!e.path.includes("\0")&&typeof e.detail=="string"&&e.detail.length>0&&(e.sha256===void 0||typeof e.sha256=="string"&&He.test(e.sha256))&&(e.cucumber===void 0||e.kind==="generated-init-script"&&sN(e.cucumber))}function av(e){return!Ke(e)||!No.test(String(e.commandId))||!ze(e,["commandId","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","artifactPolicy","resolutionEvidence"])||!(dl(String(e.kind))||["parse","format","typecheck","lint","java-compile"].includes(String(e.kind)))||e.timing!=="baseline"&&e.timing!=="post-patch"||typeof e.executable!="string"||e.executable.length===0||!ov(e.args)||e.args.some(t=>t.includes("\0"))||typeof e.workingDirectory!="string"||e.workingDirectory.length===0||e.workingDirectory.includes("\0")||!Number.isInteger(e.timeoutMs)||e.timeoutMs<=0||e.required!==!0||typeof e.purpose!="string"||e.purpose.length===0||!Ao(e.logicalTestIds)||!Ao(e.projectIds)||!Ke(e.environmentDelta)||!iN(e.artifactPolicy)||!Array.isArray(e.resolutionEvidence)||!e.resolutionEvidence.every(oN)?!1:Object.entries(e.environmentDelta).every(([t,n])=>/^[A-Z][A-Z0-9_]*$/.test(t)&&typeof n=="string"&&!n.includes("\0"))}function tf(e){return Ke(e)&&ze(e,["path","sourceSha256","resultSha256"])&&typeof e.path=="string"&&e.path.length>0&&!e.path.includes("\0")&&typeof e.sourceSha256=="string"&&He.test(e.sourceSha256)&&typeof e.resultSha256=="string"&&He.test(e.resultSha256)}function aN(e){return Ke(e)&&ze(e,["baselineId","commandId","logicalTestIds","reason"])&&/^baseline_[a-f0-9]{24}$/.test(String(e.baselineId))&&No.test(String(e.commandId))&&Ao(e.logicalTestIds,!1)&&typeof e.reason=="string"&&e.reason.length>0}function dN(e){if(!Ke(e))return!1;let t=["code","message"];return e.path!==void 0&&t.push("path"),ze(e,t)&&["ambiguous-build-tool","ambiguous-package-root","ambiguous-configuration","budget-exceeded","cancelled","entry-outside-workspace","invalid-artifact","invalid-command","malformed-manifest","missing-browser","missing-configuration","missing-dependency","missing-jdk","missing-python-environment","missing-test-identity","package-mismatch","parse-failed","report-incomplete","resolution-failed","spawn-failed","symlink-escape","timeout","unsupported-layout","unsupported-platform","wrapper-distribution-not-cached","wrapper-distribution-unrecognized"].includes(String(e.code))&&typeof e.message=="string"&&e.message.length>0&&(e.path===void 0||typeof e.path=="string"&&!e.path.includes("\0"))}function ll(e){return V({purpose:"kwikqa-validation-baseline",...e})}function Oo(e){return V({purpose:"kwikqa-validation-run",...e})}function sl(e){return typeof e=="string"&&e.length>0&&Number.isFinite(Date.parse(e))}function lN(e){if(!Ke(e)||typeof e.kind!="string")return!1;if(e.kind==="exit")return ze(e,["kind","exitCode"])&&Number.isInteger(e.exitCode);if(e.kind==="signal")return ze(e,["kind","signal"])&&typeof e.signal=="string";if(e.kind==="spawn-error"){let t=["kind",...e.code===void 0?[]:["code"]];return ze(e,t)&&(e.code===void 0||typeof e.code=="string")}return(e.kind==="timeout"||e.kind==="cancelled")&&ze(e,["kind"])}function rv(e){return Ke(e)&&ze(e,["path","sha256","storedSha256","observedBytes","storedBytes","truncated","redacted"])&&typeof e.path=="string"&&e.path.length>0&&typeof e.sha256=="string"&&He.test(e.sha256)&&typeof e.storedSha256=="string"&&He.test(e.storedSha256)&&Number.isInteger(e.observedBytes)&&e.observedBytes>=0&&Number.isInteger(e.storedBytes)&&e.storedBytes>=0&&typeof e.truncated=="boolean"&&typeof e.redacted=="boolean"}function cN(e){return Ke(e)&&ze(e,["path","sha256","bytes"])&&typeof e.path=="string"&&e.path.length>0&&typeof e.sha256=="string"&&He.test(e.sha256)&&Number.isInteger(e.bytes)&&e.bytes>=0}function nf(e){if(!rf(e))throw new Error("Validation command record is malformed or failed integrity validation.");return e}function uN(e){if(!Ke(e))return!1;let t=["classification",...e.logicalTestId===void 0?[]:["logicalTestId"],...e.commandId===void 0?[]:["commandId"],"message"];return ze(e,t)&&["fixed-target-failure","still-failing-target","unchanged-pre-existing-failure","newly-introduced-failure","unavailable-check","incomplete-check"].includes(String(e.classification))&&(e.logicalTestId===void 0||typeof e.logicalTestId=="string"&&e.logicalTestId.length>0)&&(e.commandId===void 0||typeof e.commandId=="string"&&No.test(e.commandId))&&typeof e.message=="string"&&e.message.length>0}function rf(e){if(!Ke(e))return!1;let t=e,{recordHash:n,...r}=t;return ze(e,["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===Po&&/^vld_[a-f0-9]{24}$/.test(t.validationRunId)&&No.test(t.commandId)&&He.test(t.commandHash)&&He.test(t.planHash)&&t.required===!0&&av({commandId:t.commandId,kind:t.kind,timing:t.timing,required:t.required,executable:t.executable,args:t.args,workingDirectory:t.workingDirectory,environmentDelta:t.environmentDelta,timeoutMs:t.timeoutMs,purpose:t.purpose,logicalTestIds:t.logicalTestIds,projectIds:t.projectIds,artifactPolicy:{outputDirectory:"artifacts",maxArtifacts:1,maxArtifactBytes:1},resolutionEvidence:[]})&&sl(t.startedAt)&&Number.isInteger(t.durationMs)&&t.durationMs>=0&&lN(t.termination)&&rv(t.stdout)&&rv(t.stderr)&&Array.isArray(t.artifacts)&&t.artifacts.every(cN)&&["blocked","passed","failed","unavailable","incomplete"].includes(t.status)&&He.test(n)&&V(r)===n}function zn(e){if(!Ke(e))throw new Error("Baseline manifest is not an object.");let t=e,{baselineHash:n,...r}=t;if(!ze(e,["schemaVersion","planHash","repositoryFingerprint","targetHashes","commandRecords","logicalTestOutcomes","capturedAt","baselineHash"])||t.schemaVersion!==Po||!He.test(t.planHash)||!He.test(t.repositoryFingerprint)||!Array.isArray(t.targetHashes)||!t.targetHashes.every(tf)||!Array.isArray(t.commandRecords)||!t.commandRecords.every(rf)||!Ke(t.logicalTestOutcomes)||!Object.entries(t.logicalTestOutcomes).every(([s,o])=>s.length>0&&typeof o=="string"&&["passed","failed","skipped","interrupted"].includes(o))||!sl(t.capturedAt)||!He.test(n)||ll(r)!==n)throw new Error("Baseline manifest is malformed or failed integrity validation.");return t}function gn(e){if(!Ke(e))throw new Error("Validation run manifest is not an object.");let t=e,{manifestHash:n,...r}=t,s=t.checkId===void 0?"transactionId":"checkId";if(!ze(e,["schemaVersion","validationRunId",s,"planHash","repositoryFingerprint","targetHashes","requiredCommandIds","status","commandRecords","classifications","startedAt","completedAt","manifestHash"])||!["1.1",Eo].includes(t.schemaVersion)||!/^vld_[a-f0-9]{24}$/.test(t.validationRunId)||(s==="transactionId"?!/^txn_[a-f0-9]{24}$/.test(t.transactionId??""):t.schemaVersion==="1.1"||!/^chk_[a-f0-9]{24}$/.test(t.checkId??""))||!He.test(t.planHash)||!He.test(t.repositoryFingerprint)||!Array.isArray(t.targetHashes)||!t.targetHashes.every(tf)||!Ao(t.requiredCommandIds,!1)||!t.requiredCommandIds.every(o=>No.test(o))||!Array.isArray(t.commandRecords)||!t.commandRecords.every(rf)||!Array.isArray(t.classifications)||!t.classifications.every(uN)||!["blocked","passed","failed","unavailable","incomplete"].includes(t.status)||!sl(t.startedAt)||!sl(t.completedAt)||Date.parse(t.completedAt)<Date.parse(t.startedAt)||!He.test(n)||Oo(r)!==n)throw new Error("Validation run manifest is malformed or failed integrity validation.");if(new Set(t.targetHashes.map(o=>o.path)).size!==t.targetHashes.length||new Set(t.commandRecords.map(o=>o.commandId)).size!==t.commandRecords.length||t.commandRecords.some(o=>o.validationRunId!==t.validationRunId||o.planHash!==t.planHash))throw new Error("Validation run manifest contains inconsistent evidence.");if(!pN(t))throw new Error("Validation run manifest status is inconsistent with its evidence.");return t}function pN(e){let t=new Set(e.requiredCommandIds),n=new Set(e.commandRecords.map(s=>s.commandId)),r=new Set(e.classifications.map(s=>s.classification));if(e.commandRecords.some(s=>!t.has(s.commandId)||s.timing!=="post-patch")||e.requiredCommandIds.some(s=>!n.has(s)&&!e.classifications.some(o=>o.classification==="incomplete-check"&&o.commandId===s)))return!1;switch(e.status){case"passed":return e.classifications.length>0&&[...r].every(s=>s==="fixed-target-failure")&&n.size===t.size&&e.commandRecords.every(s=>s.status==="passed");case"incomplete":return r.has("incomplete-check");case"unavailable":return!r.has("incomplete-check")&&r.has("unavailable-check");case"failed":return!r.has("incomplete-check")&&!r.has("unavailable-check");default:return!0}}function cl(e){return V({purpose:"kwikqa-resolved-validation-plan",...e})}function yn(e){if(!Ke(e))throw new Error("Resolved validation plan is not an object.");if(!ze(e,["schemaVersion","policyVersion","status",...e.transactionId===void 0?[]:["transactionId"],"proposalHash","targetLogicalTestIds","targetHashes","advisoryPlanHash","repositoryFingerprint","commands","baselineRequirements","unresolvedReasons","planHash"]))throw new Error("Resolved validation plan contains unknown or missing fields.");let t=e,{planHash:n,...r}=t;if(t.schemaVersion!==ol||t.policyVersion!==al||t.status!=="resolved"&&t.status!=="unavailable"||!He.test(t.proposalHash)||!Ao(t.targetLogicalTestIds,!1)||!He.test(t.advisoryPlanHash)||!He.test(t.repositoryFingerprint)||!Array.isArray(t.commands)||!t.commands.every(av)||t.transactionId!==void 0&&!/^txn_[a-f0-9]{24}$/.test(t.transactionId)||!Array.isArray(t.targetHashes)||!t.targetHashes.every(tf)||!Array.isArray(t.baselineRequirements)||!t.baselineRequirements.every(aN)||!Array.isArray(t.unresolvedReasons)||!t.unresolvedReasons.every(dN)||!He.test(n)||cl(r)!==n)throw new Error("Resolved validation plan is malformed or failed integrity validation.");if(new Set(t.commands.map(o=>o.commandId)).size!==t.commands.length)throw new Error("Resolved validation plan contains duplicate command ids.");if(new Set(t.targetHashes.map(o=>o.path)).size!==t.targetHashes.length)throw new Error("Resolved validation plan contains duplicate targets.");if(new Set(t.baselineRequirements.map(o=>o.baselineId)).size!==t.baselineRequirements.length)throw new Error("Resolved validation plan contains duplicate baseline ids.");let s=new Map(t.commands.map(o=>[o.commandId,o]));if(t.baselineRequirements.some(o=>{let a=s.get(o.commandId);return a===void 0||a.timing!=="baseline"}))throw new Error("Resolved validation plan baseline references are invalid.");if(t.status==="resolved"&&t.unresolvedReasons.length>0||t.status==="unavailable"&&t.unresolvedReasons.length===0)throw new Error("Resolved validation plan status is inconsistent.");return t}import{spawn as YN}from"node:child_process";import{createHash as Vo,randomUUID as XN}from"node:crypto";import{constants as Rv}from"node:fs";import{lstat as Bo,mkdir as ls,open as QN,readdir as Iv,readFile as ZN,realpath as hl,rm as ff}from"node:fs/promises";import{isAbsolute as bl,join as Ve,relative as gl,resolve as ml,sep as yl}from"node:path";var $o={policyVersion:"development-2",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","api_key","access_key","access-key","accesskey","accountkey","private_key","private-key","privatekey","session_id","session-id","sessionid","x-auth"]},fN=["maxPacketBytes","maxArtifactBytes","maxTraceEntries","maxTraceEvents","maxReportFields","maxStackFrames","maxSteps","maxStdioChunks","maxStdioBytes","maxTraceExpandedBytes","maxConsoleEvents","maxNetworkEvents","maxDomDepth","maxDomNodes","maxDomTextBytes","maxSourceFiles","maxSourceBytes","maxSourceLinesPerFile","maxImportDepth","maxDiffBytes","maxDiffHunks"];function sf(e){if(e===null||typeof e!="object")return"policy must be an object";if(typeof e.policyVersion!="string")return"policyVersion must be a string";if(e.policyVersion.length===0)return"policyVersion must not be empty";if(typeof e.workspaceRoot!="string")return"workspaceRoot must be a string";if(e.workspaceRoot.length===0)return"workspaceRoot must not be empty";if(typeof e.includeNetworkBodies!="boolean")return"includeNetworkBodies must be a boolean";if(!Array.isArray(e.sensitiveNames)||e.sensitiveNames.some(t=>typeof t!="string"||t.length===0))return"sensitiveNames must be an array of non-empty strings";if(e.sensitiveNames.some(t=>t.trim()!==t))return"sensitiveNames must not contain surrounding whitespace";for(let t of fN){let n=e[t];if(typeof n!="number"||!Number.isSafeInteger(n)||n<=0)return`${t} must be a positive safe integer`}if(!Number.isSafeInteger(e.maxNetworkBodyBytes)||e.maxNetworkBodyBytes<0||e.includeNetworkBodies&&e.maxNetworkBodyBytes===0)return"maxNetworkBodyBytes must be positive when network bodies are enabled"}var mN=/\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001B]*(?:\u0007|\u001B\\))/g;function wn(e){return e.replace(mN,"")}var st="[REDACTED]",hN=[{id:"private-key",pattern:/-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----[A-Za-z0-9+/=\s\\]*(?:-----END [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----)?/g,replacement:st},{id:"jwt",pattern:/\beyJ[A-Za-z0-9_-]{4,}\.eyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*/g,replacement:st},{id:"bearer-credential",pattern:/\b([Bb]earer\s+)[A-Za-z0-9._~+/-]{16,}=*/g,replacement:`$1${st}`},{id:"basic-credential",pattern:/\b(Basic\s+)(?=[A-Za-z+/]*[0-9+/=])[A-Za-z0-9+/]{12,}={0,2}(?![A-Za-z0-9+/=])/g,replacement:`$1${st}`},{id:"url-credentials",pattern:/\b([a-z][a-z0-9+.-]{1,20}:\/\/)[^\s:/@'"<>]+:[^\s/@'"<>]+@/gi,replacement:`$1${st}@`},{id:"chat-webhook",pattern:/https:\/\/(?:hooks\.slack\.com\/(?:services|workflows|triggers)|[A-Za-z0-9-]+\.webhook\.office\.com\/webhookb2)\/[^\s"'<>]+/g,replacement:st},{id:"aws-access-key",pattern:/\b(?:AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}\b/g,replacement:st},{id:"github-token",pattern:/\b(?:gh[pousr]_[A-Za-z0-9]{36,255}|github_pat_[A-Za-z0-9_]{22,255})\b/g,replacement:st},{id:"gitlab-token",pattern:/\bglpat-[A-Za-z0-9_-]{20,}/g,replacement:st},{id:"slack-token",pattern:/\bxox[abposr]-[A-Za-z0-9-]{10,}/g,replacement:st},{id:"stripe-key",pattern:/\b[rs]k_(?:live|test)_[A-Za-z0-9]{16,}/g,replacement:st},{id:"google-api-key",pattern:/\bAIza[0-9A-Za-z_-]{35}/g,replacement:st},{id:"npm-token",pattern:/\bnpm_[A-Za-z0-9]{36}\b/g,replacement:st},{id:"model-api-key",pattern:/\bsk-(?=[A-Za-z_-]*[0-9])[A-Za-z0-9_-]{20,}/g,replacement:st},{id:"kwikqa-token",pattern:/\bk(?:wk|rt|ss|ws)_[A-Za-z0-9_-]{20,}/g,replacement:st}];function Lo(e,t,n){let r=e,s=[];for(let{id:o,pattern:a,replacement:d}of hN){let l=0;r=r.replace(a,(...c)=>{l+=1;let u=typeof c[1]=="string"?c[1]:"";return d.replace("$1",()=>u)}),l>0&&s.push({redactionId:Y("red",[t,n,`secret:${o}`]),ruleId:`secret-value:${o}`,channel:t,locator:n,action:"mask",count:l})}return{value:r,records:s}}function ke(e,t,n,r){let s=wn(e),o=[];for(let d of[...new Set(r.map(l=>l.toLowerCase()))].sort()){let l=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`(["']?${l}["']?\\s*[:=]\\s*)(?:"[^"\\r\\n]*"|'[^'\\r\\n]*'|[^,;&}\\r\\n]*?(?=\\s+(?:and\\s+)?[A-Za-z_$][\\w$.-]*\\s*[:=]|\\s*$|[,;&}]))`,"gim"),u=0;if(s=s.replace(c,(p,f)=>(u+=1,`${f}[REDACTED]`)),u===0){let p=new RegExp(`(${l}\\s*[:=]\\s*)\\S+`,"gi");s=s.replace(p,(f,m)=>(u+=1,`${m}[REDACTED]`))}u>0&&o.push({redactionId:Y("red",[t,n,d]),ruleId:`sensitive-name:${d}`,channel:t,locator:n,action:"mask",count:u})}let a=Lo(s,t,n);return{value:a.value,records:[...o,...a.records]}}function Mo(e,t){let n=e.toLowerCase();return t.map(r=>r.toLowerCase()).sort().find(r=>n===r||n.includes(r))}function ul(e,t,n,r){let s=[],o=new Map,a=new Map;for(let l of e){let c=Mo(l.name,r);if(c===void 0){let u=Lo(l.value,t,n);s.push(u.records.length===0?l:{name:l.name,value:u.value});for(let p of u.records){let f=a.get(p.ruleId);a.set(p.ruleId,{...p,count:(f?.count??0)+p.count})}continue}o.set(c,(o.get(c)??0)+1)}let d=[...o.entries()].sort(([l],[c])=>l.localeCompare(c)).map(([l,c])=>({redactionId:Y("red",[t,n,`header:${l}`]),ruleId:`sensitive-header:${l}`,channel:t,locator:n,action:"remove",count:c}));return{value:s,records:[...d,...a.values()]}}function yr(e,t,n,r){let s;try{s=new URL(e)}catch{return ke(e,t,n,r)}let o=[];(s.username!==""||s.password!=="")&&(s.username="",s.password="",o.push({redactionId:Y("red",[t,n,"url-userinfo"]),ruleId:"url-userinfo",channel:t,locator:n,action:"remove",count:1}));let a=new Map;for(let l of[...s.searchParams.keys()]){let c=Mo(l,r);c!==void 0&&(s.searchParams.set(l,"[REDACTED]"),a.set(c,(a.get(c)??0)+1))}for(let[l,c]of[...a.entries()].sort(([u],[p])=>u.localeCompare(p)))o.push({redactionId:Y("red",[t,n,`query:${l}`]),ruleId:`sensitive-query:${l}`,channel:t,locator:n,action:"mask",count:c});let d=Lo(s.toString(),t,n);return{value:d.value,records:[...o,...d.records]}}var gN=new Set(["value","data-value","content","__playwright_value_","__playwright_checked_","__playwright_selected_"]),dv=["type","name","id","autocomplete","placeholder","aria-label"];function of(e,t,n,r){if(e==="")return{value:e,records:[]};let s=t.filter(o=>dv.includes(o.name.toLowerCase())).map(o=>Mo(o.value,r)).find(o=>o!==void 0);return s===void 0?Lo(e,"dom",n):{value:"[REDACTED]",records:[{redactionId:Y("red",["dom",n,`text:${s}`]),ruleId:`sensitive-element-text:${s}`,channel:"dom",locator:n,action:"mask",count:1}]}}function af(e,t,n){let r=e.filter(d=>dv.includes(d.name.toLowerCase())).map(d=>Mo(d.value,n)).find(d=>d!==void 0),s=[],o=new Map;for(let d of e){let l=Mo(d.name,n),c=r!==void 0&&gN.has(d.name.toLowerCase())?r:void 0,u=l??c;if(u===void 0||d.value===""){let f=Lo(d.value,"dom",t);s.push(f.records.length===0?d:{name:d.name,value:f.value});for(let m of f.records)o.set(m.ruleId,(o.get(m.ruleId)??0)+m.count);continue}s.push({name:d.name,value:"[REDACTED]"});let p=l===void 0?`sensitive-element:${u}`:`sensitive-field:${u}`;o.set(p,(o.get(p)??0)+1)}let a=[...o.entries()].sort(([d],[l])=>d.localeCompare(l)).map(([d,l])=>({redactionId:Y("red",["dom",t,d]),ruleId:d,channel:"dom",locator:t,action:"mask",count:l}));return{value:s,records:a}}var yN=["KWIKQA_TOKEN","KWIKQA_API_URL","OPENROUTER_API_KEY"],wN={anthropic:["ANTHROPIC_API_KEY"],openai:["OPENAI_API_KEY"],"azure-openai":["AZURE_OPENAI_API_KEY"],bedrock:["AWS_BEARER_TOKEN_BEDROCK"]};function df(e){let t=e.KWIKQA_ENDPOINT?.trim().toLowerCase()??"";return[...yN,...wN[t]??[]]}function lv(e){let t={...e};for(let n of df(e))delete t[n];return t}import{createHash as bN}from"node:crypto";import{createReadStream as vN}from"node:fs";import{lstat as fv,readdir as kN,realpath as pl,stat as Do}from"node:fs/promises";import{homedir as RN}from"node:os";import{delimiter as xN,isAbsolute as Fo,join as ot,relative as _N,sep as IN}from"node:path";var SN=512*1024*1024,cv=16*1024*1024,TN=64*1024;function Me(e,t){return{kind:"unavailable",reasons:[{code:e,message:t}]}}function AN(e,t){let n=_N(e,t);return n===""||!Fo(n)&&n!==".."&&!n.startsWith(`..${IN}`)}function lf(e){return e.relative===""?"the workspace root":e.relative}function mv(e,t){return e.relative===""?t:`${e.relative}/${t}`}async function PN(e,t){let n=await pl(e);if(t==="")return{kind:"location",location:{workspace:n,root:n,relative:t}};let r=t.split("/");if(Fo(t)||t.includes("\\")||t.includes("\0")||r.some(a=>a===""||a==="."||a===".."))return Me("unsupported-layout",`${t} isn't a directory inside the workspace, so the build there can't be validated.`);let s=ot(n,t),o=await pl(s).catch(()=>{});return o===void 0?Me("unsupported-layout",`${t} isn't a directory in the workspace, so the build there can't be validated.`):o!==s?Me("unsupported-layout",`${t} goes through a symbolic link, so the build there can't be validated.`):{kind:"location",location:{workspace:n,root:s,relative:t}}}async function ds(e,t=SN){try{let n=await pl(e),r=await Do(n);if(!r.isFile()||r.size>t)return;let s=bN("sha256");return await new Promise((o,a)=>{let d=vN(n);d.on("data",l=>s.update(l)),d.on("error",a),d.on("end",()=>o())}),{realPath:n,sha256:s.digest("hex")}}catch{return}}function cf(e,t){return t==="win32"||(e.mode&73)!==0}async function EN(e){let t=e.JAVA_HOME;if(t===void 0||t.trim()==="")return Me("missing-jdk","JAVA_HOME is not set. Java validation needs a JDK already on this machine; KwikQA never installs one.");if(!Fo(t))return Me("missing-jdk","JAVA_HOME must be an absolute path to a JDK.");let n=ot(t,"bin","java"),r=await ds(n);return r===void 0?Me("missing-jdk",`JAVA_HOME (${t}) has no bin/java launcher, so it is not a JDK. KwikQA never installs one.`):{kind:"resolved",jdk:{javaHome:t,launcher:n,sha256:r.sha256}}}async function CN(e,t,n){for(let r of(t??"").split(xN)){if(r===""||!Fo(r))continue;let s=ot(r,e),o=await Do(s).catch(()=>{});if(o?.isFile()===!0&&cf(o,n))return s}}var hv={maven:{name:"Maven",wrapper:"mvnw",wrapperSupport:[".mvn/wrapper/maven-wrapper.jar",".mvn/wrapper/maven-wrapper.properties"],onPath:"mvn"},gradle:{name:"Gradle",wrapper:"gradlew",wrapperSupport:["gradle/wrapper/gradle-wrapper.jar","gradle/wrapper/gradle-wrapper.properties"],onPath:"gradle"}};function uv(e){return e===void 0||e.trim()===""?void 0:e}function NN(e,t){let n=t??RN();return{gradle:uv(e.GRADLE_USER_HOME)??ot(n,".gradle"),maven:uv(e.MAVEN_USER_HOME)??ot(n,".m2")}}function ON(e,t){let n=[];for(let s of e.split(/\r?\n/u)){let o=s.trim();if(o===""||o.startsWith("#")||o.startsWith("!"))continue;let a=/^([^=:\s]+)\s*[=:]\s*(.*)$/u.exec(o);a?.[1]===t&&n.push((a[2]??"").replace(/\\(.)/gu,"$1"))}let[r]=n;return r===void 0?{kind:"absent"}:n.length===1?{kind:"value",value:r}:{kind:"repeated"}}var $N=/^(gradle-[0-9][A-Za-z0-9.-]*-(?:bin|all))\.zip$/u,MN=/^(apache-maven-[0-9][A-Za-z0-9.-]*?)(?:-bin)?\.zip$/u;function LN(e,t){let n;try{n=new URL(e)}catch{return}return n.protocol!=="https:"||n.username!==""||n.password!==""?void 0:(t==="gradle"?$N:MN).exec(n.pathname.split("/").at(-1)??"")?.[1]}async function pv(e){return(await kN(e,{withFileTypes:!0}).catch(()=>[])).filter(n=>n.isDirectory()).map(n=>n.name)}async function DN(e){return(await Do(e).catch(()=>{}))?.isFile()===!0}async function FN(e,t,n){let r=ot(e,"wrapper","dists",t),s=n==="gradle"?"gradle":"mvn";for(let o of await pv(r))for(let a of await pv(ot(r,o)))if((n==="gradle"?a.startsWith("gradle-"):a===t)&&await DN(ot(r,o,a,"bin",s)))return!0;return!1}async function jN(e,t,n,r){let s=ON(n,"distributionUrl");if(s.kind!=="value")return Me("wrapper-distribution-unrecognized",`The ${e.name} wrapper's properties name ${s.kind==="absent"?"no":"more than one"} distributionUrl, so KwikQA can't tell which distribution it would download.`);let o=LN(s.value,t);return o===void 0?Me("wrapper-distribution-unrecognized",`The ${e.name} wrapper's distributionUrl must be an https URL to a ${e.name} distribution .zip, so KwikQA can tell which distribution it would download.`):Fo(r)?await FN(r,o,t)?{kind:"cached"}:Me("wrapper-distribution-not-cached",`The ${e.name} wrapper's distribution ${o} isn't in ${ot(r,"wrapper","dists")}, and KwikQA never downloads one. Run \`./${e.wrapper} --version\` once yourself, then validate again.`):Me("wrapper-distribution-not-cached",`The ${e.name} user home (${r}) must be an absolute path, so KwikQA can't look for the distribution ${o} there.`)}async function BN(e,t,n,r,s){let o=hv[t];if(n==="win32")return Me("unsupported-platform",`${o.name} validation is unavailable on Windows. Its wrappers and tools are .cmd or .bat scripts, which need a shell, and KwikQA never starts one. Run this validation on macOS or Linux.`);let a=await EN(r);if(a.kind==="unavailable")return a;let d={kind:"jdk-launcher",path:a.jdk.launcher,sha256:a.jdk.sha256,detail:"The java launcher that JAVA_HOME names, pinned by its SHA-256."},l={JAVA_HOME:a.jdk.javaHome},c=ot(e.root,o.wrapper);if(await fv(c).catch(()=>{})!==void 0)return VN(e,t,n,l,d,s);let u=await CN(o.onPath,r.PATH,n);if(u===void 0){let f=e.relative===""?"The repository":`The build at ${lf(e)}`;return Me("missing-dependency",`${f} has no ${o.wrapper} and ${o.onPath} was not found on PATH. KwikQA never installs ${o.name}.`)}let p=await ds(u);return p===void 0?Me("missing-dependency",`${o.onPath} on PATH could not be read safely.`):{kind:"resolved",tool:{system:t,source:"path",executable:u,environmentDelta:l,resolutionEvidence:[{kind:"build-executable",path:u,sha256:p.sha256,detail:`${o.onPath} found on PATH, pinned by the SHA-256 of the file it resolves to.`},d]}}}async function VN(e,t,n,r,s,o){let a=hv[t],d=await G(e.root,a.wrapper,cv);if(d.kind!=="read")return Me("missing-dependency",`${a.wrapper} must be a regular file inside the workspace, and it is not.`);let l=await Do(ot(e.root,a.wrapper)).catch(()=>{});if(l===void 0||!cf(l,n))return Me("missing-dependency",`${a.wrapper} is not executable. Restore its execute bit, then validate again.`);let c=[],u="";for(let h of a.wrapperSupport){let g=await G(e.root,h,cv);if(g.kind!=="read")return Me("missing-dependency",`${h} is missing or unreadable. KwikQA pins the wrapper's jar and properties, so it needs them.`);h.endsWith(".properties")&&(u=new TextDecoder().decode(g.bytes)),c.push({kind:"build-support",path:mv(e,h),sha256:g.sha256,detail:`The ${a.name} wrapper's ${h.split("/").at(-1)??h}, pinned by its SHA-256.`})}let p=await jN(a,t,u,o);if(p.kind==="unavailable")return p;let f=t==="gradle"?"GRADLE_USER_HOME":"MAVEN_USER_HOME",m=e.relative===""?"The repository's":`The build at ${lf(e)}'s`;return{kind:"resolved",tool:{system:t,source:"wrapper",executable:ot(e.root,a.wrapper),environmentDelta:{...r,[f]:o},resolutionEvidence:[{kind:"build-executable",path:ot(e.root,a.wrapper),sha256:d.sha256,detail:`${m} ${a.wrapper} script, pinned by its SHA-256.`},...c,s]}}}var UN=[".venv","venv"];async function HN(e,t){let n=t==="win32"?["Scripts","python.exe"]:["bin","python"];for(let r of UN){let s=ot(e.root,r);if(await fv(s).catch(()=>{})===void 0)continue;let a=await pl(s).catch(()=>{});if(a===void 0||!AN(e.workspace,a))return Me("entry-outside-workspace",`${r} resolves outside the workspace. KwikQA runs pytest only from a virtual environment inside it.`);let d=ot(s,...n),l=await ds(d),c=await Do(d).catch(()=>{});if(l===void 0||c===void 0||!cf(c,t))return Me("missing-python-environment",`${r} has no executable ${n.join("/")}, so it is not a usable virtual environment.`);let u=await G(e.root,`${r}/pyvenv.cfg`,TN);return u.kind!=="read"?Me("missing-python-environment",`${r} has no pyvenv.cfg, so it is not a virtual environment.`):{kind:"resolved",tool:{system:"pytest",source:"virtual-environment",executable:d,environmentDelta:{},resolutionEvidence:[{kind:"build-executable",path:d,sha256:l.sha256,detail:`The ${r} virtual environment's Python, pinned by the SHA-256 of the file it resolves to.`},{kind:"build-support",path:mv(e,`${r}/pyvenv.cfg`),sha256:u.sha256,detail:`The ${r} virtual environment's configuration.`}]}}}return Me("missing-python-environment",`No project virtual environment (.venv or venv) was found at ${lf(e)}. KwikQA runs pytest only from the project's own environment, never a global Python or pip.`)}async function fl(e){let t=e.platform??process.platform,n=e.environment??process.env,r=e.userHomes??NN(n);try{let s=await PN(e.workspaceRoot,e.buildRoot??"");if(s.kind==="unavailable")return s;if(e.system==="pytest")return await HN(s.location,t);let o=e.system==="gradle"?r.gradle:r.maven;return await BN(s.location,e.system,t,n,o)}catch{return Me("missing-dependency",`The ${e.system} executable could not be resolved safely. Nothing was installed or fetched.`)}}import{constants as gv}from"node:fs";import{lstat as yv,open as zN,readdir as uf}from"node:fs/promises";import{join as jo}from"node:path";var qN=3,wv=/^TEST-[A-Za-z0-9_.$-]+\.xml$/,GN=new Set(["node_modules","src","target"]),KN={maven:["target","surefire-reports"],gradle:["build","test-results","test"]};function WN(e,t){return t.startsWith(".")||GN.has(t)?!0:e==="gradle"&&t==="build"}async function JN(e,t){let n=e;for(let r of KN[t]){n=jo(n,r);let s=await yv(n).catch(()=>{});if(s===void 0||!s.isDirectory()||s.isSymbolicLink())return}return n}async function pf(e,t,n=0){let r=[],s=await JN(e,t);if(s!==void 0&&r.push(s),n>=qN)return r;let o=await uf(e,{withFileTypes:!0}).catch(()=>[]);for(let a of o)!a.isDirectory()||a.isSymbolicLink()||WN(t,a.name)||r.push(...await pf(jo(e,a.name),t,n+1));return r}function bv(e){return`${e.ino}:${e.size}:${e.mtimeMs}:${e.ctimeMs}`}async function vv(e,t){let n=new Map;for(let r of await pf(e,t))for(let s of await uf(r,{withFileTypes:!0})){if(!wv.test(s.name))continue;let o=jo(r,s.name),a=await yv(o).catch(()=>{});a!==void 0&&n.set(o,bv(a))}return{layout:t,files:n}}async function kv(e,t,n,r){let s=gv.O_NOFOLLOW??0,o=new Set,a=0;for(let d of await pf(e,n.layout)){let l=(await uf(d,{withFileTypes:!0})).filter(c=>c.isFile()&&!c.isSymbolicLink()&&wv.test(c.name)).sort((c,u)=>c.name.localeCompare(u.name));for(let c of l){let u=jo(d,c.name),p=await zN(u,gv.O_RDONLY|s);try{let f=await p.stat();if(!f.isFile()||n.files.get(u)===bv(f))continue;if(o.has(c.name))throw new Error(`Two modules wrote a JUnit report named ${c.name}.`);if(o.add(c.name),a+=f.size,o.size>r.maxArtifacts||a>r.maxArtifactBytes)throw new Error("Validation output exceeds its artifact limit.");await oe(jo(t,c.name),await p.readFile(),{mode:384,replace:!1})}finally{await p.close()}}}}var e1=/^txn_[a-f0-9]{24}$/,t1=/^chk_[a-f0-9]{24}$/,n1=/^bsl_[a-f0-9]{24}$/,r1=/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTH)/i,i1=["KWIKQA_TOKEN","KWIKQA_API_URL","OPENROUTER_API_KEY"],s1=16*1024*1024,o1=/^[A-Za-z0-9_.-]+$/,a1=$o.sensitiveNames;function mf(e,t){let n=gl(e,t);return n===""||!bl(n)&&n!==".."&&!n.startsWith(`..${yl}`)}function Sv(e){return/^[a-f0-9]{64}$/.test(e)}function d1(e){return e.executable===process.execPath?!0:e.resolutionEvidence.some(t=>t.kind==="build-executable"&&t.path===e.executable&&bl(t.path)&&t.sha256!==void 0&&Sv(t.sha256))}function l1(e){let t=yn(e.plan),n=t.commands.find(r=>r.commandId===e.commandId);if([e.transactionId,e.checkId,e.baselineId].filter(r=>r!==void 0).length!==1||e.transactionId!==void 0&&!e1.test(e.transactionId)||e.checkId!==void 0&&!t1.test(e.checkId)||e.baselineId!==void 0&&!n1.test(e.baselineId)||t.status!=="resolved"||!Sv(t.planHash)||!gr.test(e.commandId)||n===void 0||!d1(n)||!bl(n.workingDirectory)||n.args.some(r=>r.includes("\0"))||!Number.isInteger(n.timeoutMs)||n.timeoutMs<=0||!Number.isInteger(e.limits.maxStreamBytes)||e.limits.maxStreamBytes<=0||e.limits.maxStreamBytes>Gr||!Number.isInteger(e.limits.maxTotalStreamBytes)||e.limits.maxTotalStreamBytes<e.limits.maxStreamBytes||!Number.isInteger(e.limits.terminationGraceMs)||e.limits.terminationGraceMs<0)throw new Error("Validation command or execution limits are invalid.");for(let[r,s]of Object.entries(n.environmentDelta))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r)||s.includes("\0"))throw new Error("Validation environment delta is invalid.");return n}async function c1(e,t){let n=await hl(e.workspaceRoot),r=e.checkId!==void 0?ml(n,".kwikqa","checks",e.checkId):e.baselineId!==void 0?ml(n,".kwikqa","baselines",e.baselineId):ml(n,".kwikqa","transactions",e.transactionId??"");if(!mf(n,r))throw new Error("Validation owner escapes workspace.");let s=await Bo(r);if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Validation owner directory is unsafe.");let o=e.validationRunId??`vld_${XN().replaceAll("-","").slice(0,24)}`;if(!/^vld_[a-f0-9]{24}$/.test(o))throw new Error("Validation run id is invalid.");let a=Ve(r,"validation");await ls(a,{mode:448}).catch(m=>{if(m.code!=="EEXIST")throw m});let d=await Bo(a);if(!d.isDirectory()||d.isSymbolicLink())throw new Error("Validation directory is unsafe.");let l=Ve(a,o);await ls(l,{mode:448}).catch(m=>{if(m.code!=="EEXIST")throw m});let c=await Bo(l);if(!c.isDirectory()||c.isSymbolicLink())throw new Error("Validation run directory is unsafe.");let u=Ve(l,"commands");await ls(u,{mode:448}).catch(m=>{if(m.code!=="EEXIST")throw m});let p=await Bo(u);if(!p.isDirectory()||p.isSymbolicLink())throw new Error("Validation commands directory is unsafe.");let f=Ve(u,t.commandId);return await ls(f,{mode:448}),await ls(Ve(f,"artifacts"),{mode:448}),{root:l,commandDirectory:f,runId:o}}var wl=class{constructor(t,n){this.cap=t;this.consumeGlobal=n}cap;consumeGlobal;#e=Vo("sha256");#t=[];#n=0;#r=0;add(t){this.#e.update(t),this.#n+=t.byteLength;let n=Math.max(0,this.cap-this.#r),r=this.consumeGlobal(Math.min(n,t.byteLength));r>0&&(this.#t.push(t.subarray(0,r)),this.#r+=r)}finish(){return{text:Buffer.concat(this.#t).toString("utf8"),observed:this.#n,hash:this.#e.digest("hex"),truncated:this.#r<this.#n}}};function xv(e,t){let n=Buffer.from(e,"utf8");if(n.byteLength<=t)return{text:e,truncated:!1};let r=t;for(;r>0&&(n[r]??0)>=128&&(n[r]??0)<192;)r-=1;return{text:n.subarray(0,r).toString("utf8"),truncated:!0}}function _v(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,r1.test(t)?"[REDACTED]":n]))}function u1(e){return e.kind==="timeout"||e.kind==="cancelled"?"incomplete":e.kind==="spawn-error"?"unavailable":e.kind==="signal"?"incomplete":e.exitCode===0?"passed":"failed"}function p1(e){return new Promise(t=>setTimeout(t,e))}async function f1(e,t,n,r){let s=await Iv(t,{withFileTypes:!0}),o=[],a=0;for(let d of s.sort((l,c)=>l.name.localeCompare(c.name))){if(!d.isFile()||d.isSymbolicLink())throw new Error("Validation artifact output contains an unsafe entry.");let l=Ve(t,d.name),c=await Bo(l),u=await hl(l);if(!c.isFile()||c.isSymbolicLink()||!mf(t,u)||c.mtimeMs+1<r)throw new Error("Validation artifact is stale or unsafe.");let p=await ZN(u);if(a+=p.byteLength,o.push({path:gl(e,u).split(yl).join("/"),sha256:Vo("sha256").update(p).digest("hex"),bytes:p.byteLength}),o.length>n.artifactPolicy.maxArtifacts||a>n.artifactPolicy.maxArtifactBytes)throw new Error("Validation artifact policy limit was exceeded.")}if(n.artifactPolicy.reportFile!==void 0&&!o.some(d=>d.path.split("/").at(-1)===n.artifactPolicy.reportFile))throw new Error("Required validation report artifact is missing.");return o}function m1(e){if(e.artifactPolicy.reportFile===void 0){if(e.kind.startsWith("maven-"))return"maven";if(e.kind.startsWith("gradle-"))return"gradle"}}function h1(e){return Kr(e.kind)||e.kind==="java-compile"}async function g1(e,t){let n=t.split("/");if(n[0]!==".kwikqa"||n.length<3||n.some(o=>!o1.test(o)))throw new Error("Validation output directory is outside .kwikqa.");let r=await ge(e,n.slice(0,-1)),s=Ve(r,n.at(-1)??"");return await ls(s,{mode:448}).catch(o=>{throw o.code==="EEXIST"?new Error("Validation output directory already exists; each command's output is used once."):o}),s}function y1(e,t,n){let r=e.artifactPolicy.outputDirectory;return t.cucumber===void 0?So():To({reportPath:Ve(n,r,hn),features:t.cucumber.features})}async function w1(e,t,n,r){let s=t.artifactPolicy.outputDirectory,o=t.resolutionEvidence.filter(u=>u.kind==="generated-init-script"),a=o.length===1?o[0]:void 0,d=[n,r].find(u=>t.args.includes(Ve(u,s,Wt)))??r,l=a===void 0?void 0:y1(t,a,d);if(a===void 0||l===void 0||a.path!==`${s}/${Wt}`||a.sha256!==Vo("sha256").update(l,"utf8").digest("hex"))throw new Error("Gradle init script changed after approval.");let c=new Set([Ve(n,s,Wt),Ve(r,s,Wt)]);if(!t.args.some(u=>c.has(u)))throw new Error("Gradle command does not name its approved init script.");await oe(Ve(e,Wt),l,{mode:384,replace:!1})}function Uo(e){return e instanceof Error?e.message:String(e)}async function b1(e,t,n){let r=Rv.O_NOFOLLOW??0;try{let s=(await Iv(e,{withFileTypes:!0})).sort((a,d)=>a.name.localeCompare(d.name));if(s.length>n.artifactPolicy.maxArtifacts)throw new Error("Validation output exceeds its artifact limit.");let o=0;for(let a of s){if(!a.isFile()||a.isSymbolicLink())throw new Error("Validation output contains an unsafe entry.");let d=await QN(Ve(e,a.name),Rv.O_RDONLY|r);try{let l=await d.stat();if(!l.isFile())throw new Error("Validation output contains an unsafe entry.");if(o+=l.size,o>n.artifactPolicy.maxArtifactBytes)throw new Error("Validation output exceeds its artifact limit.");await oe(Ve(t,a.name),await d.readFile(),{mode:384,replace:!1})}finally{await d.close()}}}finally{await ff(e,{recursive:!0,force:!0})}}async function Jr(e){let t=l1(e),n=await hl(e.workspaceRoot),r=await hl(t.workingDirectory);if(!mf(n,r))throw new Error("Validation working directory escapes workspace.");let s=e.repositoryRoot??n;for(let D of t.resolutionEvidence){if(D.sha256===void 0||D.kind==="generated-init-script")continue;if(D.kind==="build-executable"||D.kind==="jdk-launcher"){if((bl(D.path)?await ds(D.path):void 0)?.sha256!==D.sha256)throw new Error("Validation resolution evidence changed after approval.");continue}let ne=await G(s,ml(n,D.path),s1);if(ne.kind!=="read"||ne.sha256!==D.sha256)throw new Error("Validation resolution evidence changed after approval.")}let o=await c1(e,t),a=Kr(t.kind)?await g1(n,t.artifactPolicy.outputDirectory):void 0,d=a===void 0?void 0:m1(t),l=d===void 0?void 0:await vv(r,d),c=e.now??(()=>new Date),u=c(),p=e.limits.maxTotalStreamBytes,f=D=>{let ne=Math.min(D,p);return p-=ne,ne},m=new wl(e.limits.maxStreamBytes,f),h=new wl(e.limits.maxStreamBytes,f),g=Ve(o.commandDirectory,"artifacts"),y={...lv(e.inheritedEnvironment??process.env),...t.environmentDelta,...t.kind.startsWith("playwright-")?{PLAYWRIGHT_JSON_OUTPUT_NAME:Ve(g,t.artifactPolicy.reportFile??Co)}:{},...t.kind.startsWith("cypress-")||t.kind.startsWith("webdriverio-")?{KWIKQA_REPORT_DIR:g}:{}};if(h1(t))for(let D of i1)delete y[D];a!==void 0&&t.kind.startsWith("gradle-")&&await w1(a,t,e.workspaceRoot,n).catch(async D=>{throw await ff(a,{recursive:!0,force:!0}),D});let w;try{w=YN(t.executable,[...t.args],{cwd:t.workingDirectory,env:y,shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"]})}catch(D){throw a!==void 0&&await ff(a,{recursive:!0,force:!0}),D}w.stdout.on("data",D=>m.add(D)),w.stderr.on("data",D=>h.add(D));let b,v,R=D=>{b===void 0&&(b=D,w.kill(),v=setTimeout(()=>w.kill("SIGKILL"),e.limits.terminationGraceMs))},x=()=>R("cancelled");e.signal?.addEventListener("abort",x,{once:!0}),e.signal?.aborted&&R("cancelled");let T=setTimeout(()=>R("timeout"),t.timeoutMs),N=await new Promise(D=>{let ne=!1;w.once("error",Ae=>{ne||(ne=!0,D({kind:"spawn-error",...Ae.code===void 0?{}:{code:Ae.code}}))}),w.once("close",(Ae,vt)=>{ne||(ne=!0,D(b!==void 0?{kind:b}:vt!==null?{kind:"signal",signal:vt}:{kind:"exit",exitCode:Ae??1}))})});T!==void 0&&clearTimeout(T),v!==void 0&&clearTimeout(v),e.signal?.removeEventListener("abort",x),await p1(0);let U=e.sensitiveNames??a1,F=m.finish(),I=h.finish(),C=ke(F.text,"report","validation:stdout",U).value,A=xv(C,e.limits.maxStreamBytes),M=ke(I.text,"report","validation:stderr",U).value,$=xv(M,e.limits.maxStreamBytes),j=A.text,O=$.text,P=Ve(o.commandDirectory,"stdout.log"),E=Ve(o.commandDirectory,"stderr.log");await oe(P,j,{mode:384,replace:!1}),await oe(E,O,{mode:384,replace:!1}),a!==void 0&&l!==void 0&&await kv(r,a,l,t.artifactPolicy),a!==void 0&&await b1(a,g,t);let L=await f1(o.root,g,t,u.getTime()),B=c(),Z={schemaVersion:"1.0",validationRunId:o.runId,commandId:t.commandId,commandHash:V(t),planHash:e.plan.planHash,kind:t.kind,timing:t.timing,required:t.required,executable:t.executable,args:t.args,workingDirectory:t.workingDirectory,environmentDelta:_v(t.environmentDelta),timeoutMs:t.timeoutMs,purpose:t.purpose,logicalTestIds:t.logicalTestIds,projectIds:t.projectIds,startedAt:u.toISOString(),durationMs:Math.max(0,B.getTime()-u.getTime()),termination:N,stdout:{path:gl(o.root,P).split(yl).join("/"),observedBytes:F.observed,storedBytes:Buffer.byteLength(j),sha256:F.hash,storedSha256:Vo("sha256").update(j).digest("hex"),truncated:F.truncated||A.truncated,redacted:C!==F.text},stderr:{path:gl(o.root,E).split(yl).join("/"),observedBytes:I.observed,storedBytes:Buffer.byteLength(O),sha256:I.hash,storedSha256:Vo("sha256").update(O).digest("hex"),truncated:I.truncated||$.truncated,redacted:M!==I.text},artifacts:L,status:u1(N)},te={...Z,recordHash:V(Z)};return await oe(Ve(o.commandDirectory,"command.json"),`${le({commandId:t.commandId,planHash:e.plan.planHash,executable:t.executable,args:t.args,workingDirectory:t.workingDirectory,environmentDelta:_v(t.environmentDelta)})}
|
|
@@ -16,10 +16,10 @@ var RC=Object.create;var Ob=Object.defineProperty;var xC=Object.getOwnPropertyDe
|
|
|
16
16
|
`,{mode:384,replace:!1});let a={sequence:1,type:"prepared",at:e.now,phase:"prepared"},d={schemaVersion:Ho,transactionId:e.transactionId,manifestHash:o.manifestHash,phase:"prepared",revision:1,updatedAt:e.now,history:[a]},l={...d,stateHash:V(d)};return await oe(qn(n,"state.json"),`${le(l)}
|
|
17
17
|
`,{mode:384,replace:!1}),await Xb(e.workspaceRoot,t,e.transactionId),Ne(e.workspaceRoot,e.transactionId)}async function Ne(e,t){if(!Hn(t))throw new Error("Transaction id is invalid.");let n=await nl(e),r=await ge(n.root,[".kwikqa","transactions",t]),s=R1(Tv(await vl(qn(r,"manifest.json"),"utf8"))),o=x1(Tv(await vl(qn(r,"state.json"),"utf8")));if(s.transactionId!==t||o.transactionId!==t||o.manifestHash!==s.manifestHash)throw new Error("Transaction identity mismatch.");let a=new Map,d=new Map;for(let l of s.targets){if(!/^[a-f0-9]{32}$/.test(l.id)||l.preimageFile!==`preimages/${l.id}.bin`||l.resultFile!==`results/${l.id}.bin`)throw new Error("Transaction target record is malformed.");let c=await vl(qn(r,l.preimageFile)),u=await vl(qn(r,l.resultFile));if(c.byteLength!==l.preimageBytes||u.byteLength!==l.resultBytes||Av(c)!==l.sourceSha256||Av(u)!==l.resultSha256)throw new Error("Transaction target bytes are malformed.");a.set(l.path,c),d.set(l.path,u)}return{directory:r,manifest:s,state:o,preimages:a,results:d}}function I1(e,t){return t==="conflicted"?e!=="completed"&&e!=="rolled-back":{prepared:["applying","rolling-back"],applying:["applying","applied","rolling-back"],applied:["validating","rolling-back"],validating:["completed","rolling-back"],"rolling-back":["rolling-back","rolled-back","applying"],"rolled-back":[],completed:[],conflicted:[]}[e].includes(t)}async function kt(e){let t=await Ne(e.transaction.manifest.preview.workspace.workspaceRoot,e.transaction.manifest.transactionId);if(t.state.revision!==e.transaction.state.revision)throw new Error("Transaction state changed concurrently.");if(!I1(t.state.phase,e.phase))throw new Error("Transaction phase transition is not permitted.");let n={sequence:t.state.history.length+1,type:e.type,at:e.now,phase:e.phase,...e.path===void 0?{}:{path:e.path},...e.message===void 0?{}:{message:e.message},...e.planHash===void 0?{}:{planHash:e.planHash},...e.validationRunId===void 0?{}:{validationRunId:e.validationRunId},...e.validationManifestHash===void 0?{}:{validationManifestHash:e.validationManifestHash}},r={schemaVersion:Ho,transactionId:t.manifest.transactionId,manifestHash:t.manifest.manifestHash,phase:e.phase,revision:t.state.revision+1,updatedAt:e.now,history:[...t.state.history,n]},s={...r,stateHash:V(r)};return await oe(qn(t.directory,"state.json"),`${le(s)}
|
|
18
18
|
`,{mode:384,replace:!0}),Ne(t.manifest.preview.workspace.workspaceRoot,t.manifest.transactionId)}async function Yr(e){let t=await nl(e);return(await k1(t.transactionsDirectory,{withFileTypes:!0}).catch(r=>{if(r.code==="ENOENT")return[];throw r})).filter(r=>r.isDirectory()&&!r.isSymbolicLink()&&Hn(r.name)).map(r=>r.name).sort()}import{lstat as dD,readdir as lD}from"node:fs/promises";import{join as cD}from"node:path";var Jt={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO",vitest:"Vitest",jest:"Jest",mocha:"Mocha",pytest:"pytest",junit:"JUnit",testng:"TestNG",cucumber:"Cucumber",unknown:"Unidentified framework"},Gn={"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 Xr="1.10";var zo=["1.38.1","1.50.1","1.55.0","1.64.1"],bn=["playwright","cypress","webdriverio"],qo=["junit","testng","cucumber","pytest"],hf=["vitest","jest","mocha","unknown"];var gf={playwright:zo,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:[]};var yf={playwright:["playwright-json"],cypress:["kwikqa-json","mochawesome-json","junit-xml"],webdriverio:["kwikqa-json","wdio-json","junit-xml"],junit:["junit-xml"],testng:["testng-xml","junit-xml"],cucumber:["cucumber-json"],pytest:["junit-xml","ctrf-json","kwikqa-json"]};function Nt(e){return bn.includes(e)}function Kn(e){return qo.includes(e)}function Ev(e){return Nt(e)||Kn(e)}function Cv(e){return e.some(t=>t.error!==void 0&&t.definition!==void 0||Cv(t.steps))}function S1(e){return e.some(t=>t.attempts.some(n=>Cv(n.steps)))}function T1(e){return e.every(t=>/^[^/].*\.py$/.test(t.location.file))}function Yt(e){let{framework:t}=e;if(!Ev(t))return;let n=e.artifact.format;if(!(n===void 0||!yf[t].includes(n))){if(Nt(t))return t;if(!(t==="cucumber"&&!S1(e.logicalTests))&&!(t==="pytest"&&n==="ctrf-json"&&!T1(e.logicalTests)))return t}}function Nv(e){let t=e.artifact.format===void 0?void 0:Gn[e.artifact.format];return t===void 0?"this format":t.endsWith(" results")?t:`a ${t}`}function A1(e){return e.length<=2?e.join(" or "):`${e.slice(0,-1).join(", ")}, or ${e.at(-1)}`}function P1(e){let t=e.framework,n=e.artifact.format,r=A1(yf[t].map(s=>Gn[s]));return t==="cucumber"&&n==="cucumber-json"?"KwikQA repairs Cucumber-JVM runs, whose steps name their JVM step definitions. This run's steps name none, as Cucumber-JS reports do, so KwikQA only diagnoses it.":t==="pytest"&&n==="ctrf-json"?`KwikQA repairs pytest tests from a ${r}. This CTRF report's tests don't each name their Python file, so their test identities can't be matched, and KwikQA only diagnoses it.`:`KwikQA repairs ${Jt[t]} tests from a ${r}, whose test identities its validation can match; it only diagnoses a run read from ${Nv(e)}.`}function Wn(e){let{framework:t}=e;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(Kn(t))return P1(e);if(Nt(t)){let n=yf[t].map(r=>Gn[r]).join(", ");return`KwikQA repairs ${Jt[t]} tests from a ${n}, whose test identities its validation can match; it only diagnoses a run read from ${Nv(e)}.`}return`KwikQA diagnoses ${Jt[t]} runs but doesn't capture, repair, or validate them.`}import{join as j1}from"node:path";var cs=class extends Error{constructor(t){super(t),this.name="ReportValidationError"}};function Ze(e,t){throw new cs(`${e} must be ${t}`)}function me(e,t){return typeof e!="object"||e===null||Array.isArray(e)?Ze(t,"an object"):e}function Qr(e,t){return Array.isArray(e)?e:Ze(t,"an array")}function ie(e,t){return typeof e!="string"?Ze(t,"a string"):e}function Ie(e,t){return e===void 0?void 0:ie(e,t)}function Ot(e,t){return typeof e!="number"||!Number.isFinite(e)?Ze(t,"a finite number"):e}function Go(e,t){let n=Ot(e,t);return Number.isInteger(n)?n:Ze(t,"an integer")}function Le(e,t){let n=Go(e,t);return n<0?Ze(t,"a non-negative integer"):n}function wf(e,t){let n=ie(e,t);return!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(n)||new Date(n).toISOString()!==n?Ze(t,"an ISO 8601 UTC timestamp with millisecond precision"):n}function Ov(e,t){return typeof e!="boolean"?Ze(t,"a boolean"):e}function xe(e,t,n,r){let s=e[t];return s===void 0?void 0:n(s,`${r}.${t}`)}function ue(e,t,n){return Qr(e,t).map((r,s)=>n(r,`${t}[${s}]`))}function E1(e){return e.length===0?!0:e.length%4!==0?!1:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}function bf(e,t){let n=ie(e,t);return E1(n)?n:Ze(t,"canonical base64")}function Zr(e,t,n){let r=ie(e,t);return n.has(r)?r:Ze(t,`one of ${[...n].join(", ")}`)}function kl(e,t){return t===void 0?{}:{[e]:t}}import{readdir as C1,stat as N1}from"node:fs/promises";import{join as us}from"node:path";var Dv=/\.(?:java|kt|groovy|scala)$/,O1=/^at (?:([\w.$-]+)\/\/?)?([\w$]+(?:\.[\w$]+)*)\.([\w$<>-]+)\(([\w$-]+\.(?:java|kt|groovy|scala)):(\d+)\)\s*$/,$1=/^(?: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)\./,$v=["src/test/java","src/main/java","src/it/java","src/testFixtures/java","src/integrationTest/java","src/test/kotlin","src/main/kotlin","src/test/groovy","src/main/groovy","src/test/scala","src/main/scala"],Mv=["src/test/resources","src/main/resources"];function xl(e){return Dv.test(e)}function vf(e){return e.endsWith(".feature")}function Rt(e,t="java"){return`${(e.split("$")[0]??e).replaceAll(".","/")}.${t}`}function ps(e){let t=O1.exec(e.trim());if(t===null)return;let[,n,r,s,o,a]=t;if(r===void 0||s===void 0||o===void 0||a===void 0||n!==void 0&&n!=="app"||$1.test(`${r}.`))return;let d=o.replace(Dv,""),l=r.lastIndexOf(`.${d}`),c=l>=0?r.slice(0,l):r.split(".").slice(0,-1).join(".");return{file:`${c===""?"":`${c.replaceAll(".","/")}/`}${o}`,line:Number.parseInt(a,10),className:r,method:s}}async function Ko(e){try{return(await N1(e)).isFile()}catch{return!1}}async function Lv(e){return(await C1(e,{withFileTypes:!0}).catch(()=>[])).filter(n=>n.isDirectory()&&!n.name.startsWith(".")&&n.name!=="node_modules"&&n.name!=="src"&&n.name!=="target"&&n.name!=="build").map(n=>n.name).sort()}var M1=["pom.xml","build.gradle","build.gradle.kts"];async function Rl(e){let t=await Lv(e),n=[];for(let r of t)for(let s of await Lv(us(e,r))){let o=`${r}/${s}`;for(let a of M1)if(await Ko(us(e,o,a))){n.push(o);break}}return[...t,...n.sort()]}var ut=class{constructor(t){this.workspaceRoot=t}workspaceRoot;modules;found=new Map;every=new Map;find(t){let n=this.found.get(t);return n===void 0&&(n=this.lookup(t),this.found.set(t,n)),n}findAll(t){let n=this.every.get(t);return n===void 0&&(n=this.lookupAll(t),this.every.set(t,n)),n}async resolve(t){return xl(t)||vf(t)?await this.find(t)??t:t}async lookupAll(t){let n=[];await Ko(us(this.workspaceRoot,t))&&n.push(t);let r=vf(t)?Mv:$v;this.modules??=Rl(this.workspaceRoot);let s=[...r,...(await this.modules).flatMap(o=>r.map(a=>`${o}/${a}`))];for(let o of s){let a=`${o}/${t}`;await Ko(us(this.workspaceRoot,a))&&n.push(a)}return n}async lookup(t){if(await Ko(us(this.workspaceRoot,t)))return t;let n=vf(t)?Mv:$v;this.modules??=Rl(this.workspaceRoot);let r=[...n,...(await this.modules).flatMap(s=>n.map(o=>`${s}/${o}`))];for(let s of r){let o=`${s}/${t}`;if(await Ko(us(this.workspaceRoot,o)))return o}}};var L1=/(?:\(|\bat\s+|^)((?:webpack:\/\/[^\s()]*|file:\/\/[^\s()]*|(?:[A-Za-z]:)?[^():\s][^():]*?)):(\d+):(\d+)\)?\s*$/,D1=/^File "([^"]+\.py)", line (\d+)/,F1=/^((?:[A-Za-z]:)?[^\s:][^:]*\.py):(\d+):(?:\s|$)/;function jv(e){let t=e,n=/^webpack:\/\/[^/]*\/(.*)$/.exec(t);return n!==null&&(t=n[1]??""),t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7)).replaceAll("\\","/"),/^\/[A-Za-z]:\//.test(t)&&(t=t.slice(1))),t.replace(/^(?:\.\/)+/,"")}function Fv(e){return/^https?:\/\//.test(e)||e.includes("/__cypress/")||e.includes("node_modules/")||e.startsWith("node:")||e.startsWith("internal/")||e.includes("site-packages/")||/\/lib\/python\d/.test(e)||e.startsWith("<")}function _l(e){let t=[];for(let n of e.split(/\r?\n/)){let r=n.trim().replace(/^❯\s+/,""),s=ps(r);if(s!==void 0){t.push({file:s.file,line:s.line,column:1});continue}let o=D1.exec(r)??F1.exec(r),a=o===null?L1.exec(r):[o[0],o[1],o[2],"1"];if(a===null)continue;let[,d,l,c]=a;if(d===void 0||l===void 0||c===void 0||Fv(d))continue;let u=jv(d);u===""||Fv(u)||t.push({file:u,line:Number.parseInt(l,10),column:Number.parseInt(c,10)})}return t}function Ue(e,t){if(e===void 0)return;let n=_l(e);if(t!==void 0){let r=t.replaceAll("\\","/").replace(/^(?:\.\/)+/,""),s=n.find(o=>{let a=o.file.replaceAll("\\","/");return a===r||a.endsWith(`/${r}`)||r.endsWith(`/${a}`)});if(s!==void 0)return s}return n[0]}var Il="kwikqa-test-report",kf="1.0",B1="1",V1=new Set(["cypress","webdriverio","testng","pytest"]),U1=new Set(["passed","failed","timedOut","skipped","interrupted"]);function Bv(e,t){let n=t.replaceAll("\\","/");return/^(?:[A-Za-z]:\/|\/|file:\/\/)/.test(n)?t:j1(e,n.replace(/^(?:\.\/)+/,""))}function H1(e){let t=e.rootDir;return t===void 0?e:{...e,tests:e.tests.map(n=>({...n,file:Bv(t,n.file),attempts:n.attempts.map(r=>({...r,attachments:r.attachments.map(s=>s.path===void 0?s:{...s,path:Bv(t,s.path)})}))}))}}function Vv(e){return typeof e=="object"&&e!==null&&e.schema===Il}function z1(e,t){let n=me(e,t),r=xe(n,"line",Le,t),s=xe(n,"column",Le,t);return{file:ie(n.file,`${t}.file`),...r===void 0?{}:{line:r},...s===void 0?{}:{column:s}}}function Uv(e,t,n){let r=me(e,t),s=Ie(r.message,`${t}.message`),o=Ie(r.name,`${t}.name`),a=Ie(r.stack,`${t}.stack`),d=Ie(r.snippet,`${t}.snippet`),l=Ie(r.expected,`${t}.expected`),c=Ie(r.actual,`${t}.actual`),p=xe(r,"location",z1,t)??Ue(a,n);return{...s===void 0?{}:{message:s},...o===void 0?{}:{name:o},...a===void 0?{}:{stack:a},...d===void 0?{}:{snippet:d},...l===void 0&&c===void 0?{}:{value:`Expected: ${l??"(not recorded)"}
|
|
19
|
-
Received: ${c??"(not recorded)"}`},...p===void 0?{}:{location:p}}}function q1(e,t,n){let r=me(e,t),s=Ie(r.startTime,`${t}.startTime`);return{status:Zr(r.status,`${t}.status`,U1),retry:Le(r.retry,`${t}.retry`),...s===void 0?{}:{startTime:s},duration:Ot(r.duration??0,`${t}.duration`),errors:ue(r.errors??[],`${t}.errors`,(o,a)=>Uv(o,a,n)),attachments:ue(r.attachments??[],`${t}.attachments`,(o,a)=>{let d=me(o,a),l=Ie(d.path,`${a}.path`);return{name:ie(d.name,`${a}.name`),contentType:ie(d.contentType,`${a}.contentType`),...l===void 0?{}:{path:l}}}),stdout:ue(r.stdout??[],`${t}.stdout`,ie),stderr:ue(r.stderr??[],`${t}.stderr`,ie),steps:[]}}function G1(e,t){let n=me(e,t),r=ie(n.file,`${t}.file`),s=ue(n.titlePath,`${t}.titlePath`,ie);s.length===0&&Ze(`${t}.titlePath`,"a non-empty array");let o=xe(n,"line",Le,t),a=xe(n,"column",Le,t),d=xe(n,"timeout",Ot,t);return{file:r,titlePath:s,...o===void 0?{}:{line:o},...a===void 0?{}:{column:a},projectId:ie(n.project,`${t}.project`),...d===void 0?{}:{timeout:d},tags:ue(n.tags??[],`${t}.tags`,ie),attempts:ue(n.attempts,`${t}.attempts`,(l,c)=>q1(l,c,r))}}function Hv(e){let t=me(e,"$report");t.schema!==Il&&Ze("$report.schema",Il),String(t.schemaVersion??"").split(".")[0]!==kf.split(".")[0]&&Ze("$report.schemaVersion",`a ${kf.split(".")[0]}.x version`);let r=Zr(t.framework,"$report.framework",V1),s=Ie(t.frameworkVersion,"$report.frameworkVersion"),o=Ie(t.rootDir,"$report.rootDir"),a=Ie(t.configFile,"$report.configFile"),d=Ie(t.startTime,"$report.startTime"),l=xe(t,"duration",Ot,"$report"),c=ue(t.projects,"$report.projects",(u,p)=>{let f=me(u,p);return{id:ie(f.id,`${p}.id`),name:ie(f.name,`${p}.name`),retries:Le(f.retries??0,`${p}.retries`)}});return Qr(t.tests,"$report.tests"),{framework:r,format:"kwikqa-json",adapterVersion:B1,...s===void 0?{}:{frameworkVersion:s},...o===void 0?{}:{rootDir:o},...a===void 0?{}:{configFile:a},...d===void 0?{}:{startTime:d},...l===void 0?{}:{duration:l},projects:c,tests:ue(t.tests,"$report.tests",G1),errors:ue(t.errors??[],"$report.errors",(u,p)=>Uv(u,p,void 0)),interrupted:t.interrupted===!0,warnings:[]}}function zv(e){let t=e.map(H1),n=t[0];if(n===void 0)throw new Error("No report parts to merge.");let r=n.framework;if(t.some(u=>u.framework!==r))throw new Error("Report parts come from different frameworks.");let s=[...new Set(t.map(u=>u.frameworkVersion).filter(Boolean))],o=new Map;for(let u of t)for(let p of u.projects){let f=o.get(p.id);(f===void 0||p.retries>f.retries)&&o.set(p.id,p)}let a=t.map(u=>u.startTime).filter(u=>u!==void 0).sort(),d=[...new Set(t.map(u=>u.rootDir).filter(Boolean))],l=[...new Set(t.map(u=>u.configFile).filter(Boolean))],c=t.flatMap(u=>u.warnings);return s.length>1&&c.push(`mixed-framework-versions:${s.join(",")}`),d.length>1&&c.push("mixed-report-roots"),{framework:r,format:n.format,adapterVersion:n.adapterVersion,...s.length===1&&s[0]!==void 0?{frameworkVersion:s[0]}:{},...d.length===1&&d[0]!==void 0?{rootDir:d[0]}:{},...l.length===1&&l[0]!==void 0?{configFile:l[0]}:{},...a[0]===void 0?{}:{startTime:a[0]},duration:t.reduce((u,p)=>Math.max(u,p.duration??0),0),projects:[...o.values()],tests:t.flatMap(u=>u.tests),errors:t.flatMap(u=>u.errors),interrupted:t.some(u=>u.interrupted),warnings:c}}var K1="1";function Gv(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Array.isArray(t.suites)&&Array.isArray(t.specs)&&typeof t.capabilities=="object"&&t.capabilities!==null}function Kv(e){if(typeof e!="object"||e===null)return"";let t=e;if(typeof t.browserName=="string")return t.browserName;let n=Object.values(t);return n.length>0&&n.every(r=>typeof r=="object"&&r!==null)?"multiremote":""}function W1(e){switch(e){case"passed":return"passed";case"failed":return"failed";default:return"skipped"}}function qv(e,t,n){if(typeof e!="object"||e===null)return;let r=me(e,t),s=Ie(r.message,`${t}.message`),o=Ie(r.name,`${t}.name`),a=Ie(r.stack,`${t}.stack`),d=Ue(a,n);return{...s===void 0?{}:{message:s},...o===void 0?{}:{name:o},...a===void 0?{}:{stack:a},...d===void 0?{}:{location:d}}}function Wv(e){let t=me(e,"$report"),n=ue(t.specs,"$report.specs",ie),r=[];n.length!==1&&r.push("ambiguous-spec-file");let s=n[0]??"",o=Kv(t.capabilities),a=t.capabilities,d=typeof a.browserVersion=="string"?a.browserVersion:void 0,l=[];return Qr(t.suites,"$report.suites").forEach((c,u)=>{let p=`$report.suites[${u}]`,f=me(c,p),m=typeof f.name=="string"?f.name:"",h=new Map,g=[];ue(f.tests??[],`${p}.tests`,(y,w)=>{let b=me(y,w),v=ie(b.name,`${w}.name`),R=qv(b.error,`${w}.error`,s),x=h.get(v);x===void 0&&(x=[],h.set(v,x),g.push(v)),x.push({status:W1(b.state),retry:x.length,...typeof b.start=="string"?{startTime:b.start}:{},duration:typeof b.duration=="number"?b.duration:0,errors:R===void 0?[]:[R],attachments:[],stdout:[],stderr:[],steps:[]})}),ue(f.hooks??[],`${p}.hooks`,(y,w)=>{let b=me(y,w);if(b.state!=="failed")return;let v=qv(b.error,`${w}.error`,s),R=typeof b.title=="string"?b.title:"hook",x=typeof b.associatedTest=="string"&&b.associatedTest!==""?b.associatedTest:R,T={...v??{},message:`${R}: ${v?.message??"failed"}`},N=h.get(x),U=N?.at(-1);if(N!==void 0&&U!==void 0){U.status!=="failed"&&(N[N.length-1]={...U,status:"failed",errors:[T]});return}h.set(x,[{status:"failed",retry:0,...typeof b.start=="string"?{startTime:b.start}:{},duration:typeof b.duration=="number"?b.duration:0,errors:[T],attachments:[],stdout:[],stderr:[],steps:[]}]),g.push(x)});for(let y of g)l.push({file:s,titlePath:m===""?[y]:[m,y],projectId:o,attempts:h.get(y)??[]})}),{framework:"webdriverio",format:"wdio-json",adapterVersion:K1,...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:o,name:o,retries:0}],tests:l,errors:[],interrupted:!1,warnings:[...r,...d===void 0?[]:[`browser-version:${o}@${d}`]]}}import{isAbsolute as Tl,relative as J1,sep as Wo}from"node:path";var Sl="1970-01-01T00:00:00.000Z";function Jo(e,t){switch(e){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(n=>n!=="").join(" ")];case"webdriverio":return t.filter(n=>n!=="").slice(-2)}}function ms(e,t,n,r,s){return Y("tst",[t,n,r,...e==="playwright"?[]:[`framework:${e}`],...Jo(e,s)])}function Al(e,t){if(!Tl(t))return;let n=J1(e,t);if(!(Tl(n)||n===".."||n.startsWith(`..${Wo}`)))return n.split(Wo).join("/")}function Yo(e){let t=e.trim();return t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7)).replaceAll("\\","/"),/^\/[A-Za-z]:\//.test(t)&&(t=t.slice(1))),t.replaceAll("\\","/")}function Jv(e,t,n){let r=Yo(n),s=Wo==="\\"?r.replaceAll("/","\\"):r;if(Tl(s)||/^[A-Za-z]:\//.test(r))return Al(e,s)??r;let o=r.replace(/^(?:\.\/)+/,"");if(t===void 0)return o;let a=Al(e,t);return a===void 0||a===""?o:`${a}/${o}`}function xf(e,t,n,r,s){let o=e.location===void 0?void 0:{...e.location,file:Jv(r,s,e.location.file)};return{errorId:Y("err",[t,n]),source:n,...e.message===void 0?{}:{message:e.message},...e.name===void 0?{}:{name:e.name},...e.stack===void 0?{}:{stack:e.stack},...e.snippet===void 0?{}:{snippet:e.snippet},...e.value===void 0?{}:{value:e.value},...o===void 0?{}:{location:o}}}function Yv(e,t,n,r,s){return{title:e.title,duration:e.duration,...e.error===void 0?{}:{error:xf(e.error,t,`${n}.error`,r,s)},...e.definition===void 0?{}:{definition:e.definition},steps:e.steps.map((o,a)=>Yv(o,t,`${n}.steps[${a}]`,r,s))}}function Y1(e,t){let n=Yo(t),r=Wo==="\\"?n.replaceAll("/","\\"):n;return Tl(r)||e===void 0?r:`${e}${Wo}${r.replace(/^(?:\.[/\\])+/,"")}`}function X1(e){let t=e.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 Q1(e,t,n){return e.length===0?"zero-tests":n||e.some(r=>r.attempts.some(s=>s.status==="interrupted"))?"interrupted":t.length>0?"report-errors":"analysis-ready"}function Rf(e){if(e===void 0)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function Xv(e){let{report:t,reportHash:n,artifact:r,options:s}=e,o=s.workspaceRoot,a=new Set(e.warnings),d=t.projects.map(b=>{let v=b.testDir===void 0?void 0:Al(o,b.testDir);return{projectId:Y("prj",[`framework:${t.framework}`,b.id,b.name]),frameworkProjectId:b.id,name:b.name,repeatEach:1,retries:b.retries,...v===void 0?{}:{testDir:v}}}).sort((b,v)=>b.projectId.localeCompare(v.projectId)),l=new Map(d.map(b=>[b.frameworkProjectId,b.projectId])),c=new Set,u=[];t.tests.forEach((b,v)=>{let R=l.get(b.projectId);if(R===void 0)throw new Error(`Test ${v} references unknown project: ${b.projectId}`);let x=Jv(o,t.rootDir,b.file),T=ms(t.framework,o,R,x,b.titlePath);if(c.has(T)){a.add(`duplicate-test-identity:${x}`);return}c.add(T);let N=`$tests[${v}]`,U=b.attempts.map((I,C)=>{let A=Y("atm",[T,String(I.retry),"repeat:unknown",String(C)]),M=`${N}.attempts[${C}]`,$=I.errors.map((O,P)=>xf(O,A,`${M}.errors[${P}]`,o,t.rootDir)),j=$.find(O=>O.location!==void 0)?.location;return{attemptId:A,sourceIndex:C,retry:I.retry,repeat:{state:"unknown",reason:"not-serialized-by-report"},status:I.status,duration:I.duration,startTime:Rf(I.startTime)??Rf(t.startTime)??Sl,workerIndex:0,parallelIndex:0,errors:$,stdout:I.stdout.map(O=>({kind:"text",text:O})),stderr:I.stderr.map(O=>({kind:"text",text:O})),steps:I.steps.map((O,P)=>Yv(O,A,`${M}.steps[${P}]`,o,t.rootDir)),attachments:I.attachments.map((O,P)=>({attachmentId:Y("att",[A,String(P)]),name:O.name,contentType:O.contentType,sourceIndex:P,...O.path===void 0?{}:{path:Y1(t.rootDir,O.path)},...O.body===void 0?{}:{bodyBase64:O.body}})),annotations:[],...j===void 0?{}:{errorLocation:j}}}),F=X1(b.attempts);u.push({logicalTestId:T,projectId:R,title:b.titlePath.at(-1)??"",titlePath:b.titlePath,tags:[...b.tags??[]].sort(),location:{file:x,...b.line===void 0?{}:{line:b.line},...b.column===void 0?{}:{column:b.column}},...b.featureUri===void 0?{}:{featureUri:b.featureUri},timeout:b.timeout??0,expectedStatus:F==="skipped"?"skipped":"passed",status:F,annotations:[],attempts:U})}),u.sort((b,v)=>b.logicalTestId.localeCompare(v.logicalTestId));let p=t.errors.map((b,v)=>xf(b,r.artifactId,`$errors[${v}]`,o,t.rootDir)),f=u.reduce((b,v)=>b+v.attempts.reduce((R,x)=>R+x.attachments.length,0),0),m=u.flatMap(b=>b.attempts.map(v=>v.startTime)).filter(b=>b!==Sl).sort()[0],h=Rf(t.startTime)??m??Sl;h===Sl&&a.add("start-time-unavailable");let g={expected:0,unexpected:0,flaky:0,skipped:0};for(let b of u)g[b.status]+=1;let y=t.configFile===void 0?void 0:Al(o,Yo(t.configFile)),w=Y("run",[n,o,s.gitRoot??"",Xr,`${t.format}:${t.adapterVersion}`]);return{schemaVersion:Xr,runId:w,framework:t.framework,createdAt:h,workspace:{root:o,...s.gitRoot===void 0?{}:{gitRoot:s.gitRoot}},sourceHashes:{report:n},artifact:r,usability:Q1(u,p,t.interrupted),projects:d,...y===void 0?{}:{configFile:y},logicalTests:u,reportErrors:p,collections:{tests:u.length===0?"empty":"present",errors:p.length===0?"empty":"present",attachments:f===0?"empty":"present"},warnings:[...a].sort(),stats:{startTime:h,duration:t.duration??0,...g}}}var dR=Qd(aa(),1);import{lstat as L$,readFile as D$,realpath as rR}from"node:fs/promises";import{isAbsolute as aR,relative as F$,resolve as j$,sep as B$}from"node:path";import{access as A$}from"node:fs/promises";import{createRequire as P$}from"node:module";import{fileURLToPath as E$}from"node:url";var w$=Object.defineProperty,S=(e,t)=>w$(e,"name",{value:t,configurable:!0}),pY=class{static{S(this,"Edit")}startPosition;oldEndPosition;newEndPosition;startIndex;oldEndIndex;newEndIndex;constructor({startIndex:e,oldEndIndex:t,newEndIndex:n,startPosition:r,oldEndPosition:s,newEndPosition:o}){this.startIndex=e>>>0,this.oldEndIndex=t>>>0,this.newEndIndex=n>>>0,this.startPosition=r,this.oldEndPosition=s,this.newEndPosition=o}editPoint(e,t){let n=t,r={...e};if(t>=this.oldEndIndex){n=this.newEndIndex+(t-this.oldEndIndex);let s=e.row;r.row=this.newEndPosition.row+(e.row-this.oldEndPosition.row),r.column=s===this.oldEndPosition.row?this.newEndPosition.column+(e.column-this.oldEndPosition.column):e.column}else t>this.startIndex&&(n=this.newEndIndex,r.row=this.newEndPosition.row,r.column=this.newEndPosition.column);return{point:r,index:n}}editRange(e){let t={startIndex:e.startIndex,startPosition:{...e.startPosition},endIndex:e.endIndex,endPosition:{...e.endPosition}};return e.endIndex>=this.oldEndIndex?e.endIndex!==Number.MAX_SAFE_INTEGER&&(t.endIndex=this.newEndIndex+(e.endIndex-this.oldEndIndex),t.endPosition={row:this.newEndPosition.row+(e.endPosition.row-this.oldEndPosition.row),column:e.endPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.endPosition.column-this.oldEndPosition.column):e.endPosition.column},t.endIndex<this.newEndIndex&&(t.endIndex=Number.MAX_SAFE_INTEGER,t.endPosition={row:Number.MAX_SAFE_INTEGER,column:Number.MAX_SAFE_INTEGER})):e.endIndex>this.startIndex&&(t.endIndex=this.startIndex,t.endPosition={...this.startPosition}),e.startIndex>=this.oldEndIndex?(t.startIndex=this.newEndIndex+(e.startIndex-this.oldEndIndex),t.startPosition={row:this.newEndPosition.row+(e.startPosition.row-this.oldEndPosition.row),column:e.startPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.startPosition.column-this.oldEndPosition.column):e.startPosition.column},t.startIndex<this.newEndIndex&&(t.startIndex=Number.MAX_SAFE_INTEGER,t.startPosition={row:Number.MAX_SAFE_INTEGER,column:Number.MAX_SAFE_INTEGER})):e.startIndex>this.startIndex&&(t.startIndex=this.startIndex,t.startPosition={...this.startPosition}),t}},Tk=2,J=4,om=4*J,ft=5*J,xn=2*J,ca=2*J+2*xn,pt={row:0,column:0},kr=Symbol("INTERNAL");function ks(e){if(e!==kr)throw new Error("Illegal constructor")}S(ks,"assertInternal");function la(e){return!!e&&typeof e.row=="number"&&typeof e.column=="number"}S(la,"isPoint");function $k(e){k=e}S($k,"setModule");var k;function Rs(e){try{return new FinalizationRegistry(e)}catch(t){console.error("Unsupported FinalizationRegistry:",t);return}}S(Rs,"newFinalizer");var Ak=Rs(e=>{k._ts_lookahead_iterator_delete(e)}),b$=class{static{S(this,"LookaheadIterator")}0=0;language;positioned=!1;constructor(e,t,n){ks(e),this[0]=t,this.language=n,Ak?.register(this,t,this)}get currentTypeId(){return this.positioned?k._ts_lookahead_iterator_current_symbol(this[0]):null}get currentType(){let e=this.currentTypeId;return e===null?null:this.language.types[e]??k.UTF8ToString(k._ts_language_symbol_name(this.language[0],e))}delete(){Ak?.unregister(this),k._ts_lookahead_iterator_delete(this[0]),this[0]=0}reset(e,t){return k._ts_lookahead_iterator_reset(this[0],e[0],t)?(this.language=e,this.positioned=!1,!0):!1}resetState(e){return k._ts_lookahead_iterator_reset_state(this[0],e)?(this.positioned=!1,!0):!1}[Symbol.iterator](){return{next:S(()=>{this.positioned=!!k._ts_lookahead_iterator_next(this[0]);let e=this.currentType;return e===null?{done:!0,value:""}:{done:!1,value:e}},"next")}}};function um(e,t,n,r){let s=n-t,o=e.textCallback(t,r);if(o){for(t+=o.length;t<n;){let a=e.textCallback(t,r);if(a&&a.length>0)t+=a.length,o+=a;else break}t>n&&(o=o.slice(0,s))}return o??""}S(um,"getText");var Pk=Rs(e=>{k._ts_tree_delete(e)}),v$=class lm{static{S(this,"Tree")}0=0;textCallback;language;constructor(t,n,r,s){ks(t),this[0]=n,this.language=r,this.textCallback=s,Pk?.register(this,n,this)}copy(){let t=k._ts_tree_copy(this[0]);return new lm(kr,t,this.language,this.textCallback)}delete(){Pk?.unregister(this),k._ts_tree_delete(this[0]),this[0]=0}get rootNode(){return k._ts_tree_root_node_wasm(this[0]),Pe(this)}rootNodeWithOffset(t,n){let r=W+ft;return k.setValue(r,t,"i32"),$t(r+J,n),k._ts_tree_root_node_with_offset_wasm(this[0]),Pe(this)}edit(t){Dk(t),k._ts_tree_edit_wasm(this[0])}walk(){return this.rootNode.walk()}getChangedRanges(t){if(!(t instanceof lm))throw new TypeError("Argument must be a Tree");k._ts_tree_get_changed_ranges_wasm(this[0],t[0]);let n=k.getValue(W,"i32"),r=k.getValue(W+J,"i32"),s=new Array(n);if(n>0){let o=r;for(let a=0;a<n;a++)s[a]=jl(o),o+=ca;k._free(r)}return s}getIncludedRanges(){k._ts_tree_included_ranges_wasm(this[0]);let t=k.getValue(W,"i32"),n=k.getValue(W+J,"i32"),r=new Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=jl(s),s+=ca;k._free(n)}return r}},Ek=Rs(e=>{k._ts_tree_cursor_delete_wasm(e)}),k$=class Mk{static{S(this,"TreeCursor")}0=0;1=0;2=0;3=0;tree;constructor(t,n){ks(t),this.tree=n,xt(this),Ek?.register(this,this.tree[0],this)}copy(){let t=new Mk(kr,this.tree);return k._ts_tree_cursor_copy_wasm(this.tree[0]),xt(t),t}delete(){Ek?.unregister(this),_e(this),k._ts_tree_cursor_delete_wasm(this.tree[0]),this[0]=this[1]=this[2]=0}get currentNode(){return _e(this),k._ts_tree_cursor_current_node_wasm(this.tree[0]),Pe(this.tree)}get currentFieldId(){return _e(this),k._ts_tree_cursor_current_field_id_wasm(this.tree[0])}get currentFieldName(){return this.tree.language.fields[this.currentFieldId]}get currentDepth(){return _e(this),k._ts_tree_cursor_current_depth_wasm(this.tree[0])}get currentDescendantIndex(){return _e(this),k._ts_tree_cursor_current_descendant_index_wasm(this.tree[0])}get nodeType(){return this.tree.language.types[this.nodeTypeId]||"ERROR"}get nodeTypeId(){return _e(this),k._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeStateId(){return _e(this),k._ts_tree_cursor_current_node_state_id_wasm(this.tree[0])}get nodeId(){return _e(this),k._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return _e(this),k._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])===1}get nodeIsMissing(){return _e(this),k._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])===1}get nodeText(){_e(this);let t=k._ts_tree_cursor_start_index_wasm(this.tree[0]),n=k._ts_tree_cursor_end_index_wasm(this.tree[0]);k._ts_tree_cursor_start_position_wasm(this.tree[0]);let r=ri(W);return um(this.tree,t,n,r)}get startPosition(){return _e(this),k._ts_tree_cursor_start_position_wasm(this.tree[0]),ri(W)}get endPosition(){return _e(this),k._ts_tree_cursor_end_position_wasm(this.tree[0]),ri(W)}get startIndex(){return _e(this),k._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return _e(this),k._ts_tree_cursor_end_index_wasm(this.tree[0])}gotoFirstChild(){_e(this);let t=k._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return xt(this),t===1}gotoLastChild(){_e(this);let t=k._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);return xt(this),t===1}gotoParent(){_e(this);let t=k._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return xt(this),t===1}gotoNextSibling(){_e(this);let t=k._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return xt(this),t===1}gotoPreviousSibling(){_e(this);let t=k._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);return xt(this),t===1}gotoDescendant(t){_e(this),k._ts_tree_cursor_goto_descendant_wasm(this.tree[0],t),xt(this)}gotoFirstChildForIndex(t){_e(this),k.setValue(W+om,t,"i32");let n=k._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);return xt(this),n===1}gotoFirstChildForPosition(t){_e(this),$t(W+om,t);let n=k._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);return xt(this),n===1}reset(t){se(t),_e(this,W+ft),k._ts_tree_cursor_reset_wasm(this.tree[0]),xt(this)}resetTo(t){_e(this,W),_e(t,W+om),k._ts_tree_cursor_reset_to_wasm(this.tree[0],t.tree[0]),xt(this)}},R$=class{static{S(this,"Node")}0=0;_children;_namedChildren;constructor(e,{id:t,tree:n,startIndex:r,startPosition:s,other:o}){ks(e),this[0]=o,this.id=t,this.tree=n,this.startIndex=r,this.startPosition=s}id;startIndex;startPosition;tree;get typeId(){return se(this),k._ts_node_symbol_wasm(this.tree[0])}get grammarId(){return se(this),k._ts_node_grammar_symbol_wasm(this.tree[0])}get type(){return this.tree.language.types[this.typeId]||"ERROR"}get grammarType(){return this.tree.language.types[this.grammarId]||"ERROR"}get isNamed(){return se(this),k._ts_node_is_named_wasm(this.tree[0])===1}get isExtra(){return se(this),k._ts_node_is_extra_wasm(this.tree[0])===1}get isError(){return se(this),k._ts_node_is_error_wasm(this.tree[0])===1}get isMissing(){return se(this),k._ts_node_is_missing_wasm(this.tree[0])===1}get hasChanges(){return se(this),k._ts_node_has_changes_wasm(this.tree[0])===1}get hasError(){return se(this),k._ts_node_has_error_wasm(this.tree[0])===1}get endIndex(){return se(this),k._ts_node_end_index_wasm(this.tree[0])}get endPosition(){return se(this),k._ts_node_end_point_wasm(this.tree[0]),ri(W)}get text(){return um(this.tree,this.startIndex,this.endIndex,this.startPosition)}get parseState(){return se(this),k._ts_node_parse_state_wasm(this.tree[0])}get nextParseState(){return se(this),k._ts_node_next_parse_state_wasm(this.tree[0])}equals(e){return this.tree===e.tree&&this.id===e.id}child(e){return se(this),k._ts_node_child_wasm(this.tree[0],e),Pe(this.tree)}namedChild(e){return se(this),k._ts_node_named_child_wasm(this.tree[0],e),Pe(this.tree)}childForFieldId(e){return se(this),k._ts_node_child_by_field_id_wasm(this.tree[0],e),Pe(this.tree)}childForFieldName(e){let t=this.tree.language.fields.indexOf(e);return t!==-1?this.childForFieldId(t):null}fieldNameForChild(e){se(this);let t=k._ts_node_field_name_for_child_wasm(this.tree[0],e);return t?k.AsciiToString(t):null}fieldNameForNamedChild(e){se(this);let t=k._ts_node_field_name_for_named_child_wasm(this.tree[0],e);return t?k.AsciiToString(t):null}childrenForFieldName(e){let t=this.tree.language.fields.indexOf(e);return t!==-1&&t!==0?this.childrenForFieldId(t):[]}childrenForFieldId(e){se(this),k._ts_node_children_by_field_id_wasm(this.tree[0],e);let t=k.getValue(W,"i32"),n=k.getValue(W+J,"i32"),r=new Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=Pe(this.tree,s),s+=ft;k._free(n)}return r}firstChildForIndex(e){se(this);let t=W+ft;return k.setValue(t,e,"i32"),k._ts_node_first_child_for_byte_wasm(this.tree[0]),Pe(this.tree)}firstNamedChildForIndex(e){se(this);let t=W+ft;return k.setValue(t,e,"i32"),k._ts_node_first_named_child_for_byte_wasm(this.tree[0]),Pe(this.tree)}get childCount(){return se(this),k._ts_node_child_count_wasm(this.tree[0])}get namedChildCount(){return se(this),k._ts_node_named_child_count_wasm(this.tree[0])}get firstChild(){return this.child(0)}get firstNamedChild(){return this.namedChild(0)}get lastChild(){return this.child(this.childCount-1)}get lastNamedChild(){return this.namedChild(this.namedChildCount-1)}get children(){if(!this._children){se(this),k._ts_node_children_wasm(this.tree[0]);let e=k.getValue(W,"i32"),t=k.getValue(W+J,"i32");if(this._children=new Array(e),e>0){let n=t;for(let r=0;r<e;r++)this._children[r]=Pe(this.tree,n),n+=ft;k._free(t)}}return this._children}get namedChildren(){if(!this._namedChildren){se(this),k._ts_node_named_children_wasm(this.tree[0]);let e=k.getValue(W,"i32"),t=k.getValue(W+J,"i32");if(this._namedChildren=new Array(e),e>0){let n=t;for(let r=0;r<e;r++)this._namedChildren[r]=Pe(this.tree,n),n+=ft;k._free(t)}}return this._namedChildren}descendantsOfType(e,t=pt,n=pt){Array.isArray(e)||(e=[e]);let r=[],s=this.tree.language.types;for(let c of e)c=="ERROR"&&r.push(65535);for(let c=0,u=s.length;c<u;c++)e.includes(s[c])&&r.push(c);let o=k._malloc(J*r.length);for(let c=0,u=r.length;c<u;c++)k.setValue(o+c*J,r[c],"i32");se(this),k._ts_node_descendants_of_type_wasm(this.tree[0],o,r.length,t.row,t.column,n.row,n.column);let a=k.getValue(W,"i32"),d=k.getValue(W+J,"i32"),l=new Array(a);if(a>0){let c=d;for(let u=0;u<a;u++)l[u]=Pe(this.tree,c),c+=ft}return k._free(d),k._free(o),l}get nextSibling(){return se(this),k._ts_node_next_sibling_wasm(this.tree[0]),Pe(this.tree)}get previousSibling(){return se(this),k._ts_node_prev_sibling_wasm(this.tree[0]),Pe(this.tree)}get nextNamedSibling(){return se(this),k._ts_node_next_named_sibling_wasm(this.tree[0]),Pe(this.tree)}get previousNamedSibling(){return se(this),k._ts_node_prev_named_sibling_wasm(this.tree[0]),Pe(this.tree)}get descendantCount(){return se(this),k._ts_node_descendant_count_wasm(this.tree[0])}get parent(){return se(this),k._ts_node_parent_wasm(this.tree[0]),Pe(this.tree)}childWithDescendant(e){return se(this),se(e,1),k._ts_node_child_with_descendant_wasm(this.tree[0]),Pe(this.tree)}descendantForIndex(e,t=e){if(typeof e!="number"||typeof t!="number")throw new Error("Arguments must be numbers");se(this);let n=W+ft;return k.setValue(n,e,"i32"),k.setValue(n+J,t,"i32"),k._ts_node_descendant_for_index_wasm(this.tree[0]),Pe(this.tree)}namedDescendantForIndex(e,t=e){if(typeof e!="number"||typeof t!="number")throw new Error("Arguments must be numbers");se(this);let n=W+ft;return k.setValue(n,e,"i32"),k.setValue(n+J,t,"i32"),k._ts_node_named_descendant_for_index_wasm(this.tree[0]),Pe(this.tree)}descendantForPosition(e,t=e){if(!la(e)||!la(t))throw new Error("Arguments must be {row, column} objects");se(this);let n=W+ft;return $t(n,e),$t(n+xn,t),k._ts_node_descendant_for_position_wasm(this.tree[0]),Pe(this.tree)}namedDescendantForPosition(e,t=e){if(!la(e)||!la(t))throw new Error("Arguments must be {row, column} objects");se(this);let n=W+ft;return $t(n,e),$t(n+xn,t),k._ts_node_named_descendant_for_position_wasm(this.tree[0]),Pe(this.tree)}walk(){return se(this),k._ts_tree_cursor_new_wasm(this.tree[0]),new k$(kr,this.tree)}edit(e){if(this.startIndex>=e.oldEndIndex){this.startIndex=e.newEndIndex+(this.startIndex-e.oldEndIndex);let t,n;this.startPosition.row>e.oldEndPosition.row?(t=this.startPosition.row-e.oldEndPosition.row,n=this.startPosition.column):(t=0,n=this.startPosition.column,this.startPosition.column>=e.oldEndPosition.column&&(n=this.startPosition.column-e.oldEndPosition.column)),t>0?(this.startPosition.row+=t,this.startPosition.column=n):this.startPosition.column+=n}else this.startIndex>e.startIndex&&(this.startIndex=e.newEndIndex,this.startPosition.row=e.newEndPosition.row,this.startPosition.column=e.newEndPosition.column)}toString(){se(this);let e=k._ts_node_to_string_wasm(this.tree[0]),t=k.AsciiToString(e);return k._free(e),t}};function cm(e,t,n,r,s){for(let o=0,a=s.length;o<a;o++){let d=k.getValue(n,"i32");n+=J;let l=Pe(t,n);n+=ft,s[o]={patternIndex:r,name:e.captureNames[d],node:l}}return n}S(cm,"unmarshalCaptures");function se(e,t=0){let n=W+t*ft;k.setValue(n,e.id,"i32"),n+=J,k.setValue(n,e.startIndex,"i32"),n+=J,k.setValue(n,e.startPosition.row,"i32"),n+=J,k.setValue(n,e.startPosition.column,"i32"),n+=J,k.setValue(n,e[0],"i32")}S(se,"marshalNode");function Pe(e,t=W){let n=k.getValue(t,"i32");if(t+=J,n===0)return null;let r=k.getValue(t,"i32");t+=J;let s=k.getValue(t,"i32");t+=J;let o=k.getValue(t,"i32");t+=J;let a=k.getValue(t,"i32");return new R$(kr,{id:n,tree:e,startIndex:r,startPosition:{row:s,column:o},other:a})}S(Pe,"unmarshalNode");function _e(e,t=W){k.setValue(t+0*J,e[0],"i32"),k.setValue(t+1*J,e[1],"i32"),k.setValue(t+2*J,e[2],"i32"),k.setValue(t+3*J,e[3],"i32")}S(_e,"marshalTreeCursor");function xt(e){e[0]=k.getValue(W+0*J,"i32"),e[1]=k.getValue(W+1*J,"i32"),e[2]=k.getValue(W+2*J,"i32"),e[3]=k.getValue(W+3*J,"i32")}S(xt,"unmarshalTreeCursor");function $t(e,t){k.setValue(e,t.row,"i32"),k.setValue(e+J,t.column,"i32")}S($t,"marshalPoint");function ri(e){return{row:k.getValue(e,"i32")>>>0,column:k.getValue(e+J,"i32")>>>0}}S(ri,"unmarshalPoint");function Lk(e,t){$t(e,t.startPosition),e+=xn,$t(e,t.endPosition),e+=xn,k.setValue(e,t.startIndex,"i32"),e+=J,k.setValue(e,t.endIndex,"i32"),e+=J}S(Lk,"marshalRange");function jl(e){let t={};return t.startPosition=ri(e),e+=xn,t.endPosition=ri(e),e+=xn,t.startIndex=k.getValue(e,"i32")>>>0,e+=J,t.endIndex=k.getValue(e,"i32")>>>0,t}S(jl,"unmarshalRange");function Dk(e,t=W){$t(t,e.startPosition),t+=xn,$t(t,e.oldEndPosition),t+=xn,$t(t,e.newEndPosition),t+=xn,k.setValue(t,e.startIndex,"i32"),t+=J,k.setValue(t,e.oldEndIndex,"i32"),t+=J,k.setValue(t,e.newEndIndex,"i32"),t+=J}S(Dk,"marshalEdit");function Fk(e){let t=k.getValue(e,"i32"),n=k.getValue(e+=J,"i32"),r=k.getValue(e+=J,"i32");return{major_version:t,minor_version:n,patch_version:r}}S(Fk,"unmarshalLanguageMetadata");var x$=/^tree_sitter_\w+$/,pm=class Fl{static{S(this,"Language")}0=0;types;fields;constructor(t,n){ks(t),this[0]=n,this.types=new Array(k._ts_language_symbol_count(this[0]));for(let r=0,s=this.types.length;r<s;r++)k._ts_language_symbol_type(this[0],r)<2&&(this.types[r]=k.UTF8ToString(k._ts_language_symbol_name(this[0],r)));this.fields=new Array(k._ts_language_field_count(this[0])+1);for(let r=0,s=this.fields.length;r<s;r++){let o=k._ts_language_field_name_for_id(this[0],r);o!==0?this.fields[r]=k.UTF8ToString(o):this.fields[r]=null}}get name(){let t=k._ts_language_name(this[0]);return t===0?null:k.UTF8ToString(t)}get abiVersion(){return k._ts_language_abi_version(this[0])}get metadata(){return k._ts_language_metadata_wasm(this[0]),k.getValue(W,"i32")===0?null:Fk(W+J)}get fieldCount(){return this.fields.length-1}get stateCount(){return k._ts_language_state_count(this[0])}fieldIdForName(t){let n=this.fields.indexOf(t);return n!==-1?n:null}fieldNameForId(t){return this.fields[t]??null}idForNodeType(t,n){let r=k.lengthBytesUTF8(t),s=k._malloc(r+1);k.stringToUTF8(t,s,r+1);let o=k._ts_language_symbol_for_name(this[0],s,r,n?1:0);return k._free(s),o||null}get nodeTypeCount(){return k._ts_language_symbol_count(this[0])}nodeTypeForId(t){let n=k._ts_language_symbol_name(this[0],t);return n?k.UTF8ToString(n):null}nodeTypeIsNamed(t){return!!k._ts_language_type_is_named_wasm(this[0],t)}nodeTypeIsVisible(t){return!!k._ts_language_type_is_visible_wasm(this[0],t)}get supertypes(){k._ts_language_supertypes_wasm(this[0]);let t=k.getValue(W,"i32"),n=k.getValue(W+J,"i32"),r=new Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=k.getValue(s,"i16"),s+=Tk}return r}subtypes(t){k._ts_language_subtypes_wasm(this[0],t);let n=k.getValue(W,"i32"),r=k.getValue(W+J,"i32"),s=new Array(n);if(n>0){let o=r;for(let a=0;a<n;a++)s[a]=k.getValue(o,"i16"),o+=Tk}return s}nextState(t,n){return k._ts_language_next_state(this[0],t,n)}lookaheadIterator(t){let n=k._ts_lookahead_iterator_new(this[0],t);return n?new b$(kr,n,this):null}static async load(t){let n;if(t instanceof Uint8Array)n=t;else if(globalThis.process?.versions.node)n=await(await import("fs/promises")).readFile(t);else{let s=await fetch(t);if(!s.ok){let a=await s.text();throw new Error(`Language.load failed with status ${s.status}.
|
|
19
|
+
Received: ${c??"(not recorded)"}`},...p===void 0?{}:{location:p}}}function q1(e,t,n){let r=me(e,t),s=Ie(r.startTime,`${t}.startTime`);return{status:Zr(r.status,`${t}.status`,U1),retry:Le(r.retry,`${t}.retry`),...s===void 0?{}:{startTime:s},duration:Ot(r.duration??0,`${t}.duration`),errors:ue(r.errors??[],`${t}.errors`,(o,a)=>Uv(o,a,n)),attachments:ue(r.attachments??[],`${t}.attachments`,(o,a)=>{let d=me(o,a),l=Ie(d.path,`${a}.path`);return{name:ie(d.name,`${a}.name`),contentType:ie(d.contentType,`${a}.contentType`),...l===void 0?{}:{path:l}}}),stdout:ue(r.stdout??[],`${t}.stdout`,ie),stderr:ue(r.stderr??[],`${t}.stderr`,ie),steps:[]}}function G1(e,t){let n=me(e,t),r=ie(n.file,`${t}.file`),s=ue(n.titlePath,`${t}.titlePath`,ie);s.length===0&&Ze(`${t}.titlePath`,"a non-empty array");let o=xe(n,"line",Le,t),a=xe(n,"column",Le,t),d=xe(n,"timeout",Ot,t);return{file:r,titlePath:s,...o===void 0?{}:{line:o},...a===void 0?{}:{column:a},projectId:ie(n.project,`${t}.project`),...d===void 0?{}:{timeout:d},tags:ue(n.tags??[],`${t}.tags`,ie),attempts:ue(n.attempts,`${t}.attempts`,(l,c)=>q1(l,c,r))}}function Hv(e){let t=me(e,"$report");t.schema!==Il&&Ze("$report.schema",Il),String(t.schemaVersion??"").split(".")[0]!==kf.split(".")[0]&&Ze("$report.schemaVersion",`a ${kf.split(".")[0]}.x version`);let r=Zr(t.framework,"$report.framework",V1),s=Ie(t.frameworkVersion,"$report.frameworkVersion"),o=Ie(t.rootDir,"$report.rootDir"),a=Ie(t.configFile,"$report.configFile"),d=Ie(t.startTime,"$report.startTime"),l=xe(t,"duration",Ot,"$report"),c=ue(t.projects,"$report.projects",(u,p)=>{let f=me(u,p);return{id:ie(f.id,`${p}.id`),name:ie(f.name,`${p}.name`),retries:Le(f.retries??0,`${p}.retries`)}});return Qr(t.tests,"$report.tests"),{framework:r,format:"kwikqa-json",adapterVersion:B1,...s===void 0?{}:{frameworkVersion:s},...o===void 0?{}:{rootDir:o},...a===void 0?{}:{configFile:a},...d===void 0?{}:{startTime:d},...l===void 0?{}:{duration:l},projects:c,tests:ue(t.tests,"$report.tests",G1),errors:ue(t.errors??[],"$report.errors",(u,p)=>Uv(u,p,void 0)),interrupted:t.interrupted===!0,warnings:[]}}function zv(e){let t=e.map(H1),n=t[0];if(n===void 0)throw new Error("No report parts to merge.");let r=n.framework;if(t.some(u=>u.framework!==r))throw new Error("Report parts come from different frameworks.");let s=[...new Set(t.map(u=>u.frameworkVersion).filter(Boolean))],o=new Map;for(let u of t)for(let p of u.projects){let f=o.get(p.id);(f===void 0||p.retries>f.retries)&&o.set(p.id,p)}let a=t.map(u=>u.startTime).filter(u=>u!==void 0).sort(),d=[...new Set(t.map(u=>u.rootDir).filter(Boolean))],l=[...new Set(t.map(u=>u.configFile).filter(Boolean))],c=t.flatMap(u=>u.warnings);return s.length>1&&c.push(`mixed-framework-versions:${s.join(",")}`),d.length>1&&c.push("mixed-report-roots"),{framework:r,format:n.format,adapterVersion:n.adapterVersion,...s.length===1&&s[0]!==void 0?{frameworkVersion:s[0]}:{},...d.length===1&&d[0]!==void 0?{rootDir:d[0]}:{},...l.length===1&&l[0]!==void 0?{configFile:l[0]}:{},...a[0]===void 0?{}:{startTime:a[0]},duration:t.reduce((u,p)=>Math.max(u,p.duration??0),0),projects:[...o.values()],tests:t.flatMap(u=>u.tests),errors:t.flatMap(u=>u.errors),interrupted:t.some(u=>u.interrupted),warnings:c}}var K1="1";function Gv(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Array.isArray(t.suites)&&Array.isArray(t.specs)&&typeof t.capabilities=="object"&&t.capabilities!==null}function Kv(e){if(typeof e!="object"||e===null)return"";let t=e;if(typeof t.browserName=="string")return t.browserName;let n=Object.values(t);return n.length>0&&n.every(r=>typeof r=="object"&&r!==null)?"multiremote":""}function W1(e){switch(e){case"passed":return"passed";case"failed":return"failed";default:return"skipped"}}function qv(e,t,n){if(typeof e!="object"||e===null)return;let r=me(e,t),s=Ie(r.message,`${t}.message`),o=Ie(r.name,`${t}.name`),a=Ie(r.stack,`${t}.stack`),d=Ue(a,n);return{...s===void 0?{}:{message:s},...o===void 0?{}:{name:o},...a===void 0?{}:{stack:a},...d===void 0?{}:{location:d}}}function Wv(e){let t=me(e,"$report"),n=ue(t.specs,"$report.specs",ie),r=[];n.length!==1&&r.push("ambiguous-spec-file");let s=n[0]??"",o=Kv(t.capabilities),a=t.capabilities,d=typeof a.browserVersion=="string"?a.browserVersion:void 0,l=[];return Qr(t.suites,"$report.suites").forEach((c,u)=>{let p=`$report.suites[${u}]`,f=me(c,p),m=typeof f.name=="string"?f.name:"",h=new Map,g=[];ue(f.tests??[],`${p}.tests`,(y,w)=>{let b=me(y,w),v=ie(b.name,`${w}.name`),R=qv(b.error,`${w}.error`,s),x=h.get(v);x===void 0&&(x=[],h.set(v,x),g.push(v)),x.push({status:W1(b.state),retry:x.length,...typeof b.start=="string"?{startTime:b.start}:{},duration:typeof b.duration=="number"?b.duration:0,errors:R===void 0?[]:[R],attachments:[],stdout:[],stderr:[],steps:[]})}),ue(f.hooks??[],`${p}.hooks`,(y,w)=>{let b=me(y,w);if(b.state!=="failed")return;let v=qv(b.error,`${w}.error`,s),R=typeof b.title=="string"?b.title:"hook",x=typeof b.associatedTest=="string"&&b.associatedTest!==""?b.associatedTest:R,T={...v??{},message:`${R}: ${v?.message??"failed"}`},N=h.get(x),U=N?.at(-1);if(N!==void 0&&U!==void 0){U.status!=="failed"&&(N[N.length-1]={...U,status:"failed",errors:[T]});return}h.set(x,[{status:"failed",retry:0,...typeof b.start=="string"?{startTime:b.start}:{},duration:typeof b.duration=="number"?b.duration:0,errors:[T],attachments:[],stdout:[],stderr:[],steps:[]}]),g.push(x)});for(let y of g)l.push({file:s,titlePath:m===""?[y]:[m,y],projectId:o,attempts:h.get(y)??[]})}),{framework:"webdriverio",format:"wdio-json",adapterVersion:K1,...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:o,name:o,retries:0}],tests:l,errors:[],interrupted:!1,warnings:[...r,...d===void 0?[]:[`browser-version:${o}@${d}`]]}}import{isAbsolute as Tl,relative as J1,sep as Wo}from"node:path";var Sl="1970-01-01T00:00:00.000Z";function Jo(e,t){switch(e){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(n=>n!=="").join(" ")];case"webdriverio":return t.filter(n=>n!=="").slice(-2)}}function ms(e,t,n,r,s){return Y("tst",[t,n,r,...e==="playwright"?[]:[`framework:${e}`],...Jo(e,s)])}function Al(e,t){if(!Tl(t))return;let n=J1(e,t);if(!(Tl(n)||n===".."||n.startsWith(`..${Wo}`)))return n.split(Wo).join("/")}function Yo(e){let t=e.trim();return t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7)).replaceAll("\\","/"),/^\/[A-Za-z]:\//.test(t)&&(t=t.slice(1))),t.replaceAll("\\","/")}function Jv(e,t,n){let r=Yo(n),s=Wo==="\\"?r.replaceAll("/","\\"):r;if(Tl(s)||/^[A-Za-z]:\//.test(r))return Al(e,s)??r;let o=r.replace(/^(?:\.\/)+/,"");if(t===void 0)return o;let a=Al(e,t);return a===void 0||a===""?o:`${a}/${o}`}function xf(e,t,n,r,s){let o=e.location===void 0?void 0:{...e.location,file:Jv(r,s,e.location.file)};return{errorId:Y("err",[t,n]),source:n,...e.message===void 0?{}:{message:e.message},...e.name===void 0?{}:{name:e.name},...e.stack===void 0?{}:{stack:e.stack},...e.snippet===void 0?{}:{snippet:e.snippet},...e.value===void 0?{}:{value:e.value},...o===void 0?{}:{location:o}}}function Yv(e,t,n,r,s){return{title:e.title,duration:e.duration,...e.error===void 0?{}:{error:xf(e.error,t,`${n}.error`,r,s)},...e.definition===void 0?{}:{definition:e.definition},steps:e.steps.map((o,a)=>Yv(o,t,`${n}.steps[${a}]`,r,s))}}function Y1(e,t){let n=Yo(t),r=Wo==="\\"?n.replaceAll("/","\\"):n;return Tl(r)||e===void 0?r:`${e}${Wo}${r.replace(/^(?:\.[/\\])+/,"")}`}function X1(e){let t=e.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 Q1(e,t,n){return e.length===0?"zero-tests":n||e.some(r=>r.attempts.some(s=>s.status==="interrupted"))?"interrupted":t.length>0?"report-errors":"analysis-ready"}function Rf(e){if(e===void 0)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function Xv(e){let{report:t,reportHash:n,artifact:r,options:s}=e,o=s.workspaceRoot,a=new Set(e.warnings),d=t.projects.map(b=>{let v=b.testDir===void 0?void 0:Al(o,b.testDir);return{projectId:Y("prj",[`framework:${t.framework}`,b.id,b.name]),frameworkProjectId:b.id,name:b.name,repeatEach:1,retries:b.retries,...v===void 0?{}:{testDir:v}}}).sort((b,v)=>b.projectId.localeCompare(v.projectId)),l=new Map(d.map(b=>[b.frameworkProjectId,b.projectId])),c=new Set,u=[];t.tests.forEach((b,v)=>{let R=l.get(b.projectId);if(R===void 0)throw new Error(`Test ${v} references unknown project: ${b.projectId}`);let x=Jv(o,t.rootDir,b.file),T=ms(t.framework,o,R,x,b.titlePath);if(c.has(T)){a.add(`duplicate-test-identity:${x}`);return}c.add(T);let N=`$tests[${v}]`,U=b.attempts.map((I,C)=>{let A=Y("atm",[T,String(I.retry),"repeat:unknown",String(C)]),M=`${N}.attempts[${C}]`,$=I.errors.map((O,P)=>xf(O,A,`${M}.errors[${P}]`,o,t.rootDir)),j=$.find(O=>O.location!==void 0)?.location;return{attemptId:A,sourceIndex:C,retry:I.retry,repeat:{state:"unknown",reason:"not-serialized-by-report"},status:I.status,duration:I.duration,startTime:Rf(I.startTime)??Rf(t.startTime)??Sl,workerIndex:0,parallelIndex:0,errors:$,stdout:I.stdout.map(O=>({kind:"text",text:O})),stderr:I.stderr.map(O=>({kind:"text",text:O})),steps:I.steps.map((O,P)=>Yv(O,A,`${M}.steps[${P}]`,o,t.rootDir)),attachments:I.attachments.map((O,P)=>({attachmentId:Y("att",[A,String(P)]),name:O.name,contentType:O.contentType,sourceIndex:P,...O.path===void 0?{}:{path:Y1(t.rootDir,O.path)},...O.body===void 0?{}:{bodyBase64:O.body}})),annotations:[],...j===void 0?{}:{errorLocation:j}}}),F=X1(b.attempts);u.push({logicalTestId:T,projectId:R,title:b.titlePath.at(-1)??"",titlePath:b.titlePath,tags:[...b.tags??[]].sort(),location:{file:x,...b.line===void 0?{}:{line:b.line},...b.column===void 0?{}:{column:b.column}},...b.featureUri===void 0?{}:{featureUri:b.featureUri},timeout:b.timeout??0,expectedStatus:F==="skipped"?"skipped":"passed",status:F,annotations:[],attempts:U})}),u.sort((b,v)=>b.logicalTestId.localeCompare(v.logicalTestId));let p=t.errors.map((b,v)=>xf(b,r.artifactId,`$errors[${v}]`,o,t.rootDir)),f=u.reduce((b,v)=>b+v.attempts.reduce((R,x)=>R+x.attachments.length,0),0),m=u.flatMap(b=>b.attempts.map(v=>v.startTime)).filter(b=>b!==Sl).sort()[0],h=Rf(t.startTime)??m??Sl;h===Sl&&a.add("start-time-unavailable");let g={expected:0,unexpected:0,flaky:0,skipped:0};for(let b of u)g[b.status]+=1;let y=t.configFile===void 0?void 0:Al(o,Yo(t.configFile)),w=Y("run",[n,o,s.gitRoot??"",Xr,`${t.format}:${t.adapterVersion}`]);return{schemaVersion:Xr,runId:w,framework:t.framework,createdAt:h,workspace:{root:o,...s.gitRoot===void 0?{}:{gitRoot:s.gitRoot}},sourceHashes:{report:n},artifact:r,usability:Q1(u,p,t.interrupted),projects:d,...y===void 0?{}:{configFile:y},logicalTests:u,reportErrors:p,collections:{tests:u.length===0?"empty":"present",errors:p.length===0?"empty":"present",attachments:f===0?"empty":"present"},warnings:[...a].sort(),stats:{startTime:h,duration:t.duration??0,...g}}}var dR=Qd(aa(),1);import{lstat as L$,readFile as D$,realpath as rR}from"node:fs/promises";import{isAbsolute as aR,relative as F$,resolve as j$,sep as B$}from"node:path";import{access as A$}from"node:fs/promises";import{createRequire as P$}from"node:module";import{fileURLToPath as E$}from"node:url";var w$=Object.defineProperty,S=(e,t)=>w$(e,"name",{value:t,configurable:!0}),fY=class{static{S(this,"Edit")}startPosition;oldEndPosition;newEndPosition;startIndex;oldEndIndex;newEndIndex;constructor({startIndex:e,oldEndIndex:t,newEndIndex:n,startPosition:r,oldEndPosition:s,newEndPosition:o}){this.startIndex=e>>>0,this.oldEndIndex=t>>>0,this.newEndIndex=n>>>0,this.startPosition=r,this.oldEndPosition=s,this.newEndPosition=o}editPoint(e,t){let n=t,r={...e};if(t>=this.oldEndIndex){n=this.newEndIndex+(t-this.oldEndIndex);let s=e.row;r.row=this.newEndPosition.row+(e.row-this.oldEndPosition.row),r.column=s===this.oldEndPosition.row?this.newEndPosition.column+(e.column-this.oldEndPosition.column):e.column}else t>this.startIndex&&(n=this.newEndIndex,r.row=this.newEndPosition.row,r.column=this.newEndPosition.column);return{point:r,index:n}}editRange(e){let t={startIndex:e.startIndex,startPosition:{...e.startPosition},endIndex:e.endIndex,endPosition:{...e.endPosition}};return e.endIndex>=this.oldEndIndex?e.endIndex!==Number.MAX_SAFE_INTEGER&&(t.endIndex=this.newEndIndex+(e.endIndex-this.oldEndIndex),t.endPosition={row:this.newEndPosition.row+(e.endPosition.row-this.oldEndPosition.row),column:e.endPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.endPosition.column-this.oldEndPosition.column):e.endPosition.column},t.endIndex<this.newEndIndex&&(t.endIndex=Number.MAX_SAFE_INTEGER,t.endPosition={row:Number.MAX_SAFE_INTEGER,column:Number.MAX_SAFE_INTEGER})):e.endIndex>this.startIndex&&(t.endIndex=this.startIndex,t.endPosition={...this.startPosition}),e.startIndex>=this.oldEndIndex?(t.startIndex=this.newEndIndex+(e.startIndex-this.oldEndIndex),t.startPosition={row:this.newEndPosition.row+(e.startPosition.row-this.oldEndPosition.row),column:e.startPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.startPosition.column-this.oldEndPosition.column):e.startPosition.column},t.startIndex<this.newEndIndex&&(t.startIndex=Number.MAX_SAFE_INTEGER,t.startPosition={row:Number.MAX_SAFE_INTEGER,column:Number.MAX_SAFE_INTEGER})):e.startIndex>this.startIndex&&(t.startIndex=this.startIndex,t.startPosition={...this.startPosition}),t}},Tk=2,J=4,om=4*J,ft=5*J,xn=2*J,ca=2*J+2*xn,pt={row:0,column:0},kr=Symbol("INTERNAL");function ks(e){if(e!==kr)throw new Error("Illegal constructor")}S(ks,"assertInternal");function la(e){return!!e&&typeof e.row=="number"&&typeof e.column=="number"}S(la,"isPoint");function $k(e){k=e}S($k,"setModule");var k;function Rs(e){try{return new FinalizationRegistry(e)}catch(t){console.error("Unsupported FinalizationRegistry:",t);return}}S(Rs,"newFinalizer");var Ak=Rs(e=>{k._ts_lookahead_iterator_delete(e)}),b$=class{static{S(this,"LookaheadIterator")}0=0;language;positioned=!1;constructor(e,t,n){ks(e),this[0]=t,this.language=n,Ak?.register(this,t,this)}get currentTypeId(){return this.positioned?k._ts_lookahead_iterator_current_symbol(this[0]):null}get currentType(){let e=this.currentTypeId;return e===null?null:this.language.types[e]??k.UTF8ToString(k._ts_language_symbol_name(this.language[0],e))}delete(){Ak?.unregister(this),k._ts_lookahead_iterator_delete(this[0]),this[0]=0}reset(e,t){return k._ts_lookahead_iterator_reset(this[0],e[0],t)?(this.language=e,this.positioned=!1,!0):!1}resetState(e){return k._ts_lookahead_iterator_reset_state(this[0],e)?(this.positioned=!1,!0):!1}[Symbol.iterator](){return{next:S(()=>{this.positioned=!!k._ts_lookahead_iterator_next(this[0]);let e=this.currentType;return e===null?{done:!0,value:""}:{done:!1,value:e}},"next")}}};function um(e,t,n,r){let s=n-t,o=e.textCallback(t,r);if(o){for(t+=o.length;t<n;){let a=e.textCallback(t,r);if(a&&a.length>0)t+=a.length,o+=a;else break}t>n&&(o=o.slice(0,s))}return o??""}S(um,"getText");var Pk=Rs(e=>{k._ts_tree_delete(e)}),v$=class lm{static{S(this,"Tree")}0=0;textCallback;language;constructor(t,n,r,s){ks(t),this[0]=n,this.language=r,this.textCallback=s,Pk?.register(this,n,this)}copy(){let t=k._ts_tree_copy(this[0]);return new lm(kr,t,this.language,this.textCallback)}delete(){Pk?.unregister(this),k._ts_tree_delete(this[0]),this[0]=0}get rootNode(){return k._ts_tree_root_node_wasm(this[0]),Pe(this)}rootNodeWithOffset(t,n){let r=W+ft;return k.setValue(r,t,"i32"),$t(r+J,n),k._ts_tree_root_node_with_offset_wasm(this[0]),Pe(this)}edit(t){Dk(t),k._ts_tree_edit_wasm(this[0])}walk(){return this.rootNode.walk()}getChangedRanges(t){if(!(t instanceof lm))throw new TypeError("Argument must be a Tree");k._ts_tree_get_changed_ranges_wasm(this[0],t[0]);let n=k.getValue(W,"i32"),r=k.getValue(W+J,"i32"),s=new Array(n);if(n>0){let o=r;for(let a=0;a<n;a++)s[a]=jl(o),o+=ca;k._free(r)}return s}getIncludedRanges(){k._ts_tree_included_ranges_wasm(this[0]);let t=k.getValue(W,"i32"),n=k.getValue(W+J,"i32"),r=new Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=jl(s),s+=ca;k._free(n)}return r}},Ek=Rs(e=>{k._ts_tree_cursor_delete_wasm(e)}),k$=class Mk{static{S(this,"TreeCursor")}0=0;1=0;2=0;3=0;tree;constructor(t,n){ks(t),this.tree=n,xt(this),Ek?.register(this,this.tree[0],this)}copy(){let t=new Mk(kr,this.tree);return k._ts_tree_cursor_copy_wasm(this.tree[0]),xt(t),t}delete(){Ek?.unregister(this),_e(this),k._ts_tree_cursor_delete_wasm(this.tree[0]),this[0]=this[1]=this[2]=0}get currentNode(){return _e(this),k._ts_tree_cursor_current_node_wasm(this.tree[0]),Pe(this.tree)}get currentFieldId(){return _e(this),k._ts_tree_cursor_current_field_id_wasm(this.tree[0])}get currentFieldName(){return this.tree.language.fields[this.currentFieldId]}get currentDepth(){return _e(this),k._ts_tree_cursor_current_depth_wasm(this.tree[0])}get currentDescendantIndex(){return _e(this),k._ts_tree_cursor_current_descendant_index_wasm(this.tree[0])}get nodeType(){return this.tree.language.types[this.nodeTypeId]||"ERROR"}get nodeTypeId(){return _e(this),k._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeStateId(){return _e(this),k._ts_tree_cursor_current_node_state_id_wasm(this.tree[0])}get nodeId(){return _e(this),k._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return _e(this),k._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])===1}get nodeIsMissing(){return _e(this),k._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])===1}get nodeText(){_e(this);let t=k._ts_tree_cursor_start_index_wasm(this.tree[0]),n=k._ts_tree_cursor_end_index_wasm(this.tree[0]);k._ts_tree_cursor_start_position_wasm(this.tree[0]);let r=ri(W);return um(this.tree,t,n,r)}get startPosition(){return _e(this),k._ts_tree_cursor_start_position_wasm(this.tree[0]),ri(W)}get endPosition(){return _e(this),k._ts_tree_cursor_end_position_wasm(this.tree[0]),ri(W)}get startIndex(){return _e(this),k._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return _e(this),k._ts_tree_cursor_end_index_wasm(this.tree[0])}gotoFirstChild(){_e(this);let t=k._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return xt(this),t===1}gotoLastChild(){_e(this);let t=k._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);return xt(this),t===1}gotoParent(){_e(this);let t=k._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return xt(this),t===1}gotoNextSibling(){_e(this);let t=k._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return xt(this),t===1}gotoPreviousSibling(){_e(this);let t=k._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);return xt(this),t===1}gotoDescendant(t){_e(this),k._ts_tree_cursor_goto_descendant_wasm(this.tree[0],t),xt(this)}gotoFirstChildForIndex(t){_e(this),k.setValue(W+om,t,"i32");let n=k._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);return xt(this),n===1}gotoFirstChildForPosition(t){_e(this),$t(W+om,t);let n=k._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);return xt(this),n===1}reset(t){se(t),_e(this,W+ft),k._ts_tree_cursor_reset_wasm(this.tree[0]),xt(this)}resetTo(t){_e(this,W),_e(t,W+om),k._ts_tree_cursor_reset_to_wasm(this.tree[0],t.tree[0]),xt(this)}},R$=class{static{S(this,"Node")}0=0;_children;_namedChildren;constructor(e,{id:t,tree:n,startIndex:r,startPosition:s,other:o}){ks(e),this[0]=o,this.id=t,this.tree=n,this.startIndex=r,this.startPosition=s}id;startIndex;startPosition;tree;get typeId(){return se(this),k._ts_node_symbol_wasm(this.tree[0])}get grammarId(){return se(this),k._ts_node_grammar_symbol_wasm(this.tree[0])}get type(){return this.tree.language.types[this.typeId]||"ERROR"}get grammarType(){return this.tree.language.types[this.grammarId]||"ERROR"}get isNamed(){return se(this),k._ts_node_is_named_wasm(this.tree[0])===1}get isExtra(){return se(this),k._ts_node_is_extra_wasm(this.tree[0])===1}get isError(){return se(this),k._ts_node_is_error_wasm(this.tree[0])===1}get isMissing(){return se(this),k._ts_node_is_missing_wasm(this.tree[0])===1}get hasChanges(){return se(this),k._ts_node_has_changes_wasm(this.tree[0])===1}get hasError(){return se(this),k._ts_node_has_error_wasm(this.tree[0])===1}get endIndex(){return se(this),k._ts_node_end_index_wasm(this.tree[0])}get endPosition(){return se(this),k._ts_node_end_point_wasm(this.tree[0]),ri(W)}get text(){return um(this.tree,this.startIndex,this.endIndex,this.startPosition)}get parseState(){return se(this),k._ts_node_parse_state_wasm(this.tree[0])}get nextParseState(){return se(this),k._ts_node_next_parse_state_wasm(this.tree[0])}equals(e){return this.tree===e.tree&&this.id===e.id}child(e){return se(this),k._ts_node_child_wasm(this.tree[0],e),Pe(this.tree)}namedChild(e){return se(this),k._ts_node_named_child_wasm(this.tree[0],e),Pe(this.tree)}childForFieldId(e){return se(this),k._ts_node_child_by_field_id_wasm(this.tree[0],e),Pe(this.tree)}childForFieldName(e){let t=this.tree.language.fields.indexOf(e);return t!==-1?this.childForFieldId(t):null}fieldNameForChild(e){se(this);let t=k._ts_node_field_name_for_child_wasm(this.tree[0],e);return t?k.AsciiToString(t):null}fieldNameForNamedChild(e){se(this);let t=k._ts_node_field_name_for_named_child_wasm(this.tree[0],e);return t?k.AsciiToString(t):null}childrenForFieldName(e){let t=this.tree.language.fields.indexOf(e);return t!==-1&&t!==0?this.childrenForFieldId(t):[]}childrenForFieldId(e){se(this),k._ts_node_children_by_field_id_wasm(this.tree[0],e);let t=k.getValue(W,"i32"),n=k.getValue(W+J,"i32"),r=new Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=Pe(this.tree,s),s+=ft;k._free(n)}return r}firstChildForIndex(e){se(this);let t=W+ft;return k.setValue(t,e,"i32"),k._ts_node_first_child_for_byte_wasm(this.tree[0]),Pe(this.tree)}firstNamedChildForIndex(e){se(this);let t=W+ft;return k.setValue(t,e,"i32"),k._ts_node_first_named_child_for_byte_wasm(this.tree[0]),Pe(this.tree)}get childCount(){return se(this),k._ts_node_child_count_wasm(this.tree[0])}get namedChildCount(){return se(this),k._ts_node_named_child_count_wasm(this.tree[0])}get firstChild(){return this.child(0)}get firstNamedChild(){return this.namedChild(0)}get lastChild(){return this.child(this.childCount-1)}get lastNamedChild(){return this.namedChild(this.namedChildCount-1)}get children(){if(!this._children){se(this),k._ts_node_children_wasm(this.tree[0]);let e=k.getValue(W,"i32"),t=k.getValue(W+J,"i32");if(this._children=new Array(e),e>0){let n=t;for(let r=0;r<e;r++)this._children[r]=Pe(this.tree,n),n+=ft;k._free(t)}}return this._children}get namedChildren(){if(!this._namedChildren){se(this),k._ts_node_named_children_wasm(this.tree[0]);let e=k.getValue(W,"i32"),t=k.getValue(W+J,"i32");if(this._namedChildren=new Array(e),e>0){let n=t;for(let r=0;r<e;r++)this._namedChildren[r]=Pe(this.tree,n),n+=ft;k._free(t)}}return this._namedChildren}descendantsOfType(e,t=pt,n=pt){Array.isArray(e)||(e=[e]);let r=[],s=this.tree.language.types;for(let c of e)c=="ERROR"&&r.push(65535);for(let c=0,u=s.length;c<u;c++)e.includes(s[c])&&r.push(c);let o=k._malloc(J*r.length);for(let c=0,u=r.length;c<u;c++)k.setValue(o+c*J,r[c],"i32");se(this),k._ts_node_descendants_of_type_wasm(this.tree[0],o,r.length,t.row,t.column,n.row,n.column);let a=k.getValue(W,"i32"),d=k.getValue(W+J,"i32"),l=new Array(a);if(a>0){let c=d;for(let u=0;u<a;u++)l[u]=Pe(this.tree,c),c+=ft}return k._free(d),k._free(o),l}get nextSibling(){return se(this),k._ts_node_next_sibling_wasm(this.tree[0]),Pe(this.tree)}get previousSibling(){return se(this),k._ts_node_prev_sibling_wasm(this.tree[0]),Pe(this.tree)}get nextNamedSibling(){return se(this),k._ts_node_next_named_sibling_wasm(this.tree[0]),Pe(this.tree)}get previousNamedSibling(){return se(this),k._ts_node_prev_named_sibling_wasm(this.tree[0]),Pe(this.tree)}get descendantCount(){return se(this),k._ts_node_descendant_count_wasm(this.tree[0])}get parent(){return se(this),k._ts_node_parent_wasm(this.tree[0]),Pe(this.tree)}childWithDescendant(e){return se(this),se(e,1),k._ts_node_child_with_descendant_wasm(this.tree[0]),Pe(this.tree)}descendantForIndex(e,t=e){if(typeof e!="number"||typeof t!="number")throw new Error("Arguments must be numbers");se(this);let n=W+ft;return k.setValue(n,e,"i32"),k.setValue(n+J,t,"i32"),k._ts_node_descendant_for_index_wasm(this.tree[0]),Pe(this.tree)}namedDescendantForIndex(e,t=e){if(typeof e!="number"||typeof t!="number")throw new Error("Arguments must be numbers");se(this);let n=W+ft;return k.setValue(n,e,"i32"),k.setValue(n+J,t,"i32"),k._ts_node_named_descendant_for_index_wasm(this.tree[0]),Pe(this.tree)}descendantForPosition(e,t=e){if(!la(e)||!la(t))throw new Error("Arguments must be {row, column} objects");se(this);let n=W+ft;return $t(n,e),$t(n+xn,t),k._ts_node_descendant_for_position_wasm(this.tree[0]),Pe(this.tree)}namedDescendantForPosition(e,t=e){if(!la(e)||!la(t))throw new Error("Arguments must be {row, column} objects");se(this);let n=W+ft;return $t(n,e),$t(n+xn,t),k._ts_node_named_descendant_for_position_wasm(this.tree[0]),Pe(this.tree)}walk(){return se(this),k._ts_tree_cursor_new_wasm(this.tree[0]),new k$(kr,this.tree)}edit(e){if(this.startIndex>=e.oldEndIndex){this.startIndex=e.newEndIndex+(this.startIndex-e.oldEndIndex);let t,n;this.startPosition.row>e.oldEndPosition.row?(t=this.startPosition.row-e.oldEndPosition.row,n=this.startPosition.column):(t=0,n=this.startPosition.column,this.startPosition.column>=e.oldEndPosition.column&&(n=this.startPosition.column-e.oldEndPosition.column)),t>0?(this.startPosition.row+=t,this.startPosition.column=n):this.startPosition.column+=n}else this.startIndex>e.startIndex&&(this.startIndex=e.newEndIndex,this.startPosition.row=e.newEndPosition.row,this.startPosition.column=e.newEndPosition.column)}toString(){se(this);let e=k._ts_node_to_string_wasm(this.tree[0]),t=k.AsciiToString(e);return k._free(e),t}};function cm(e,t,n,r,s){for(let o=0,a=s.length;o<a;o++){let d=k.getValue(n,"i32");n+=J;let l=Pe(t,n);n+=ft,s[o]={patternIndex:r,name:e.captureNames[d],node:l}}return n}S(cm,"unmarshalCaptures");function se(e,t=0){let n=W+t*ft;k.setValue(n,e.id,"i32"),n+=J,k.setValue(n,e.startIndex,"i32"),n+=J,k.setValue(n,e.startPosition.row,"i32"),n+=J,k.setValue(n,e.startPosition.column,"i32"),n+=J,k.setValue(n,e[0],"i32")}S(se,"marshalNode");function Pe(e,t=W){let n=k.getValue(t,"i32");if(t+=J,n===0)return null;let r=k.getValue(t,"i32");t+=J;let s=k.getValue(t,"i32");t+=J;let o=k.getValue(t,"i32");t+=J;let a=k.getValue(t,"i32");return new R$(kr,{id:n,tree:e,startIndex:r,startPosition:{row:s,column:o},other:a})}S(Pe,"unmarshalNode");function _e(e,t=W){k.setValue(t+0*J,e[0],"i32"),k.setValue(t+1*J,e[1],"i32"),k.setValue(t+2*J,e[2],"i32"),k.setValue(t+3*J,e[3],"i32")}S(_e,"marshalTreeCursor");function xt(e){e[0]=k.getValue(W+0*J,"i32"),e[1]=k.getValue(W+1*J,"i32"),e[2]=k.getValue(W+2*J,"i32"),e[3]=k.getValue(W+3*J,"i32")}S(xt,"unmarshalTreeCursor");function $t(e,t){k.setValue(e,t.row,"i32"),k.setValue(e+J,t.column,"i32")}S($t,"marshalPoint");function ri(e){return{row:k.getValue(e,"i32")>>>0,column:k.getValue(e+J,"i32")>>>0}}S(ri,"unmarshalPoint");function Lk(e,t){$t(e,t.startPosition),e+=xn,$t(e,t.endPosition),e+=xn,k.setValue(e,t.startIndex,"i32"),e+=J,k.setValue(e,t.endIndex,"i32"),e+=J}S(Lk,"marshalRange");function jl(e){let t={};return t.startPosition=ri(e),e+=xn,t.endPosition=ri(e),e+=xn,t.startIndex=k.getValue(e,"i32")>>>0,e+=J,t.endIndex=k.getValue(e,"i32")>>>0,t}S(jl,"unmarshalRange");function Dk(e,t=W){$t(t,e.startPosition),t+=xn,$t(t,e.oldEndPosition),t+=xn,$t(t,e.newEndPosition),t+=xn,k.setValue(t,e.startIndex,"i32"),t+=J,k.setValue(t,e.oldEndIndex,"i32"),t+=J,k.setValue(t,e.newEndIndex,"i32"),t+=J}S(Dk,"marshalEdit");function Fk(e){let t=k.getValue(e,"i32"),n=k.getValue(e+=J,"i32"),r=k.getValue(e+=J,"i32");return{major_version:t,minor_version:n,patch_version:r}}S(Fk,"unmarshalLanguageMetadata");var x$=/^tree_sitter_\w+$/,pm=class Fl{static{S(this,"Language")}0=0;types;fields;constructor(t,n){ks(t),this[0]=n,this.types=new Array(k._ts_language_symbol_count(this[0]));for(let r=0,s=this.types.length;r<s;r++)k._ts_language_symbol_type(this[0],r)<2&&(this.types[r]=k.UTF8ToString(k._ts_language_symbol_name(this[0],r)));this.fields=new Array(k._ts_language_field_count(this[0])+1);for(let r=0,s=this.fields.length;r<s;r++){let o=k._ts_language_field_name_for_id(this[0],r);o!==0?this.fields[r]=k.UTF8ToString(o):this.fields[r]=null}}get name(){let t=k._ts_language_name(this[0]);return t===0?null:k.UTF8ToString(t)}get abiVersion(){return k._ts_language_abi_version(this[0])}get metadata(){return k._ts_language_metadata_wasm(this[0]),k.getValue(W,"i32")===0?null:Fk(W+J)}get fieldCount(){return this.fields.length-1}get stateCount(){return k._ts_language_state_count(this[0])}fieldIdForName(t){let n=this.fields.indexOf(t);return n!==-1?n:null}fieldNameForId(t){return this.fields[t]??null}idForNodeType(t,n){let r=k.lengthBytesUTF8(t),s=k._malloc(r+1);k.stringToUTF8(t,s,r+1);let o=k._ts_language_symbol_for_name(this[0],s,r,n?1:0);return k._free(s),o||null}get nodeTypeCount(){return k._ts_language_symbol_count(this[0])}nodeTypeForId(t){let n=k._ts_language_symbol_name(this[0],t);return n?k.UTF8ToString(n):null}nodeTypeIsNamed(t){return!!k._ts_language_type_is_named_wasm(this[0],t)}nodeTypeIsVisible(t){return!!k._ts_language_type_is_visible_wasm(this[0],t)}get supertypes(){k._ts_language_supertypes_wasm(this[0]);let t=k.getValue(W,"i32"),n=k.getValue(W+J,"i32"),r=new Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=k.getValue(s,"i16"),s+=Tk}return r}subtypes(t){k._ts_language_subtypes_wasm(this[0],t);let n=k.getValue(W,"i32"),r=k.getValue(W+J,"i32"),s=new Array(n);if(n>0){let o=r;for(let a=0;a<n;a++)s[a]=k.getValue(o,"i16"),o+=Tk}return s}nextState(t,n){return k._ts_language_next_state(this[0],t,n)}lookaheadIterator(t){let n=k._ts_lookahead_iterator_new(this[0],t);return n?new b$(kr,n,this):null}static async load(t){let n;if(t instanceof Uint8Array)n=t;else if(globalThis.process?.versions.node)n=await(await import("fs/promises")).readFile(t);else{let s=await fetch(t);if(!s.ok){let a=await s.text();throw new Error(`Language.load failed with status ${s.status}.
|
|
20
20
|
|
|
21
21
|
${a}`)}let o=s.clone();try{n=await WebAssembly.compileStreaming(s)}catch(a){console.error("wasm streaming compile failed:",a),console.error("falling back to ArrayBuffer instantiation"),n=new Uint8Array(await o.arrayBuffer())}}let r=await k.loadWebAssemblyModule(n,{loadAsync:!0});return Fl.loadFromWasmExports(r,{sync:!1})}static loadFromWasmExports(t,{sync:n}){let r=Object.keys(t),s=r.find(a=>x$.test(a)&&!a.includes("external_scanner_"));if(!s)throw console.log(`Couldn't find language function in Wasm file. Symbols:
|
|
22
|
-
${JSON.stringify(r,null,2)}`),new Error(`Language.${n?"loadSync":"load"} failed: no language function found in Wasm file`);let o=t[s]();return new Fl(kr,o)}static loadSync(t){let n=k.loadWebAssemblyModule(t,{loadAsync:!1});return Fl.loadFromWasmExports(n,{sync:!0})}};async function jk(moduleArg={}){var moduleRtn,Module=moduleArg,ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope<"u",ENVIRONMENT_IS_NODE=typeof process=="object"&&process.versions?.node&&process.type!="renderer";if(ENVIRONMENT_IS_NODE){let{createRequire:e}=await import("module");var require=e(import.meta.url)}Module.currentQueryProgressCallback=null,Module.currentProgressCallback=null,Module.currentLogCallback=null,Module.currentParseCallback=null;var arguments_=[],thisProgram="./this.program",quit_=S((e,t)=>{throw t},"quit_"),_scriptName=import.meta.url,scriptDirectory="";function locateFile(e){return Module.locateFile?Module.locateFile(e,scriptDirectory):scriptDirectory+e}S(locateFile,"locateFile");var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");_scriptName.startsWith("file:")&&(scriptDirectory=require("path").dirname(require("url").fileURLToPath(_scriptName))+"/"),readBinary=S(e=>{e=isFileURI(e)?new URL(e):e;var t=fs.readFileSync(e);return t},"readBinary"),readAsync=S(async(e,t=!0)=>{e=isFileURI(e)?new URL(e):e;var n=fs.readFileSync(e,t?void 0:"utf8");return n},"readAsync"),process.argv.length>1&&(thisProgram=process.argv[1].replace(/\\/g,"/")),arguments_=process.argv.slice(2),quit_=S((e,t)=>{throw process.exitCode=e,t},"quit_")}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}ENVIRONMENT_IS_WORKER&&(readBinary=S(e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)},"readBinary")),readAsync=S(async e=>{if(isFileURI(e))return new Promise((n,r)=>{var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=()=>{if(s.status==200||s.status==0&&s.response){n(s.response);return}r(s.status)},s.onerror=r,s.send(null)});var t=await fetch(e,{credentials:"same-origin"});if(t.ok)return t.arrayBuffer();throw new Error(t.status+" : "+t.url)},"readAsync")}var out=console.log.bind(console),err=console.error.bind(console),dynamicLibraries=[],wasmBinary,ABORT=!1,EXITSTATUS,isFileURI=S(e=>e.startsWith("file://"),"isFileURI"),readyPromiseResolve,readyPromiseReject,wasmMemory,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP64,HEAPU64,HEAP_DATA_VIEW,runtimeInitialized=!1;function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e),Module.HEAP64=HEAP64=new BigInt64Array(e),Module.HEAPU64=HEAPU64=new BigUint64Array(e),Module.HEAP_DATA_VIEW=HEAP_DATA_VIEW=new DataView(e),LE_HEAP_UPDATE()}S(updateMemoryViews,"updateMemoryViews");function initMemory(){if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var e=Module.INITIAL_MEMORY||33554432;wasmMemory=new WebAssembly.Memory({initial:e/65536,maximum:32768})}updateMemoryViews()}S(initMemory,"initMemory");var __RELOC_FUNCS__=[];function preRun(){if(Module.preRun)for(typeof Module.preRun=="function"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(onPreRuns)}S(preRun,"preRun");function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),wasmExports.__wasm_call_ctors(),callRuntimeCallbacks(onPostCtors)}S(initRuntime,"initRuntime");function preMain(){}S(preMain,"preMain");function postRun(){if(Module.postRun)for(typeof Module.postRun=="function"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(onPostRuns)}S(postRun,"postRun");function abort(e){Module.onAbort?.(e),e="Aborted("+e+")",err(e),ABORT=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw readyPromiseReject?.(t),t}S(abort,"abort");var wasmBinaryFile;function findWasmBinary(){return Module.locateFile?locateFile("web-tree-sitter.wasm"):new URL("web-tree-sitter.wasm",import.meta.url).href}S(findWasmBinary,"findWasmBinary");function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}S(getBinarySync,"getBinarySync");async function getWasmBinary(e){if(!wasmBinary)try{var t=await readAsync(e);return new Uint8Array(t)}catch{}return getBinarySync(e)}S(getWasmBinary,"getWasmBinary");async function instantiateArrayBuffer(e,t){try{var n=await getWasmBinary(e),r=await WebAssembly.instantiate(n,t);return r}catch(s){err(`failed to asynchronously prepare wasm: ${s}`),abort(s)}}S(instantiateArrayBuffer,"instantiateArrayBuffer");async function instantiateAsync(e,t,n){if(!e&&!isFileURI(t)&&!ENVIRONMENT_IS_NODE)try{var r=fetch(t,{credentials:"same-origin"}),s=await WebAssembly.instantiateStreaming(r,n);return s}catch(o){err(`wasm streaming compile failed: ${o}`),err("falling back to ArrayBuffer instantiation")}return instantiateArrayBuffer(t,n)}S(instantiateAsync,"instantiateAsync");function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}S(getWasmImports,"getWasmImports");async function createWasm(){function e(o,a){wasmExports=o.exports,wasmExports=relocateExports(wasmExports,1024);var d=getDylinkMetadata(a);return d.neededDynlibs&&(dynamicLibraries=d.neededDynlibs.concat(dynamicLibraries)),mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),assignWasmExports(wasmExports),wasmExports}S(e,"receiveInstance");function t(o){return e(o.instance,o.module)}S(t,"receiveInstantiationResult");var n=getWasmImports();if(Module.instantiateWasm)return new Promise((o,a)=>{Module.instantiateWasm(n,(d,l)=>{o(e(d,l))})});wasmBinaryFile??=findWasmBinary();var r=await instantiateAsync(wasmBinary,wasmBinaryFile,n),s=t(r);return s}S(createWasm,"createWasm");class ExitStatus{static{S(this,"ExitStatus")}name="ExitStatus";constructor(t){this.message=`Program terminated with exit(${t})`,this.status=t}}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(e,t){var n=GOT[t];return n||(n=GOT[t]=new WebAssembly.Global({value:"i32",mutable:!0})),currentModuleWeakSymbols.has(t)||(n.required=!0),n}},LE_ATOMICS_NATIVE_BYTE_ORDER=[],LE_HEAP_LOAD_F32=S(e=>HEAP_DATA_VIEW.getFloat32(e,!0),"LE_HEAP_LOAD_F32"),LE_HEAP_LOAD_F64=S(e=>HEAP_DATA_VIEW.getFloat64(e,!0),"LE_HEAP_LOAD_F64"),LE_HEAP_LOAD_I16=S(e=>HEAP_DATA_VIEW.getInt16(e,!0),"LE_HEAP_LOAD_I16"),LE_HEAP_LOAD_I32=S(e=>HEAP_DATA_VIEW.getInt32(e,!0),"LE_HEAP_LOAD_I32"),LE_HEAP_LOAD_I64=S(e=>HEAP_DATA_VIEW.getBigInt64(e,!0),"LE_HEAP_LOAD_I64"),LE_HEAP_LOAD_U32=S(e=>HEAP_DATA_VIEW.getUint32(e,!0),"LE_HEAP_LOAD_U32"),LE_HEAP_STORE_F32=S((e,t)=>HEAP_DATA_VIEW.setFloat32(e,t,!0),"LE_HEAP_STORE_F32"),LE_HEAP_STORE_F64=S((e,t)=>HEAP_DATA_VIEW.setFloat64(e,t,!0),"LE_HEAP_STORE_F64"),LE_HEAP_STORE_I16=S((e,t)=>HEAP_DATA_VIEW.setInt16(e,t,!0),"LE_HEAP_STORE_I16"),LE_HEAP_STORE_I32=S((e,t)=>HEAP_DATA_VIEW.setInt32(e,t,!0),"LE_HEAP_STORE_I32"),LE_HEAP_STORE_I64=S((e,t)=>HEAP_DATA_VIEW.setBigInt64(e,t,!0),"LE_HEAP_STORE_I64"),LE_HEAP_STORE_U32=S((e,t)=>HEAP_DATA_VIEW.setUint32(e,t,!0),"LE_HEAP_STORE_U32"),callRuntimeCallbacks=S(e=>{for(;e.length>0;)e.shift()(Module)},"callRuntimeCallbacks"),onPostRuns=[],addOnPostRun=S(e=>onPostRuns.push(e),"addOnPostRun"),onPreRuns=[],addOnPreRun=S(e=>onPreRuns.push(e),"addOnPreRun"),UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,findStringEnd=S((e,t,n,r)=>{var s=t+n;if(r)return s;for(;e[t]&&!(t>=s);)++t;return t},"findStringEnd"),UTF8ArrayToString=S((e,t=0,n,r)=>{var s=findStringEnd(e,t,n,r);if(s-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(t,s));for(var o="";t<s;){var a=e[t++];if(!(a&128)){o+=String.fromCharCode(a);continue}var d=e[t++]&63;if((a&224)==192){o+=String.fromCharCode((a&31)<<6|d);continue}var l=e[t++]&63;if((a&240)==224?a=(a&15)<<12|d<<6|l:a=(a&7)<<18|d<<12|l<<6|e[t++]&63,a<65536)o+=String.fromCharCode(a);else{var c=a-65536;o+=String.fromCharCode(55296|c>>10,56320|c&1023)}}return o},"UTF8ArrayToString"),getDylinkMetadata=S(e=>{var t=0,n=0;function r(){return e[t++]}S(r,"getU8");function s(){for(var A=0,M=1;;){var $=e[t++];if(A+=($&127)*M,M*=128,!($&128))break}return A}S(s,"getLEB");function o(){var A=s();return t+=A,UTF8ArrayToString(e,t-A,A)}S(o,"getString");function a(){for(var A=s(),M=[];A--;)M.push(o());return M}S(a,"getStringList");function d(A,M){if(A)throw new Error(M)}if(S(d,"failIf"),e instanceof WebAssembly.Module){var l=WebAssembly.Module.customSections(e,"dylink.0");d(l.length===0,"need dylink section"),e=new Uint8Array(l[0]),n=e.length}else{var c=new Uint32Array(new Uint8Array(e.subarray(0,24)).buffer),u=c[0]==1836278016||c[0]==6386541;d(!u,"need to see wasm magic number"),d(e[8]!==0,"need the dylink section to be first"),t=9;var p=s();n=t+p;var f=o();d(f!=="dylink.0")}for(var m={neededDynlibs:[],tlsExports:new Set,weakImports:new Set,runtimePaths:[]},h=1,g=2,y=3,w=4,b=5,v=256,R=3,x=1;t<n;){var T=r(),N=s();if(T===h)m.memorySize=s(),m.memoryAlign=s(),m.tableSize=s(),m.tableAlign=s();else if(T===g)m.neededDynlibs=a();else if(T===y)for(var U=s();U--;){var F=o(),I=s();I&v&&m.tlsExports.add(F)}else if(T===w)for(var U=s();U--;){var C=o(),F=o(),I=s();(I&R)==x&&m.weakImports.add(F)}else T===b?m.runtimePaths=a():t+=N}return m},"getDylinkMetadata");function getValue(e,t="i8"){switch(t.endsWith("*")&&(t="*"),t){case"i1":return HEAP8[e];case"i8":return HEAP8[e];case"i16":return LE_HEAP_LOAD_I16((e>>1)*2);case"i32":return LE_HEAP_LOAD_I32((e>>2)*4);case"i64":return LE_HEAP_LOAD_I64((e>>3)*8);case"float":return LE_HEAP_LOAD_F32((e>>2)*4);case"double":return LE_HEAP_LOAD_F64((e>>3)*8);case"*":return LE_HEAP_LOAD_U32((e>>2)*4);default:abort(`invalid type for getValue: ${t}`)}}S(getValue,"getValue");var newDSO=S((e,t,n)=>{var r={refcount:1/0,name:e,exports:n,global:!0};return LDSO.loadedLibsByName[e]=r,t!=null&&(LDSO.loadedLibsByHandle[t]=r),r},"newDSO"),LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=82240,alignMemory=S((e,t)=>Math.ceil(e/t)*t,"alignMemory"),getMemory=S(e=>{if(runtimeInitialized)return _calloc(e,1);var t=___heap_base,n=t+alignMemory(e,16);return ___heap_base=n,GOT.__heap_base.value=n,t},"getMemory"),isInternalSym=S(e=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(e)||e.startsWith("__em_js__"),"isInternalSym"),uleb128EncodeWithLen=S(e=>{let t=e.length;return[t%128|128,t>>7,...e]},"uleb128EncodeWithLen"),wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111},generateTypePack=S(e=>uleb128EncodeWithLen(Array.from(e,t=>{var n=wasmTypeCodes[t];return n})),"generateTypePack"),convertJsFunctionToWasm=S((e,t)=>{var n=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(t.slice(1)),...generateTypePack(t[0]==="v"?"":t[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),r=new WebAssembly.Module(n),s=new WebAssembly.Instance(r,{e:{f:e}}),o=s.exports.f;return o},"convertJsFunctionToWasm"),wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:31,element:"anyfunc"}),getWasmTableEntry=S(e=>{var t=wasmTableMirror[e];return t||(wasmTableMirror[e]=t=wasmTable.get(e)),t},"getWasmTableEntry"),updateTableMap=S((e,t)=>{if(functionsInTableMap)for(var n=e;n<e+t;n++){var r=getWasmTableEntry(n);r&&functionsInTableMap.set(r,n)}},"updateTableMap"),functionsInTableMap,getFunctionAddress=S(e=>(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(e)||0),"getFunctionAddress"),freeTableIndexes=[],getEmptyTableSlot=S(()=>freeTableIndexes.length?freeTableIndexes.pop():wasmTable.grow(1),"getEmptyTableSlot"),setWasmTableEntry=S((e,t)=>{wasmTable.set(e,t),wasmTableMirror[e]=wasmTable.get(e)},"setWasmTableEntry"),addFunction=S((e,t)=>{var n=getFunctionAddress(e);if(n)return n;var r=getEmptyTableSlot();try{setWasmTableEntry(r,e)}catch(o){if(!(o instanceof TypeError))throw o;var s=convertJsFunctionToWasm(e,t);setWasmTableEntry(r,s)}return functionsInTableMap.set(e,r),r},"addFunction"),updateGOT=S((e,t)=>{for(var n in e)if(!isInternalSym(n)){var r=e[n];GOT[n]||=new WebAssembly.Global({value:"i32",mutable:!0}),(t||GOT[n].value==0)&&(typeof r=="function"?GOT[n].value=addFunction(r):typeof r=="number"?GOT[n].value=r:err(`unhandled export type for '${n}': ${typeof r}`))}},"updateGOT"),relocateExports=S((e,t,n)=>{var r={};for(var s in e){var o=e[s];typeof o=="object"&&(o=o.value),typeof o=="number"&&(o+=t),r[s]=o}return updateGOT(r,n),r},"relocateExports"),isSymbolDefined=S(e=>{var t=wasmImports[e];return!(!t||t.stub)},"isSymbolDefined"),dynCall=S((e,t,n=[],r=!1)=>{var s=getWasmTableEntry(t),o=s(...n);function a(d){return d}return S(a,"convert"),o},"dynCall"),stackSave=S(()=>_emscripten_stack_get_current(),"stackSave"),stackRestore=S(e=>__emscripten_stack_restore(e),"stackRestore"),createInvokeFunction=S(e=>(t,...n)=>{var r=stackSave();try{return dynCall(e,t,n)}catch(s){if(stackRestore(r),s!==s+0)throw s;if(_setThrew(1,0),e[0]=="j")return 0n}},"createInvokeFunction"),resolveGlobalSymbol=S((e,t=!1)=>{var n;return isSymbolDefined(e)?n=wasmImports[e]:e.startsWith("invoke_")&&(n=wasmImports[e]=createInvokeFunction(e.split("_")[1])),{sym:n,name:e}},"resolveGlobalSymbol"),onPostCtors=[],addOnPostCtor=S(e=>onPostCtors.push(e),"addOnPostCtor"),UTF8ToString=S((e,t,n)=>e?UTF8ArrayToString(HEAPU8,e,t,n):"","UTF8ToString"),loadWebAssemblyModule=S((binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);function loadModule(){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;handle&&(HEAP8[handle+8]=1,LE_HEAP_STORE_U32((handle+12>>2)*4,memoryBase),LE_HEAP_STORE_I32((handle+16>>2)*4,metadata.memorySize),LE_HEAP_STORE_U32((handle+20>>2)*4,tableBase),LE_HEAP_STORE_I32((handle+24>>2)*4,metadata.tableSize)),metadata.tableSize&&wasmTable.grow(metadata.tableSize);var moduleExports;function resolveSymbol(e){var t=resolveGlobalSymbol(e).sym;return!t&&localScope&&(t=localScope[e]),t||(t=moduleExports[e]),t}S(resolveSymbol,"resolveSymbol");var proxyHandler={get(e,t){switch(t){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(t in wasmImports&&!wasmImports[t].stub){var n=wasmImports[t];return n}if(!(t in e)){var r;e[t]=(...s)=>(r||=resolveSymbol(t),r(...s))}return e[t]}},proxy=new Proxy({},proxyHandler);currentModuleWeakSymbols=metadata.weakImports;var info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),flags.allowUndefined||reportUndefinedSymbols();function addEmAsm(addr,body){for(var args=[],arity=0;arity<16&&body.indexOf("$"+arity)!=-1;arity++)args.push("$"+arity);args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if(S(addEmAsm,"addEmAsm"),"__start_em_asm"in moduleExports)for(var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;start<stop;){var jsString=UTF8ToString(start);addEmAsm(start,jsString),start=HEAPU8.indexOf(0,start)+1}function addEmJs(name,cSig,body){var jsArgs=[];if(cSig=cSig.slice(1,-1),cSig!="void"){cSig=cSig.split(",");for(var i in cSig){var jsArg=cSig[i].split(" ").pop();jsArgs.push(jsArg.replace("*",""))}}var func=`(${jsArgs}) => ${body};`;moduleExports[name]=eval(func)}S(addEmJs,"addEmJs");for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;applyRelocs&&(runtimeInitialized?applyRelocs():__RELOC_FUNCS__.push(applyRelocs));var init=moduleExports.__wasm_call_ctors;return init&&(runtimeInitialized?init():addOnPostCtor(init)),moduleExports}if(S(postInstantiation,"postInstantiation"),flags.loadAsync)return(async()=>{var e;return binary instanceof WebAssembly.Module?e=new WebAssembly.Instance(binary,info):{module:binary,instance:e}=await WebAssembly.instantiate(binary,info),postInstantiation(binary,e)})();var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}return S(loadModule,"loadModule"),flags={...flags,rpath:{parentLibPath:libName,paths:metadata.runtimePaths}},flags.loadAsync?metadata.neededDynlibs.reduce((e,t)=>e.then(()=>loadDynamicLibrary(t,flags,localScope)),Promise.resolve()).then(loadModule):(metadata.neededDynlibs.forEach(e=>loadDynamicLibrary(e,flags,localScope)),loadModule())},"loadWebAssemblyModule"),mergeLibSymbols=S((e,t)=>{for(var[n,r]of Object.entries(e)){let s=S(a=>{isSymbolDefined(a)||(wasmImports[a]=r)},"setImport");s(n);let o="__main_argc_argv";n=="main"&&s(o),n==o&&s("main")}},"mergeLibSymbols"),asyncLoad=S(async e=>{var t=await readAsync(e);return new Uint8Array(t)},"asyncLoad");function loadDynamicLibrary(e,t={global:!0,nodelete:!0},n,r){var s=LDSO.loadedLibsByName[e];if(s)return t.global?s.global||(s.global=!0,mergeLibSymbols(s.exports,e)):n&&Object.assign(n,s.exports),t.nodelete&&s.refcount!==1/0&&(s.refcount=1/0),s.refcount++,r&&(LDSO.loadedLibsByHandle[r]=s),t.loadAsync?Promise.resolve(!0):!0;s=newDSO(e,r,"loading"),s.refcount=t.nodelete?1/0:1,s.global=t.global;function o(){if(r){var l=LE_HEAP_LOAD_U32((r+28>>2)*4),c=LE_HEAP_LOAD_U32((r+32>>2)*4);if(l&&c){var u=HEAP8.slice(l,l+c);return t.loadAsync?Promise.resolve(u):u}}var p=locateFile(e);if(t.loadAsync)return asyncLoad(p);if(!readBinary)throw new Error(`${p}: file not found, and synchronous loading of external files is not available`);return readBinary(p)}S(o,"loadLibData");function a(){return t.loadAsync?o().then(l=>loadWebAssemblyModule(l,t,e,n,r)):loadWebAssemblyModule(o(),t,e,n,r)}S(a,"getExports");function d(l){s.global?mergeLibSymbols(l,e):n&&Object.assign(n,l),s.exports=l}return S(d,"moduleLoaded"),t.loadAsync?a().then(l=>(d(l),!0)):(d(a()),!0)}S(loadDynamicLibrary,"loadDynamicLibrary");var reportUndefinedSymbols=S(()=>{for(var[e,t]of Object.entries(GOT))if(t.value==0){var n=resolveGlobalSymbol(e,!0).sym;if(!n&&!t.required)continue;if(typeof n=="function")t.value=addFunction(n,n.sig);else if(typeof n=="number")t.value=n;else throw new Error(`bad export type for '${e}': ${typeof n}`)}},"reportUndefinedSymbols"),runDependencies=0,dependenciesFulfilled=null,removeRunDependency=S(e=>{if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0&&dependenciesFulfilled){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}},"removeRunDependency"),addRunDependency=S(e=>{runDependencies++,Module.monitorRunDependencies?.(runDependencies)},"addRunDependency"),loadDylibs=S(async()=>{if(!dynamicLibraries.length){reportUndefinedSymbols();return}addRunDependency("loadDylibs");for(var e of dynamicLibraries)await loadDynamicLibrary(e,{loadAsync:!0,global:!0,nodelete:!0,allowUndefined:!0});reportUndefinedSymbols(),removeRunDependency("loadDylibs")},"loadDylibs"),noExitRuntime=!0;function setValue(e,t,n="i8"){switch(n.endsWith("*")&&(n="*"),n){case"i1":HEAP8[e]=t;break;case"i8":HEAP8[e]=t;break;case"i16":LE_HEAP_STORE_I16((e>>1)*2,t);break;case"i32":LE_HEAP_STORE_I32((e>>2)*4,t);break;case"i64":LE_HEAP_STORE_I64((e>>3)*8,BigInt(t));break;case"float":LE_HEAP_STORE_F32((e>>2)*4,t);break;case"double":LE_HEAP_STORE_F64((e>>3)*8,t);break;case"*":LE_HEAP_STORE_U32((e>>2)*4,t);break;default:abort(`invalid type for setValue: ${n}`)}}S(setValue,"setValue");var ___memory_base=new WebAssembly.Global({value:"i32",mutable:!1},1024),___stack_high=82240,___stack_low=16704,___stack_pointer=new WebAssembly.Global({value:"i32",mutable:!0},82240),___table_base=new WebAssembly.Global({value:"i32",mutable:!1},1),__abort_js=S(()=>abort(""),"__abort_js");__abort_js.sig="v";var getHeapMax=S(()=>2147483648,"getHeapMax"),growMemory=S(e=>{var t=wasmMemory.buffer.byteLength,n=(e-t+65535)/65536|0;try{return wasmMemory.grow(n),updateMemoryViews(),1}catch{}},"growMemory"),_emscripten_resize_heap=S(e=>{var t=HEAPU8.length;e>>>=0;var n=getHeapMax();if(e>n)return!1;for(var r=1;r<=4;r*=2){var s=t*(1+.2/r);s=Math.min(s,e+100663296);var o=Math.min(n,alignMemory(Math.max(e,s),65536)),a=growMemory(o);if(a)return!0}return!1},"_emscripten_resize_heap");_emscripten_resize_heap.sig="ip";var _fd_close=S(e=>52,"_fd_close");_fd_close.sig="ii";var INT53_MAX=9007199254740992,INT53_MIN=-9007199254740992,bigintToI53Checked=S(e=>e<INT53_MIN||e>INT53_MAX?NaN:Number(e),"bigintToI53Checked");function _fd_seek(e,t,n,r){return t=bigintToI53Checked(t),70}S(_fd_seek,"_fd_seek"),_fd_seek.sig="iijip";var printCharBuffers=[null,[],[]],printChar=S((e,t)=>{var n=printCharBuffers[e];t===0||t===10?((e===1?out:err)(UTF8ArrayToString(n)),n.length=0):n.push(t)},"printChar"),_fd_write=S((e,t,n,r)=>{for(var s=0,o=0;o<n;o++){var a=LE_HEAP_LOAD_U32((t>>2)*4),d=LE_HEAP_LOAD_U32((t+4>>2)*4);t+=8;for(var l=0;l<d;l++)printChar(e,HEAPU8[a+l]);s+=d}return LE_HEAP_STORE_U32((r>>2)*4,s),0},"_fd_write");_fd_write.sig="iippp";function _tree_sitter_log_callback(e,t){if(Module.currentLogCallback){let n=UTF8ToString(t);Module.currentLogCallback(n,e!==0)}}S(_tree_sitter_log_callback,"_tree_sitter_log_callback");function _tree_sitter_parse_callback(e,t,n,r,s){let a=Module.currentParseCallback(t,{row:n,column:r});typeof a=="string"?(setValue(s,a.length,"i32"),stringToUTF16(a,e,10240)):setValue(s,0,"i32")}S(_tree_sitter_parse_callback,"_tree_sitter_parse_callback");function _tree_sitter_progress_callback(e,t){return Module.currentProgressCallback?Module.currentProgressCallback({currentOffset:e,hasError:t}):!1}S(_tree_sitter_progress_callback,"_tree_sitter_progress_callback");function _tree_sitter_query_progress_callback(e){return Module.currentQueryProgressCallback?Module.currentQueryProgressCallback({currentOffset:e}):!1}S(_tree_sitter_query_progress_callback,"_tree_sitter_query_progress_callback");var runtimeKeepaliveCounter=0,keepRuntimeAlive=S(()=>noExitRuntime||runtimeKeepaliveCounter>0,"keepRuntimeAlive"),_proc_exit=S(e=>{EXITSTATUS=e,keepRuntimeAlive()||(Module.onExit?.(e),ABORT=!0),quit_(e,new ExitStatus(e))},"_proc_exit");_proc_exit.sig="vi";var exitJS=S((e,t)=>{EXITSTATUS=e,_proc_exit(e)},"exitJS"),handleException=S(e=>{if(e instanceof ExitStatus||e=="unwind")return EXITSTATUS;quit_(1,e)},"handleException"),lengthBytesUTF8=S(e=>{for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);r<=127?t++:r<=2047?t+=2:r>=55296&&r<=57343?(t+=4,++n):t+=3}return t},"lengthBytesUTF8"),stringToUTF8Array=S((e,t,n,r)=>{if(!(r>0))return 0;for(var s=n,o=n+r-1,a=0;a<e.length;++a){var d=e.codePointAt(a);if(d<=127){if(n>=o)break;t[n++]=d}else if(d<=2047){if(n+1>=o)break;t[n++]=192|d>>6,t[n++]=128|d&63}else if(d<=65535){if(n+2>=o)break;t[n++]=224|d>>12,t[n++]=128|d>>6&63,t[n++]=128|d&63}else{if(n+3>=o)break;t[n++]=240|d>>18,t[n++]=128|d>>12&63,t[n++]=128|d>>6&63,t[n++]=128|d&63,a++}}return t[n]=0,n-s},"stringToUTF8Array"),stringToUTF8=S((e,t,n)=>stringToUTF8Array(e,HEAPU8,t,n),"stringToUTF8"),stackAlloc=S(e=>__emscripten_stack_alloc(e),"stackAlloc"),stringToUTF8OnStack=S(e=>{var t=lengthBytesUTF8(e)+1,n=stackAlloc(t);return stringToUTF8(e,n,t),n},"stringToUTF8OnStack"),AsciiToString=S(e=>{for(var t="";;){var n=HEAPU8[e++];if(!n)return t;t+=String.fromCharCode(n)}},"AsciiToString"),stringToUTF16=S((e,t,n)=>{if(n??=2147483647,n<2)return 0;n-=2;for(var r=t,s=n<e.length*2?n/2:e.length,o=0;o<s;++o){var a=e.charCodeAt(o);LE_HEAP_STORE_I16((t>>1)*2,a),t+=2}return LE_HEAP_STORE_I16((t>>1)*2,0),t-r},"stringToUTF16");LE_ATOMICS_NATIVE_BYTE_ORDER=new Int8Array(new Int16Array([1]).buffer)[0]===1?[(e=>e),(e=>e),void 0,(e=>e)]:[(e=>e),(e=>((e&65280)<<8|(e&255)<<24)>>16),void 0,(e=>e>>24&255|e>>8&65280|(e&65280)<<8|(e&255)<<24)];function LE_HEAP_UPDATE(){HEAPU16.unsigned=(e=>e&65535),HEAPU32.unsigned=(e=>e>>>0)}if(S(LE_HEAP_UPDATE,"LE_HEAP_UPDATE"),initMemory(),Module.noExitRuntime&&(noExitRuntime=Module.noExitRuntime),Module.print&&(out=Module.print),Module.printErr&&(err=Module.printErr),Module.dynamicLibraries&&(dynamicLibraries=Module.dynamicLibraries),Module.wasmBinary&&(wasmBinary=Module.wasmBinary),Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.preInit)for(typeof Module.preInit=="function"&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.shift()();Module.setValue=setValue,Module.getValue=getValue,Module.UTF8ToString=UTF8ToString,Module.stringToUTF8=stringToUTF8,Module.lengthBytesUTF8=lengthBytesUTF8,Module.AsciiToString=AsciiToString,Module.stringToUTF16=stringToUTF16,Module.loadWebAssemblyModule=loadWebAssemblyModule,Module.LE_HEAP_STORE_I64=LE_HEAP_STORE_I64;var ASM_CONSTS={},_malloc,_calloc,_realloc,_free,_ts_range_edit,_memcmp,_ts_language_symbol_count,_ts_language_state_count,_ts_language_abi_version,_ts_language_name,_ts_language_field_count,_ts_language_next_state,_ts_language_symbol_name,_ts_language_symbol_for_name,_strncmp,_ts_language_symbol_type,_ts_language_field_name_for_id,_ts_lookahead_iterator_new,_ts_lookahead_iterator_delete,_ts_lookahead_iterator_reset_state,_ts_lookahead_iterator_reset,_ts_lookahead_iterator_next,_ts_lookahead_iterator_current_symbol,_ts_point_edit,_ts_parser_delete,_ts_parser_reset,_ts_parser_set_language,_ts_parser_set_included_ranges,_ts_query_new,_ts_query_delete,_iswspace,_iswalnum,_ts_query_copy,_ts_query_pattern_count,_ts_query_capture_count,_ts_query_string_count,_ts_query_capture_name_for_id,_ts_query_capture_quantifier_for_id,_ts_query_string_value_for_id,_ts_query_predicates_for_pattern,_ts_query_start_byte_for_pattern,_ts_query_end_byte_for_pattern,_ts_query_is_pattern_rooted,_ts_query_is_pattern_non_local,_ts_query_is_pattern_guaranteed_at_step,_ts_query_disable_capture,_ts_query_disable_pattern,_ts_tree_copy,_ts_tree_delete,_ts_init,_ts_parser_new_wasm,_ts_parser_enable_logger_wasm,_ts_parser_parse_wasm,_ts_parser_included_ranges_wasm,_ts_language_type_is_named_wasm,_ts_language_type_is_visible_wasm,_ts_language_metadata_wasm,_ts_language_supertypes_wasm,_ts_language_subtypes_wasm,_ts_tree_root_node_wasm,_ts_tree_root_node_with_offset_wasm,_ts_tree_edit_wasm,_ts_tree_included_ranges_wasm,_ts_tree_get_changed_ranges_wasm,_ts_tree_cursor_new_wasm,_ts_tree_cursor_copy_wasm,_ts_tree_cursor_delete_wasm,_ts_tree_cursor_reset_wasm,_ts_tree_cursor_reset_to_wasm,_ts_tree_cursor_goto_first_child_wasm,_ts_tree_cursor_goto_last_child_wasm,_ts_tree_cursor_goto_first_child_for_index_wasm,_ts_tree_cursor_goto_first_child_for_position_wasm,_ts_tree_cursor_goto_next_sibling_wasm,_ts_tree_cursor_goto_previous_sibling_wasm,_ts_tree_cursor_goto_descendant_wasm,_ts_tree_cursor_goto_parent_wasm,_ts_tree_cursor_current_node_type_id_wasm,_ts_tree_cursor_current_node_state_id_wasm,_ts_tree_cursor_current_node_is_named_wasm,_ts_tree_cursor_current_node_is_missing_wasm,_ts_tree_cursor_current_node_id_wasm,_ts_tree_cursor_start_position_wasm,_ts_tree_cursor_end_position_wasm,_ts_tree_cursor_start_index_wasm,_ts_tree_cursor_end_index_wasm,_ts_tree_cursor_current_field_id_wasm,_ts_tree_cursor_current_depth_wasm,_ts_tree_cursor_current_descendant_index_wasm,_ts_tree_cursor_current_node_wasm,_ts_node_symbol_wasm,_ts_node_field_name_for_child_wasm,_ts_node_field_name_for_named_child_wasm,_ts_node_children_by_field_id_wasm,_ts_node_first_child_for_byte_wasm,_ts_node_first_named_child_for_byte_wasm,_ts_node_grammar_symbol_wasm,_ts_node_child_count_wasm,_ts_node_named_child_count_wasm,_ts_node_child_wasm,_ts_node_named_child_wasm,_ts_node_child_by_field_id_wasm,_ts_node_next_sibling_wasm,_ts_node_prev_sibling_wasm,_ts_node_next_named_sibling_wasm,_ts_node_prev_named_sibling_wasm,_ts_node_descendant_count_wasm,_ts_node_parent_wasm,_ts_node_child_with_descendant_wasm,_ts_node_descendant_for_index_wasm,_ts_node_named_descendant_for_index_wasm,_ts_node_descendant_for_position_wasm,_ts_node_named_descendant_for_position_wasm,_ts_node_start_point_wasm,_ts_node_end_point_wasm,_ts_node_start_index_wasm,_ts_node_end_index_wasm,_ts_node_to_string_wasm,_ts_node_children_wasm,_ts_node_named_children_wasm,_ts_node_descendants_of_type_wasm,_ts_node_is_named_wasm,_ts_node_has_changes_wasm,_ts_node_has_error_wasm,_ts_node_is_error_wasm,_ts_node_is_missing_wasm,_ts_node_is_extra_wasm,_ts_node_parse_state_wasm,_ts_node_next_parse_state_wasm,_ts_query_matches_wasm,_ts_query_captures_wasm,_memset,_memcpy,_memmove,_iswalpha,_iswblank,_iswdigit,_iswlower,_iswpunct,_iswupper,_iswxdigit,_memchr,_strlen,_strcmp,_strncat,_strncpy,_towlower,_towupper,_setThrew,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,___wasm_apply_data_relocs;function assignWasmExports(e){Module._malloc=_malloc=e.malloc,Module._calloc=_calloc=e.calloc,Module._realloc=_realloc=e.realloc,Module._free=_free=e.free,Module._ts_range_edit=_ts_range_edit=e.ts_range_edit,Module._memcmp=_memcmp=e.memcmp,Module._ts_language_symbol_count=_ts_language_symbol_count=e.ts_language_symbol_count,Module._ts_language_state_count=_ts_language_state_count=e.ts_language_state_count,Module._ts_language_abi_version=_ts_language_abi_version=e.ts_language_abi_version,Module._ts_language_name=_ts_language_name=e.ts_language_name,Module._ts_language_field_count=_ts_language_field_count=e.ts_language_field_count,Module._ts_language_next_state=_ts_language_next_state=e.ts_language_next_state,Module._ts_language_symbol_name=_ts_language_symbol_name=e.ts_language_symbol_name,Module._ts_language_symbol_for_name=_ts_language_symbol_for_name=e.ts_language_symbol_for_name,Module._strncmp=_strncmp=e.strncmp,Module._ts_language_symbol_type=_ts_language_symbol_type=e.ts_language_symbol_type,Module._ts_language_field_name_for_id=_ts_language_field_name_for_id=e.ts_language_field_name_for_id,Module._ts_lookahead_iterator_new=_ts_lookahead_iterator_new=e.ts_lookahead_iterator_new,Module._ts_lookahead_iterator_delete=_ts_lookahead_iterator_delete=e.ts_lookahead_iterator_delete,Module._ts_lookahead_iterator_reset_state=_ts_lookahead_iterator_reset_state=e.ts_lookahead_iterator_reset_state,Module._ts_lookahead_iterator_reset=_ts_lookahead_iterator_reset=e.ts_lookahead_iterator_reset,Module._ts_lookahead_iterator_next=_ts_lookahead_iterator_next=e.ts_lookahead_iterator_next,Module._ts_lookahead_iterator_current_symbol=_ts_lookahead_iterator_current_symbol=e.ts_lookahead_iterator_current_symbol,Module._ts_point_edit=_ts_point_edit=e.ts_point_edit,Module._ts_parser_delete=_ts_parser_delete=e.ts_parser_delete,Module._ts_parser_reset=_ts_parser_reset=e.ts_parser_reset,Module._ts_parser_set_language=_ts_parser_set_language=e.ts_parser_set_language,Module._ts_parser_set_included_ranges=_ts_parser_set_included_ranges=e.ts_parser_set_included_ranges,Module._ts_query_new=_ts_query_new=e.ts_query_new,Module._ts_query_delete=_ts_query_delete=e.ts_query_delete,Module._iswspace=_iswspace=e.iswspace,Module._iswalnum=_iswalnum=e.iswalnum,Module._ts_query_copy=_ts_query_copy=e.ts_query_copy,Module._ts_query_pattern_count=_ts_query_pattern_count=e.ts_query_pattern_count,Module._ts_query_capture_count=_ts_query_capture_count=e.ts_query_capture_count,Module._ts_query_string_count=_ts_query_string_count=e.ts_query_string_count,Module._ts_query_capture_name_for_id=_ts_query_capture_name_for_id=e.ts_query_capture_name_for_id,Module._ts_query_capture_quantifier_for_id=_ts_query_capture_quantifier_for_id=e.ts_query_capture_quantifier_for_id,Module._ts_query_string_value_for_id=_ts_query_string_value_for_id=e.ts_query_string_value_for_id,Module._ts_query_predicates_for_pattern=_ts_query_predicates_for_pattern=e.ts_query_predicates_for_pattern,Module._ts_query_start_byte_for_pattern=_ts_query_start_byte_for_pattern=e.ts_query_start_byte_for_pattern,Module._ts_query_end_byte_for_pattern=_ts_query_end_byte_for_pattern=e.ts_query_end_byte_for_pattern,Module._ts_query_is_pattern_rooted=_ts_query_is_pattern_rooted=e.ts_query_is_pattern_rooted,Module._ts_query_is_pattern_non_local=_ts_query_is_pattern_non_local=e.ts_query_is_pattern_non_local,Module._ts_query_is_pattern_guaranteed_at_step=_ts_query_is_pattern_guaranteed_at_step=e.ts_query_is_pattern_guaranteed_at_step,Module._ts_query_disable_capture=_ts_query_disable_capture=e.ts_query_disable_capture,Module._ts_query_disable_pattern=_ts_query_disable_pattern=e.ts_query_disable_pattern,Module._ts_tree_copy=_ts_tree_copy=e.ts_tree_copy,Module._ts_tree_delete=_ts_tree_delete=e.ts_tree_delete,Module._ts_init=_ts_init=e.ts_init,Module._ts_parser_new_wasm=_ts_parser_new_wasm=e.ts_parser_new_wasm,Module._ts_parser_enable_logger_wasm=_ts_parser_enable_logger_wasm=e.ts_parser_enable_logger_wasm,Module._ts_parser_parse_wasm=_ts_parser_parse_wasm=e.ts_parser_parse_wasm,Module._ts_parser_included_ranges_wasm=_ts_parser_included_ranges_wasm=e.ts_parser_included_ranges_wasm,Module._ts_language_type_is_named_wasm=_ts_language_type_is_named_wasm=e.ts_language_type_is_named_wasm,Module._ts_language_type_is_visible_wasm=_ts_language_type_is_visible_wasm=e.ts_language_type_is_visible_wasm,Module._ts_language_metadata_wasm=_ts_language_metadata_wasm=e.ts_language_metadata_wasm,Module._ts_language_supertypes_wasm=_ts_language_supertypes_wasm=e.ts_language_supertypes_wasm,Module._ts_language_subtypes_wasm=_ts_language_subtypes_wasm=e.ts_language_subtypes_wasm,Module._ts_tree_root_node_wasm=_ts_tree_root_node_wasm=e.ts_tree_root_node_wasm,Module._ts_tree_root_node_with_offset_wasm=_ts_tree_root_node_with_offset_wasm=e.ts_tree_root_node_with_offset_wasm,Module._ts_tree_edit_wasm=_ts_tree_edit_wasm=e.ts_tree_edit_wasm,Module._ts_tree_included_ranges_wasm=_ts_tree_included_ranges_wasm=e.ts_tree_included_ranges_wasm,Module._ts_tree_get_changed_ranges_wasm=_ts_tree_get_changed_ranges_wasm=e.ts_tree_get_changed_ranges_wasm,Module._ts_tree_cursor_new_wasm=_ts_tree_cursor_new_wasm=e.ts_tree_cursor_new_wasm,Module._ts_tree_cursor_copy_wasm=_ts_tree_cursor_copy_wasm=e.ts_tree_cursor_copy_wasm,Module._ts_tree_cursor_delete_wasm=_ts_tree_cursor_delete_wasm=e.ts_tree_cursor_delete_wasm,Module._ts_tree_cursor_reset_wasm=_ts_tree_cursor_reset_wasm=e.ts_tree_cursor_reset_wasm,Module._ts_tree_cursor_reset_to_wasm=_ts_tree_cursor_reset_to_wasm=e.ts_tree_cursor_reset_to_wasm,Module._ts_tree_cursor_goto_first_child_wasm=_ts_tree_cursor_goto_first_child_wasm=e.ts_tree_cursor_goto_first_child_wasm,Module._ts_tree_cursor_goto_last_child_wasm=_ts_tree_cursor_goto_last_child_wasm=e.ts_tree_cursor_goto_last_child_wasm,Module._ts_tree_cursor_goto_first_child_for_index_wasm=_ts_tree_cursor_goto_first_child_for_index_wasm=e.ts_tree_cursor_goto_first_child_for_index_wasm,Module._ts_tree_cursor_goto_first_child_for_position_wasm=_ts_tree_cursor_goto_first_child_for_position_wasm=e.ts_tree_cursor_goto_first_child_for_position_wasm,Module._ts_tree_cursor_goto_next_sibling_wasm=_ts_tree_cursor_goto_next_sibling_wasm=e.ts_tree_cursor_goto_next_sibling_wasm,Module._ts_tree_cursor_goto_previous_sibling_wasm=_ts_tree_cursor_goto_previous_sibling_wasm=e.ts_tree_cursor_goto_previous_sibling_wasm,Module._ts_tree_cursor_goto_descendant_wasm=_ts_tree_cursor_goto_descendant_wasm=e.ts_tree_cursor_goto_descendant_wasm,Module._ts_tree_cursor_goto_parent_wasm=_ts_tree_cursor_goto_parent_wasm=e.ts_tree_cursor_goto_parent_wasm,Module._ts_tree_cursor_current_node_type_id_wasm=_ts_tree_cursor_current_node_type_id_wasm=e.ts_tree_cursor_current_node_type_id_wasm,Module._ts_tree_cursor_current_node_state_id_wasm=_ts_tree_cursor_current_node_state_id_wasm=e.ts_tree_cursor_current_node_state_id_wasm,Module._ts_tree_cursor_current_node_is_named_wasm=_ts_tree_cursor_current_node_is_named_wasm=e.ts_tree_cursor_current_node_is_named_wasm,Module._ts_tree_cursor_current_node_is_missing_wasm=_ts_tree_cursor_current_node_is_missing_wasm=e.ts_tree_cursor_current_node_is_missing_wasm,Module._ts_tree_cursor_current_node_id_wasm=_ts_tree_cursor_current_node_id_wasm=e.ts_tree_cursor_current_node_id_wasm,Module._ts_tree_cursor_start_position_wasm=_ts_tree_cursor_start_position_wasm=e.ts_tree_cursor_start_position_wasm,Module._ts_tree_cursor_end_position_wasm=_ts_tree_cursor_end_position_wasm=e.ts_tree_cursor_end_position_wasm,Module._ts_tree_cursor_start_index_wasm=_ts_tree_cursor_start_index_wasm=e.ts_tree_cursor_start_index_wasm,Module._ts_tree_cursor_end_index_wasm=_ts_tree_cursor_end_index_wasm=e.ts_tree_cursor_end_index_wasm,Module._ts_tree_cursor_current_field_id_wasm=_ts_tree_cursor_current_field_id_wasm=e.ts_tree_cursor_current_field_id_wasm,Module._ts_tree_cursor_current_depth_wasm=_ts_tree_cursor_current_depth_wasm=e.ts_tree_cursor_current_depth_wasm,Module._ts_tree_cursor_current_descendant_index_wasm=_ts_tree_cursor_current_descendant_index_wasm=e.ts_tree_cursor_current_descendant_index_wasm,Module._ts_tree_cursor_current_node_wasm=_ts_tree_cursor_current_node_wasm=e.ts_tree_cursor_current_node_wasm,Module._ts_node_symbol_wasm=_ts_node_symbol_wasm=e.ts_node_symbol_wasm,Module._ts_node_field_name_for_child_wasm=_ts_node_field_name_for_child_wasm=e.ts_node_field_name_for_child_wasm,Module._ts_node_field_name_for_named_child_wasm=_ts_node_field_name_for_named_child_wasm=e.ts_node_field_name_for_named_child_wasm,Module._ts_node_children_by_field_id_wasm=_ts_node_children_by_field_id_wasm=e.ts_node_children_by_field_id_wasm,Module._ts_node_first_child_for_byte_wasm=_ts_node_first_child_for_byte_wasm=e.ts_node_first_child_for_byte_wasm,Module._ts_node_first_named_child_for_byte_wasm=_ts_node_first_named_child_for_byte_wasm=e.ts_node_first_named_child_for_byte_wasm,Module._ts_node_grammar_symbol_wasm=_ts_node_grammar_symbol_wasm=e.ts_node_grammar_symbol_wasm,Module._ts_node_child_count_wasm=_ts_node_child_count_wasm=e.ts_node_child_count_wasm,Module._ts_node_named_child_count_wasm=_ts_node_named_child_count_wasm=e.ts_node_named_child_count_wasm,Module._ts_node_child_wasm=_ts_node_child_wasm=e.ts_node_child_wasm,Module._ts_node_named_child_wasm=_ts_node_named_child_wasm=e.ts_node_named_child_wasm,Module._ts_node_child_by_field_id_wasm=_ts_node_child_by_field_id_wasm=e.ts_node_child_by_field_id_wasm,Module._ts_node_next_sibling_wasm=_ts_node_next_sibling_wasm=e.ts_node_next_sibling_wasm,Module._ts_node_prev_sibling_wasm=_ts_node_prev_sibling_wasm=e.ts_node_prev_sibling_wasm,Module._ts_node_next_named_sibling_wasm=_ts_node_next_named_sibling_wasm=e.ts_node_next_named_sibling_wasm,Module._ts_node_prev_named_sibling_wasm=_ts_node_prev_named_sibling_wasm=e.ts_node_prev_named_sibling_wasm,Module._ts_node_descendant_count_wasm=_ts_node_descendant_count_wasm=e.ts_node_descendant_count_wasm,Module._ts_node_parent_wasm=_ts_node_parent_wasm=e.ts_node_parent_wasm,Module._ts_node_child_with_descendant_wasm=_ts_node_child_with_descendant_wasm=e.ts_node_child_with_descendant_wasm,Module._ts_node_descendant_for_index_wasm=_ts_node_descendant_for_index_wasm=e.ts_node_descendant_for_index_wasm,Module._ts_node_named_descendant_for_index_wasm=_ts_node_named_descendant_for_index_wasm=e.ts_node_named_descendant_for_index_wasm,Module._ts_node_descendant_for_position_wasm=_ts_node_descendant_for_position_wasm=e.ts_node_descendant_for_position_wasm,Module._ts_node_named_descendant_for_position_wasm=_ts_node_named_descendant_for_position_wasm=e.ts_node_named_descendant_for_position_wasm,Module._ts_node_start_point_wasm=_ts_node_start_point_wasm=e.ts_node_start_point_wasm,Module._ts_node_end_point_wasm=_ts_node_end_point_wasm=e.ts_node_end_point_wasm,Module._ts_node_start_index_wasm=_ts_node_start_index_wasm=e.ts_node_start_index_wasm,Module._ts_node_end_index_wasm=_ts_node_end_index_wasm=e.ts_node_end_index_wasm,Module._ts_node_to_string_wasm=_ts_node_to_string_wasm=e.ts_node_to_string_wasm,Module._ts_node_children_wasm=_ts_node_children_wasm=e.ts_node_children_wasm,Module._ts_node_named_children_wasm=_ts_node_named_children_wasm=e.ts_node_named_children_wasm,Module._ts_node_descendants_of_type_wasm=_ts_node_descendants_of_type_wasm=e.ts_node_descendants_of_type_wasm,Module._ts_node_is_named_wasm=_ts_node_is_named_wasm=e.ts_node_is_named_wasm,Module._ts_node_has_changes_wasm=_ts_node_has_changes_wasm=e.ts_node_has_changes_wasm,Module._ts_node_has_error_wasm=_ts_node_has_error_wasm=e.ts_node_has_error_wasm,Module._ts_node_is_error_wasm=_ts_node_is_error_wasm=e.ts_node_is_error_wasm,Module._ts_node_is_missing_wasm=_ts_node_is_missing_wasm=e.ts_node_is_missing_wasm,Module._ts_node_is_extra_wasm=_ts_node_is_extra_wasm=e.ts_node_is_extra_wasm,Module._ts_node_parse_state_wasm=_ts_node_parse_state_wasm=e.ts_node_parse_state_wasm,Module._ts_node_next_parse_state_wasm=_ts_node_next_parse_state_wasm=e.ts_node_next_parse_state_wasm,Module._ts_query_matches_wasm=_ts_query_matches_wasm=e.ts_query_matches_wasm,Module._ts_query_captures_wasm=_ts_query_captures_wasm=e.ts_query_captures_wasm,Module._memset=_memset=e.memset,Module._memcpy=_memcpy=e.memcpy,Module._memmove=_memmove=e.memmove,Module._iswalpha=_iswalpha=e.iswalpha,Module._iswblank=_iswblank=e.iswblank,Module._iswdigit=_iswdigit=e.iswdigit,Module._iswlower=_iswlower=e.iswlower,Module._iswpunct=_iswpunct=e.iswpunct,Module._iswupper=_iswupper=e.iswupper,Module._iswxdigit=_iswxdigit=e.iswxdigit,Module._memchr=_memchr=e.memchr,Module._strlen=_strlen=e.strlen,Module._strcmp=_strcmp=e.strcmp,Module._strncat=_strncat=e.strncat,Module._strncpy=_strncpy=e.strncpy,Module._towlower=_towlower=e.towlower,Module._towupper=_towupper=e.towupper,_setThrew=e.setThrew,__emscripten_stack_restore=e._emscripten_stack_restore,__emscripten_stack_alloc=e._emscripten_stack_alloc,_emscripten_stack_get_current=e.emscripten_stack_get_current,___wasm_apply_data_relocs=e.__wasm_apply_data_relocs}S(assignWasmExports,"assignWasmExports");var wasmImports={__heap_base:___heap_base,__indirect_function_table:wasmTable,__memory_base:___memory_base,__stack_high:___stack_high,__stack_low:___stack_low,__stack_pointer:___stack_pointer,__table_base:___table_base,_abort_js:__abort_js,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,memory:wasmMemory,tree_sitter_log_callback:_tree_sitter_log_callback,tree_sitter_parse_callback:_tree_sitter_parse_callback,tree_sitter_progress_callback:_tree_sitter_progress_callback,tree_sitter_query_progress_callback:_tree_sitter_query_progress_callback};function callMain(e=[]){var t=resolveGlobalSymbol("main").sym;if(t){e.unshift(thisProgram);var n=e.length,r=stackAlloc((n+1)*4),s=r;e.forEach(a=>{LE_HEAP_STORE_U32((s>>2)*4,stringToUTF8OnStack(a)),s+=4}),LE_HEAP_STORE_U32((s>>2)*4,0);try{var o=t(n,r);return exitJS(o,!0),o}catch(a){return handleException(a)}}}S(callMain,"callMain");function run(e=arguments_){if(runDependencies>0){dependenciesFulfilled=run;return}if(preRun(),runDependencies>0){dependenciesFulfilled=run;return}function t(){if(Module.calledRun=!0,!ABORT){initRuntime(),readyPromiseResolve?.(Module),Module.onRuntimeInitialized?.();var n=Module.noInitialRun||!1;n||callMain(e),postRun()}}S(t,"doRun"),Module.setStatus?(Module.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>Module.setStatus(""),1),t()},1)):t()}S(run,"run");var wasmExports;return wasmExports=await createWasm(),run(),runtimeInitialized?moduleRtn=Module:moduleRtn=new Promise((e,t)=>{readyPromiseResolve=e,readyPromiseReject=t}),moduleRtn}S(jk,"Module");var _$=jk,Bk=null;async function Vk(e){return Bk??=await _$(e)}S(Vk,"initializeBinding");function Uk(){return!!Bk}S(Uk,"checkModule");var W,am,dm,Ck=Rs(e=>{k._ts_parser_delete(e[0]),k._free(e[1])}),fm=class{static{S(this,"Parser")}0=0;1=0;logCallback=null;language=null;static async init(e){$k(await Vk(e)),W=k._ts_init(),am=k.getValue(W,"i32"),dm=k.getValue(W+J,"i32")}constructor(){this.initialize(),Ck?.register(this,[this[0],this[1]],this)}initialize(){if(!Uk())throw new Error("cannot construct a Parser before calling `init()`");k._ts_parser_new_wasm(),this[0]=k.getValue(W,"i32"),this[1]=k.getValue(W+J,"i32")}delete(){Ck?.unregister(this),k._ts_parser_delete(this[0]),k._free(this[1]),this[0]=0,this[1]=0}setLanguage(e){let t;if(!e)t=0,this.language=null;else if(e.constructor===pm){t=e[0];let n=k._ts_language_abi_version(t);if(n<dm||am<n)throw new Error(`Incompatible language version ${n}. Compatibility range ${dm} through ${am}.`);this.language=e}else throw new Error("Argument must be a Language");return k._ts_parser_set_language(this[0],t),this}parse(e,t,n){if(typeof e=="string")k.currentParseCallback=d=>e.slice(d);else if(typeof e=="function")k.currentParseCallback=e;else throw new Error("Argument must be a string or a function");n?.progressCallback?k.currentProgressCallback=n.progressCallback:k.currentProgressCallback=null,this.logCallback?(k.currentLogCallback=this.logCallback,k._ts_parser_enable_logger_wasm(this[0],1)):(k.currentLogCallback=null,k._ts_parser_enable_logger_wasm(this[0],0));let r=0,s=0;if(n?.includedRanges){r=n.includedRanges.length,s=k._calloc(r,ca);let d=s;for(let l=0;l<r;l++)Lk(d,n.includedRanges[l]),d+=ca}let o=k._ts_parser_parse_wasm(this[0],this[1],t?t[0]:0,s,r);if(!o)return k.currentParseCallback=null,k.currentLogCallback=null,k.currentProgressCallback=null,null;if(!this.language)throw new Error("Parser must have a language to parse");let a=new v$(kr,o,this.language,k.currentParseCallback);return k.currentParseCallback=null,k.currentLogCallback=null,k.currentProgressCallback=null,a}reset(){k._ts_parser_reset(this[0])}getIncludedRanges(){k._ts_parser_included_ranges_wasm(this[0]);let e=k.getValue(W,"i32"),t=k.getValue(W+J,"i32"),n=new Array(e);if(e>0){let r=t;for(let s=0;s<e;s++)n[s]=jl(r),r+=ca;k._free(t)}return n}setLogger(e){if(!e)this.logCallback=null;else{if(typeof e!="function")throw new Error("Logger callback must be a function");this.logCallback=e}return this}getLogger(){return this.logCallback}},I$=1,S$=2,T$=/[\w-]+/g,fY={Zero:0,ZeroOrOne:1,ZeroOrMore:2,One:3,OneOrMore:4},Nk=S(e=>e.type==="capture","isCaptureStep"),mm=S(e=>e.type==="string","isStringStep"),en={Syntax:1,NodeName:2,FieldName:3,CaptureName:4,PatternStructure:5},da=class Hk extends Error{constructor(t,n,r,s){super(Hk.formatMessage(t,n)),this.kind=t,this.info=n,this.index=r,this.length=s,this.name="QueryError"}kind;info;index;length;static{S(this,"QueryError")}static formatMessage(t,n){switch(t){case en.NodeName:return`Bad node name '${n.word}'`;case en.FieldName:return`Bad field name '${n.word}'`;case en.CaptureName:return`Bad capture name @${n.word}`;case en.PatternStructure:return`Bad pattern structure at offset ${n.suffix}`;case en.Syntax:return`Bad syntax at offset ${n.suffix}`}}};function zk(e,t,n,r){if(e.length!==3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}`);if(!Nk(e[1]))throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}"`);let s=n==="eq?"||n==="any-eq?",o=!n.startsWith("any-");if(Nk(e[2])){let a=e[1].name,d=e[2].name;r[t].push(l=>{let c=[],u=[];for(let f of l)f.name===a&&c.push(f.node),f.name===d&&u.push(f.node);let p=S((f,m,h)=>h?f.text===m.text:f.text!==m.text,"compare");return o?c.every(f=>u.some(m=>p(f,m,s))):c.some(f=>u.some(m=>p(f,m,s)))})}else{let a=e[1].name,d=e[2].value,l=S(u=>u.text===d,"matches"),c=S(u=>u.text!==d,"doesNotMatch");r[t].push(u=>{let p=[];for(let m of u)m.name===a&&p.push(m.node);let f=s?l:c;return o?p.every(f):p.some(f)})}}S(zk,"parseAnyPredicate");function qk(e,t,n,r){if(e.length!==3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}.`);if(e[1].type!=="capture")throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);if(e[2].type!=="string")throw new Error(`Second argument of \`#${n}\` predicate must be a string. Got @${e[2].name}.`);let s=n==="match?"||n==="any-match?",o=!n.startsWith("any-"),a=e[1].name,d=new RegExp(e[2].value);r[t].push(l=>{let c=[];for(let p of l)p.name===a&&c.push(p.node.text);let u=S((p,f)=>f?d.test(p):!d.test(p),"test");return c.length===0?!s:o?c.every(p=>u(p,s)):c.some(p=>u(p,s))})}S(qk,"parseMatchPredicate");function Gk(e,t,n,r){if(e.length<2)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected at least 1. Got ${e.length-1}.`);if(e[1].type!=="capture")throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);let s=n==="any-of?",o=e[1].name,a=e.slice(2);if(!a.every(mm))throw new Error(`Arguments to \`#${n}\` predicate must be strings.".`);let d=a.map(l=>l.value);r[t].push(l=>{let c=[];for(let u of l)u.name===o&&c.push(u.node.text);return c.length===0?!s:c.every(u=>d.includes(u))===s})}S(Gk,"parseAnyOfPredicate");function Kk(e,t,n,r,s){if(e.length<2||e.length>3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(mm))throw new Error(`Arguments to \`#${n}\` predicate must be strings.".`);let o=n==="is?"?r:s;o[t]||(o[t]={}),o[t][e[1].value]=e[2]?.value??null}S(Kk,"parseIsPredicate");function Wk(e,t,n){if(e.length<2||e.length>3)throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(mm))throw new Error('Arguments to `#set!` predicate must be strings.".');n[t]||(n[t]={}),n[t][e[1].value]=e[2]?.value??null}S(Wk,"parseSetDirective");function Jk(e,t,n,r,s,o,a,d,l,c,u){if(t===I$){let p=r[n];o.push({type:"capture",name:p})}else if(t===S$)o.push({type:"string",value:s[n]});else if(o.length>0){if(o[0].type!=="string")throw new Error("Predicates must begin with a literal value");let p=o[0].value;switch(p){case"any-not-eq?":case"not-eq?":case"any-eq?":case"eq?":zk(o,e,p,a);break;case"any-not-match?":case"not-match?":case"any-match?":case"match?":qk(o,e,p,a);break;case"not-any-of?":case"any-of?":Gk(o,e,p,a);break;case"is?":case"is-not?":Kk(o,e,p,c,u);break;case"set!":Wk(o,e,l);break;default:d[e].push({operator:p,operands:o.slice(1)})}o.length=0}}S(Jk,"parsePattern");var Ok=Rs(e=>{k._ts_query_delete(e)}),mY=class{static{S(this,"Query")}0=0;exceededMatchLimit;textPredicates;captureNames;captureQuantifiers;predicates;setProperties;assertedProperties;refutedProperties;matchLimit;constructor(e,t){let n=k.lengthBytesUTF8(t),r=k._malloc(n+1);k.stringToUTF8(t,r,n+1);let s=k._ts_query_new(e[0],r,n,W,W+J);if(!s){let y=k.getValue(W+J,"i32"),w=k.getValue(W,"i32"),b=k.UTF8ToString(r,w).length,v=t.slice(b,b+100).split(`
|
|
22
|
+
${JSON.stringify(r,null,2)}`),new Error(`Language.${n?"loadSync":"load"} failed: no language function found in Wasm file`);let o=t[s]();return new Fl(kr,o)}static loadSync(t){let n=k.loadWebAssemblyModule(t,{loadAsync:!1});return Fl.loadFromWasmExports(n,{sync:!0})}};async function jk(moduleArg={}){var moduleRtn,Module=moduleArg,ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope<"u",ENVIRONMENT_IS_NODE=typeof process=="object"&&process.versions?.node&&process.type!="renderer";if(ENVIRONMENT_IS_NODE){let{createRequire:e}=await import("module");var require=e(import.meta.url)}Module.currentQueryProgressCallback=null,Module.currentProgressCallback=null,Module.currentLogCallback=null,Module.currentParseCallback=null;var arguments_=[],thisProgram="./this.program",quit_=S((e,t)=>{throw t},"quit_"),_scriptName=import.meta.url,scriptDirectory="";function locateFile(e){return Module.locateFile?Module.locateFile(e,scriptDirectory):scriptDirectory+e}S(locateFile,"locateFile");var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");_scriptName.startsWith("file:")&&(scriptDirectory=require("path").dirname(require("url").fileURLToPath(_scriptName))+"/"),readBinary=S(e=>{e=isFileURI(e)?new URL(e):e;var t=fs.readFileSync(e);return t},"readBinary"),readAsync=S(async(e,t=!0)=>{e=isFileURI(e)?new URL(e):e;var n=fs.readFileSync(e,t?void 0:"utf8");return n},"readAsync"),process.argv.length>1&&(thisProgram=process.argv[1].replace(/\\/g,"/")),arguments_=process.argv.slice(2),quit_=S((e,t)=>{throw process.exitCode=e,t},"quit_")}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}ENVIRONMENT_IS_WORKER&&(readBinary=S(e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)},"readBinary")),readAsync=S(async e=>{if(isFileURI(e))return new Promise((n,r)=>{var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=()=>{if(s.status==200||s.status==0&&s.response){n(s.response);return}r(s.status)},s.onerror=r,s.send(null)});var t=await fetch(e,{credentials:"same-origin"});if(t.ok)return t.arrayBuffer();throw new Error(t.status+" : "+t.url)},"readAsync")}var out=console.log.bind(console),err=console.error.bind(console),dynamicLibraries=[],wasmBinary,ABORT=!1,EXITSTATUS,isFileURI=S(e=>e.startsWith("file://"),"isFileURI"),readyPromiseResolve,readyPromiseReject,wasmMemory,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP64,HEAPU64,HEAP_DATA_VIEW,runtimeInitialized=!1;function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e),Module.HEAP64=HEAP64=new BigInt64Array(e),Module.HEAPU64=HEAPU64=new BigUint64Array(e),Module.HEAP_DATA_VIEW=HEAP_DATA_VIEW=new DataView(e),LE_HEAP_UPDATE()}S(updateMemoryViews,"updateMemoryViews");function initMemory(){if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var e=Module.INITIAL_MEMORY||33554432;wasmMemory=new WebAssembly.Memory({initial:e/65536,maximum:32768})}updateMemoryViews()}S(initMemory,"initMemory");var __RELOC_FUNCS__=[];function preRun(){if(Module.preRun)for(typeof Module.preRun=="function"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(onPreRuns)}S(preRun,"preRun");function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),wasmExports.__wasm_call_ctors(),callRuntimeCallbacks(onPostCtors)}S(initRuntime,"initRuntime");function preMain(){}S(preMain,"preMain");function postRun(){if(Module.postRun)for(typeof Module.postRun=="function"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(onPostRuns)}S(postRun,"postRun");function abort(e){Module.onAbort?.(e),e="Aborted("+e+")",err(e),ABORT=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw readyPromiseReject?.(t),t}S(abort,"abort");var wasmBinaryFile;function findWasmBinary(){return Module.locateFile?locateFile("web-tree-sitter.wasm"):new URL("web-tree-sitter.wasm",import.meta.url).href}S(findWasmBinary,"findWasmBinary");function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}S(getBinarySync,"getBinarySync");async function getWasmBinary(e){if(!wasmBinary)try{var t=await readAsync(e);return new Uint8Array(t)}catch{}return getBinarySync(e)}S(getWasmBinary,"getWasmBinary");async function instantiateArrayBuffer(e,t){try{var n=await getWasmBinary(e),r=await WebAssembly.instantiate(n,t);return r}catch(s){err(`failed to asynchronously prepare wasm: ${s}`),abort(s)}}S(instantiateArrayBuffer,"instantiateArrayBuffer");async function instantiateAsync(e,t,n){if(!e&&!isFileURI(t)&&!ENVIRONMENT_IS_NODE)try{var r=fetch(t,{credentials:"same-origin"}),s=await WebAssembly.instantiateStreaming(r,n);return s}catch(o){err(`wasm streaming compile failed: ${o}`),err("falling back to ArrayBuffer instantiation")}return instantiateArrayBuffer(t,n)}S(instantiateAsync,"instantiateAsync");function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}S(getWasmImports,"getWasmImports");async function createWasm(){function e(o,a){wasmExports=o.exports,wasmExports=relocateExports(wasmExports,1024);var d=getDylinkMetadata(a);return d.neededDynlibs&&(dynamicLibraries=d.neededDynlibs.concat(dynamicLibraries)),mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),assignWasmExports(wasmExports),wasmExports}S(e,"receiveInstance");function t(o){return e(o.instance,o.module)}S(t,"receiveInstantiationResult");var n=getWasmImports();if(Module.instantiateWasm)return new Promise((o,a)=>{Module.instantiateWasm(n,(d,l)=>{o(e(d,l))})});wasmBinaryFile??=findWasmBinary();var r=await instantiateAsync(wasmBinary,wasmBinaryFile,n),s=t(r);return s}S(createWasm,"createWasm");class ExitStatus{static{S(this,"ExitStatus")}name="ExitStatus";constructor(t){this.message=`Program terminated with exit(${t})`,this.status=t}}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(e,t){var n=GOT[t];return n||(n=GOT[t]=new WebAssembly.Global({value:"i32",mutable:!0})),currentModuleWeakSymbols.has(t)||(n.required=!0),n}},LE_ATOMICS_NATIVE_BYTE_ORDER=[],LE_HEAP_LOAD_F32=S(e=>HEAP_DATA_VIEW.getFloat32(e,!0),"LE_HEAP_LOAD_F32"),LE_HEAP_LOAD_F64=S(e=>HEAP_DATA_VIEW.getFloat64(e,!0),"LE_HEAP_LOAD_F64"),LE_HEAP_LOAD_I16=S(e=>HEAP_DATA_VIEW.getInt16(e,!0),"LE_HEAP_LOAD_I16"),LE_HEAP_LOAD_I32=S(e=>HEAP_DATA_VIEW.getInt32(e,!0),"LE_HEAP_LOAD_I32"),LE_HEAP_LOAD_I64=S(e=>HEAP_DATA_VIEW.getBigInt64(e,!0),"LE_HEAP_LOAD_I64"),LE_HEAP_LOAD_U32=S(e=>HEAP_DATA_VIEW.getUint32(e,!0),"LE_HEAP_LOAD_U32"),LE_HEAP_STORE_F32=S((e,t)=>HEAP_DATA_VIEW.setFloat32(e,t,!0),"LE_HEAP_STORE_F32"),LE_HEAP_STORE_F64=S((e,t)=>HEAP_DATA_VIEW.setFloat64(e,t,!0),"LE_HEAP_STORE_F64"),LE_HEAP_STORE_I16=S((e,t)=>HEAP_DATA_VIEW.setInt16(e,t,!0),"LE_HEAP_STORE_I16"),LE_HEAP_STORE_I32=S((e,t)=>HEAP_DATA_VIEW.setInt32(e,t,!0),"LE_HEAP_STORE_I32"),LE_HEAP_STORE_I64=S((e,t)=>HEAP_DATA_VIEW.setBigInt64(e,t,!0),"LE_HEAP_STORE_I64"),LE_HEAP_STORE_U32=S((e,t)=>HEAP_DATA_VIEW.setUint32(e,t,!0),"LE_HEAP_STORE_U32"),callRuntimeCallbacks=S(e=>{for(;e.length>0;)e.shift()(Module)},"callRuntimeCallbacks"),onPostRuns=[],addOnPostRun=S(e=>onPostRuns.push(e),"addOnPostRun"),onPreRuns=[],addOnPreRun=S(e=>onPreRuns.push(e),"addOnPreRun"),UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,findStringEnd=S((e,t,n,r)=>{var s=t+n;if(r)return s;for(;e[t]&&!(t>=s);)++t;return t},"findStringEnd"),UTF8ArrayToString=S((e,t=0,n,r)=>{var s=findStringEnd(e,t,n,r);if(s-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(t,s));for(var o="";t<s;){var a=e[t++];if(!(a&128)){o+=String.fromCharCode(a);continue}var d=e[t++]&63;if((a&224)==192){o+=String.fromCharCode((a&31)<<6|d);continue}var l=e[t++]&63;if((a&240)==224?a=(a&15)<<12|d<<6|l:a=(a&7)<<18|d<<12|l<<6|e[t++]&63,a<65536)o+=String.fromCharCode(a);else{var c=a-65536;o+=String.fromCharCode(55296|c>>10,56320|c&1023)}}return o},"UTF8ArrayToString"),getDylinkMetadata=S(e=>{var t=0,n=0;function r(){return e[t++]}S(r,"getU8");function s(){for(var A=0,M=1;;){var $=e[t++];if(A+=($&127)*M,M*=128,!($&128))break}return A}S(s,"getLEB");function o(){var A=s();return t+=A,UTF8ArrayToString(e,t-A,A)}S(o,"getString");function a(){for(var A=s(),M=[];A--;)M.push(o());return M}S(a,"getStringList");function d(A,M){if(A)throw new Error(M)}if(S(d,"failIf"),e instanceof WebAssembly.Module){var l=WebAssembly.Module.customSections(e,"dylink.0");d(l.length===0,"need dylink section"),e=new Uint8Array(l[0]),n=e.length}else{var c=new Uint32Array(new Uint8Array(e.subarray(0,24)).buffer),u=c[0]==1836278016||c[0]==6386541;d(!u,"need to see wasm magic number"),d(e[8]!==0,"need the dylink section to be first"),t=9;var p=s();n=t+p;var f=o();d(f!=="dylink.0")}for(var m={neededDynlibs:[],tlsExports:new Set,weakImports:new Set,runtimePaths:[]},h=1,g=2,y=3,w=4,b=5,v=256,R=3,x=1;t<n;){var T=r(),N=s();if(T===h)m.memorySize=s(),m.memoryAlign=s(),m.tableSize=s(),m.tableAlign=s();else if(T===g)m.neededDynlibs=a();else if(T===y)for(var U=s();U--;){var F=o(),I=s();I&v&&m.tlsExports.add(F)}else if(T===w)for(var U=s();U--;){var C=o(),F=o(),I=s();(I&R)==x&&m.weakImports.add(F)}else T===b?m.runtimePaths=a():t+=N}return m},"getDylinkMetadata");function getValue(e,t="i8"){switch(t.endsWith("*")&&(t="*"),t){case"i1":return HEAP8[e];case"i8":return HEAP8[e];case"i16":return LE_HEAP_LOAD_I16((e>>1)*2);case"i32":return LE_HEAP_LOAD_I32((e>>2)*4);case"i64":return LE_HEAP_LOAD_I64((e>>3)*8);case"float":return LE_HEAP_LOAD_F32((e>>2)*4);case"double":return LE_HEAP_LOAD_F64((e>>3)*8);case"*":return LE_HEAP_LOAD_U32((e>>2)*4);default:abort(`invalid type for getValue: ${t}`)}}S(getValue,"getValue");var newDSO=S((e,t,n)=>{var r={refcount:1/0,name:e,exports:n,global:!0};return LDSO.loadedLibsByName[e]=r,t!=null&&(LDSO.loadedLibsByHandle[t]=r),r},"newDSO"),LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=82240,alignMemory=S((e,t)=>Math.ceil(e/t)*t,"alignMemory"),getMemory=S(e=>{if(runtimeInitialized)return _calloc(e,1);var t=___heap_base,n=t+alignMemory(e,16);return ___heap_base=n,GOT.__heap_base.value=n,t},"getMemory"),isInternalSym=S(e=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(e)||e.startsWith("__em_js__"),"isInternalSym"),uleb128EncodeWithLen=S(e=>{let t=e.length;return[t%128|128,t>>7,...e]},"uleb128EncodeWithLen"),wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111},generateTypePack=S(e=>uleb128EncodeWithLen(Array.from(e,t=>{var n=wasmTypeCodes[t];return n})),"generateTypePack"),convertJsFunctionToWasm=S((e,t)=>{var n=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(t.slice(1)),...generateTypePack(t[0]==="v"?"":t[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),r=new WebAssembly.Module(n),s=new WebAssembly.Instance(r,{e:{f:e}}),o=s.exports.f;return o},"convertJsFunctionToWasm"),wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:31,element:"anyfunc"}),getWasmTableEntry=S(e=>{var t=wasmTableMirror[e];return t||(wasmTableMirror[e]=t=wasmTable.get(e)),t},"getWasmTableEntry"),updateTableMap=S((e,t)=>{if(functionsInTableMap)for(var n=e;n<e+t;n++){var r=getWasmTableEntry(n);r&&functionsInTableMap.set(r,n)}},"updateTableMap"),functionsInTableMap,getFunctionAddress=S(e=>(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(e)||0),"getFunctionAddress"),freeTableIndexes=[],getEmptyTableSlot=S(()=>freeTableIndexes.length?freeTableIndexes.pop():wasmTable.grow(1),"getEmptyTableSlot"),setWasmTableEntry=S((e,t)=>{wasmTable.set(e,t),wasmTableMirror[e]=wasmTable.get(e)},"setWasmTableEntry"),addFunction=S((e,t)=>{var n=getFunctionAddress(e);if(n)return n;var r=getEmptyTableSlot();try{setWasmTableEntry(r,e)}catch(o){if(!(o instanceof TypeError))throw o;var s=convertJsFunctionToWasm(e,t);setWasmTableEntry(r,s)}return functionsInTableMap.set(e,r),r},"addFunction"),updateGOT=S((e,t)=>{for(var n in e)if(!isInternalSym(n)){var r=e[n];GOT[n]||=new WebAssembly.Global({value:"i32",mutable:!0}),(t||GOT[n].value==0)&&(typeof r=="function"?GOT[n].value=addFunction(r):typeof r=="number"?GOT[n].value=r:err(`unhandled export type for '${n}': ${typeof r}`))}},"updateGOT"),relocateExports=S((e,t,n)=>{var r={};for(var s in e){var o=e[s];typeof o=="object"&&(o=o.value),typeof o=="number"&&(o+=t),r[s]=o}return updateGOT(r,n),r},"relocateExports"),isSymbolDefined=S(e=>{var t=wasmImports[e];return!(!t||t.stub)},"isSymbolDefined"),dynCall=S((e,t,n=[],r=!1)=>{var s=getWasmTableEntry(t),o=s(...n);function a(d){return d}return S(a,"convert"),o},"dynCall"),stackSave=S(()=>_emscripten_stack_get_current(),"stackSave"),stackRestore=S(e=>__emscripten_stack_restore(e),"stackRestore"),createInvokeFunction=S(e=>(t,...n)=>{var r=stackSave();try{return dynCall(e,t,n)}catch(s){if(stackRestore(r),s!==s+0)throw s;if(_setThrew(1,0),e[0]=="j")return 0n}},"createInvokeFunction"),resolveGlobalSymbol=S((e,t=!1)=>{var n;return isSymbolDefined(e)?n=wasmImports[e]:e.startsWith("invoke_")&&(n=wasmImports[e]=createInvokeFunction(e.split("_")[1])),{sym:n,name:e}},"resolveGlobalSymbol"),onPostCtors=[],addOnPostCtor=S(e=>onPostCtors.push(e),"addOnPostCtor"),UTF8ToString=S((e,t,n)=>e?UTF8ArrayToString(HEAPU8,e,t,n):"","UTF8ToString"),loadWebAssemblyModule=S((binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);function loadModule(){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;handle&&(HEAP8[handle+8]=1,LE_HEAP_STORE_U32((handle+12>>2)*4,memoryBase),LE_HEAP_STORE_I32((handle+16>>2)*4,metadata.memorySize),LE_HEAP_STORE_U32((handle+20>>2)*4,tableBase),LE_HEAP_STORE_I32((handle+24>>2)*4,metadata.tableSize)),metadata.tableSize&&wasmTable.grow(metadata.tableSize);var moduleExports;function resolveSymbol(e){var t=resolveGlobalSymbol(e).sym;return!t&&localScope&&(t=localScope[e]),t||(t=moduleExports[e]),t}S(resolveSymbol,"resolveSymbol");var proxyHandler={get(e,t){switch(t){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(t in wasmImports&&!wasmImports[t].stub){var n=wasmImports[t];return n}if(!(t in e)){var r;e[t]=(...s)=>(r||=resolveSymbol(t),r(...s))}return e[t]}},proxy=new Proxy({},proxyHandler);currentModuleWeakSymbols=metadata.weakImports;var info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),flags.allowUndefined||reportUndefinedSymbols();function addEmAsm(addr,body){for(var args=[],arity=0;arity<16&&body.indexOf("$"+arity)!=-1;arity++)args.push("$"+arity);args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if(S(addEmAsm,"addEmAsm"),"__start_em_asm"in moduleExports)for(var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;start<stop;){var jsString=UTF8ToString(start);addEmAsm(start,jsString),start=HEAPU8.indexOf(0,start)+1}function addEmJs(name,cSig,body){var jsArgs=[];if(cSig=cSig.slice(1,-1),cSig!="void"){cSig=cSig.split(",");for(var i in cSig){var jsArg=cSig[i].split(" ").pop();jsArgs.push(jsArg.replace("*",""))}}var func=`(${jsArgs}) => ${body};`;moduleExports[name]=eval(func)}S(addEmJs,"addEmJs");for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;applyRelocs&&(runtimeInitialized?applyRelocs():__RELOC_FUNCS__.push(applyRelocs));var init=moduleExports.__wasm_call_ctors;return init&&(runtimeInitialized?init():addOnPostCtor(init)),moduleExports}if(S(postInstantiation,"postInstantiation"),flags.loadAsync)return(async()=>{var e;return binary instanceof WebAssembly.Module?e=new WebAssembly.Instance(binary,info):{module:binary,instance:e}=await WebAssembly.instantiate(binary,info),postInstantiation(binary,e)})();var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}return S(loadModule,"loadModule"),flags={...flags,rpath:{parentLibPath:libName,paths:metadata.runtimePaths}},flags.loadAsync?metadata.neededDynlibs.reduce((e,t)=>e.then(()=>loadDynamicLibrary(t,flags,localScope)),Promise.resolve()).then(loadModule):(metadata.neededDynlibs.forEach(e=>loadDynamicLibrary(e,flags,localScope)),loadModule())},"loadWebAssemblyModule"),mergeLibSymbols=S((e,t)=>{for(var[n,r]of Object.entries(e)){let s=S(a=>{isSymbolDefined(a)||(wasmImports[a]=r)},"setImport");s(n);let o="__main_argc_argv";n=="main"&&s(o),n==o&&s("main")}},"mergeLibSymbols"),asyncLoad=S(async e=>{var t=await readAsync(e);return new Uint8Array(t)},"asyncLoad");function loadDynamicLibrary(e,t={global:!0,nodelete:!0},n,r){var s=LDSO.loadedLibsByName[e];if(s)return t.global?s.global||(s.global=!0,mergeLibSymbols(s.exports,e)):n&&Object.assign(n,s.exports),t.nodelete&&s.refcount!==1/0&&(s.refcount=1/0),s.refcount++,r&&(LDSO.loadedLibsByHandle[r]=s),t.loadAsync?Promise.resolve(!0):!0;s=newDSO(e,r,"loading"),s.refcount=t.nodelete?1/0:1,s.global=t.global;function o(){if(r){var l=LE_HEAP_LOAD_U32((r+28>>2)*4),c=LE_HEAP_LOAD_U32((r+32>>2)*4);if(l&&c){var u=HEAP8.slice(l,l+c);return t.loadAsync?Promise.resolve(u):u}}var p=locateFile(e);if(t.loadAsync)return asyncLoad(p);if(!readBinary)throw new Error(`${p}: file not found, and synchronous loading of external files is not available`);return readBinary(p)}S(o,"loadLibData");function a(){return t.loadAsync?o().then(l=>loadWebAssemblyModule(l,t,e,n,r)):loadWebAssemblyModule(o(),t,e,n,r)}S(a,"getExports");function d(l){s.global?mergeLibSymbols(l,e):n&&Object.assign(n,l),s.exports=l}return S(d,"moduleLoaded"),t.loadAsync?a().then(l=>(d(l),!0)):(d(a()),!0)}S(loadDynamicLibrary,"loadDynamicLibrary");var reportUndefinedSymbols=S(()=>{for(var[e,t]of Object.entries(GOT))if(t.value==0){var n=resolveGlobalSymbol(e,!0).sym;if(!n&&!t.required)continue;if(typeof n=="function")t.value=addFunction(n,n.sig);else if(typeof n=="number")t.value=n;else throw new Error(`bad export type for '${e}': ${typeof n}`)}},"reportUndefinedSymbols"),runDependencies=0,dependenciesFulfilled=null,removeRunDependency=S(e=>{if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0&&dependenciesFulfilled){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}},"removeRunDependency"),addRunDependency=S(e=>{runDependencies++,Module.monitorRunDependencies?.(runDependencies)},"addRunDependency"),loadDylibs=S(async()=>{if(!dynamicLibraries.length){reportUndefinedSymbols();return}addRunDependency("loadDylibs");for(var e of dynamicLibraries)await loadDynamicLibrary(e,{loadAsync:!0,global:!0,nodelete:!0,allowUndefined:!0});reportUndefinedSymbols(),removeRunDependency("loadDylibs")},"loadDylibs"),noExitRuntime=!0;function setValue(e,t,n="i8"){switch(n.endsWith("*")&&(n="*"),n){case"i1":HEAP8[e]=t;break;case"i8":HEAP8[e]=t;break;case"i16":LE_HEAP_STORE_I16((e>>1)*2,t);break;case"i32":LE_HEAP_STORE_I32((e>>2)*4,t);break;case"i64":LE_HEAP_STORE_I64((e>>3)*8,BigInt(t));break;case"float":LE_HEAP_STORE_F32((e>>2)*4,t);break;case"double":LE_HEAP_STORE_F64((e>>3)*8,t);break;case"*":LE_HEAP_STORE_U32((e>>2)*4,t);break;default:abort(`invalid type for setValue: ${n}`)}}S(setValue,"setValue");var ___memory_base=new WebAssembly.Global({value:"i32",mutable:!1},1024),___stack_high=82240,___stack_low=16704,___stack_pointer=new WebAssembly.Global({value:"i32",mutable:!0},82240),___table_base=new WebAssembly.Global({value:"i32",mutable:!1},1),__abort_js=S(()=>abort(""),"__abort_js");__abort_js.sig="v";var getHeapMax=S(()=>2147483648,"getHeapMax"),growMemory=S(e=>{var t=wasmMemory.buffer.byteLength,n=(e-t+65535)/65536|0;try{return wasmMemory.grow(n),updateMemoryViews(),1}catch{}},"growMemory"),_emscripten_resize_heap=S(e=>{var t=HEAPU8.length;e>>>=0;var n=getHeapMax();if(e>n)return!1;for(var r=1;r<=4;r*=2){var s=t*(1+.2/r);s=Math.min(s,e+100663296);var o=Math.min(n,alignMemory(Math.max(e,s),65536)),a=growMemory(o);if(a)return!0}return!1},"_emscripten_resize_heap");_emscripten_resize_heap.sig="ip";var _fd_close=S(e=>52,"_fd_close");_fd_close.sig="ii";var INT53_MAX=9007199254740992,INT53_MIN=-9007199254740992,bigintToI53Checked=S(e=>e<INT53_MIN||e>INT53_MAX?NaN:Number(e),"bigintToI53Checked");function _fd_seek(e,t,n,r){return t=bigintToI53Checked(t),70}S(_fd_seek,"_fd_seek"),_fd_seek.sig="iijip";var printCharBuffers=[null,[],[]],printChar=S((e,t)=>{var n=printCharBuffers[e];t===0||t===10?((e===1?out:err)(UTF8ArrayToString(n)),n.length=0):n.push(t)},"printChar"),_fd_write=S((e,t,n,r)=>{for(var s=0,o=0;o<n;o++){var a=LE_HEAP_LOAD_U32((t>>2)*4),d=LE_HEAP_LOAD_U32((t+4>>2)*4);t+=8;for(var l=0;l<d;l++)printChar(e,HEAPU8[a+l]);s+=d}return LE_HEAP_STORE_U32((r>>2)*4,s),0},"_fd_write");_fd_write.sig="iippp";function _tree_sitter_log_callback(e,t){if(Module.currentLogCallback){let n=UTF8ToString(t);Module.currentLogCallback(n,e!==0)}}S(_tree_sitter_log_callback,"_tree_sitter_log_callback");function _tree_sitter_parse_callback(e,t,n,r,s){let a=Module.currentParseCallback(t,{row:n,column:r});typeof a=="string"?(setValue(s,a.length,"i32"),stringToUTF16(a,e,10240)):setValue(s,0,"i32")}S(_tree_sitter_parse_callback,"_tree_sitter_parse_callback");function _tree_sitter_progress_callback(e,t){return Module.currentProgressCallback?Module.currentProgressCallback({currentOffset:e,hasError:t}):!1}S(_tree_sitter_progress_callback,"_tree_sitter_progress_callback");function _tree_sitter_query_progress_callback(e){return Module.currentQueryProgressCallback?Module.currentQueryProgressCallback({currentOffset:e}):!1}S(_tree_sitter_query_progress_callback,"_tree_sitter_query_progress_callback");var runtimeKeepaliveCounter=0,keepRuntimeAlive=S(()=>noExitRuntime||runtimeKeepaliveCounter>0,"keepRuntimeAlive"),_proc_exit=S(e=>{EXITSTATUS=e,keepRuntimeAlive()||(Module.onExit?.(e),ABORT=!0),quit_(e,new ExitStatus(e))},"_proc_exit");_proc_exit.sig="vi";var exitJS=S((e,t)=>{EXITSTATUS=e,_proc_exit(e)},"exitJS"),handleException=S(e=>{if(e instanceof ExitStatus||e=="unwind")return EXITSTATUS;quit_(1,e)},"handleException"),lengthBytesUTF8=S(e=>{for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);r<=127?t++:r<=2047?t+=2:r>=55296&&r<=57343?(t+=4,++n):t+=3}return t},"lengthBytesUTF8"),stringToUTF8Array=S((e,t,n,r)=>{if(!(r>0))return 0;for(var s=n,o=n+r-1,a=0;a<e.length;++a){var d=e.codePointAt(a);if(d<=127){if(n>=o)break;t[n++]=d}else if(d<=2047){if(n+1>=o)break;t[n++]=192|d>>6,t[n++]=128|d&63}else if(d<=65535){if(n+2>=o)break;t[n++]=224|d>>12,t[n++]=128|d>>6&63,t[n++]=128|d&63}else{if(n+3>=o)break;t[n++]=240|d>>18,t[n++]=128|d>>12&63,t[n++]=128|d>>6&63,t[n++]=128|d&63,a++}}return t[n]=0,n-s},"stringToUTF8Array"),stringToUTF8=S((e,t,n)=>stringToUTF8Array(e,HEAPU8,t,n),"stringToUTF8"),stackAlloc=S(e=>__emscripten_stack_alloc(e),"stackAlloc"),stringToUTF8OnStack=S(e=>{var t=lengthBytesUTF8(e)+1,n=stackAlloc(t);return stringToUTF8(e,n,t),n},"stringToUTF8OnStack"),AsciiToString=S(e=>{for(var t="";;){var n=HEAPU8[e++];if(!n)return t;t+=String.fromCharCode(n)}},"AsciiToString"),stringToUTF16=S((e,t,n)=>{if(n??=2147483647,n<2)return 0;n-=2;for(var r=t,s=n<e.length*2?n/2:e.length,o=0;o<s;++o){var a=e.charCodeAt(o);LE_HEAP_STORE_I16((t>>1)*2,a),t+=2}return LE_HEAP_STORE_I16((t>>1)*2,0),t-r},"stringToUTF16");LE_ATOMICS_NATIVE_BYTE_ORDER=new Int8Array(new Int16Array([1]).buffer)[0]===1?[(e=>e),(e=>e),void 0,(e=>e)]:[(e=>e),(e=>((e&65280)<<8|(e&255)<<24)>>16),void 0,(e=>e>>24&255|e>>8&65280|(e&65280)<<8|(e&255)<<24)];function LE_HEAP_UPDATE(){HEAPU16.unsigned=(e=>e&65535),HEAPU32.unsigned=(e=>e>>>0)}if(S(LE_HEAP_UPDATE,"LE_HEAP_UPDATE"),initMemory(),Module.noExitRuntime&&(noExitRuntime=Module.noExitRuntime),Module.print&&(out=Module.print),Module.printErr&&(err=Module.printErr),Module.dynamicLibraries&&(dynamicLibraries=Module.dynamicLibraries),Module.wasmBinary&&(wasmBinary=Module.wasmBinary),Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.preInit)for(typeof Module.preInit=="function"&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.shift()();Module.setValue=setValue,Module.getValue=getValue,Module.UTF8ToString=UTF8ToString,Module.stringToUTF8=stringToUTF8,Module.lengthBytesUTF8=lengthBytesUTF8,Module.AsciiToString=AsciiToString,Module.stringToUTF16=stringToUTF16,Module.loadWebAssemblyModule=loadWebAssemblyModule,Module.LE_HEAP_STORE_I64=LE_HEAP_STORE_I64;var ASM_CONSTS={},_malloc,_calloc,_realloc,_free,_ts_range_edit,_memcmp,_ts_language_symbol_count,_ts_language_state_count,_ts_language_abi_version,_ts_language_name,_ts_language_field_count,_ts_language_next_state,_ts_language_symbol_name,_ts_language_symbol_for_name,_strncmp,_ts_language_symbol_type,_ts_language_field_name_for_id,_ts_lookahead_iterator_new,_ts_lookahead_iterator_delete,_ts_lookahead_iterator_reset_state,_ts_lookahead_iterator_reset,_ts_lookahead_iterator_next,_ts_lookahead_iterator_current_symbol,_ts_point_edit,_ts_parser_delete,_ts_parser_reset,_ts_parser_set_language,_ts_parser_set_included_ranges,_ts_query_new,_ts_query_delete,_iswspace,_iswalnum,_ts_query_copy,_ts_query_pattern_count,_ts_query_capture_count,_ts_query_string_count,_ts_query_capture_name_for_id,_ts_query_capture_quantifier_for_id,_ts_query_string_value_for_id,_ts_query_predicates_for_pattern,_ts_query_start_byte_for_pattern,_ts_query_end_byte_for_pattern,_ts_query_is_pattern_rooted,_ts_query_is_pattern_non_local,_ts_query_is_pattern_guaranteed_at_step,_ts_query_disable_capture,_ts_query_disable_pattern,_ts_tree_copy,_ts_tree_delete,_ts_init,_ts_parser_new_wasm,_ts_parser_enable_logger_wasm,_ts_parser_parse_wasm,_ts_parser_included_ranges_wasm,_ts_language_type_is_named_wasm,_ts_language_type_is_visible_wasm,_ts_language_metadata_wasm,_ts_language_supertypes_wasm,_ts_language_subtypes_wasm,_ts_tree_root_node_wasm,_ts_tree_root_node_with_offset_wasm,_ts_tree_edit_wasm,_ts_tree_included_ranges_wasm,_ts_tree_get_changed_ranges_wasm,_ts_tree_cursor_new_wasm,_ts_tree_cursor_copy_wasm,_ts_tree_cursor_delete_wasm,_ts_tree_cursor_reset_wasm,_ts_tree_cursor_reset_to_wasm,_ts_tree_cursor_goto_first_child_wasm,_ts_tree_cursor_goto_last_child_wasm,_ts_tree_cursor_goto_first_child_for_index_wasm,_ts_tree_cursor_goto_first_child_for_position_wasm,_ts_tree_cursor_goto_next_sibling_wasm,_ts_tree_cursor_goto_previous_sibling_wasm,_ts_tree_cursor_goto_descendant_wasm,_ts_tree_cursor_goto_parent_wasm,_ts_tree_cursor_current_node_type_id_wasm,_ts_tree_cursor_current_node_state_id_wasm,_ts_tree_cursor_current_node_is_named_wasm,_ts_tree_cursor_current_node_is_missing_wasm,_ts_tree_cursor_current_node_id_wasm,_ts_tree_cursor_start_position_wasm,_ts_tree_cursor_end_position_wasm,_ts_tree_cursor_start_index_wasm,_ts_tree_cursor_end_index_wasm,_ts_tree_cursor_current_field_id_wasm,_ts_tree_cursor_current_depth_wasm,_ts_tree_cursor_current_descendant_index_wasm,_ts_tree_cursor_current_node_wasm,_ts_node_symbol_wasm,_ts_node_field_name_for_child_wasm,_ts_node_field_name_for_named_child_wasm,_ts_node_children_by_field_id_wasm,_ts_node_first_child_for_byte_wasm,_ts_node_first_named_child_for_byte_wasm,_ts_node_grammar_symbol_wasm,_ts_node_child_count_wasm,_ts_node_named_child_count_wasm,_ts_node_child_wasm,_ts_node_named_child_wasm,_ts_node_child_by_field_id_wasm,_ts_node_next_sibling_wasm,_ts_node_prev_sibling_wasm,_ts_node_next_named_sibling_wasm,_ts_node_prev_named_sibling_wasm,_ts_node_descendant_count_wasm,_ts_node_parent_wasm,_ts_node_child_with_descendant_wasm,_ts_node_descendant_for_index_wasm,_ts_node_named_descendant_for_index_wasm,_ts_node_descendant_for_position_wasm,_ts_node_named_descendant_for_position_wasm,_ts_node_start_point_wasm,_ts_node_end_point_wasm,_ts_node_start_index_wasm,_ts_node_end_index_wasm,_ts_node_to_string_wasm,_ts_node_children_wasm,_ts_node_named_children_wasm,_ts_node_descendants_of_type_wasm,_ts_node_is_named_wasm,_ts_node_has_changes_wasm,_ts_node_has_error_wasm,_ts_node_is_error_wasm,_ts_node_is_missing_wasm,_ts_node_is_extra_wasm,_ts_node_parse_state_wasm,_ts_node_next_parse_state_wasm,_ts_query_matches_wasm,_ts_query_captures_wasm,_memset,_memcpy,_memmove,_iswalpha,_iswblank,_iswdigit,_iswlower,_iswpunct,_iswupper,_iswxdigit,_memchr,_strlen,_strcmp,_strncat,_strncpy,_towlower,_towupper,_setThrew,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,___wasm_apply_data_relocs;function assignWasmExports(e){Module._malloc=_malloc=e.malloc,Module._calloc=_calloc=e.calloc,Module._realloc=_realloc=e.realloc,Module._free=_free=e.free,Module._ts_range_edit=_ts_range_edit=e.ts_range_edit,Module._memcmp=_memcmp=e.memcmp,Module._ts_language_symbol_count=_ts_language_symbol_count=e.ts_language_symbol_count,Module._ts_language_state_count=_ts_language_state_count=e.ts_language_state_count,Module._ts_language_abi_version=_ts_language_abi_version=e.ts_language_abi_version,Module._ts_language_name=_ts_language_name=e.ts_language_name,Module._ts_language_field_count=_ts_language_field_count=e.ts_language_field_count,Module._ts_language_next_state=_ts_language_next_state=e.ts_language_next_state,Module._ts_language_symbol_name=_ts_language_symbol_name=e.ts_language_symbol_name,Module._ts_language_symbol_for_name=_ts_language_symbol_for_name=e.ts_language_symbol_for_name,Module._strncmp=_strncmp=e.strncmp,Module._ts_language_symbol_type=_ts_language_symbol_type=e.ts_language_symbol_type,Module._ts_language_field_name_for_id=_ts_language_field_name_for_id=e.ts_language_field_name_for_id,Module._ts_lookahead_iterator_new=_ts_lookahead_iterator_new=e.ts_lookahead_iterator_new,Module._ts_lookahead_iterator_delete=_ts_lookahead_iterator_delete=e.ts_lookahead_iterator_delete,Module._ts_lookahead_iterator_reset_state=_ts_lookahead_iterator_reset_state=e.ts_lookahead_iterator_reset_state,Module._ts_lookahead_iterator_reset=_ts_lookahead_iterator_reset=e.ts_lookahead_iterator_reset,Module._ts_lookahead_iterator_next=_ts_lookahead_iterator_next=e.ts_lookahead_iterator_next,Module._ts_lookahead_iterator_current_symbol=_ts_lookahead_iterator_current_symbol=e.ts_lookahead_iterator_current_symbol,Module._ts_point_edit=_ts_point_edit=e.ts_point_edit,Module._ts_parser_delete=_ts_parser_delete=e.ts_parser_delete,Module._ts_parser_reset=_ts_parser_reset=e.ts_parser_reset,Module._ts_parser_set_language=_ts_parser_set_language=e.ts_parser_set_language,Module._ts_parser_set_included_ranges=_ts_parser_set_included_ranges=e.ts_parser_set_included_ranges,Module._ts_query_new=_ts_query_new=e.ts_query_new,Module._ts_query_delete=_ts_query_delete=e.ts_query_delete,Module._iswspace=_iswspace=e.iswspace,Module._iswalnum=_iswalnum=e.iswalnum,Module._ts_query_copy=_ts_query_copy=e.ts_query_copy,Module._ts_query_pattern_count=_ts_query_pattern_count=e.ts_query_pattern_count,Module._ts_query_capture_count=_ts_query_capture_count=e.ts_query_capture_count,Module._ts_query_string_count=_ts_query_string_count=e.ts_query_string_count,Module._ts_query_capture_name_for_id=_ts_query_capture_name_for_id=e.ts_query_capture_name_for_id,Module._ts_query_capture_quantifier_for_id=_ts_query_capture_quantifier_for_id=e.ts_query_capture_quantifier_for_id,Module._ts_query_string_value_for_id=_ts_query_string_value_for_id=e.ts_query_string_value_for_id,Module._ts_query_predicates_for_pattern=_ts_query_predicates_for_pattern=e.ts_query_predicates_for_pattern,Module._ts_query_start_byte_for_pattern=_ts_query_start_byte_for_pattern=e.ts_query_start_byte_for_pattern,Module._ts_query_end_byte_for_pattern=_ts_query_end_byte_for_pattern=e.ts_query_end_byte_for_pattern,Module._ts_query_is_pattern_rooted=_ts_query_is_pattern_rooted=e.ts_query_is_pattern_rooted,Module._ts_query_is_pattern_non_local=_ts_query_is_pattern_non_local=e.ts_query_is_pattern_non_local,Module._ts_query_is_pattern_guaranteed_at_step=_ts_query_is_pattern_guaranteed_at_step=e.ts_query_is_pattern_guaranteed_at_step,Module._ts_query_disable_capture=_ts_query_disable_capture=e.ts_query_disable_capture,Module._ts_query_disable_pattern=_ts_query_disable_pattern=e.ts_query_disable_pattern,Module._ts_tree_copy=_ts_tree_copy=e.ts_tree_copy,Module._ts_tree_delete=_ts_tree_delete=e.ts_tree_delete,Module._ts_init=_ts_init=e.ts_init,Module._ts_parser_new_wasm=_ts_parser_new_wasm=e.ts_parser_new_wasm,Module._ts_parser_enable_logger_wasm=_ts_parser_enable_logger_wasm=e.ts_parser_enable_logger_wasm,Module._ts_parser_parse_wasm=_ts_parser_parse_wasm=e.ts_parser_parse_wasm,Module._ts_parser_included_ranges_wasm=_ts_parser_included_ranges_wasm=e.ts_parser_included_ranges_wasm,Module._ts_language_type_is_named_wasm=_ts_language_type_is_named_wasm=e.ts_language_type_is_named_wasm,Module._ts_language_type_is_visible_wasm=_ts_language_type_is_visible_wasm=e.ts_language_type_is_visible_wasm,Module._ts_language_metadata_wasm=_ts_language_metadata_wasm=e.ts_language_metadata_wasm,Module._ts_language_supertypes_wasm=_ts_language_supertypes_wasm=e.ts_language_supertypes_wasm,Module._ts_language_subtypes_wasm=_ts_language_subtypes_wasm=e.ts_language_subtypes_wasm,Module._ts_tree_root_node_wasm=_ts_tree_root_node_wasm=e.ts_tree_root_node_wasm,Module._ts_tree_root_node_with_offset_wasm=_ts_tree_root_node_with_offset_wasm=e.ts_tree_root_node_with_offset_wasm,Module._ts_tree_edit_wasm=_ts_tree_edit_wasm=e.ts_tree_edit_wasm,Module._ts_tree_included_ranges_wasm=_ts_tree_included_ranges_wasm=e.ts_tree_included_ranges_wasm,Module._ts_tree_get_changed_ranges_wasm=_ts_tree_get_changed_ranges_wasm=e.ts_tree_get_changed_ranges_wasm,Module._ts_tree_cursor_new_wasm=_ts_tree_cursor_new_wasm=e.ts_tree_cursor_new_wasm,Module._ts_tree_cursor_copy_wasm=_ts_tree_cursor_copy_wasm=e.ts_tree_cursor_copy_wasm,Module._ts_tree_cursor_delete_wasm=_ts_tree_cursor_delete_wasm=e.ts_tree_cursor_delete_wasm,Module._ts_tree_cursor_reset_wasm=_ts_tree_cursor_reset_wasm=e.ts_tree_cursor_reset_wasm,Module._ts_tree_cursor_reset_to_wasm=_ts_tree_cursor_reset_to_wasm=e.ts_tree_cursor_reset_to_wasm,Module._ts_tree_cursor_goto_first_child_wasm=_ts_tree_cursor_goto_first_child_wasm=e.ts_tree_cursor_goto_first_child_wasm,Module._ts_tree_cursor_goto_last_child_wasm=_ts_tree_cursor_goto_last_child_wasm=e.ts_tree_cursor_goto_last_child_wasm,Module._ts_tree_cursor_goto_first_child_for_index_wasm=_ts_tree_cursor_goto_first_child_for_index_wasm=e.ts_tree_cursor_goto_first_child_for_index_wasm,Module._ts_tree_cursor_goto_first_child_for_position_wasm=_ts_tree_cursor_goto_first_child_for_position_wasm=e.ts_tree_cursor_goto_first_child_for_position_wasm,Module._ts_tree_cursor_goto_next_sibling_wasm=_ts_tree_cursor_goto_next_sibling_wasm=e.ts_tree_cursor_goto_next_sibling_wasm,Module._ts_tree_cursor_goto_previous_sibling_wasm=_ts_tree_cursor_goto_previous_sibling_wasm=e.ts_tree_cursor_goto_previous_sibling_wasm,Module._ts_tree_cursor_goto_descendant_wasm=_ts_tree_cursor_goto_descendant_wasm=e.ts_tree_cursor_goto_descendant_wasm,Module._ts_tree_cursor_goto_parent_wasm=_ts_tree_cursor_goto_parent_wasm=e.ts_tree_cursor_goto_parent_wasm,Module._ts_tree_cursor_current_node_type_id_wasm=_ts_tree_cursor_current_node_type_id_wasm=e.ts_tree_cursor_current_node_type_id_wasm,Module._ts_tree_cursor_current_node_state_id_wasm=_ts_tree_cursor_current_node_state_id_wasm=e.ts_tree_cursor_current_node_state_id_wasm,Module._ts_tree_cursor_current_node_is_named_wasm=_ts_tree_cursor_current_node_is_named_wasm=e.ts_tree_cursor_current_node_is_named_wasm,Module._ts_tree_cursor_current_node_is_missing_wasm=_ts_tree_cursor_current_node_is_missing_wasm=e.ts_tree_cursor_current_node_is_missing_wasm,Module._ts_tree_cursor_current_node_id_wasm=_ts_tree_cursor_current_node_id_wasm=e.ts_tree_cursor_current_node_id_wasm,Module._ts_tree_cursor_start_position_wasm=_ts_tree_cursor_start_position_wasm=e.ts_tree_cursor_start_position_wasm,Module._ts_tree_cursor_end_position_wasm=_ts_tree_cursor_end_position_wasm=e.ts_tree_cursor_end_position_wasm,Module._ts_tree_cursor_start_index_wasm=_ts_tree_cursor_start_index_wasm=e.ts_tree_cursor_start_index_wasm,Module._ts_tree_cursor_end_index_wasm=_ts_tree_cursor_end_index_wasm=e.ts_tree_cursor_end_index_wasm,Module._ts_tree_cursor_current_field_id_wasm=_ts_tree_cursor_current_field_id_wasm=e.ts_tree_cursor_current_field_id_wasm,Module._ts_tree_cursor_current_depth_wasm=_ts_tree_cursor_current_depth_wasm=e.ts_tree_cursor_current_depth_wasm,Module._ts_tree_cursor_current_descendant_index_wasm=_ts_tree_cursor_current_descendant_index_wasm=e.ts_tree_cursor_current_descendant_index_wasm,Module._ts_tree_cursor_current_node_wasm=_ts_tree_cursor_current_node_wasm=e.ts_tree_cursor_current_node_wasm,Module._ts_node_symbol_wasm=_ts_node_symbol_wasm=e.ts_node_symbol_wasm,Module._ts_node_field_name_for_child_wasm=_ts_node_field_name_for_child_wasm=e.ts_node_field_name_for_child_wasm,Module._ts_node_field_name_for_named_child_wasm=_ts_node_field_name_for_named_child_wasm=e.ts_node_field_name_for_named_child_wasm,Module._ts_node_children_by_field_id_wasm=_ts_node_children_by_field_id_wasm=e.ts_node_children_by_field_id_wasm,Module._ts_node_first_child_for_byte_wasm=_ts_node_first_child_for_byte_wasm=e.ts_node_first_child_for_byte_wasm,Module._ts_node_first_named_child_for_byte_wasm=_ts_node_first_named_child_for_byte_wasm=e.ts_node_first_named_child_for_byte_wasm,Module._ts_node_grammar_symbol_wasm=_ts_node_grammar_symbol_wasm=e.ts_node_grammar_symbol_wasm,Module._ts_node_child_count_wasm=_ts_node_child_count_wasm=e.ts_node_child_count_wasm,Module._ts_node_named_child_count_wasm=_ts_node_named_child_count_wasm=e.ts_node_named_child_count_wasm,Module._ts_node_child_wasm=_ts_node_child_wasm=e.ts_node_child_wasm,Module._ts_node_named_child_wasm=_ts_node_named_child_wasm=e.ts_node_named_child_wasm,Module._ts_node_child_by_field_id_wasm=_ts_node_child_by_field_id_wasm=e.ts_node_child_by_field_id_wasm,Module._ts_node_next_sibling_wasm=_ts_node_next_sibling_wasm=e.ts_node_next_sibling_wasm,Module._ts_node_prev_sibling_wasm=_ts_node_prev_sibling_wasm=e.ts_node_prev_sibling_wasm,Module._ts_node_next_named_sibling_wasm=_ts_node_next_named_sibling_wasm=e.ts_node_next_named_sibling_wasm,Module._ts_node_prev_named_sibling_wasm=_ts_node_prev_named_sibling_wasm=e.ts_node_prev_named_sibling_wasm,Module._ts_node_descendant_count_wasm=_ts_node_descendant_count_wasm=e.ts_node_descendant_count_wasm,Module._ts_node_parent_wasm=_ts_node_parent_wasm=e.ts_node_parent_wasm,Module._ts_node_child_with_descendant_wasm=_ts_node_child_with_descendant_wasm=e.ts_node_child_with_descendant_wasm,Module._ts_node_descendant_for_index_wasm=_ts_node_descendant_for_index_wasm=e.ts_node_descendant_for_index_wasm,Module._ts_node_named_descendant_for_index_wasm=_ts_node_named_descendant_for_index_wasm=e.ts_node_named_descendant_for_index_wasm,Module._ts_node_descendant_for_position_wasm=_ts_node_descendant_for_position_wasm=e.ts_node_descendant_for_position_wasm,Module._ts_node_named_descendant_for_position_wasm=_ts_node_named_descendant_for_position_wasm=e.ts_node_named_descendant_for_position_wasm,Module._ts_node_start_point_wasm=_ts_node_start_point_wasm=e.ts_node_start_point_wasm,Module._ts_node_end_point_wasm=_ts_node_end_point_wasm=e.ts_node_end_point_wasm,Module._ts_node_start_index_wasm=_ts_node_start_index_wasm=e.ts_node_start_index_wasm,Module._ts_node_end_index_wasm=_ts_node_end_index_wasm=e.ts_node_end_index_wasm,Module._ts_node_to_string_wasm=_ts_node_to_string_wasm=e.ts_node_to_string_wasm,Module._ts_node_children_wasm=_ts_node_children_wasm=e.ts_node_children_wasm,Module._ts_node_named_children_wasm=_ts_node_named_children_wasm=e.ts_node_named_children_wasm,Module._ts_node_descendants_of_type_wasm=_ts_node_descendants_of_type_wasm=e.ts_node_descendants_of_type_wasm,Module._ts_node_is_named_wasm=_ts_node_is_named_wasm=e.ts_node_is_named_wasm,Module._ts_node_has_changes_wasm=_ts_node_has_changes_wasm=e.ts_node_has_changes_wasm,Module._ts_node_has_error_wasm=_ts_node_has_error_wasm=e.ts_node_has_error_wasm,Module._ts_node_is_error_wasm=_ts_node_is_error_wasm=e.ts_node_is_error_wasm,Module._ts_node_is_missing_wasm=_ts_node_is_missing_wasm=e.ts_node_is_missing_wasm,Module._ts_node_is_extra_wasm=_ts_node_is_extra_wasm=e.ts_node_is_extra_wasm,Module._ts_node_parse_state_wasm=_ts_node_parse_state_wasm=e.ts_node_parse_state_wasm,Module._ts_node_next_parse_state_wasm=_ts_node_next_parse_state_wasm=e.ts_node_next_parse_state_wasm,Module._ts_query_matches_wasm=_ts_query_matches_wasm=e.ts_query_matches_wasm,Module._ts_query_captures_wasm=_ts_query_captures_wasm=e.ts_query_captures_wasm,Module._memset=_memset=e.memset,Module._memcpy=_memcpy=e.memcpy,Module._memmove=_memmove=e.memmove,Module._iswalpha=_iswalpha=e.iswalpha,Module._iswblank=_iswblank=e.iswblank,Module._iswdigit=_iswdigit=e.iswdigit,Module._iswlower=_iswlower=e.iswlower,Module._iswpunct=_iswpunct=e.iswpunct,Module._iswupper=_iswupper=e.iswupper,Module._iswxdigit=_iswxdigit=e.iswxdigit,Module._memchr=_memchr=e.memchr,Module._strlen=_strlen=e.strlen,Module._strcmp=_strcmp=e.strcmp,Module._strncat=_strncat=e.strncat,Module._strncpy=_strncpy=e.strncpy,Module._towlower=_towlower=e.towlower,Module._towupper=_towupper=e.towupper,_setThrew=e.setThrew,__emscripten_stack_restore=e._emscripten_stack_restore,__emscripten_stack_alloc=e._emscripten_stack_alloc,_emscripten_stack_get_current=e.emscripten_stack_get_current,___wasm_apply_data_relocs=e.__wasm_apply_data_relocs}S(assignWasmExports,"assignWasmExports");var wasmImports={__heap_base:___heap_base,__indirect_function_table:wasmTable,__memory_base:___memory_base,__stack_high:___stack_high,__stack_low:___stack_low,__stack_pointer:___stack_pointer,__table_base:___table_base,_abort_js:__abort_js,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,memory:wasmMemory,tree_sitter_log_callback:_tree_sitter_log_callback,tree_sitter_parse_callback:_tree_sitter_parse_callback,tree_sitter_progress_callback:_tree_sitter_progress_callback,tree_sitter_query_progress_callback:_tree_sitter_query_progress_callback};function callMain(e=[]){var t=resolveGlobalSymbol("main").sym;if(t){e.unshift(thisProgram);var n=e.length,r=stackAlloc((n+1)*4),s=r;e.forEach(a=>{LE_HEAP_STORE_U32((s>>2)*4,stringToUTF8OnStack(a)),s+=4}),LE_HEAP_STORE_U32((s>>2)*4,0);try{var o=t(n,r);return exitJS(o,!0),o}catch(a){return handleException(a)}}}S(callMain,"callMain");function run(e=arguments_){if(runDependencies>0){dependenciesFulfilled=run;return}if(preRun(),runDependencies>0){dependenciesFulfilled=run;return}function t(){if(Module.calledRun=!0,!ABORT){initRuntime(),readyPromiseResolve?.(Module),Module.onRuntimeInitialized?.();var n=Module.noInitialRun||!1;n||callMain(e),postRun()}}S(t,"doRun"),Module.setStatus?(Module.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>Module.setStatus(""),1),t()},1)):t()}S(run,"run");var wasmExports;return wasmExports=await createWasm(),run(),runtimeInitialized?moduleRtn=Module:moduleRtn=new Promise((e,t)=>{readyPromiseResolve=e,readyPromiseReject=t}),moduleRtn}S(jk,"Module");var _$=jk,Bk=null;async function Vk(e){return Bk??=await _$(e)}S(Vk,"initializeBinding");function Uk(){return!!Bk}S(Uk,"checkModule");var W,am,dm,Ck=Rs(e=>{k._ts_parser_delete(e[0]),k._free(e[1])}),fm=class{static{S(this,"Parser")}0=0;1=0;logCallback=null;language=null;static async init(e){$k(await Vk(e)),W=k._ts_init(),am=k.getValue(W,"i32"),dm=k.getValue(W+J,"i32")}constructor(){this.initialize(),Ck?.register(this,[this[0],this[1]],this)}initialize(){if(!Uk())throw new Error("cannot construct a Parser before calling `init()`");k._ts_parser_new_wasm(),this[0]=k.getValue(W,"i32"),this[1]=k.getValue(W+J,"i32")}delete(){Ck?.unregister(this),k._ts_parser_delete(this[0]),k._free(this[1]),this[0]=0,this[1]=0}setLanguage(e){let t;if(!e)t=0,this.language=null;else if(e.constructor===pm){t=e[0];let n=k._ts_language_abi_version(t);if(n<dm||am<n)throw new Error(`Incompatible language version ${n}. Compatibility range ${dm} through ${am}.`);this.language=e}else throw new Error("Argument must be a Language");return k._ts_parser_set_language(this[0],t),this}parse(e,t,n){if(typeof e=="string")k.currentParseCallback=d=>e.slice(d);else if(typeof e=="function")k.currentParseCallback=e;else throw new Error("Argument must be a string or a function");n?.progressCallback?k.currentProgressCallback=n.progressCallback:k.currentProgressCallback=null,this.logCallback?(k.currentLogCallback=this.logCallback,k._ts_parser_enable_logger_wasm(this[0],1)):(k.currentLogCallback=null,k._ts_parser_enable_logger_wasm(this[0],0));let r=0,s=0;if(n?.includedRanges){r=n.includedRanges.length,s=k._calloc(r,ca);let d=s;for(let l=0;l<r;l++)Lk(d,n.includedRanges[l]),d+=ca}let o=k._ts_parser_parse_wasm(this[0],this[1],t?t[0]:0,s,r);if(!o)return k.currentParseCallback=null,k.currentLogCallback=null,k.currentProgressCallback=null,null;if(!this.language)throw new Error("Parser must have a language to parse");let a=new v$(kr,o,this.language,k.currentParseCallback);return k.currentParseCallback=null,k.currentLogCallback=null,k.currentProgressCallback=null,a}reset(){k._ts_parser_reset(this[0])}getIncludedRanges(){k._ts_parser_included_ranges_wasm(this[0]);let e=k.getValue(W,"i32"),t=k.getValue(W+J,"i32"),n=new Array(e);if(e>0){let r=t;for(let s=0;s<e;s++)n[s]=jl(r),r+=ca;k._free(t)}return n}setLogger(e){if(!e)this.logCallback=null;else{if(typeof e!="function")throw new Error("Logger callback must be a function");this.logCallback=e}return this}getLogger(){return this.logCallback}},I$=1,S$=2,T$=/[\w-]+/g,mY={Zero:0,ZeroOrOne:1,ZeroOrMore:2,One:3,OneOrMore:4},Nk=S(e=>e.type==="capture","isCaptureStep"),mm=S(e=>e.type==="string","isStringStep"),en={Syntax:1,NodeName:2,FieldName:3,CaptureName:4,PatternStructure:5},da=class Hk extends Error{constructor(t,n,r,s){super(Hk.formatMessage(t,n)),this.kind=t,this.info=n,this.index=r,this.length=s,this.name="QueryError"}kind;info;index;length;static{S(this,"QueryError")}static formatMessage(t,n){switch(t){case en.NodeName:return`Bad node name '${n.word}'`;case en.FieldName:return`Bad field name '${n.word}'`;case en.CaptureName:return`Bad capture name @${n.word}`;case en.PatternStructure:return`Bad pattern structure at offset ${n.suffix}`;case en.Syntax:return`Bad syntax at offset ${n.suffix}`}}};function zk(e,t,n,r){if(e.length!==3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}`);if(!Nk(e[1]))throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}"`);let s=n==="eq?"||n==="any-eq?",o=!n.startsWith("any-");if(Nk(e[2])){let a=e[1].name,d=e[2].name;r[t].push(l=>{let c=[],u=[];for(let f of l)f.name===a&&c.push(f.node),f.name===d&&u.push(f.node);let p=S((f,m,h)=>h?f.text===m.text:f.text!==m.text,"compare");return o?c.every(f=>u.some(m=>p(f,m,s))):c.some(f=>u.some(m=>p(f,m,s)))})}else{let a=e[1].name,d=e[2].value,l=S(u=>u.text===d,"matches"),c=S(u=>u.text!==d,"doesNotMatch");r[t].push(u=>{let p=[];for(let m of u)m.name===a&&p.push(m.node);let f=s?l:c;return o?p.every(f):p.some(f)})}}S(zk,"parseAnyPredicate");function qk(e,t,n,r){if(e.length!==3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}.`);if(e[1].type!=="capture")throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);if(e[2].type!=="string")throw new Error(`Second argument of \`#${n}\` predicate must be a string. Got @${e[2].name}.`);let s=n==="match?"||n==="any-match?",o=!n.startsWith("any-"),a=e[1].name,d=new RegExp(e[2].value);r[t].push(l=>{let c=[];for(let p of l)p.name===a&&c.push(p.node.text);let u=S((p,f)=>f?d.test(p):!d.test(p),"test");return c.length===0?!s:o?c.every(p=>u(p,s)):c.some(p=>u(p,s))})}S(qk,"parseMatchPredicate");function Gk(e,t,n,r){if(e.length<2)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected at least 1. Got ${e.length-1}.`);if(e[1].type!=="capture")throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);let s=n==="any-of?",o=e[1].name,a=e.slice(2);if(!a.every(mm))throw new Error(`Arguments to \`#${n}\` predicate must be strings.".`);let d=a.map(l=>l.value);r[t].push(l=>{let c=[];for(let u of l)u.name===o&&c.push(u.node.text);return c.length===0?!s:c.every(u=>d.includes(u))===s})}S(Gk,"parseAnyOfPredicate");function Kk(e,t,n,r,s){if(e.length<2||e.length>3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(mm))throw new Error(`Arguments to \`#${n}\` predicate must be strings.".`);let o=n==="is?"?r:s;o[t]||(o[t]={}),o[t][e[1].value]=e[2]?.value??null}S(Kk,"parseIsPredicate");function Wk(e,t,n){if(e.length<2||e.length>3)throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(mm))throw new Error('Arguments to `#set!` predicate must be strings.".');n[t]||(n[t]={}),n[t][e[1].value]=e[2]?.value??null}S(Wk,"parseSetDirective");function Jk(e,t,n,r,s,o,a,d,l,c,u){if(t===I$){let p=r[n];o.push({type:"capture",name:p})}else if(t===S$)o.push({type:"string",value:s[n]});else if(o.length>0){if(o[0].type!=="string")throw new Error("Predicates must begin with a literal value");let p=o[0].value;switch(p){case"any-not-eq?":case"not-eq?":case"any-eq?":case"eq?":zk(o,e,p,a);break;case"any-not-match?":case"not-match?":case"any-match?":case"match?":qk(o,e,p,a);break;case"not-any-of?":case"any-of?":Gk(o,e,p,a);break;case"is?":case"is-not?":Kk(o,e,p,c,u);break;case"set!":Wk(o,e,l);break;default:d[e].push({operator:p,operands:o.slice(1)})}o.length=0}}S(Jk,"parsePattern");var Ok=Rs(e=>{k._ts_query_delete(e)}),hY=class{static{S(this,"Query")}0=0;exceededMatchLimit;textPredicates;captureNames;captureQuantifiers;predicates;setProperties;assertedProperties;refutedProperties;matchLimit;constructor(e,t){let n=k.lengthBytesUTF8(t),r=k._malloc(n+1);k.stringToUTF8(t,r,n+1);let s=k._ts_query_new(e[0],r,n,W,W+J);if(!s){let y=k.getValue(W+J,"i32"),w=k.getValue(W,"i32"),b=k.UTF8ToString(r,w).length,v=t.slice(b,b+100).split(`
|
|
23
23
|
`)[0],R=v.match(T$)?.[0]??"";switch(k._free(r),y){case en.Syntax:throw new da(en.Syntax,{suffix:`${b}: '${v}'...`},b,0);case en.NodeName:throw new da(y,{word:R},b,R.length);case en.FieldName:throw new da(y,{word:R},b,R.length);case en.CaptureName:throw new da(y,{word:R},b,R.length);case en.PatternStructure:throw new da(y,{suffix:`${b}: '${v}'...`},b,0)}}let o=k._ts_query_string_count(s),a=k._ts_query_capture_count(s),d=k._ts_query_pattern_count(s),l=new Array(a),c=new Array(d),u=new Array(o);for(let y=0;y<a;y++){let w=k._ts_query_capture_name_for_id(s,y,W),b=k.getValue(W,"i32");l[y]=k.UTF8ToString(w,b)}for(let y=0;y<d;y++){let w=new Array(a);for(let b=0;b<a;b++){let v=k._ts_query_capture_quantifier_for_id(s,y,b);w[b]=v}c[y]=w}for(let y=0;y<o;y++){let w=k._ts_query_string_value_for_id(s,y,W),b=k.getValue(W,"i32");u[y]=k.UTF8ToString(w,b)}let p=new Array(d),f=new Array(d),m=new Array(d),h=new Array(d),g=new Array(d);for(let y=0;y<d;y++){let w=k._ts_query_predicates_for_pattern(s,y,W),b=k.getValue(W,"i32");h[y]=[],g[y]=[];let v=new Array,R=w;for(let x=0;x<b;x++){let T=k.getValue(R,"i32");R+=J;let N=k.getValue(R,"i32");R+=J,Jk(y,T,N,l,u,v,g,h,p,f,m)}Object.freeze(g[y]),Object.freeze(h[y]),Object.freeze(p[y]),Object.freeze(f[y]),Object.freeze(m[y])}k._free(r),this[0]=s,this.captureNames=l,this.captureQuantifiers=c,this.textPredicates=g,this.predicates=h,this.setProperties=p,this.assertedProperties=f,this.refutedProperties=m,this.exceededMatchLimit=!1,Ok?.register(this,s,this)}delete(){Ok?.unregister(this),k._ts_query_delete(this[0]),this[0]=0}matches(e,t={}){let n=t.startPosition??pt,r=t.endPosition??pt,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??pt,d=t.endContainingPosition??pt,l=t.startContainingIndex??0,c=t.endContainingIndex??0,u=t.matchLimit??4294967295,p=t.maxStartDepth??4294967295,f=t.progressCallback;if(typeof u!="number")throw new Error("Arguments must be numbers");if(this.matchLimit=u,o!==0&&s>o)throw new Error("`startIndex` cannot be greater than `endIndex`");if(r!==pt&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw new Error("`startPosition` cannot be greater than `endPosition`");if(c!==0&&l>c)throw new Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(d!==pt&&(a.row>d.row||a.row===d.row&&a.column>d.column))throw new Error("`startContainingPosition` cannot be greater than `endContainingPosition`");f&&(k.currentQueryProgressCallback=f),se(e),k._ts_query_matches_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,s,o,a.row,a.column,d.row,d.column,l,c,u,p);let m=k.getValue(W,"i32"),h=k.getValue(W+J,"i32"),g=k.getValue(W+2*J,"i32"),y=new Array(m);this.exceededMatchLimit=!!g;let w=0,b=h;for(let v=0;v<m;v++){let R=k.getValue(b,"i32");b+=J;let x=k.getValue(b,"i32");b+=J;let T=new Array(x);if(b=cm(this,e.tree,b,R,T),this.textPredicates[R].every(N=>N(T))){y[w]={patternIndex:R,captures:T};let N=this.setProperties[R];y[w].setProperties=N;let U=this.assertedProperties[R];y[w].assertedProperties=U;let F=this.refutedProperties[R];y[w].refutedProperties=F,w++}}return y.length=w,k._free(h),k.currentQueryProgressCallback=null,y}captures(e,t={}){let n=t.startPosition??pt,r=t.endPosition??pt,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??pt,d=t.endContainingPosition??pt,l=t.startContainingIndex??0,c=t.endContainingIndex??0,u=t.matchLimit??4294967295,p=t.maxStartDepth??4294967295,f=t.progressCallback;if(typeof u!="number")throw new Error("Arguments must be numbers");if(this.matchLimit=u,o!==0&&s>o)throw new Error("`startIndex` cannot be greater than `endIndex`");if(r!==pt&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw new Error("`startPosition` cannot be greater than `endPosition`");if(c!==0&&l>c)throw new Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(d!==pt&&(a.row>d.row||a.row===d.row&&a.column>d.column))throw new Error("`startContainingPosition` cannot be greater than `endContainingPosition`");f&&(k.currentQueryProgressCallback=f),se(e),k._ts_query_captures_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,s,o,a.row,a.column,d.row,d.column,l,c,u,p);let m=k.getValue(W,"i32"),h=k.getValue(W+J,"i32"),g=k.getValue(W+2*J,"i32"),y=new Array;this.exceededMatchLimit=!!g;let w=new Array,b=h;for(let v=0;v<m;v++){let R=k.getValue(b,"i32");b+=J;let x=k.getValue(b,"i32");b+=J;let T=k.getValue(b,"i32");if(b+=J,w.length=x,b=cm(this,e.tree,b,R,w),this.textPredicates[R].every(N=>N(w))){let N=w[T],U=this.setProperties[R];N.setProperties=U;let F=this.assertedProperties[R];N.assertedProperties=F;let I=this.refutedProperties[R];N.refutedProperties=I,y.push(N)}}return k._free(h),k.currentQueryProgressCallback=null,y}predicatesForPattern(e){return this.predicates[e]}disableCapture(e){let t=k.lengthBytesUTF8(e),n=k._malloc(t+1);k.stringToUTF8(e,n,t+1),k._ts_query_disable_capture(this[0],n,t),k._free(n)}disablePattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);k._ts_query_disable_pattern(this[0],e)}didExceedMatchLimit(){return this.exceededMatchLimit}startIndexForPattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return k._ts_query_start_byte_for_pattern(this[0],e)}endIndexForPattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return k._ts_query_end_byte_for_pattern(this[0],e)}patternCount(){return k._ts_query_pattern_count(this[0])}captureIndexForName(e){return this.captureNames.indexOf(e)}isPatternRooted(e){return k._ts_query_is_pattern_rooted(this[0],e)===1}isPatternNonLocal(e){return k._ts_query_is_pattern_non_local(this[0],e)===1}isPatternGuaranteedAtStep(e){return k._ts_query_is_pattern_guaranteed_at_step(this[0],e)===1}};var C$={runtime:{file:"web-tree-sitter.wasm",pkg:"web-tree-sitter"},java:{file:"tree-sitter-java.wasm",pkg:"tree-sitter-java"},python:{file:"tree-sitter-python.wasm",pkg:"tree-sitter-python"}};async function N$(e){return A$(e).then(()=>!0,()=>!1)}async function Yk(e){let{file:t,pkg:n}=C$[e],r=E$(new URL(`./tree-sitter/${t}`,import.meta.url));return await N$(r)?r:P$(import.meta.url).resolve(`${n}/${t}`)}var Xk,Qk=new Map;async function O$(e){Xk??=Yk("runtime").then(n=>fm.init({locateFile:()=>n})),await Xk;let t=Qk.get(e);return t===void 0&&(t=Yk(e).then(n=>pm.load(n)),Qk.set(e,t)),t}function Zk(e){if(/\.java$/i.test(e))return"java";if(/\.py$/i.test(e))return"python"}async function Mt(e,t){let n=await O$(e),r=new fm;try{return r.setLanguage(n),r.parse(t)??void 0}finally{r.delete()}}async function eR(e,t){let n=await Mt(e,t);if(n===void 0)return!1;try{return!n.rootNode.hasError}finally{n.delete()}}var $$={java:{comments:["line_comment","block_comment"],strings:["string_literal","character_literal"]},python:{comments:["comment"],strings:["string_content"]}};function tR(e){return{start:e.startIndex,end:e.endIndex}}function M$(e,t){if(t==="python")return tR(e);let n=e.type==="string_literal"&&e.text.startsWith('"""')?3:1;return{start:e.startIndex+n,end:Math.max(e.startIndex+n,e.endIndex-n)}}async function nR(e,t){let n=await Mt(e,t);if(n!==void 0)try{let r=$$[e];return{comments:n.rootNode.descendantsOfType([...r.comments]).map(tR),strings:n.rootNode.descendantsOfType([...r.strings]).map(s=>M$(s,e))}}finally{n.delete()}}var V$=2*1024*1024,U$=new Set(["it","test","specify","xit","fit","xtest","xspecify"]),H$=new Set(["describe","context","suite","xdescribe","fdescribe","xcontext"]),z$=new Set(["only","skip","fixme","serial","parallel","fail","slow"]);function ua(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof e.type=="string"}function q$(e){let t=[],n=e;for(;ua(n)&&n.type==="MemberExpression";){let o=n.property;ua(o)&&o.type==="Identifier"&&t.unshift(String(o.name)),n=n.object}if(!ua(n)||n.type!=="Identifier")return;t.unshift(String(n.name));let s=t.filter(o=>!z$.has(o)).at(-1);if(s!==void 0){if(H$.has(s))return"suite";if(U$.has(s))return"test"}}function G$(e){if(ua(e)){if(e.type==="StringLiteral")return String(e.value);if(e.type==="TemplateLiteral"){let t=e.expressions,n=e.quasis;if(t.length===0&&n.length===1)return n[0]?.value.cooked}}}async function lR(e,t){return/\.java$/i.test(t)?K$(e):/\.py$/i.test(t)?W$(e):Y$(e,t)}function cR(e,t){return{titlePath:e,line:t.startPosition.row+1,column:t.startPosition.column+1}}var uR=new Set(["class_declaration","interface_declaration","enum_declaration","record_declaration"]);function pR(e,t,n){let r=e.childForFieldName("body");if(r!==null){for(let s of r.namedChildren)if(s.type==="method_declaration"){let o=s.childForFieldName("name");o!==null&&n.push(cR([...t,o.text],o))}else if(uR.has(s.type)){let o=s.childForFieldName("name")?.text;o!==void 0&&pR(s,[...t,o],n)}}}async function K$(e){let t=await Mt("java",e);if(t===void 0)return[];try{if(t.rootNode.hasError)return[];let n=[];for(let r of t.rootNode.namedChildren){if(!uR.has(r.type))continue;let s=r.childForFieldName("name")?.text;if(s===void 0)continue;let o=t.rootNode.namedChildren.find(d=>d.type==="package_declaration")?.namedChildren.find(d=>d.type==="scoped_identifier"||d.type==="identifier")?.text,a=o===void 0?s:`${o}.${s}`;pR(r,[a],n)}return n}finally{t.delete()}}function iR(e,t,n){let r=e.childForFieldName("name");r!==null&&n.push(cR([...t,r.text],r))}function sR(e){return e.type==="decorated_definition"?e.childForFieldName("definition"):e}async function W$(e){let t=await Mt("python",e);if(t===void 0)return[];try{if(t.rootNode.hasError)return[];let n=[];for(let r of t.rootNode.namedChildren){let s=sR(r);if(s?.type==="function_definition"&&iR(s,[],n),s?.type!=="class_definition")continue;let o=s.childForFieldName("name")?.text??"";for(let a of s.childForFieldName("body")?.namedChildren??[]){let d=sR(a);d?.type==="function_definition"&&iR(d,[o],n)}}return n}finally{t.delete()}}function oR(e,t){return t.exec(e)?.[0]??e}function J$(e,t){let n=t.at(-1)??"";return/\.java$/i.test(e)?[...t.slice(0,-1).flatMap(r=>r.split("$")),oR(n,/^[\w$]+/)]:/\.py$/i.test(e)?[...t.slice(0,-1),oR(n,/^\w+/)]:t}function Y$(e,t){if(!/\.[cm]?[jt]sx?$/i.test(t))return[];let n=[],r=/\.([cm]?[jt]sx?)$/i.exec(t)?.[1]?.toLowerCase()??"ts";r.includes("t")&&n.push("typescript"),(r.endsWith("x")||!r.includes("t"))&&n.push("jsx");let s;try{s=(0,dR.parse)(e,{sourceType:"unambiguous",errorRecovery:!0,plugins:n})}catch{return[]}let o=[],a=(d,l)=>{if(Array.isArray(d)){for(let c of d)a(c,l);return}if(ua(d)){if(d.type==="CallExpression"){let c=q$(d.callee),u=d.arguments,p=G$(u[0]);if(c!==void 0&&p!==void 0){if(c==="test"){let f=d.loc;f!==void 0&&o.push({titlePath:[...l,p],line:f.start.line,column:f.start.column+1});return}for(let f of u.slice(1))a(f,[...l,p]);return}}for(let[c,u]of Object.entries(d))c==="loc"||c==="start"||c==="end"||c==="extra"||typeof u=="object"&&u!==null&&a(u,l)}};return a(s,[]),o}function X$(e,t){let n=F$(e,t);return n===""||!aR(n)&&n!==".."&&!n.startsWith(`..${B$}`)}async function fR(e,t){if(!(aR(t)||t.split("/").includes("..")))try{let n=await rR(e),r=await rR(j$(n,t));if(!X$(n,r))return;let s=await L$(r);return!s.isFile()||s.size>V$?void 0:await D$(r,"utf8")}catch{return}}function mR(e,t,n,r){let s=Jo(e,n),o=Jo(e,J$(t,r));return s.length===o.length&&s.every((a,d)=>a===o[d])}async function hm(e,t,n,r){let s=await fR(e,t);return s===void 0?void 0:(await lR(s,t)).some(a=>mR(n,t,a.titlePath,r))}async function gm(e){let t=e.logicalTests.filter(s=>s.location.line===void 0);if(t.length===0)return e;let n=new Map;for(let s of new Set(t.map(o=>o.location.file))){let o=await fR(e.workspace.root,s);n.set(s,o===void 0?[]:await lR(o,s))}let r=e.logicalTests.map(s=>{if(s.location.line!==void 0)return s;let o=(n.get(s.location.file)??[]).filter(d=>mR(e.framework,s.location.file,d.titlePath,s.titlePath)),a=o.length===1?o[0]:void 0;return a===void 0?s:{...s,location:{...s.location,line:a.line,column:a.column}}});return{...e,logicalTests:r}}import{isAbsolute as hR,relative as Q$,sep as gR}from"node:path";function bm(e){return{...e}}function Bl(e,t,n){return{errorId:Y("err",[t,n]),source:n,...e.message===void 0?{}:{message:e.message},...e.name===void 0?{}:{name:e.name},...e.stack===void 0?{}:{stack:e.stack},...e.snippet===void 0?{}:{snippet:e.snippet},...e.value===void 0?{}:{value:e.value},...e.location===void 0?{}:{location:bm(e.location)}}}function bR(e){return{type:e.type,...e.description===void 0?{}:{description:e.description},...e.location===void 0?{}:{location:bm(e.location)}}}function yR(e){return"text"in e?{kind:"text",text:e.text}:{kind:"base64",base64:e.buffer}}function Z$(e,t,n){return{attachmentId:Y("att",[t,String(n)]),name:e.name,contentType:e.contentType,sourceIndex:n,...e.path===void 0?{}:{path:e.path},...e.body===void 0?{}:{bodyBase64:e.body}}}function vR(e,t,n){return{title:e.title,duration:e.duration,...e.error===void 0?{}:{error:Bl(e.error,t,`${n}.error`)},steps:e.steps.map((r,s)=>vR(r,t,`${n}.steps[${s}]`))}}function eM(e){let t=[],n=(r,s,o)=>{r.forEach((a,d)=>{let l=`${o}[${d}]`,c=a.title.length===0?s:[...s,a.title];a.specs.forEach((u,p)=>{u.tests.forEach((f,m)=>{t.push({titlePath:[...c,u.title],spec:u,test:f,sourcePath:`${l}.specs[${p}].tests[${m}]`})})}),n(a.suites,c,`${l}.suites`)})};return n(e.suites,[],"$report.suites"),t}function ym(e,t){if(!hR(t))return;let n=Q$(e,t);if(!(hR(n)||n===".."||n.startsWith(`..${gR}`)))return n.split(gR).join("/")}function tM(e,t){return e.config.projects.map(n=>{let r=n.testDir===void 0?void 0:ym(t,n.testDir);return{projectId:Y("prj",[n.id,n.name]),frameworkProjectId:n.id,name:n.name,repeatEach:n.repeatEach,retries:n.retries,...r===void 0?{}:{testDir:r}}}).sort((n,r)=>n.projectId.localeCompare(r.projectId))}function nM(e,t,n,r){let s=Y("atm",[t,String(e.retry),"repeat:unknown",String(n)]),o=[];return e.error!==void 0&&o.push(Bl(e.error,s,`${r}.error`)),e.errors.forEach((a,d)=>{o.push(Bl(a,s,`${r}.errors[${d}]`))}),{attemptId:s,sourceIndex:n,retry:e.retry,repeat:{state:"unknown",reason:"not-serialized-by-playwright-json-reporter"},status:e.status,duration:e.duration,startTime:new Date(e.startTime).toISOString(),workerIndex:e.workerIndex,parallelIndex:e.parallelIndex,errors:o,stdout:e.stdout.map(yR),stderr:e.stderr.map(yR),steps:e.steps.map((a,d)=>vR(a,s,`${r}.steps[${d}]`)),attachments:e.attachments.map((a,d)=>Z$(a,s,d)),annotations:e.annotations.map(bR),...e.errorLocation===void 0?{}:{errorLocation:bm(e.errorLocation)}}}var rM=/\u001b\[[0-9;]*m/g,kR=/^Testing stopped early after (\d+) maximum allowed failures?\.?$/,iM=/^Timed out waiting [\d.]+s for the /;function wm(e){return(e.message??"").replace(rM,"").trim()}function sM(e){return kR.test(wm(e))}var pa=e=>e.status==="interrupted";function oM(e,t,n,r){let s=e.reduce((p,f)=>p+f.attempts.filter(pa).length,0),o=e.filter(p=>p.attempts.length===0).length,a=n.map(p=>kR.exec(wm(p))).find(p=>p!==null),d=r??(a===void 0?void 0:Number(a[1])),l=new Map(t.map(p=>[p.projectId,p.retries])),c=e.filter(p=>p.status==="unexpected"&&!p.attempts.some(pa)&&p.attempts.length>(l.get(p.projectId)??0)).length;return d!==void 0&&d>0&&(a!==void 0||c>=d)&&(s>0||o>0||a!==void 0)?{cause:"max-failures",limit:d,cutOffAttempts:s,notStarted:o}:n.some(p=>iM.test(wm(p)))?{cause:"global-timeout",cutOffAttempts:s,notStarted:o}:s===0?void 0:{cause:"interrupted",cutOffAttempts:s,notStarted:o}}function aM(e,t,n){return e.length===0?"zero-tests":n!==void 0&&n.cause!=="max-failures"||e.some(s=>s.attempts.some(pa))?"interrupted":(n?.cause==="max-failures"?t.filter(s=>!sM(s)):t).length>0?"report-errors":"analysis-ready"}function RR(e){let{report:t,reportHash:n,artifact:r,options:s}=e,o=s.workspaceRoot,a=tM(t,o),d=t.config.rootDir===void 0?void 0:ym(o,t.config.rootDir),l=v=>{let R=v.replaceAll("\\","/");return d===void 0||d===""?R:`${d}/${R}`},c=t.config.configFile===void 0?void 0:ym(o,t.config.configFile),u=new Map(a.map(v=>[v.frameworkProjectId,v.projectId])),f=eM(t).map(({spec:v,test:R,titlePath:x,sourcePath:T})=>{let N=u.get(R.projectId);if(N===void 0)throw new Error(`Validated test references unknown project ID: ${R.projectId}`);let U=l(v.file),F=Y("tst",[o,N,U,...x]);return{logicalTestId:F,projectId:N,title:v.title,titlePath:x,tags:[...v.tags].sort(),location:{file:U,line:v.line,column:v.column},timeout:R.timeout,expectedStatus:R.expectedStatus,status:R.status,annotations:R.annotations.map(bR),attempts:R.results.map((I,C)=>nM(I,F,C,`${T}.results[${C}]`))}});f.sort((v,R)=>v.logicalTestId.localeCompare(R.logicalTestId));let m=t.errors.map((v,R)=>Bl(v,r.artifactId,`$report.errors[${R}]`)),h=oM(f,a,m,t.config.maxFailures),g=h?.cause==="max-failures"?f.map(v=>v.attempts.some(pa)?{...v,attempts:v.attempts.filter(R=>!pa(R))}:v):f,y=g.reduce((v,R)=>v+R.attempts.reduce((x,T)=>x+T.attachments.length,0),0),w=new Date(t.stats.startTime).toISOString(),b=Y("run",[n,o,s.gitRoot??"",Xr,"1"]);return{schemaVersion:Xr,runId:b,framework:"playwright",createdAt:w,workspace:{root:o,...s.gitRoot===void 0?{}:{gitRoot:s.gitRoot}},sourceHashes:{report:n},artifact:r,usability:aM(g,m,h),...h===void 0?{}:{stop:h},projects:a,...c===void 0?{}:{configFile:c},logicalTests:g,reportErrors:m,collections:{tests:g.length===0?"empty":"present",errors:m.length===0?"empty":"present",attachments:y===0?"empty":"present"},warnings:[...e.warnings].sort(),stats:{...t.stats,startTime:w}}}function vm(e,t){let n=me(e,t),r=xe(n,"line",Le,t),s=xe(n,"column",Le,t);return{file:ie(n.file,`${t}.file`),...r===void 0?{}:{line:r},...s===void 0?{}:{column:s}}}function fa(e,t){let n=me(e,t),r=xe(n,"message",ie,t),s=xe(n,"name",ie,t),o=xe(n,"stack",ie,t),a=xe(n,"snippet",ie,t),d=xe(n,"value",ie,t),l=xe(n,"location",vm,t);return{...r===void 0?{}:{message:r},...s===void 0?{}:{name:s},...o===void 0?{}:{stack:o},...a===void 0?{}:{snippet:a},...d===void 0?{}:{value:d},...l===void 0?{}:{location:l}}}function IR(e,t){let n=me(e,t),r=xe(n,"description",ie,t),s=xe(n,"location",vm,t);return{type:ie(n.type,`${t}.type`),...r===void 0?{}:{description:r},...s===void 0?{}:{location:s}}}function xR(e,t){let n=me(e,t),r=typeof n.text=="string",s=typeof n.buffer=="string";return r===s?Ze(t,"exactly one of text or buffer"):r?{text:ie(n.text,`${t}.text`)}:{buffer:bf(n.buffer,`${t}.buffer`)}}function dM(e,t){let n=me(e,t),r=xe(n,"path",ie,t),s=xe(n,"body",bf,t);return{name:ie(n.name,`${t}.name`),contentType:ie(n.contentType,`${t}.contentType`),...r===void 0?{}:{path:r},...s===void 0?{}:{body:s}}}function SR(e,t){let n=me(e,t),r=xe(n,"error",fa,t);return{title:ie(n.title,`${t}.title`),duration:Ot(n.duration,`${t}.duration`),...r===void 0?{}:{error:r},steps:ue(n.steps??[],`${t}.steps`,SR)}}var TR=new Set(["passed","failed","timedOut","skipped","interrupted"]),lM=new Set(["expected","unexpected","flaky","skipped"]);function cM(e,t){let n=me(e,t),r=xe(n,"error",fa,t),s=xe(n,"errorLocation",vm,t);return{workerIndex:Go(n.workerIndex,`${t}.workerIndex`),parallelIndex:n.parallelIndex===void 0?Go(n.workerIndex,`${t}.workerIndex`):Go(n.parallelIndex,`${t}.parallelIndex`),status:Zr(n.status,`${t}.status`,TR),duration:Ot(n.duration,`${t}.duration`),startTime:wf(n.startTime,`${t}.startTime`),retry:Le(n.retry,`${t}.retry`),...r===void 0?{}:{error:r},errors:ue(n.errors??[],`${t}.errors`,fa),stdout:ue(n.stdout??[],`${t}.stdout`,xR),stderr:ue(n.stderr??[],`${t}.stderr`,xR),steps:ue(n.steps??[],`${t}.steps`,SR),attachments:ue(n.attachments??[],`${t}.attachments`,dM),annotations:ue(n.annotations??[],`${t}.annotations`,IR),...s===void 0?{}:{errorLocation:s}}}function uM(e,t){let n=me(e,t);return{timeout:Ot(n.timeout,`${t}.timeout`),annotations:ue(n.annotations??[],`${t}.annotations`,IR),expectedStatus:Zr(n.expectedStatus,`${t}.expectedStatus`,TR),projectName:ie(n.projectName,`${t}.projectName`),projectId:ie(n.projectId,`${t}.projectId`),results:ue(n.results,`${t}.results`,cM),status:Zr(n.status,`${t}.status`,lM)}}function pM(e,t){let n=me(e,t);return{title:ie(n.title,`${t}.title`),ok:Ov(n.ok,`${t}.ok`),tags:ue(n.tags??[],`${t}.tags`,ie),tests:ue(n.tests,`${t}.tests`,uM),file:ie(n.file,`${t}.file`),line:Le(n.line,`${t}.line`),column:Le(n.column,`${t}.column`)}}function AR(e,t){let n=me(e,t),r=xe(n,"file",ie,t),s=xe(n,"line",Le,t),o=xe(n,"column",Le,t);return{title:ie(n.title,`${t}.title`),...r===void 0?{}:{file:r},...s===void 0?{}:{line:s},...o===void 0?{}:{column:o},suites:ue(n.suites??[],`${t}.suites`,AR),specs:ue(n.specs??[],`${t}.specs`,pM)}}function fM(e,t){let n=me(e,t);return{id:ie(n.id,`${t}.id`),name:ie(n.name,`${t}.name`),repeatEach:Le(n.repeatEach,`${t}.repeatEach`),retries:Le(n.retries,`${t}.retries`),...kl("testDir",Ie(n.testDir,`${t}.testDir`))}}function _R(e){return{version:ie(e.version,"$report.config.version"),projects:ue(e.projects,"$report.config.projects",fM),...kl("rootDir",Ie(e.rootDir,"$report.config.rootDir")),...kl("configFile",Ie(e.configFile,"$report.config.configFile")),...mM(hM(e.maxFailures))}}function mM(e){return e===void 0?{}:{maxFailures:e}}function hM(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:void 0}function gM(e){let t={expected:0,skipped:0,unexpected:0,flaky:0},n=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,s=a=>{for(let d of a.specs)for(let l of d.tests){t[l.status]+=1;for(let c of l.results){let u=Date.parse(c.startTime);n=Math.min(n,u),r=Math.max(r,u+c.duration)}}for(let d of a.suites)s(d)};for(let a of e)s(a);let o=Number.isFinite(n)?n:0;return{startTime:new Date(o).toISOString(),duration:Number.isFinite(r)?r-o:0,...t}}function PR(e){let t=me(e,"$report"),n=me(t.config,"$report.config"),r=ue(t.suites,"$report.suites",AR);if(t.stats===void 0)return{config:_R(n),suites:r,errors:ue(t.errors??[],"$report.errors",fa),stats:gM(r),statsDerived:!0};let s=me(t.stats,"$report.stats");return{config:_R(n),suites:r,errors:ue(t.errors??[],"$report.errors",fa),stats:{startTime:wf(s.startTime,"$report.stats.startTime"),duration:Ot(s.duration,"$report.stats.duration"),expected:Le(s.expected,"$report.stats.expected"),skipped:Le(s.skipped,"$report.stats.skipped"),unexpected:Le(s.unexpected,"$report.stats.unexpected"),flaky:Le(s.flaky,"$report.stats.flaky")}}}var yM=new TextDecoder("utf-8",{fatal:!0});function ii(e,t,n){return{kind:"unreadable",artifact:{artifactId:Y("art",[e??"unavailable",t??"bytes"]),kind:"report",availability:"unreadable",...t===void 0?{}:{path:t},...e===void 0?{}:{sha256:e},warnings:[]},diagnostic:n}}function wM(e){return new Set(e??zo)}var km=[...zo].sort((e,t)=>e.localeCompare(t,"en",{numeric:!0}))[0]?.split(".").slice(0,2).join(".");function bM(e){let t=e?.config?.version;if(typeof t!="string"||km===void 0)return;let[n,r]=t.split(".").map(d=>Number.parseInt(d,10)),[s,o]=km.split(".").map(Number);return n===void 0||r===void 0||Number.isNaN(n)||Number.isNaN(r)?void 0:n<(s??0)||n===s&&r<(o??0)?t:void 0}function xs(e,t){let n=Ce(e);if(e.byteLength===0)return ii(n,t.reportPath,{reasonCode:"empty-input",message:"The Playwright JSON report is empty.",...t.reportPath===void 0?{}:{path:t.reportPath}});let r;try{r=yM.decode(e)}catch{return ii(n,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(f){return ii(n,t.reportPath,{reasonCode:"invalid-json",message:f instanceof Error?f.message:"The report is not valid JSON.",...t.reportPath===void 0?{}:{path:t.reportPath}})}let o;try{o=PR(s)}catch(f){let m=f instanceof cs?f.message:"The JSON value is not a supported Playwright report.",h=bM(s);return ii(n,t.reportPath,{reasonCode:"invalid-report-shape",message:h===void 0?m:`Playwright ${h} reports aren't supported: KwikQA reads Playwright ${km} or later. (${m})`,...t.reportPath===void 0?{}:{path:t.reportPath}})}let a=new Set;for(let f of o.config.projects){if(a.has(f.id))return ii(n,t.reportPath,{reasonCode:"invalid-report-shape",message:`$report.config.projects contains duplicate project ID: ${f.id}`,...t.reportPath===void 0?{}:{path:t.reportPath}});a.add(f.id)}if(new Set(t.incompatiblePlaywrightVersions??[]).has(o.config.version))return ii(n,t.reportPath,{reasonCode:"incompatible-playwright-version",message:`Playwright ${o.config.version} is configured as incompatible.`,...t.reportPath===void 0?{}:{path:t.reportPath}});let c=wM(t.testedPlaywrightVersions).has(o.config.version),u=[];c||u.push(`unverified-producer-version:${o.config.version}`),o.config.projects.some(f=>f.repeatEach>1)&&u.push("repeat-index-unavailable"),o.statsDerived===!0&&u.push("run-stats-derived");let p={artifactId:Y("art",[n]),kind:"report",availability:"present",...t.reportPath===void 0?{}:{path:t.reportPath},sha256:n,format:"playwright-json",formatVersion:o.config.version,versionConfidence:c?"verified":"unverified",warnings:[...u].sort()};try{return{kind:"parsed",run:RR({report:o,reportHash:n,artifact:p,options:t,warnings:u})}}catch(f){return ii(n,t.reportPath,{reasonCode:"invalid-report-shape",message:f instanceof Error?f.message:"The report could not be normalized.",...t.reportPath===void 0?{}:{path:t.reportPath}})}}import{createHash as KL}from"node:crypto";import{readdir as WL,readFile as JL,stat as YL}from"node:fs/promises";import{basename as XL,dirname as QL,join as ZL}from"node:path";import{resolve as vM}from"node:path";var kM="1",RM="application/vnd.allure.playwright-trace";function xm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _m(e){return xm(e)&&typeof e.uuid=="string"&&typeof e.status=="string"&&Array.isArray(e.labels)&&(typeof e.historyId=="string"||typeof e.fullName=="string")}function Im(e){return xm(e)&&typeof e.uuid=="string"&&typeof e.status!="string"&&(Array.isArray(e.children)||Array.isArray(e.befores)||Array.isArray(e.afters))}function Sm(e){return xm(e)&&e.uuid===void 0&&Array.isArray(e.errors)&&Array.isArray(e.attachments)}var xM={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 Xn(e,t){return e.labels?.find(n=>n.name===t)?.value}var ER={passed:"passed",failed:"failed",broken:"failed",skipped:"skipped"};function Vl(e){return e==="junit"||e==="testng"}function ma(e,t){let n=e?.message?.trim()||void 0,r=e?.trace?.trim()||void 0;if(n===void 0&&r===void 0)return;let s=Ue(r,t);return{...n===void 0?{}:{message:n},...r===void 0?{}:{stack:r},...s===void 0?{}:{location:s}}}function CR(e){for(let t of(e??"").split(`
|
|
24
24
|
`)){let n=ps(t);if(n!==void 0)return n}}function Tm(e){return typeof e.start=="number"&&typeof e.stop=="number"&&e.stop>=e.start?e.stop-e.start:0}function $R(e){let t=typeof e=="number"?new Date(e):void 0;return t===void 0||Number.isNaN(t.getTime())?{}:{startTime:t.toISOString()}}function Am(e,t){let r=e.status==="failed"||e.status==="broken"?ma(e.statusDetails,t):void 0;return{title:e.name??"",duration:Tm(e),...r===void 0?{}:{error:r},steps:(e.steps??[]).map(s=>Am(s,t))}}function MR(e,t){return[...(e.attachments??[]).flatMap(r=>r.source===void 0?[]:[{name:r.name??r.source,contentType:r.type===RM?"application/zip":r.type??"",path:t===void 0?r.source:vM(t,r.source)}]),...(e.steps??[]).flatMap(r=>MR(r,t))]}function _M(e){return e.replace(/^\[/,"").replace(/\]$/,"").split("]/[").map(t=>{let n=t.indexOf(":");return{type:t.slice(0,n),value:t.slice(n+1)}})}function IM(e){let t=Xn(e,"junit.platform.uniqueid")??e.parameters?.find(a=>a.name==="UniqueId")?.value;if(t===void 0)return;let n=_M(t),r=n.findIndex(a=>a.type==="test-template"||a.type==="test-factory");if(r<0)return;let s=n.slice(r+1).map(a=>/^#(\d+)$/.exec(a.value)?.[1]);return s.length===0||s.includes(void 0)?void 0:`${(n[r]?.value??"").replace(/\(([^)]*)\)$/,(a,d)=>`(${d.split(",").map(c=>c.trim().split(/[.$]/).at(-1)??"").filter(c=>c!=="").join(", ")})`)}${s.map(a=>`[${a}]`).join("")}`}function SM(e){let t=e.split(".").filter(r=>r!==""),n=t.length;for(;n>1&&/^[A-Z]/.test(t[n-1]??"");)n-=1;return{file:`${t.slice(0,n).join("/")}.py`,classes:t.slice(n)}}function TM(e){let t=e.titlePath??[],n=t.findIndex(r=>r.endsWith(".py"));return n>=0?{file:t.slice(0,n+1).join("/"),classes:t.slice(n+1)}:SM((e.fullName??"").split("#")[0]??"")}function Rm(e,t){return{file:Rt(e),titlePath:[...e.split("$").filter(n=>n!==""),t],projectId:""}}function NR(e,t,n){let r=Xn(e,"testClass");if(r!==void 0&&Vl(t))return Rm(r,n);if(t==="pytest"){let{file:o,classes:a}=TM(e);return{file:o,titlePath:[...a,n],projectId:""}}if(t==="playwright"){let o=(e.fullName??n).split(" \u203A ");return{file:Xn(e,"suite")??o[0]??"",titlePath:o.length>1?o.slice(1):[n],projectId:Xn(e,"parentSuite")??""}}let s=Xn(e,"suite");return{file:s!==void 0&&/\.[cm]?[jt]sx?$/.test(s)?s:"",titlePath:[e.fullName??n],projectId:""}}function OR(e,t,n,r){return{status:"failed",retry:t,...$R(e.start),duration:Tm(e),errors:n===void 0?[]:[n],attachments:[],stdout:[],stderr:[],steps:(e.steps??[]).map(s=>Am(s,r))}}function LR(e){let t=[],n=[],r=[];for(let I of e)_m(I.json)?t.push({...I.json,...I.directory===void 0?{}:{directory:I.directory}}):Im(I.json)?n.push(I.json):Sm(I.json)&&r.push(...I.json.errors);if(t.length===0)throw new Error("The Allure results hold no test result.");let s=new Set(t.map(I=>xM[Xn(I,"framework")??""]??"unknown")),o=s.size===1?[...s][0]??"unknown":"unknown",a=[];s.size>1&&a.push("allure-mixed-frameworks");let d=new Map;for(let I of t){let C=I.historyId??`uuid:${I.uuid}`,A=d.get(C)??{key:C,results:[]};d.set(C,A),A.results.push(I)}let l=new Map,c=I=>{let C=Xn(I,"testMethod");if(o==="junit")return IM(I)??C??I.name??"";if(o!=="testng")return I.name??"";let A=C??I.name??"",M=(I.parameters??[]).map(P=>P.value??"");if(M.length===0)return A;let $=`${Xn(I,"testClass")??""}\0${A}`,j=l.get($)??new Map;l.set($,j);let O=j.get(JSON.stringify(M))??j.size;return j.set(JSON.stringify(M),O),`${A}[${O}]`},u=0,p=0,f=new Map,m=[],h=[...d.values()].sort((I,C)=>{let A=M=>Math.min(...M.results.map($=>$.start??0));return A(I)-A(C)||I.key.localeCompare(C.key)});for(let I of h){let C=[...I.results].sort((j,O)=>(j.start??0)-(O.start??0)||j.uuid.localeCompare(O.uuid)),A=C.filter((j,O)=>{let P=j.status==="passed"&&O<C.length-1;return P&&(u+=1),!P}),M=A.at(-1);if(M===void 0)continue;f.set(I.key,M);let $=NR(M,o,c(M));m.push({file:$.file,titlePath:$.titlePath,projectId:$.projectId,attempts:A.map((j,O)=>{let P=O<A.length-1,E=ER[j.status??""];!P&&E===void 0&&(p+=1);let L=P?"failed":E??"skipped",B=L==="passed"?void 0:ma(j.statusDetails,$.file);return{status:L,retry:O,...$R(j.start),duration:Tm(j),errors:B===void 0?[]:[B],attachments:MR(j,j.directory),stdout:[],stderr:[],steps:(j.steps??[]).map(Z=>Am(Z,$.file))}})})}u>0&&a.push(`allure-passed-before-retry-ignored:${u}`),p>0&&a.push(`allure-unknown-status:${p}`);let g=new Map;for(let I of d.values()){let C=f.get(I.key);if(C!==void 0)for(let A of I.results)g.set(A.uuid,C)}let y=new Set;for(let I of n){let C=(I.children??[]).map(M=>g.get(M)).filter(M=>M!==void 0);if(C.some(M=>ER[M.status??""]==="failed"))continue;let A=[...(I.befores??[]).map(M=>({fixture:M,phase:"setup"})),...(I.afters??[]).map(M=>({fixture:M,phase:"teardown"}))].filter(({fixture:M})=>M.status==="failed"||M.status==="broken");for(let{fixture:M,phase:$}of A){let j=Vl(o)?CR(M.statusDetails?.trace):void 0,O=M.name??j?.method??"fixture",P=C[0],E=j?.className??(P===void 0?void 0:Xn(P,"testClass")),L=`${O} (${$})`,B=E!==void 0&&Vl(o)?Rm(E,L):P===void 0?void 0:NR(P,o,L);if(B===void 0)continue;let Z=`${E??B.file}\0${O}`;y.has(Z)||(y.add(Z),m.push({...B,attempts:[OR(M,0,ma(M.statusDetails,B.file),B.file)]}))}}let w=[],b=new Map,v=[...r].sort((I,C)=>(I.timestamp??0)-(C.timestamp??0));for(let I of v){let C=Vl(o)?CR(I.trace):void 0;if(C===void 0){let P=ma(I,"");P!==void 0&&w.push(P);continue}let A=`${C.className}\0${C.method}`;if(y.has(A))continue;let M=/\bdid not run\b/.test(I.message??"")?"setup":"teardown",$=Rm(C.className,`${C.method} (${M})`),j=b.get(A)??{...$,attempts:[]};b.set(A,j);let O=I.timestamp===void 0?{}:{start:I.timestamp};j.attempts.push(OR(O,j.attempts.length,ma(I,$.file),$.file))}m.push(...b.values());let R=new Map;if(o==="playwright")for(let I of m)for(let C of I.attempts.flatMap(A=>A.errors)){let A=C.location?.file;A!==void 0&&!R.has(I.file)&&A.replaceAll("\\","/").endsWith(`/${I.file}`)&&R.set(I.file,A)}let x=m.map(I=>{let C=R.get(I.file);return C===void 0?I:{...I,file:C}}),T=t.flatMap(I=>typeof I.start=="number"?[I.start]:[]),N=t.flatMap(I=>typeof I.stop=="number"?[I.stop]:[]),U=T.length===0?void 0:new Date(Math.min(...T)).toISOString(),F=[...new Set(x.map(I=>I.projectId))].sort();return{framework:o,format:"allure-json",adapterVersion:kM,...U===void 0?{}:{startTime:U},duration:T.length===0||N.length===0?0:Math.max(...N)-Math.min(...T),projects:(F.length===0?[""]:F).map(I=>({id:I,name:I,retries:0})),tests:x,errors:w,interrupted:!1,warnings:a}}var AM="1",PM=["0.2.0","1.0.0"];function DR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pm(e){return DR(e)&&e.reportFormat==="CTRF"&&DR(e.results)&&Array.isArray(e.results.tests)}var EM=[...bn,...qo,...hf];function CM(e){let t=e?.trim().toLowerCase()??"";return EM.includes(t)?t:"unknown"}var NM={passed:"passed",failed:"failed",skipped:"skipped",pending:"skipped"};function BR(e){if(typeof e!="number")return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function OM(e,t){let n=e.message?.trim()||void 0,r=e.trace?.trim()||void 0,s=e.snippet?.trimEnd()||void 0;if(n===void 0&&r===void 0)return;let o=Ue(r,t);return{...n===void 0?{}:{message:n},...r===void 0?{}:{stack:r},...s===void 0?{}:{snippet:s},...o===void 0?{}:{location:o}}}function $M(e){return(e.attachments??[]).flatMap(t=>t.path===void 0||t.path===""?[]:[{name:t.name??t.path,contentType:t.contentType??"",path:t.path}])}function FR(e,t,n,r,s){let o=BR(e.start),a=e.duration,d=typeof e.start=="number"&&typeof e.stop=="number"?e.stop-e.start:void 0,l=typeof a=="number"&&a>=0?a:d??0,c=t==="passed"?void 0:OM(e,r);return{status:t,retry:n,...o===void 0?{}:{startTime:o},duration:l>=0?l:0,errors:c===void 0?[]:[c],attachments:$M(e),stdout:e.stdout??[],stderr:e.stderr??[],steps:s}}function jR(e,t){if(t===void 0||e==="")return!1;let n=t.replaceAll("\\","/"),r=e.replaceAll("\\","/");return n===r||n.endsWith(`/${r}`)}function MM(e,t){let n=(e.suite??[]).filter(d=>d!==""),r=e.name??"",s=n.findIndex(d=>jR(d,e.filePath)),o=s<0?n:n.slice(s+1),a=s>0?n.slice(0,s).join(" \u203A "):"";if(t==="pytest"&&r.includes("::")){let d=r.split("::");return{titlePath:jR(d[0]??"",e.filePath)?d.slice(1):d,projectId:a}}if(t==="jest"){let d=`${o.join(" ")} `,l=o.length>0&&r.startsWith(d)?r.slice(d.length):r;return{titlePath:[...o,l],projectId:a}}return{titlePath:[...o,r],projectId:a}}function VR(e){if(!Pm(e))throw new Error("A CTRF report needs results with a tests array.");let t=e,n=CM(t.results.tool?.name),r=t.results.tool?.version?.trim()||void 0,s=[],o=t.specVersion??"";PM.includes(o)||s.push(`unverified-ctrf-spec-version:${o===""?"unrecorded":o}`);let a=0,d=0,l=!1,c=g=>{let y=NM[g.status??""];return y===void 0&&(a+=1),y??"skipped"},u=t.results.tests.map(g=>{let y=g.filePath??"",w=MM(g,n),b=g.retryAttempts??[];typeof g.retries=="number"&&g.retries>b.length&&(l=!0);let v=(g.steps??[]).map(T=>({title:T.name??"",duration:0,steps:[]})),R=[...b.map((T,N)=>FR(T,c(T),N,y,[])),FR(g,c(g),b.length,y,v)],x=R.at(-1)?.status==="passed"&&R.slice(0,-1).some(T=>T.status==="failed");return typeof g.flaky=="boolean"&&g.flaky!==x&&(d+=1),{file:y,titlePath:w.titlePath,...typeof g.line=="number"&&g.line>0?{line:g.line}:{},projectId:w.projectId,...g.tags===void 0?{}:{tags:g.tags},attempts:R}});a>0&&s.push(`ctrf-other-status:${a}`),d>0&&s.push(`ctrf-flaky-mismatch:${d}`),l&&s.push("final-attempt-only");let{start:p,stop:f}=t.results.summary??{},m=BR(p),h=[...new Set(u.map(g=>g.projectId))].sort();return{framework:n,format:"ctrf-json",adapterVersion:AM,...r===void 0?{}:{frameworkVersion:r},...m===void 0?{}:{startTime:m},duration:typeof p=="number"&&typeof f=="number"&&f>=p?f-p:0,projects:(h.length===0?[""]:h).map(g=>({id:g,name:g,retries:0})),tests:u,errors:[],interrupted:!1,warnings:s}}var LM="3";function DM(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Em(e){return Array.isArray(e)&&e.length>0&&e.every(t=>DM(t)&&typeof t.uri=="string"&&typeof t.keyword=="string"&&Array.isArray(t.elements))}function FM(e){return e.startsWith("classpath:")?e.slice(10).replace(/^\/+/,""):e.startsWith("file:")&&!e.startsWith("file://")?e.slice(5):e}var HR=new Set(["undefined","ambiguous","pending"]),jM=1e6;function UR(e){let t=e.result?.duration;return typeof t=="number"&&t>0?t/jM:0}function BM(e,t){return t!==void 0?`${t} hook`:`${(e.keyword??"").trim()} ${e.name??""}`.trim()}function VM(e,t){if(t!==void 0||e.hidden!==!0)return t;let n=(e.keyword??"").trim();return n==="Before"||n==="After"?n:void 0}function UM(e,t,n,r){let s=e.result?.status??"",o=e.result?.error_message?.trim()||void 0,a=typeof e.line=="number"?{file:r,line:e.line}:void 0;if(HR.has(s))return{message:`${s[0]?.toUpperCase()}${s.slice(1)} step: ${t}`,...o===void 0?{}:{stack:o},...a===void 0?{}:{location:a}};if(s!=="failed"||o===void 0)return;let d=o.split(/\r?\n/),l=d.findIndex(p=>/^\s*at\s/.test(p)),c=(l<0?d:d.slice(0,l)).join(`
|
|
25
25
|
`).trim()||o,u=Ue(o,r)??a;return{message:n===void 0?c:`${n} hook failed: ${c}`,stack:o,...u===void 0?{}:{location:u}}}function HM(e){let t=e.match?.location;if(t===void 0)return;let n=t.indexOf("("),r=t.lastIndexOf(")");if(n<0||r<n)return;let s=t.slice(0,n),o=s.lastIndexOf(".");if(o<=0)return;let a=s.slice(0,o),d=t.slice(n+1,r).split(",").map(l=>l.trim()).filter(l=>l!=="").map(l=>l.split(/[.$]/).at(-1)??l);return{className:a,file:Rt(a),method:s.slice(o+1),parameters:d}}function zM(e){return(e.embeddings??[]).flatMap(t=>t.data===void 0||t.data===""?[]:[{name:t.name??"attachment",contentType:t.mime_type??t.media?.type??"",body:t.data}])}function qM(e,t,n){let r=e.map(({step:c})=>c.result?.status??""),s=r.some(c=>c==="failed"||HR.has(c))?"failed":r.some(c=>c==="passed")?"passed":"skipped",o=[],a=[],d=[];for(let c of e){let{step:u}=c,p=VM(u,c.hook),f=BM(u,p),m=UM(u,f,p,t);m!==void 0&&a.length===0&&a.push(m);let h=HM(u);o.push({title:f,duration:UR(u),...m===void 0?{}:{error:m},...h===void 0?{}:{definition:h},steps:[]}),d.push(...zM(u))}let l=n===void 0||Number.isNaN(new Date(n).getTime())?void 0:new Date(n).toISOString();return{status:s,retry:0,...l===void 0?{}:{startTime:l},duration:e.reduce((c,{step:u})=>c+UR(u),0),errors:a,attachments:d,stdout:[],stderr:[],steps:o}}function GM(...e){return[...new Set(e.flatMap(t=>(t??[]).flatMap(n=>n.name??[])))].sort()}function zR(e){if(!Em(e))throw new Error("A Cucumber report is an array of features.");let t=[],n=[];for(let s of e){let o=FM(s.uri),a=[],d=[];for(let u of s.elements){if(u.type==="background"){d.push(u);continue}a.push({element:u,background:d}),d=[]}let l=new Map;for(let{element:u}of a){let p=u.name??"";l.set(p,(l.get(p)??0)+1)}let c=new Map;for(let{element:u,background:p}of a){let f=u.name??"",m=(c.get(f)??0)+1;c.set(f,m);let h=[...p.flatMap(g=>(g.before??[]).map(y=>({step:y,hook:"Before"}))),...(u.before??[]).map(g=>({step:g,hook:"Before"})),...p.flatMap(g=>(g.steps??[]).map(y=>({step:y}))),...(u.steps??[]).map(g=>({step:g})),...(u.after??[]).map(g=>({step:g,hook:"After"})),...p.flatMap(g=>(g.after??[]).map(y=>({step:y,hook:"After"})))];u.start_timestamp!==void 0&&n.push(u.start_timestamp),t.push({file:o,featureUri:s.uri,titlePath:[s.name??"",f,...(l.get(f)??0)>1?[`Example #${m}`]:[]],...typeof u.line=="number"?{line:u.line}:{},projectId:"",tags:GM(s.tags,u.tags),attempts:[qM(h,o,u.start_timestamp)]})}}let r=n.map(s=>new Date(s)).filter(s=>!Number.isNaN(s.getTime())).map(s=>s.toISOString()).sort()[0];return{framework:"cucumber",format:"cucumber-json",adapterVersion:LM,...r===void 0?{}:{startTime:r},duration:t.reduce((s,o)=>s+(o.attempts[0]?.duration??0),0),projects:[{id:"",name:"",retries:0}],tests:t,errors:[],interrupted:!1,warnings:["final-attempt-only"]}}import{statSync as iL}from"node:fs";import{basename as sL,dirname as oL,isAbsolute as aL,join as dL,resolve as lL}from"node:path";import{readdirSync as KM,readFileSync as WM,statSync as JM}from"node:fs";import{join as Rr}from"node:path";var YM=new Set(["node_modules",".venv","venv","env","site-packages","__pycache__","build","dist","target"]),XM=2;function Nm(e){try{return JM(e).isFile()}catch{return!1}}function Cm(e,t){try{return t.test(WM(e,"utf8"))}catch{return!1}}function QM(e){return Nm(Rr(e,"pytest.ini"))||Cm(Rr(e,"pyproject.toml"),/^\[tool\.pytest\.ini_options\]/m)||Cm(Rr(e,"setup.cfg"),/^\[tool:pytest\]/m)||Cm(Rr(e,"tox.ini"),/^\[pytest\]/m)}var qR=new Map;function ZM(e){let t=qR.get(e);if(t!==void 0)return t;let n=[],r=(o,a)=>{if(a>XM)return;let d=[];try{d=KM(Rr(e,o),{withFileTypes:!0}).filter(l=>l.isDirectory()&&!l.isSymbolicLink()).map(l=>l.name).filter(l=>!l.startsWith(".")&&!YM.has(l)).sort()}catch{return}for(let l of d){let c=o===""?l:`${o}/${l}`;QM(Rr(e,c))&&n.push(c),r(c,a+1)}};r("",1);let s=n.sort();return qR.set(e,s),s}function ha(e,t,n=ZM(e)){if(t===""||t.startsWith("/")||t.split("/").includes(".."))return;if(Nm(Rr(e,t)))return t;let r=n.filter(s=>Nm(Rr(e,s,t)));return r.length===1?`${r[0]}/${t}`:void 0}var Ul=class extends Error{constructor(t){super(t),this.name="XmlError"}},eL=64,tL=5e5,nL=/^[A-Za-z_:][\w.:-]*/,rL={lt:"<",gt:">",amp:"&",quot:'"',apos:"'"};function GR(e){return e.replace(/&(#x[0-9A-Fa-f]+|#\d+|[A-Za-z]+);/g,(t,n)=>{if(n.startsWith("#x")){let s=Number.parseInt(n.slice(2),16);return s<=1114111?String.fromCodePoint(s):t}if(n.startsWith("#")){let s=Number.parseInt(n.slice(1),10);return s<=1114111?String.fromCodePoint(s):t}let r=rL[n];if(r===void 0)throw new Ul(`Unknown XML entity: &${n};`);return r})}function Hl(e){let t=0,n=0,r=e.charCodeAt(0)===65279?e.slice(1):e,s=c=>{throw new Ul(`${c} at offset ${t}`)},o=()=>{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=nL.exec(r.slice(t,t+256));return c===null?s("Expected a name"):(t+=c[0].length,c[0])},d=c=>{c>eL&&s("XML nests too deeply"),n+=1,n>tL&&s("XML has too many nodes"),r[t]!=="<"&&s("Expected an element"),t+=1;let u=a(),p={};for(;;){for(;/\s/.test(r[t]??"");)t+=1;if(r.startsWith("/>",t))return t+=2,{name:u,attributes:p,children:[]};if(r[t]===">"){t+=1;break}let g=a();for(;/\s/.test(r[t]??"");)t+=1;for(r[t]!=="="&&s(`Expected = after attribute ${g}`),t+=1;/\s/.test(r[t]??"");)t+=1;let y=r[t];if(y!=='"'&&y!=="'")return s("Expected a quoted attribute value");let w=r.indexOf(y,t+1);w<0&&s("Unterminated attribute value");let b=r.slice(t+1,w);b.includes("<")&&s("Attribute values must not contain <"),p[g]=GR(b),t=w+1}let f=[],m="",h=()=>{m.length>0&&(f.push(m),n+=1,m="")};for(;;){if(t>=r.length&&s(`Unterminated element <${u}>`),r.startsWith("</",t)){t+=2;let w=a();for(w!==u&&s(`Expected </${u}> but found </${w}>`);/\s/.test(r[t]??"");)t+=1;return r[t]!==">"&&s("Expected >"),t+=1,h(),{name:u,attributes:p,children:f}}if(r.startsWith("<![CDATA[",t)){let w=r.indexOf("]]>",t);w<0&&s("Unterminated CDATA section"),m+=r.slice(t+9,w),t=w+3;continue}if(r.startsWith("<!--",t)){let w=r.indexOf("-->",t);w<0&&s("Unterminated comment"),t=w+3;continue}if(r.startsWith("<?",t)){let w=r.indexOf("?>",t);w<0&&s("Unterminated processing instruction"),t=w+2;continue}if(r[t]==="<"){h(),f.push(d(c+1));continue}let g=r.indexOf("<",t),y=g<0?r.length:g;m+=GR(r.slice(t,y)),t=y}};o();let l=d(0);return o(),t<r.length&&s("Unexpected content after the root element"),l}function ce(e,t){return e.children.filter(n=>typeof n!="string"&&(t===void 0||n.name===t))}function mt(e){return e.children.map(t=>typeof t=="string"?t:mt(t)).join("")}var ya="4",cL=/(?:^|[\\/])cypress[\\/]|\.cy\.[cm]?[jt]sx?$/,uL=/webpack:\/\/|__cypress|CypressError/;function YR(e){let t=e.slice(0,4096).replace(/^\uFEFF/,"");return/^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<testsuites?\b/.test(t)}function oi(e){if(e.name==="testsuite")return[e];if(e.name!=="testsuites")throw new Error("A JUnit report's root must be testsuites.");let t=[],n=r=>{for(let s of ce(r,"testsuite"))t.push(s),n(s)};return n(e),t}function Om(e){let t=new Map;for(let n of ce(e,"properties"))for(let r of ce(n,"property")){let s=r.attributes.name;s!==void 0&&t.set(s,r.attributes.value??mt(r))}return t}function pL(e,t){if(e.name!=="testsuites"||e.attributes.id===void 0)return!1;let n=t.flatMap(r=>ce(r,"testcase").map(s=>({suite:r,testcase:s})));return n.length>0&&n.every(({suite:r,testcase:s})=>s.attributes.classname===r.attributes.name)}function fL(e){let t=Object.entries(e.attributes).find(([s])=>s.endsWith("noNamespaceSchemaLocation"))?.[1];if(e.name!=="testsuite"||t===void 0||!t.includes("surefire"))return;let n=Om(e),r=`${n.get("surefire.test.class.path")??""}:${n.get("java.class.path")??""}`;return/[\\/]testng-[\d.]+\.jar/.test(r)?"surefire-testng":"surefire-junit"}var mL=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/;function hL(e){let t=e.attributes.name??"",n=ce(e,"properties");return e.name==="testsuite"&&e.attributes.timestamp!==void 0&&e.attributes.hostname!==void 0&&n.length===1&&n.every(r=>ce(r,"property").length===0)&&mL.test(t)&&ce(e,"testcase").every(r=>r.attributes.classname===t)}function $m(e){if(e.some(n=>/\bat org\.testng\./.test(n)))return"testng";let t=n=>/\bat org\.junit\./.test(n)||/<testcase\b[^>]*\bname="[^"]*\(\)"/.test(n);return e.some(t)?"junit":void 0}function gL(e,t){let n=fL(e);if(n!==void 0)return n;if(hL(e))return"gradle";let r=oi(e),s=e.name==="testsuites"?e.attributes.name:void 0;if(r.some(d=>Om(d).has("capabilities")))return"webdriverio";if(s==="vitest tests")return"vitest";if(s==="jest tests")return"jest";if(s==="pytest tests"||r.some(d=>d.attributes.name==="pytest"))return"pytest";let o=r.some(d=>d.attributes.name==="Root Suite"),a=r.some(d=>cL.test(d.attributes.file??""));return o&&a||uL.test(t)?"cypress":o?"mocha":pL(e,r)?"playwright":"unknown"}function ai(e){let t=Number.parseFloat(e??"");return Number.isFinite(t)&&t>=0?Math.round(t*1e3):0}function yL(e){if(e===void 0)return;let t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?$/.test(e)?`${e}Z`:e,n=new Date(t);return Number.isNaN(n.getTime())?void 0:n.toISOString()}function Mm(e){return e.map(t=>yL(t.attributes.timestamp)).filter(t=>t!==void 0).sort()[0]}function zl(e,t){return e.name==="testsuites"&&e.attributes.time!==void 0?ai(e.attributes.time):t.reduce((n,r)=>n+ai(r.attributes.time),0)}function ql(e,t,n={retriedAsSkipped:!0}){let r=ce(e,"failure")[0]??ce(e,"error")[0]??void 0,s=ce(e,"system-err").map(o=>mt(o).trim()).filter(o=>o!=="").join(`
|
|
@@ -142,7 +142,7 @@ footer{margin-top:40px;padding-bottom:40px;color:var(--muted);font-size:13px;bor
|
|
|
142
142
|
`))}function hV(e){if(e.requests.length===0)return mi("sent","What was sent","<p>Nothing: no model request was made.</p>");let t=e.requests.map(n=>`<tr><td>${q(n.group)}</td><td>${q(n.purpose)}</td><td>${q(n.model)}${n.zeroDataRetention?", zero data retention":""}</td><td><code>${q(n.packetHash)}</code></td><td>${q(n.tokens??"")}</td><td>${q(n.outcome)}</td></tr>`).join("");return mi("sent","What was sent",`<p>Each request carried only the redacted evidence of one group, as its preview showed.</p><table><thead><tr><th>For</th><th>Request</th><th>Model</th><th>Evidence packet</th><th>Tokens</th><th>Outcome</th></tr></thead><tbody>${t}</tbody></table>`)}function Ms(e){let t=["default-src 'none'",`style-src 'sha256-${eI(Q_)}'`,`script-src 'sha256-${eI(Z_)}'`,"base-uri 'none'","form-action 'none'"].join("; "),n=e.flaky.length===0?"":mi("flaky","Flaky tests",`<p>These tests failed and then passed. KwikQA reports them and doesn't repair them.</p>${Yh(e.flaky)}`),r=e.notAnalyzed,s=r.unclassified.length===0&&r.runErrors.length===0?"":mi("not-analyzed","Not analyzed",[r.runErrors.length===0?"":`<h4>Run-level errors</h4><ul>${r.runErrors.map(o=>`<li>${Xh(o)}</li>`).join("")}</ul>`,r.unclassified.length===0?"":`<h4>Failures no rule could classify</h4>${Yh(r.unclassified)}`].join(`
|
|
143
143
|
`));return["<!doctype html>",'<html lang="en">',"<head>",'<meta charset="utf-8">','<meta name="viewport" content="width=device-width, initial-scale=1">',`<meta name="${Mc}" content="${nI}">`,`<meta http-equiv="Content-Security-Policy" content="${t}">`,'<meta name="referrer" content="no-referrer">',`<title>${q(e.title)}</title>`,`<style>${Q_}</style>`,"</head>","<body>","<header>",'<p class="brand">KwikQA</p>',"<h1>Failure report</h1>",`<p class="lede">${q(e.title.replace(/^KwikQA report: /,""))}. ${q(e.run.diagnosedBy)}</p>`,"</header>","<main>",pV(e),uV(e.groups),`<section id="groups" aria-label="Failure group details">${e.groups.map(cV).join(`
|
|
144
144
|
`)}</section>`,n,s,fV(e),mV(e),hV(e),"</main>",`<footer><p>Generated by KwikQA ${q(e.footer.kwikqaVersion)} from record <code>${q(e.footer.recordId)}</code> of run <code>${q(e.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>${Z_}</script>`,"</body>","</html>",""].join(`
|
|
145
|
-
`)}var Ls="kwikqa-report.html",oI=4096;async function vV(e){let t=await wV(e,"r");try{let n=Buffer.alloc(oI),{bytesRead:r}=await t.read(n,0,oI,0);return n.subarray(0,r).toString("utf8")}finally{await t.close()}}async function hi(e,t){let n=bV(e,t??Ls),r=await gV(n).catch(s=>{if(s.code!=="ENOENT")throw s});return r===void 0?{kind:"writable",path:n}:r.isFile()?(await vV(n)).includes(`<meta name="${Mc}"`)?{kind:"writable",path:n}:{kind:"refused",path:n,message:`${n} exists and isn't a KwikQA report, so KwikQA won't replace it. Choose another path with --output.`}:{kind:"refused",path:n,message:`${n} exists and isn't a regular file, so KwikQA won't write a report there.`}}async function Qh(e,t){let n=await hi(sI(e),e);return n.kind==="refused"||(await yV(sI(e),{recursive:!0}),await oe(e,t,{mode:420,replace:!0})),n}import{basename as t6}from"node:path";import{createRequire as kV}from"module";var RV=kV("/"),Bs,xV,_V;try{Bs=RV("worker_threads"),xV=Bs.Worker,_V=Bs.isMarkedAsUntransferable}catch{}var et=Uint8Array,Ds=Uint16Array,IV=Int32Array,aI=new et([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]),dI=new et([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),SV=new et([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),lI=function(e,t){for(var n=new Ds(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var s=new IV(n[30]),r=1;r<30;++r)for(var o=n[r];o<n[r+1];++o)s[o]=o-n[r]<<5|r;return{b:n,r:s}},Bs=lI(aI,2),cI=Bs.b,TV=Bs.r;cI[28]=258,TV[258]=28;var uI=lI(dI,0),AV=uI.b,Ate=uI.r,ng=new Ds(32768);for(we=0;we<32768;++we)tr=(we&43690)>>1|(we&21845)<<1,tr=(tr&52428)>>2|(tr&13107)<<2,tr=(tr&61680)>>4|(tr&3855)<<4,ng[we]=((tr&65280)>>8|(tr&255)<<8)>>1;var tr,we,Ha=(function(e,t,n){for(var r=e.length,s=0,o=new Ds(t);s<r;++s)e[s]&&++o[e[s]-1];var a=new Ds(t);for(s=1;s<t;++s)a[s]=a[s-1]+o[s-1]<<1;var d;if(n){d=new Ds(1<<t);var l=15-t;for(s=0;s<r;++s)if(e[s])for(var c=s<<4|e[s],u=t-e[s],p=a[e[s]-1]++<<u,f=p|(1<<u)-1;p<=f;++p)d[ng[p]>>l]=c}else for(d=new Ds(r),s=0;s<r;++s)e[s]&&(d[s]=ng[a[e[s]-1]++]>>15-e[s]);return d}),qa=new et(288);for(we=0;we<144;++we)qa[we]=8;var we;for(we=144;we<256;++we)qa[we]=9;var we;for(we=256;we<280;++we)qa[we]=7;var we;for(we=280;we<288;++we)qa[we]=8;var we,pI=new et(32);for(we=0;we<32;++we)pI[we]=5;var we;var PV=Ha(qa,9,1);var EV=Ha(pI,5,1),Zh=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},nn=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},eg=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},CV=function(e){return(e+7)/8|0},za=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new et(e.subarray(t,n))};var NV=["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"],Ye=function(e,t,n){var r=new Error(t||NV[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Ye),!n)throw r;return r},OV=function(e,t,n,r){var s=e.length,o=r?r.length:0;if(!s||t.f&&!t.l)return n||new et(0);var a=!n,d=a||t.i!=2,l=t.i;a&&(n=new et(s*3));var c=function(qt){var Ct=n.length;if(qt>Ct){var _o=new et(Math.max(Ct*2,qt));_o.set(n),n=_o}},u=t.f||0,p=t.p||0,f=t.b||0,m=t.l,h=t.d,g=t.m,y=t.n,w=s*8;do{if(!m){u=nn(e,p,1);var b=nn(e,p+1,3);if(p+=3,b)if(b==1)m=PV,h=EV,g=9,y=5;else if(b==2){var T=nn(e,p,31)+257,N=nn(e,p+10,15)+4,U=T+nn(e,p+5,31)+1;p+=14;for(var F=new et(U),I=new et(19),C=0;C<N;++C)I[SV[C]]=nn(e,p+C*3,7);p+=N*3;for(var A=Zh(I),M=(1<<A)-1,$=Ha(I,A,1),C=0;C<U;){var j=$[nn(e,p,M)];p+=j&15;var v=j>>4;if(v<16)F[C++]=v;else{var O=0,P=0;for(v==16?(P=3+nn(e,p,3),p+=2,O=F[C-1]):v==17?(P=3+nn(e,p,7),p+=3):v==18&&(P=11+nn(e,p,127),p+=7);P--;)F[C++]=O}}var E=F.subarray(0,T),L=F.subarray(T);g=Zh(E),y=Zh(L),m=Ha(E,g,1),h=Ha(L,y,1)}else Ye(1);else{var v=CV(p)+4,R=e[v-4]|e[v-3]<<8,x=v+R;if(x>s){l&&Ye(0);break}d&&c(f+R),n.set(e.subarray(v,x),f),t.b=f+=R,t.p=p=x*8,t.f=u;continue}if(p>w){l&&Ye(0);break}}d&&c(f+131072);for(var B=(1<<g)-1,Z=(1<<y)-1,te=p;;te=p){var O=m[eg(e,p)&B],D=O>>4;if(p+=O&15,p>w){l&&Ye(0);break}if(O||Ye(2),D<256)n[f++]=D;else if(D==256){te=p,m=null;break}else{var ne=D-254;if(D>264){var C=D-257,Ae=aI[C];ne=nn(e,p,(1<<Ae)-1)+cI[C],p+=Ae}var vt=h[eg(e,p)&Z],fn=vt>>4;vt||Ye(3),p+=vt&15;var L=AV[fn];if(fn>3){var Ae=dI[fn];L+=eg(e,p)&(1<<Ae)-1,p+=Ae}if(p>w){l&&Ye(0);break}d&&c(f+131072);var Et=f+ne;if(f<L){var Bn=o-L,$e=Math.min(L,Et);for(Bn+f<0&&Ye(3);f<$e;++f)n[f]=r[Bn+f]}for(;f<Et;++f)n[f]=n[f-L]}}t.l=m,t.p=te,t.b=f,t.f=u,m&&(u=1,t.m=g,t.d=h,t.n=y)}while(!u);return f!=n.length&&a?za(n,0,f):n.subarray(0,f)};var Ua=new et(0);var Fs=function(e,t){return e[t]|e[t+1]<<8},js=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},tg=function(e,t){return js(e,t)+js(e,t+4)*4294967296};var $V=(function(){function e(t,n){typeof t=="function"&&(n=t,t={}),this.ondata=n;var r=t&&t.dictionary&&t.dictionary.subarray(-32768);this.s={i:0,b:r?r.length:0},this.o=new et(32768),this.p=new et(0),r&&this.o.set(r)}return e.prototype.e=function(t){if(this.ondata||Ye(5),this.d&&Ye(4),!this.p.length)this.p=t;else if(t.length){var n=new et(this.p.length+t.length);n.set(this.p),n.set(t,this.p.length),this.p=n}},e.prototype.c=function(t){this.s.i=+(this.d=t||!1);var n=this.s.b,r=OV(this.p,this.s,this.o);this.ondata(za(r,n,this.s.b),this.d),this.o=za(r,this.s.b-32768),this.s.b=this.o.length,this.p=za(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(t,n){this.e(t),this.c(n)},e})();var rg=typeof TextDecoder<"u"&&new TextDecoder,MV=0;try{rg.decode(Ua,{stream:!0}),MV=1}catch{}var LV=function(e){for(var t="",n=0;;){var r=e[n++],s=(r>127)+(r>223)+(r>239);if(n+s>e.length)return{s:t,r:za(e,n-1)};s?s==3?(r=((r&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|r>>10,56320|r&1023)):s&1?t+=String.fromCharCode((r&31)<<6|e[n++]&63):t+=String.fromCharCode((r&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(r)}};function DV(e,t){if(t){for(var n="",r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}else{if(rg)return rg.decode(e);var s=LV(e),o=s.s,n=s.r;return n.length&&Ye(8),o}}var FV=function(e,t,n,r,s,o,a){var d=s==4294967295,l=o==4294967295,c=a==4294967295,u=t+n,p=d+l+c;if(r&&p){for(;t+4<u;t+=4+Fs(e,t+2))if(Fs(e,t)==1)return[d?tg(e,t+4+8*l):s,l?tg(e,t+4):o,c?tg(e,t+4+8*(l+d)):a,1];r<2&&Ye(13)}return[s,o,a,0]};var jV=(function(){function e(){}return e.prototype.push=function(t,n){this.ondata(null,t,n)},e.compression=0,e})();var fI=(function(){function e(){var t=this;this.i=new $V(function(n,r){t.ondata(null,n,r)})}return e.prototype.push=function(t,n){try{this.i.push(t,n)}catch(r){this.ondata(r,null,n)}},e.compression=8,e})();var mI=(function(){function e(t){this.onfile=t,this.k=[],this.o={0:jV},this.p=Ua}return e.prototype.push=function(t,n){var r=this;if(this.onfile||Ye(5),this.p||Ye(4),this.c>0){var s=Math.min(this.c,t.length),o=t.subarray(0,s);if(this.c-=s,this.d?this.d.push(o,!this.c):this.k[0].push(o),t=t.subarray(s),t.length)return this.push(t,n)}else{var a=0,d=0,l=void 0,c=void 0;this.p.length?t.length?(c=new et(this.p.length+t.length),c.set(this.p),c.set(t,this.p.length)):c=this.p:c=t;for(var u=c.length,p=this.c,f=p&&this.d,m=function(){var w=js(c,d);if(w==67324752){a=1,l=d,h.d=null,h.c=0;var b=Fs(c,d+6),v=Fs(c,d+8),R=b&2048,x=b&8,T=Fs(c,d+26),N=Fs(c,d+28);if(u>d+30+T+N){var U=[];h.k.unshift(U),a=2;var F=js(c,d+18),I=js(c,d+22),C=DV(c.subarray(d+30,d+=30+T),!R),A=FV(c,d,N,2,F,I,0),M=A[0],$=A[1],j=A[3];x&&(M=-1-j),d+=N,h.c=M;var O,P={name:C,compression:v,start:function(){if(P.ondata||Ye(5),!M)P.ondata(null,Ua,!0);else{var E=r.o[v];E||P.ondata(Ye(14,"unknown compression type "+v,1),null,!1),O=M<0?new E(C):new E(C,M,$),O.ondata=function(te,D,ne){P.ondata(te,D,ne)};for(var L=0,B=U;L<B.length;L++){var Z=B[L];O.push(Z,!1)}r.k[0]==U&&r.c?r.d=O:O.push(Ua,!0)}},terminate:function(){O&&O.terminate&&O.terminate()}};M>=0&&(P.size=M,P.originalSize=$),h.onfile(P)}return"break"}else if(p){if(w==134695760)return l=d+=12+(p==-2&&8),a=3,h.c=0,"break";if(w==33639248)return l=d-=4,a=3,h.c=0,"break"}},h=this;d<u-4;++d){var g=m();if(g==="break")break}if(this.p=Ua,p<0){var y=a?c.subarray(0,l-12-(p==-2&&8)-(js(c,l-16)==134695760&&4)):c.subarray(0,d);f?f.push(y,!!a):this.k[+(a==2)].push(y)}if(a&2)return this.push(c.subarray(d),n);this.p=c.subarray(d)}n&&(this.c&&Ye(13),this.p=null)},e.prototype.register=function(t){this.o[t.compression]=t},e})();var hI=65536;function BV(e,t){let n=new Uint8Array(t),r=0;for(let s of e)n.set(s,r),r+=s.length;return n}function Lc(e,t,n){if(e.byteLength===0)return{kind:"unreadable",message:"Archive is empty."};if(e[0]!==80||e[1]!==75)return{kind:"unreadable",message:"Archive does not begin with a ZIP signature."};let r=new Map,s=[],o=0,a=0,d,l=new Set,c=new mI;c.register(fI),c.onfile=u=>{let p=u.name,f=typeof u.originalSize=="number"&&u.originalSize>0,m=u.originalSize??0;if(!Vp(p)){s.push({entry:p,reason:"unsafe-entry-name",declaredBytes:m});return}if(!n(p))return;if(l.has(p)){s.push({entry:p,reason:"duplicate-selected-name",declaredBytes:m});return}if(o>=t.maxEntries){s.push({entry:p,reason:"entry-budget-exceeded",declaredBytes:m});return}let h=t.maxExpandedBytes-a;if(f&&m>h){s.push({entry:p,reason:"expanded-budget-exceeded",declaredBytes:m});return}o+=1,l.add(p);let g=[],y=0,w=!1;u.ondata=(b,v,R)=>{if(d!==void 0||w)return;if(b!==null){d=`Archive entry ${p} could not be inflated.`;return}y+=v.length;let x=f&&y>m;if(x||y>h){w=!0,g.length=0,s.push({entry:p,reason:x?"declared-size-mismatch":"expanded-budget-exceeded",declaredBytes:m});return}if(g.push(v.slice()),R){if(f&&y!==m){g.length=0,w=!0,s.push({entry:p,reason:"declared-size-mismatch",declaredBytes:m});return}a+=y,r.set(p,BV(g,y))}},u.start()};try{for(let u=0;u<e.byteLength;u+=hI){let p=Math.min(u+hI,e.byteLength);if(c.push(e.subarray(u,p),p===e.byteLength),d!==void 0)break}}catch{return{kind:"unreadable",message:"Archive could not be read as a ZIP container."}}return d!==void 0?{kind:"unreadable",message:d}:{kind:"read",contents:{entries:r,skipped:s}}}var VV=/(?:\bcy\.(?:get|contains)|\.(?:find|contains)|\b(?:get|getAll|find|findAll|query|queryAll)By\w+|\b(?:frame)?[Ll]ocator|(?<![\w$])\${1,2})\((?:[^()]|\([^()]*\))*\)/g;function UV(e,t){let n=e.replace(/\\/g,"/");return n===t||n.endsWith(`/${t}`)}function gI(e,t){let n=new Map;for(let r of e){if(r.attemptId===void 0||r.line===void 0||n.has(r.attemptId))continue;let s=r.line,o=t.find(c=>c.kind==="source-range"&&c.attemptId===r.attemptId&&c.locator.type==="source-range"&&UV(r.file,c.locator.path)&&c.locator.startLine<=s&&s<=c.locator.endLine);if(o===void 0||o.locator.type!=="source-range")continue;let a=o.observation.split(`
|
|
145
|
+
`)}var Ls="kwikqa-report.html",oI=4096;async function vV(e){let t=await wV(e,"r");try{let n=Buffer.alloc(oI),{bytesRead:r}=await t.read(n,0,oI,0);return n.subarray(0,r).toString("utf8")}finally{await t.close()}}async function hi(e,t){let n=bV(e,t??Ls),r=await gV(n).catch(s=>{if(s.code!=="ENOENT")throw s});return r===void 0?{kind:"writable",path:n}:r.isFile()?(await vV(n)).includes(`<meta name="${Mc}"`)?{kind:"writable",path:n}:{kind:"refused",path:n,message:`${n} exists and isn't a KwikQA report, so KwikQA won't replace it. Choose another path with --output.`}:{kind:"refused",path:n,message:`${n} exists and isn't a regular file, so KwikQA won't write a report there.`}}async function Qh(e,t){let n=await hi(sI(e),e);return n.kind==="refused"||(await yV(sI(e),{recursive:!0}),await oe(e,t,{mode:420,replace:!0})),n}import{basename as t6}from"node:path";import{createRequire as kV}from"module";var RV=kV("/"),Bs,xV,_V;try{Bs=RV("worker_threads"),xV=Bs.Worker,_V=Bs.isMarkedAsUntransferable}catch{}var et=Uint8Array,Ds=Uint16Array,IV=Int32Array,aI=new et([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]),dI=new et([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),SV=new et([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),lI=function(e,t){for(var n=new Ds(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var s=new IV(n[30]),r=1;r<30;++r)for(var o=n[r];o<n[r+1];++o)s[o]=o-n[r]<<5|r;return{b:n,r:s}},Bs=lI(aI,2),cI=Bs.b,TV=Bs.r;cI[28]=258,TV[258]=28;var uI=lI(dI,0),AV=uI.b,Pte=uI.r,ng=new Ds(32768);for(we=0;we<32768;++we)tr=(we&43690)>>1|(we&21845)<<1,tr=(tr&52428)>>2|(tr&13107)<<2,tr=(tr&61680)>>4|(tr&3855)<<4,ng[we]=((tr&65280)>>8|(tr&255)<<8)>>1;var tr,we,Ha=(function(e,t,n){for(var r=e.length,s=0,o=new Ds(t);s<r;++s)e[s]&&++o[e[s]-1];var a=new Ds(t);for(s=1;s<t;++s)a[s]=a[s-1]+o[s-1]<<1;var d;if(n){d=new Ds(1<<t);var l=15-t;for(s=0;s<r;++s)if(e[s])for(var c=s<<4|e[s],u=t-e[s],p=a[e[s]-1]++<<u,f=p|(1<<u)-1;p<=f;++p)d[ng[p]>>l]=c}else for(d=new Ds(r),s=0;s<r;++s)e[s]&&(d[s]=ng[a[e[s]-1]++]>>15-e[s]);return d}),qa=new et(288);for(we=0;we<144;++we)qa[we]=8;var we;for(we=144;we<256;++we)qa[we]=9;var we;for(we=256;we<280;++we)qa[we]=7;var we;for(we=280;we<288;++we)qa[we]=8;var we,pI=new et(32);for(we=0;we<32;++we)pI[we]=5;var we;var PV=Ha(qa,9,1);var EV=Ha(pI,5,1),Zh=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},nn=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},eg=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},CV=function(e){return(e+7)/8|0},za=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new et(e.subarray(t,n))};var NV=["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"],Ye=function(e,t,n){var r=new Error(t||NV[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Ye),!n)throw r;return r},OV=function(e,t,n,r){var s=e.length,o=r?r.length:0;if(!s||t.f&&!t.l)return n||new et(0);var a=!n,d=a||t.i!=2,l=t.i;a&&(n=new et(s*3));var c=function(qt){var Ct=n.length;if(qt>Ct){var _o=new et(Math.max(Ct*2,qt));_o.set(n),n=_o}},u=t.f||0,p=t.p||0,f=t.b||0,m=t.l,h=t.d,g=t.m,y=t.n,w=s*8;do{if(!m){u=nn(e,p,1);var b=nn(e,p+1,3);if(p+=3,b)if(b==1)m=PV,h=EV,g=9,y=5;else if(b==2){var T=nn(e,p,31)+257,N=nn(e,p+10,15)+4,U=T+nn(e,p+5,31)+1;p+=14;for(var F=new et(U),I=new et(19),C=0;C<N;++C)I[SV[C]]=nn(e,p+C*3,7);p+=N*3;for(var A=Zh(I),M=(1<<A)-1,$=Ha(I,A,1),C=0;C<U;){var j=$[nn(e,p,M)];p+=j&15;var v=j>>4;if(v<16)F[C++]=v;else{var O=0,P=0;for(v==16?(P=3+nn(e,p,3),p+=2,O=F[C-1]):v==17?(P=3+nn(e,p,7),p+=3):v==18&&(P=11+nn(e,p,127),p+=7);P--;)F[C++]=O}}var E=F.subarray(0,T),L=F.subarray(T);g=Zh(E),y=Zh(L),m=Ha(E,g,1),h=Ha(L,y,1)}else Ye(1);else{var v=CV(p)+4,R=e[v-4]|e[v-3]<<8,x=v+R;if(x>s){l&&Ye(0);break}d&&c(f+R),n.set(e.subarray(v,x),f),t.b=f+=R,t.p=p=x*8,t.f=u;continue}if(p>w){l&&Ye(0);break}}d&&c(f+131072);for(var B=(1<<g)-1,Z=(1<<y)-1,te=p;;te=p){var O=m[eg(e,p)&B],D=O>>4;if(p+=O&15,p>w){l&&Ye(0);break}if(O||Ye(2),D<256)n[f++]=D;else if(D==256){te=p,m=null;break}else{var ne=D-254;if(D>264){var C=D-257,Ae=aI[C];ne=nn(e,p,(1<<Ae)-1)+cI[C],p+=Ae}var vt=h[eg(e,p)&Z],fn=vt>>4;vt||Ye(3),p+=vt&15;var L=AV[fn];if(fn>3){var Ae=dI[fn];L+=eg(e,p)&(1<<Ae)-1,p+=Ae}if(p>w){l&&Ye(0);break}d&&c(f+131072);var Et=f+ne;if(f<L){var Bn=o-L,$e=Math.min(L,Et);for(Bn+f<0&&Ye(3);f<$e;++f)n[f]=r[Bn+f]}for(;f<Et;++f)n[f]=n[f-L]}}t.l=m,t.p=te,t.b=f,t.f=u,m&&(u=1,t.m=g,t.d=h,t.n=y)}while(!u);return f!=n.length&&a?za(n,0,f):n.subarray(0,f)};var Ua=new et(0);var Fs=function(e,t){return e[t]|e[t+1]<<8},js=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},tg=function(e,t){return js(e,t)+js(e,t+4)*4294967296};var $V=(function(){function e(t,n){typeof t=="function"&&(n=t,t={}),this.ondata=n;var r=t&&t.dictionary&&t.dictionary.subarray(-32768);this.s={i:0,b:r?r.length:0},this.o=new et(32768),this.p=new et(0),r&&this.o.set(r)}return e.prototype.e=function(t){if(this.ondata||Ye(5),this.d&&Ye(4),!this.p.length)this.p=t;else if(t.length){var n=new et(this.p.length+t.length);n.set(this.p),n.set(t,this.p.length),this.p=n}},e.prototype.c=function(t){this.s.i=+(this.d=t||!1);var n=this.s.b,r=OV(this.p,this.s,this.o);this.ondata(za(r,n,this.s.b),this.d),this.o=za(r,this.s.b-32768),this.s.b=this.o.length,this.p=za(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(t,n){this.e(t),this.c(n)},e})();var rg=typeof TextDecoder<"u"&&new TextDecoder,MV=0;try{rg.decode(Ua,{stream:!0}),MV=1}catch{}var LV=function(e){for(var t="",n=0;;){var r=e[n++],s=(r>127)+(r>223)+(r>239);if(n+s>e.length)return{s:t,r:za(e,n-1)};s?s==3?(r=((r&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|r>>10,56320|r&1023)):s&1?t+=String.fromCharCode((r&31)<<6|e[n++]&63):t+=String.fromCharCode((r&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(r)}};function DV(e,t){if(t){for(var n="",r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}else{if(rg)return rg.decode(e);var s=LV(e),o=s.s,n=s.r;return n.length&&Ye(8),o}}var FV=function(e,t,n,r,s,o,a){var d=s==4294967295,l=o==4294967295,c=a==4294967295,u=t+n,p=d+l+c;if(r&&p){for(;t+4<u;t+=4+Fs(e,t+2))if(Fs(e,t)==1)return[d?tg(e,t+4+8*l):s,l?tg(e,t+4):o,c?tg(e,t+4+8*(l+d)):a,1];r<2&&Ye(13)}return[s,o,a,0]};var jV=(function(){function e(){}return e.prototype.push=function(t,n){this.ondata(null,t,n)},e.compression=0,e})();var fI=(function(){function e(){var t=this;this.i=new $V(function(n,r){t.ondata(null,n,r)})}return e.prototype.push=function(t,n){try{this.i.push(t,n)}catch(r){this.ondata(r,null,n)}},e.compression=8,e})();var mI=(function(){function e(t){this.onfile=t,this.k=[],this.o={0:jV},this.p=Ua}return e.prototype.push=function(t,n){var r=this;if(this.onfile||Ye(5),this.p||Ye(4),this.c>0){var s=Math.min(this.c,t.length),o=t.subarray(0,s);if(this.c-=s,this.d?this.d.push(o,!this.c):this.k[0].push(o),t=t.subarray(s),t.length)return this.push(t,n)}else{var a=0,d=0,l=void 0,c=void 0;this.p.length?t.length?(c=new et(this.p.length+t.length),c.set(this.p),c.set(t,this.p.length)):c=this.p:c=t;for(var u=c.length,p=this.c,f=p&&this.d,m=function(){var w=js(c,d);if(w==67324752){a=1,l=d,h.d=null,h.c=0;var b=Fs(c,d+6),v=Fs(c,d+8),R=b&2048,x=b&8,T=Fs(c,d+26),N=Fs(c,d+28);if(u>d+30+T+N){var U=[];h.k.unshift(U),a=2;var F=js(c,d+18),I=js(c,d+22),C=DV(c.subarray(d+30,d+=30+T),!R),A=FV(c,d,N,2,F,I,0),M=A[0],$=A[1],j=A[3];x&&(M=-1-j),d+=N,h.c=M;var O,P={name:C,compression:v,start:function(){if(P.ondata||Ye(5),!M)P.ondata(null,Ua,!0);else{var E=r.o[v];E||P.ondata(Ye(14,"unknown compression type "+v,1),null,!1),O=M<0?new E(C):new E(C,M,$),O.ondata=function(te,D,ne){P.ondata(te,D,ne)};for(var L=0,B=U;L<B.length;L++){var Z=B[L];O.push(Z,!1)}r.k[0]==U&&r.c?r.d=O:O.push(Ua,!0)}},terminate:function(){O&&O.terminate&&O.terminate()}};M>=0&&(P.size=M,P.originalSize=$),h.onfile(P)}return"break"}else if(p){if(w==134695760)return l=d+=12+(p==-2&&8),a=3,h.c=0,"break";if(w==33639248)return l=d-=4,a=3,h.c=0,"break"}},h=this;d<u-4;++d){var g=m();if(g==="break")break}if(this.p=Ua,p<0){var y=a?c.subarray(0,l-12-(p==-2&&8)-(js(c,l-16)==134695760&&4)):c.subarray(0,d);f?f.push(y,!!a):this.k[+(a==2)].push(y)}if(a&2)return this.push(c.subarray(d),n);this.p=c.subarray(d)}n&&(this.c&&Ye(13),this.p=null)},e.prototype.register=function(t){this.o[t.compression]=t},e})();var hI=65536;function BV(e,t){let n=new Uint8Array(t),r=0;for(let s of e)n.set(s,r),r+=s.length;return n}function Lc(e,t,n){if(e.byteLength===0)return{kind:"unreadable",message:"Archive is empty."};if(e[0]!==80||e[1]!==75)return{kind:"unreadable",message:"Archive does not begin with a ZIP signature."};let r=new Map,s=[],o=0,a=0,d,l=new Set,c=new mI;c.register(fI),c.onfile=u=>{let p=u.name,f=typeof u.originalSize=="number"&&u.originalSize>0,m=u.originalSize??0;if(!Vp(p)){s.push({entry:p,reason:"unsafe-entry-name",declaredBytes:m});return}if(!n(p))return;if(l.has(p)){s.push({entry:p,reason:"duplicate-selected-name",declaredBytes:m});return}if(o>=t.maxEntries){s.push({entry:p,reason:"entry-budget-exceeded",declaredBytes:m});return}let h=t.maxExpandedBytes-a;if(f&&m>h){s.push({entry:p,reason:"expanded-budget-exceeded",declaredBytes:m});return}o+=1,l.add(p);let g=[],y=0,w=!1;u.ondata=(b,v,R)=>{if(d!==void 0||w)return;if(b!==null){d=`Archive entry ${p} could not be inflated.`;return}y+=v.length;let x=f&&y>m;if(x||y>h){w=!0,g.length=0,s.push({entry:p,reason:x?"declared-size-mismatch":"expanded-budget-exceeded",declaredBytes:m});return}if(g.push(v.slice()),R){if(f&&y!==m){g.length=0,w=!0,s.push({entry:p,reason:"declared-size-mismatch",declaredBytes:m});return}a+=y,r.set(p,BV(g,y))}},u.start()};try{for(let u=0;u<e.byteLength;u+=hI){let p=Math.min(u+hI,e.byteLength);if(c.push(e.subarray(u,p),p===e.byteLength),d!==void 0)break}}catch{return{kind:"unreadable",message:"Archive could not be read as a ZIP container."}}return d!==void 0?{kind:"unreadable",message:d}:{kind:"read",contents:{entries:r,skipped:s}}}var VV=/(?:\bcy\.(?:get|contains)|\.(?:find|contains)|\b(?:get|getAll|find|findAll|query|queryAll)By\w+|\b(?:frame)?[Ll]ocator|(?<![\w$])\${1,2})\((?:[^()]|\([^()]*\))*\)/g;function UV(e,t){let n=e.replace(/\\/g,"/");return n===t||n.endsWith(`/${t}`)}function gI(e,t){let n=new Map;for(let r of e){if(r.attemptId===void 0||r.line===void 0||n.has(r.attemptId))continue;let s=r.line,o=t.find(c=>c.kind==="source-range"&&c.attemptId===r.attemptId&&c.locator.type==="source-range"&&UV(r.file,c.locator.path)&&c.locator.startLine<=s&&s<=c.locator.endLine);if(o===void 0||o.locator.type!=="source-range")continue;let a=o.observation.split(`
|
|
146
146
|
`).slice(1),d=Math.max(o.locator.startLine,s-3),l=a.slice(d-o.locator.startLine,s-o.locator.startLine+1);n.set(r.attemptId,l.flatMap(c=>c.match(VV)??[]))}return n}var HV={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"},zV={button:"button",submit:"button",reset:"button",checkbox:"checkbox",radio:"radio",range:"slider",text:"textbox",search:"searchbox",email:"textbox",tel:"textbox",url:"textbox",password:"textbox"},qV=new Set(["script","style","head","title","meta","link"]);function gt(e){let t=e[0];return typeof t=="string"?t.toLowerCase():void 0}function lt(e){let t=e[1];if(typeof t!="object"||t===null||Array.isArray(t))return{};let n={};for(let[r,s]of Object.entries(t))typeof s=="string"&&(n[r.toLowerCase()]=s);return n}function tt(e){let t=typeof e[1]=="object"&&e[1]!==null&&!Array.isArray(e[1]);return e.slice(t?2:1)}function nr(e,t=0){let n=gt(e);if(n===void 0||qV.has(n)||t>12)return"";let r=[];for(let s of tt(e))typeof s=="string"?r.push(s):Array.isArray(s)&&r.push(nr(s,t+1));return r.join(" ").replace(/\s+/g," ").trim()}function gi(e){let t=lt(e),n=t.role;if(n!==void 0&&n.length>0)return n.toLowerCase();let r=gt(e);if(r!==void 0)return r==="a"?t.href===void 0?void 0:"link":r==="input"?zV[(t.type??"text").toLowerCase()]:HV[r]}function Bc(e){let t=lt(e),n=t["aria-label"]??t.alt??t.title;return n!==void 0&&n.trim().length>0?n.trim():nr(e)}function yI(e){return e.replace(/\s+/g," ").trim()}function Dc(e,t,n){let r=yI(e),s=yI(t);return n?r===s:r.toLowerCase().includes(s.toLowerCase())}var GV=new Set(["input","textarea","select"]);function bI(e){let t=[];for(let n of tt(e))if(typeof n=="string")t.push(n);else if(Array.isArray(n)){let r=gt(n);if(r!==void 0&&GV.has(r))continue;t.push(nr(n))}return t.join(" ").replace(/\s+/g," ").trim()}function KV(e,t){let n,r=s=>{if(n===void 0){if(gt(s)==="label"&<(s).for===t){n=bI(s);return}for(let o of tt(s))Array.isArray(o)&&r(o)}};return r(e),n}function wI(e,t){let n=lt(e),r=[];for(let o of["aria-label","placeholder","title"]){let a=n[o];a!==void 0&&a.trim().length>0&&r.push(a.trim())}for(let o=t.path.length-1;o>=0;o-=1){let a=kI(t.root,t.path.slice(0,o));if(a===void 0)break;if(gt(a)==="label"){r.push(bI(a));break}}let s=n.id;if(s!==void 0){let o=KV(t.root,s);o!==void 0&&r.push(o)}return r}var WV=`"((?:[^"\\\\]|\\\\.)*)"|'((?:[^'\\\\]|\\\\.)*)'`;function JV(e){return e.replace(/\\(.)/g,"$1")}function Fc(e){let t=new RegExp(`^(?:${WV})([is])?$`).exec(e.trim());if(t===null)return;let n=t[1]??t[2];if(n!==void 0)return{value:JV(n),caseSensitive:t[3]!=="i"}}function YV(e){let t=/^\[\s*([\w:-]+)\s*=\s*(.+?)\s*\]$/.exec(e.trim());if(t===null)return;let n=t[1]?.toLowerCase(),r=Fc(t[2]??"");if(!(n===void 0||r===void 0))return{describe:`[${n}]`,matches:s=>{let o=lt(s)[n];return o!==void 0&&Dc(o,r.value,r.caseSensitive)}}}function XV(e,t){if(e==="role"){let n=/^([\w-]+)(?:\[(.*)\])?$/.exec(t.trim()),r=n?.[1]?.toLowerCase();if(r===void 0)return;let s=n?.[2];if(s===void 0||s.trim()==="")return{describe:`role=${r}`,matches:d=>gi(d)===r};let o=/^name\s*=\s*(.+)$/.exec(s.trim()),a=o===null?void 0:Fc(o[1]??"");return a===void 0?void 0:{describe:`role=${r}[name]`,matches:(d,l)=>gi(d)===r&&[Bc(d),...wI(d,l)].some(c=>Dc(c,a.value,a.caseSensitive))}}if(e==="label"){let n=Fc(t);return n===void 0?void 0:{describe:"label",matches:(r,s)=>wI(r,s).some(o=>Dc(o,n.value,n.caseSensitive))}}if(e==="text"){let n=Fc(t);if(n===void 0)return;let r=s=>Dc(nr(s),n.value,n.caseSensitive);return{describe:"text",matches:s=>r(s)&&!tt(s).some(o=>Array.isArray(o)&&r(o))}}if(e==="testid"||e==="attr")return YV(t)}function vI(e){let t=e.match(/^[A-Za-z][\w-]*|#[\w-]+|\.[\w-]+|\[[^\]]*\]/g);if(t===null||t.join("")!==e)return;let n=[];for(let r of t)if(r.startsWith("#")){let s=r.slice(1);n.push(o=>lt(o).id===s)}else if(r.startsWith(".")){let s=r.slice(1);n.push(o=>(lt(o).class??"").split(/\s+/).includes(s))}else if(r.startsWith("[")){let s=/^\[\s*([\w:-]+)\s*(?:=\s*["']?([^"'\]]*)["']?)?\s*\]$/.exec(r),o=s?.[1]?.toLowerCase();if(o===void 0)return;let a=s?.[2];n.push(d=>{let l=lt(d)[o];return l===void 0?!1:a===void 0||a===""?!0:l===a})}else{let s=r.toLowerCase();n.push(o=>gt(o)===s)}return{describe:e,matches:r=>n.every(s=>s(r))}}function QV(e){let t=e.trim(),n=/^internal:([\w-]+)=([\s\S]+)$/.exec(t);if(n!==null)return XV(n[1]??"",n[2]??"");let r=/^role=([\w-]+)$/.exec(t);if(r!==null){let s=r[1]?.toLowerCase();return s===void 0?void 0:{describe:t,matches:o=>gi(o)===s}}return vI(t)}function ZV(e){let t=[],n="",r;for(let s=0;s<e.length;s+=1){let o=e[s];if(o!==void 0){if(r!==void 0){if(o==="\\"){n+=o+(e[s+1]??""),s+=1;continue}o===r&&(r=void 0),n+=o;continue}if(o==='"'||o==="'"){r=o,n+=o;continue}if(o===">"&&e[s+1]===">"){t.push(n),n="",s+=1;continue}n+=o}}return t.push(n),t.map(s=>s.trim()).filter(s=>s.length>0)}function eU(e){if(/^(?:internal:|role=)/.test(e))return[e];let t=[],n="",r=0,s;for(let o of e){if(s!==void 0){o===s&&(s=void 0),n+=o;continue}if((o==='"'||o==="'")&&(s=o),(o==="["||o==="(")&&(r+=1),(o==="]"||o===")")&&(r=Math.max(0,r-1)),r===0&&(o===" "||o===">")){n.trim()!==""&&t.push(n.trim()),n="";continue}n+=o}return n.trim()!==""&&t.push(n.trim()),t.length===0?[e]:t}function jc(e,t){let n=[{node:e,path:t}];return tt(e).forEach((r,s)=>{Array.isArray(r)&&n.push(...jc(r,[...t,s]))}),n}function kI(e,t){let n=e;for(let r of t){let s=tt(n)[r];if(!Array.isArray(s))return;n=s}return n}var tU=/:(?:(first)|(last)|(?:eq|nth)\((-?\d+)\))$/;function nU(e){let t=[],n="",r=0,s,o=!1,a=()=>{n.trim()!==""&&(t.push({part:n.trim(),child:o}),n="",o=!1)};for(let d of e){if(s!==void 0){d===s&&(s=void 0),n+=d;continue}if((d==='"'||d==="'")&&(s=d),(d==="["||d==="(")&&(r+=1),(d==="]"||d===")")&&(r=Math.max(0,r-1)),r===0&&(d===" "||d===">")){a(),d===">"&&(o=t.length>0);continue}n+=d}return a(),t}function rU(e,t){for(let n=0;n<Math.min(e.path.length,t.path.length);n+=1){let r=(e.path[n]??0)-(t.path[n]??0);if(r!==0)return r}return e.path.length-t.path.length}function iU(e,t,n){let r=t.slice(0,n.index),s=r.includes(">>")?[]:nU(r);if(s.length===0)return{kind:"unsupported",reason:`${n[0]} after ${r||"nothing"}`};let o=[];for(let[c,{part:u,child:p}]of s.entries()){let f=vI(u);if(f===void 0)return{kind:"unsupported",reason:u};let m=c===0?jc(e,[]):o.flatMap(g=>p?tt(g.node).flatMap((y,w)=>Array.isArray(y)?[{node:y,path:[...g.path,w]}]:[]):jc(g.node,g.path).slice(1)),h=new Map;for(let g of m)f.matches(g.node,{root:e,path:g.path})&&h.set(g.path.join("."),g);o=[...h.values()]}let a=[...o].sort(rU),d=n[1]!==void 0?0:n[2]!==void 0?a.length-1:Number(n[3])<0?Number(n[3])+a.length:Number(n[3]),l=a[d];return{kind:"resolved",matches:l===void 0?[]:[l]}}function Ga(e,t){if(!Array.isArray(e))return{kind:"unsupported",reason:"snapshot root is not an element"};let n=tU.exec(t.trim());if(n!==null)return iU(e,t.trim(),n);let r=ZV(t).flatMap(eU);if(r.length===0)return{kind:"unsupported",reason:"empty selector"};let s=[{node:e,path:[]}];for(let o of r){if(o===".."){let l=new Map;for(let c of s){if(c.path.length===0)continue;let u=c.path.slice(0,-1),p=kI(e,u);p!==void 0&&l.set(u.join("."),{node:p,path:u})}s=[...l.values()];continue}let a=QV(o);if(a===void 0)return{kind:"unsupported",reason:o};let d=new Map;for(let l of s)for(let c of jc(l.node,l.path))a.matches(c.node,{root:e,path:c.path})&&d.set(c.path.join("."),c);if(s=[...d.values()],s.length===0)break}return{kind:"resolved",matches:s}}var xI=new Set(["script","style","noscript","template","head"]),RI=120,sU=200,oU={__playwright_value_:"value",__playwright_checked_:"checked",__playwright_selected_:"selected"},aU=new Set(["button","link","textbox","searchbox","checkbox","radio","combobox","listbox","option","menuitem","tab","switch","slider","spinbutton","heading","dialog","img","cell","row"]),_I=["data-testid","data-test-id","data-test","data-qa","data-cy"],dU=new Set(["internal","role","testid","data","name","text","label","attr","has","nth","visible","true","false","exact","css","xpath","and","the"]);function lU(e){let t=[];for(let[n,r]of Object.entries(lt(e))){let s=oU[n];if(s!==void 0){t.push({name:s,value:je(r,RI)});continue}n.startsWith("__playwright")||/^on[a-z]+$/.test(n)||t.push({name:n,value:je(r,RI)})}return t.sort((n,r)=>n.name.localeCompare(r.name))}function II(e,t){let n,r=(s,o)=>{if(n===void 0){if(lt(s).__playwright_target__===t){n={node:s,path:o};return}tt(s).forEach((a,d)=>{Array.isArray(a)&&r(a,[...o,d])})}};return r(e,[]),n}function cU(e){return tt(e).filter(t=>typeof t=="string").join(" ").replace(/\s+/g," ").trim()}function Ka(e,t,n){let r=[],s=[],o=0,a=0,d=!1,l=(c,u)=>{if(d)return;let p=gt(c);if(p===void 0||xI.has(p))return;if(u>n.maxDepth||a>=n.maxNodes){d=!0;return}let f=`${t}/${a}`,m=lU(c),h=af(m,f,n.sensitiveNames),g=of(je(cU(c),sU),m,f,n.sensitiveNames);s.push(...h.records,...g.records);let y=h.value.map(v=>` ${v.name}="${v.value}"`).join(""),w=`${" ".repeat(u)}<${p}${y}>${g.value===""?"":` ${g.value}`}`,b=Buffer.byteLength(w,"utf8")+1;if(o+b>n.maxBytes){d=!0;return}r.push(w),o+=b,a+=1;for(let v of tt(c))Array.isArray(v)&&l(v,u+1)};return l(e,0),{text:r.join(`
|
|
147
147
|
`),redactions:s,nodes:a,truncated:d}}function Wa(e,t=[],n){let r=lt(e),s=gi(e),o=Bc(e),a=je(o===""&&n!==void 0?n:o,80),d=[s===void 0?`<${gt(e)??"?"}>`:s];a!==""&&d.push(JSON.stringify(a));for(let c of[...new Set([...t,..._I,"id","name"])]){let u=r[c];u!==void 0&&u!==""&&d.push(`${c}=${je(u,60)}`)}let l=r.placeholder;return l!==void 0&&l!==""&&d.push(`placeholder=${JSON.stringify(je(l,60))}`),d.join(" ")}function Vs(e){let t=e.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(n=>n.length>=3&&!dU.has(n));return[...new Set(t)]}function uU(e){return/(?:^|>>\s*)(?:internal:)?role=([\w-]+)/.exec(e)?.[1]?.toLowerCase()}function pU(e){return[...e.matchAll(/\[\s*([\w:-]+)\s*=/g)].map(t=>t[1]?.toLowerCase()).filter(t=>t!==void 0&&t!=="name")}function Vc(e,t,n,r,s,o){let a=Vs(t),d=uU(t),l=pU(t),c=new Set(n.map(R=>R.path.join("."))),u=[],p=0,f=new Map,m=R=>{if(gt(R)==="label"){let x=lt(R).for;x!==void 0&&f.set(x,nr(R))}for(let x of tt(R))Array.isArray(x)&&m(x)};m(e);let h=(R,x,T)=>{let N=gt(R);if(N===void 0||xI.has(N))return;let U=lt(R),F=(U.id===void 0?void 0:f.get(U.id))??T,I=gi(R),C=l.some(M=>U[M]!==void 0)||_I.some(M=>U[M]!==void 0);if(I!==void 0&&aU.has(I)||C){let M=Wa(R,l,F),$=`${M} ${je(nr(R),200)}`.toLowerCase(),j=c.has(x.join(".")),O=(j?100:0)+(d!==void 0&&I===d?2:0)+a.filter(P=>$.includes(P)).length*3;u.push({line:`${j?"match: ":""}${M}`,score:O,order:p++})}let A=N==="label"?nr(R):T;tt(R).forEach((M,$)=>{Array.isArray(M)&&h(M,[...x,$],A)})};h(e,[],void 0);let g=[...u].sort((R,x)=>x.score-R.score||R.order-x.order),y=[],w=[],b=0,v=g.length>s.maxItems;for(let R of g.slice(0,s.maxItems)){let x=ke(R.line,"dom",r,o),T=Buffer.byteLength(x.value,"utf8")+1;if(b+T>s.maxBytes){v=!0;break}w.push(...x.records),y.push(x.value),b+=T}return{text:y.join(`
|
|
148
148
|
`),redactions:w,nodes:y.length,truncated:v}}var SI=256,TI={before:"before",action:"action",input:"action",after:"after"};function ig(e){return Array.isArray(e)&&typeof e[0]=="string"}function fU(e){return Array.isArray(e)&&Array.isArray(e[0])&&typeof e[0][0]=="number"&&typeof e[0][1]=="number"}function AI(e){let t=e[1],n=typeof t=="object"&&t!==null&&!Array.isArray(t);return e.slice(n?2:1)}function mU(e){let t=X(e.snapshotName),n=X(e.callId),r=TI[X(e.phase)??""];if(t!==void 0){let s=t.indexOf("@");s>0&&(r??=TI[t.slice(0,s)],n??=t.slice(s+1))}return{...n===void 0?{}:{callId:n},...r===void 0?{}:{phase:r},...t===void 0?{}:{name:t}}}var Uc=class{frames=new Map;literals=new Map;byCall=new Map;add(t,n,r){let s=Te(r.snapshot);if(s===void 0||s.html===void 0)return;let o=mU(s),a=X(s.frameId)??X(s.pageId)??"unknown-frame",d=`${t}
|
|
@@ -208,7 +208,7 @@ ${e.lines.join(`
|
|
|
208
208
|
${r}`},u=n.noun??"merge-request note",p=`${u.charAt(0).toUpperCase()}${u.slice(1)}`;try{let f=await h3(o,d,l);if(f!==void 0){let h=await o.call("PUT",`${d}/${f}`,c);if(h.ok)return e.print(`${p}: updated.`);if(h.status!==403&&h.status!==404)throw new eo(await ty(h))}if(f===void 0&&!s)return e.print(`No ${u}: nothing failed, and there is no earlier note to update.`);let m=await o.call("POST",d,c);if(!m.ok)throw new eo(await ty(m));e.print(`${p}: posted.`)}catch(f){let m=f instanceof eo?f.message:`GitLab couldn't be reached (${f instanceof Error?f.message:String(f)})`;e.error(`No ${u}: ${m}.`)}}async function g3(e,t,n,r,s,o){let a=l=>e.print(`No merge-request note: ${l}.`),d=n.pullRequest;if(d===void 0)return a("this pipeline isn't for a merge request, or its branch has more than one");if(d.fork)return a("the merge request comes from a fork, whose pipeline gets none of this project's variables");if(n.token===void 0)return a("GITLAB_TOKEN isn't set; CI_JOB_TOKEN can't write notes, so add a token that can as a masked CI/CD variable: a fine-grained token with Work Item read, create, and update, or one with the `api` scope");if(n.apiUrl===void 0||n.projectId===void 0)return a("CI_API_V4_URL or the merge request's project isn't what GitLab sets");await yd(e,t,{apiUrl:n.apiUrl,project:n.projectId,number:d.number,token:n.token,marker:xT(n,o)},r,s)}async function wd(e,t,n,r,s){e.print("");for(let o of r.trimEnd().split(`
|
|
209
209
|
`))e.print(o);e.print(""),await g3(e,t,n,r,s.failures,s.command??"ci")}var Pi=class extends Error{};async function bd(e,t){if(e.status===429)return"GitLab's rate limit was reached";if(e.status===401)return"GitLab refused GITLAB_TOKEN";if(e.status===403)return t;if(e.status===404)return"GitLab found no such project or commit with GITLAB_TOKEN";let n=await e.json().catch(()=>{}),r=typeof n?.message=="string"?n.message:n?.message===void 0?"":JSON.stringify(n.message),s=r===""?"":`: ${r.replace(/\s+/g," ").slice(0,200)}`;return`GitLab answered ${e.status}${s}`}function Ei(e,t){return`/projects/${e}${t}`}function ny(e){return`/repository/branches/${encodeURIComponent(e)}`}async function ry(e,t,n){let r=new to(e,t.apiUrl,t.token),s=on(n);try{let o=await r.call("GET",Ei(t.project,`/merge_requests?state=opened&source_branch=${encodeURIComponent(s)}&per_page=100`));if(!o.ok)return{kind:"unknown",reason:await bd(o,"GITLAB_TOKEN can't read merge requests")};let a=(await o.json()).find(l=>typeof l.iid=="number"&&typeof l.description=="string"&&l.description.startsWith(Ii(n)));if(typeof a?.iid=="number")return{kind:"open",number:a.iid,...typeof a.web_url=="string"?{url:a.web_url}:{}};let d=await r.call("GET",Ei(t.project,ny(s)));return d.status===404?{kind:"none"}:d.ok?{kind:"branch"}:{kind:"unknown",reason:await bd(d,"GITLAB_TOKEN can't read branches")}}catch(o){return{kind:"unknown",reason:`GitLab couldn't be reached (${o instanceof Error?o.message:String(o)})`}}}async function iy(e,t,n,r,s){let o=s.runUrl===void 0?"a later pipeline":`[a later pipeline](${s.runUrl})`;await yd(e,t,{apiUrl:n.apiUrl,project:n.project,number:r.number,token:n.token,marker:`<!-- kwikqa-fix-seen group=${r.fingerprint} -->`,noun:"note on the fix merge request"},`This failure group failed again in ${o}, at commit ${Re(s.commit.slice(0,12))}. KwikQA asks for no other repair while this merge request is open.
|
|
210
210
|
`,!0)}async function sy(e,t,n){let r=new to(t,n.apiUrl,n.token),s=on(n.fingerprint),o=!1;try{let a=await md(n);if("failure"in a)return{kind:"failed",reason:a.failure};let{files:d}=a;for(let f of d){let m=await r.call("GET",Ei(n.project,`/repository/files/${encodeURIComponent(f.path)}?ref=${n.base.commit}`));if(m.status===404)return{kind:"skipped",reason:Ti(f,n.base.branch)};if(!m.ok)throw new Pi(await bd(m,"GITLAB_TOKEN can't read the repository"));let h=await m.json(),g=typeof h.content=="string"&&h.encoding==="base64"?Buffer.from(h.content,"base64"):void 0;if(g===void 0||!hd(g,f))return{kind:"skipped",reason:Ti(f,n.base.branch)}}if((await r.call("GET",Ei(n.project,ny(s)))).ok)return{kind:"skipped",reason:`${s} already exists, from an earlier pipeline; KwikQA never pushes to a branch it didn't create`};let c=await r.call("POST",Ei(n.project,"/repository/commits"),{branch:s,start_sha:n.base.commit,commit_message:n.commitMessage,actions:d.map(f=>({action:"update",file_path:f.path,content:Buffer.from(f.bytes).toString("base64"),encoding:"base64"}))});if(!c.ok)throw new Pi(await bd(c,"GITLAB_TOKEN can't push a branch; it needs the `api` scope and at least the Developer role"));o=!0;let u=await r.call("POST",Ei(n.project,"/merge_requests"),{source_branch:s,target_branch:n.base.branch,title:`Draft: ${n.title}`,description:n.description,labels:Nr,remove_source_branch:!0});if(!u.ok)throw new Pi(await bd(u,"GITLAB_TOKEN can't open a merge request; it needs the `api` scope and at least the Developer role"));let p=await u.json();if(typeof p.iid!="number")throw new Pi("GitLab returned no merge request");return o=!1,{kind:"opened",number:p.iid,...typeof p.web_url=="string"&&p.web_url.startsWith("https://")?{url:p.web_url}:{}}}catch(a){let d=a instanceof Pi?a.message:`GitLab couldn't be reached (${a instanceof Error?a.message:String(a)})`;return o&&await r.call("DELETE",Ei(n.project,ny(s))).catch(()=>{}),{kind:"failed",reason:d}}}var y3=/^[\w.-]+(?:\/[\w.-]+)+$/,w3=/^\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)$/,b3=/^\/([\w.-]+(?:\/[\w.-]+)+)\/-\/merge_requests\/(\d+)$/;function _T(e){let t=Number(e);return/^\d+$/.test(e??"")&&Number.isSafeInteger(t)&&t>0?t:void 0}function v3(e,t){if(e===void 0||!e.startsWith("https:"))return;let n=new URL(e),r=w3.exec(n.pathname);if(r?.[1]!==void 0&&Number(r[2])===t)return{kind:"github",apiUrl:n.host==="github.com"?"https://api.github.com":n.host.endsWith(".ghe.com")?`https://api.${n.host}`:`${n.origin}/api/v3`,repository:r[1]};let s=b3.exec(n.pathname);if(s?.[1]!==void 0&&Number(s[2])===t)return{kind:"gitlab",apiUrl:`${n.origin}/api/v4`,project:s[1]}}function k3(e){let t=e??"",r=/^[\w.-]+@[\w.-]+:(?!\/)(.+)$/.exec(t)?.[1];if(r===void 0)try{r=new URL(t).pathname}catch{return}let s=r.replace(/^\/+/,"").replace(/\/+$/,"").replace(/\.git$/,"");return y3.test(s)?s:void 0}function Ci(e){if(!e.JENKINS_URL&&!e.JENKINS_HOME||_T(e.BUILD_NUMBER)===void 0)return;let t=_T(e.CHANGE_ID),n=Mp(e.CHANGE_URL),r=t===void 0?void 0:v3(n,t),s=r?.kind==="github"?r.repository:r?.kind==="gitlab"?r.project:k3(e.GIT_URL),o=Mp(e.BUILD_URL),a=e.CHANGE_BRANCH||e.BRANCH_NAME||e.GIT_LOCAL_BRANCH||e.GIT_BRANCH?.replace(/^origin\//,"")||void 0,d=/^[0-9a-f]{40}$/.test(e.GIT_COMMIT??"")?e.GIT_COMMIT:void 0,l=(e.GITHUB_TOKEN??"").trim(),c=(e.GITLAB_TOKEN??"").trim();return{...s===void 0?{}:{repository:s},...o===void 0?{}:{runUrl:o},job:e.JOB_NAME??"",...e.STAGE_NAME?{stage:e.STAGE_NAME}:{},...a===void 0?{}:{branch:a},...d===void 0?{}:{commit:{sha:d}},...r===void 0?{}:{host:r},...l===""?{}:{githubToken:l},...c===""?{}:{gitlabToken:c},...t===void 0?{}:{pullRequest:{number:t,...r?.kind==="gitlab"?{name:`Merge request !${t}`}:{},...n===void 0?{}:{url:n},fork:!1}}}}function IT(e,t="ci"){let n=e.stage===void 0?"":` stage=${encodeURIComponent(e.stage)}`;return`<!-- kwikqa-${t} jenkins job=${encodeURIComponent(e.job)}${n} -->`}async function R3(e,t,n,r,s,o){let a=n.pullRequest,d=n.host;if(a===void 0)return e.print("No pull-request comment: this build isn't for a pull request.");if(d===void 0)return e.print(a.url?.startsWith("http:")===!0?"No pull-request comment: the pull request's page isn't https, and KwikQA sends tokens only over https.":"No pull-request comment: the pull request isn't on GitHub or GitLab, the hosts KwikQA comments on from Jenkins so far.");let l=IT(n,o);return d.kind==="github"?n.githubToken===void 0?e.print("No pull-request comment: GITHUB_TOKEN isn't set; bind a token that can comment on pull requests with withCredentials."):dd(e,t,{apiUrl:d.apiUrl,repository:d.repository,number:a.number,token:n.githubToken,marker:l,forbidden:"GITHUB_TOKEN can't comment on this pull request; it needs Pull requests read and write, or a classic token's `repo` scope"},r,s):n.gitlabToken===void 0?e.print("No merge-request note: GITLAB_TOKEN isn't set; bind a token that can write notes with withCredentials: a fine-grained token with Work Item read, create, and update, or one with the `api` scope."):yd(e,t,{apiUrl:d.apiUrl,project:d.project,number:a.number,token:n.gitlabToken,marker:l},r,s)}async function vd(e,t,n,r,s){e.print("");for(let o of r.trimEnd().split(`
|
|
211
|
-
`))e.print(o);e.print(""),await R3(e,t,n,r,s.failures,s.command??"ci")}import{realpath as
|
|
211
|
+
`))e.print(o);e.print(""),await R3(e,t,n,r,s.failures,s.command??"ci")}import{realpath as wJ}from"node:fs/promises";var ST=20,TT={passed:"passed",failed:"failed","not-checked":"not checked"},x3={passed:"Every gate passed.",failed:"At least one gate found a problem.",incomplete:"No gate found a problem, but not every gate could run, so this is not a pass."};function AT(e){let t=`${e.changedFiles} changed file${e.changedFiles===1?"":"s"}`,n=[`### KwikQA check: ${e.outcome}`,"",`${x3[e.outcome]} Compared ${t} with ${Re(e.base.revision)} (${Re(e.base.commit.slice(0,7))}).`,"","| Gate | Result |","| --- | --- |",...e.gates.map(r=>`| ${sn(r.title)} | ${TT[r.status]} |`)];for(let r of e.gates){if(r.findings.length===0)continue;n.push("",`**${sn(r.title)}**`,"");for(let o of r.findings.slice(0,ST)){let a=o.path===void 0?"":`${Re(`${o.path}${o.line===void 0?"":`:${o.line}`}`)} `;n.push(`- ${TT[o.kind]}: ${a}${sn(o.message)}`)}let s=r.findings.length-ST;s>0&&n.push(`- and ${s} more in the job's log`)}return e.runUrl!==void 0&&n.push("",`Every finding is in the log of [this run](${e.runUrl}).`),`${n.join(`
|
|
212
212
|
`)}
|
|
213
213
|
`}function oy(e,t){return`### KwikQA check: ${sn(e)}
|
|
214
214
|
|
|
@@ -261,23 +261,23 @@ ${l.join(`
|
|
|
261
261
|
`);return t.at(-1)===""?t.slice(0,-1):t}function Ow(e,t){let n=IE(e),r=IE(t),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s+=1;let o=0;for(;o<n.length-s&&o<r.length-s&&n[n.length-1-o]===r[r.length-1-o];)o+=1;let a=n.slice(s,n.length-o),d=r.slice(s,r.length-o);if((a.length+1)*(d.length+1)>M9)return;let l=d.length+1,c=new Int32Array((a.length+1)*l);for(let g=a.length-1;g>=0;g-=1)for(let y=d.length-1;y>=0;y-=1)c[g*l+y]=a[g]===d[y]?(c[(g+1)*l+y+1]??0)+1:Math.max(c[(g+1)*l+y]??0,c[g*l+y+1]??0);let u=[],p,f=()=>{p!==void 0&&u.push(p),p=void 0},m=0,h=0;for(;m<a.length||h<d.length;){if(m<a.length&&h<d.length&&a[m]===d[h]){f(),m+=1,h+=1;continue}p??={resultLine:s+h+1,deleted:[],added:[]},h<d.length&&(m>=a.length||(c[m*l+h+1]??0)>(c[(m+1)*l+h]??0))?(p.added.push(d[h]??""),h+=1):(p.deleted.push(a[m]??""),m+=1)}return f(),u}function SE(e,t){let n=1;for(let r=0;r<t&&r<e.length;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}function Dw(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}}async function L9(e,t,n){let r=await or(e.gitRoot,t.commit,Mr(e.workspaceRoot,e.gitRoot,n),_E);if(r.kind==="absent")return{kind:"repair-config-missing",message:`\`kwikqa check\` judges changes by the committed ${n}, and ${t.revision} has none. Run \`kwikqa init\`, then commit ${n}.`};let s=r.kind==="read"?Dw(r.bytes):void 0,o;try{o=s===void 0?void 0:JSON.parse(s)}catch{o=void 0}if(o===void 0)return{kind:"repair-config-invalid",message:`The committed ${n} is not UTF-8 JSON of at most ${_E} bytes.`};let a=cr(o);return a.kind==="valid"?a:{kind:"repair-config-invalid",message:`The committed ${n} is invalid: ${a.issues.join(" ")}`}}var D9=/\.(?:[cm]?[jt]sx?|java|py)$/i;function F9(e){return e.startsWith(".kwikqa/")||e===Ls}async function j9(e,t,n){let r=u=>({findings:[{kind:"not-checked",path:e,message:u}]}),s=Fd(e);if(!D9.test(e)||s===void 0)return r("KwikQA checks JavaScript, TypeScript, Java, and Python test code, so this file's change was not checked.");let o=Ow(t,n);if(o===void 0)return r("The changed part of this file is too large to compare line by line.");let a=o.reduce((u,p)=>u+p.deleted.length+p.added.length,0);if(!await yo(e,n))return{changedLines:a,findings:[{kind:"failed",path:e,message:"The file no longer parses."}]};if(!await yo(e,t))return{changedLines:a,findings:[{kind:"not-checked",path:e,message:"The file didn't parse before the change, so the change can't be compared."}]};let d=[],l=await _w(t,n,s);if(l.length>0){let u=l.map(f=>f.split(/[.:!]/).at(-1)??f),p=o.find(f=>f.deleted.some(m=>u.some(h=>m.includes(h))))??o[0];d.push({kind:"failed",path:e,...p===void 0?{}:{line:p.resultLine},message:Iw("change",l)})}let c=await fp(t,n,s);if(c.length>0){let u=m=>o.some(h=>m>=h.resultLine&&m<h.resultLine+h.added.length),p=c.flatMap(m=>m.patternCalls.map(h=>SE(n,h.start))),f=p.find(u)??p[0];d.push({kind:"failed",path:e,...f===void 0?{}:{line:f},message:Sw("change",c.map(m=>m.matcher))})}for(let u of await xw(t,n,s))d.push({kind:"failed",path:e,line:SE(n,u.start),message:TE(up)});for(let u of o)for(let p of await mp(u.deleted.join(`
|
|
262
262
|
`),u.added.join(`
|
|
263
263
|
`),{},"change",s)){let f=await B9(u,p,s);d.push({kind:"failed",path:e,line:f,message:TE(p)})}return{changedLines:a,findings:d}}async function B9(e,t,n){for(let[r,s]of e.added.entries())if((await mp("",s,{},"change",n)).includes(t))return e.resultLine+r;return e.resultLine}function TE(e){let t=`${e.charAt(0).toUpperCase()}${e.slice(1)}`;return t.endsWith(".")?t:`${t}.`}function V9(e){return[...e].sort((t,n)=>(t.path===void 0?1:0)-(n.path===void 0?1:0)||(t.path??"").localeCompare(n.path??"")||(t.line??0)-(n.line??0))}function Lw(e,t){let n=V9(t);return{gate:e,status:n.some(r=>r.kind==="failed")?"failed":n.some(r=>r.kind==="not-checked")?"not-checked":"passed",findings:n}}async function Fw(e){let t=new Date().toISOString(),n=await N9(e.workspaceRoot),r=await an(n),s=e.configPath??$9,o=await uy(r,"HEAD");if(o===void 0)return{kind:"unavailable",reason:"no-repository",message:"`kwikqa check` compares your changes with a commit, so it needs a git repository with at least one commit."};let a={revision:"HEAD",commit:o};if(e.base!==void 0){let F=await uy(r,e.base),I=F===void 0?void 0:await BT(r,F);if(I===void 0)return{kind:"unavailable",reason:"unknown-base",message:F===void 0?`\`--base ${e.base}\` names no commit in this repository. Fetch it first, or name a branch, tag, or commit.`:`The current branch shares no history with ${e.base}.`};a={revision:e.base,commit:I}}let d=await L9({workspaceRoot:n,gitRoot:r},a,s);if(d.kind!=="valid")return{kind:"unavailable",reason:d.kind,message:d.message};let{config:l}=d,c=e.analysis===void 0?void 0:await vE(O9(n,e.analysis),e.analysis);if(c?.kind==="unreadable")return{kind:"unavailable",reason:"analysis-unreadable",message:c.message};let u=[],p=[],f=0,m=0;for(let F of await VT(r,a.commit)){let I=UT(n,r,F.path);if(I===void 0){u.push({path:F.path,change:F.change,scope:"outside"}),p.push({kind:"failed",path:F.path,message:"Outside this workspace, so outside the test code kwikqa.config.json lets KwikQA edit."});continue}if(F9(I))continue;let C=Zn(I)?void 0:pi(I,l.editablePaths);if(C===void 0||Sn(I,l)){let P=F.change==="deleted"?void 0:await G(n,I,bp);u.push({path:I,change:F.change,scope:"outside",...P?.kind==="read"?{sha256:P.sha256}:{}}),p.push({kind:"failed",path:I,message:"Outside the test code kwikqa.config.json lets KwikQA edit. KwikQA never changes other files to make a test pass, so a change that does fails the check."});continue}if(f+=1,F.change==="deleted"){u.push({path:I,change:"deleted",scope:C.class}),p.push({kind:"failed",path:I,message:"Deleted. Deleting test code deletes the tests it holds or supports."});continue}let A=F.change==="added"?{kind:"read",bytes:new Uint8Array}:await or(r,a.commit,F.path,bp),M=await G(n,I,bp),$=A.kind==="read"?Dw(A.bytes):A.kind,j=M.kind==="read"?Dw(M.bytes):void 0,O;M.kind==="unauthorized"?O={findings:[{kind:"failed",path:I,message:"Not a regular file inside the workspace, such as a symbolic link."}]}:$==="over-budget"||M.kind==="over-budget"?O={findings:[{kind:"not-checked",path:I,message:`Larger than ${bp} bytes, so its change was not checked.`}]}:$===void 0||$==="absent"||j===void 0?O={findings:[{kind:"not-checked",path:I,message:"Not readable as UTF-8 text, so its change was not checked."}]}:O=await j9(I,$,j),m+=O.changedLines??0,u.push({path:I,change:F.change,scope:C.class,...O.changedLines===void 0?{}:{changedLines:O.changedLines},...M.kind==="read"?{sha256:M.sha256}:{}}),p.push(...O.findings)}if(u.length===0)return{kind:"nothing-to-check",base:a,message:a.revision==="HEAD"?"Nothing to check: there are no uncommitted changes.":`Nothing to check: nothing changed since the branch left ${a.revision}.`};let{maxFiles:h,maxChangedLines:g}=l.budgets;(f>h||m>g)&&p.push({kind:"failed",message:`The change touches ${f} test file${f===1?"":"s"} and ${m} line${m===1?"":"s"}; kwikqa.config.json lets one repair change at most ${h} file${h===1?"":"s"} and ${g} lines.`});let y=await xE({workspaceRoot:n,gitRoot:r,base:a,changes:u,...c===void 0?{}:{analysis:c.record}}),w=Lw("scope-and-policy",p),b={...Lw("ownership",y.findings),...y.analysis===void 0?{}:{analysis:y.analysis}},v={workspaceRoot:n,gitRoot:r,base:a,changes:u,tests:y.tests,earlierGateFailed:w.status==="failed"||b.status==="failed",...e.validation===void 0?{}:{interaction:e.validation},...e.validationTimeoutMs===void 0?{}:{timeoutMs:e.validationTimeoutMs}},R=y.record,x=R?.framework!==void 0&&Kn(R.framework)?R.framework:void 0,T=Lw("validation",R!==void 0&&x!==void 0?await hE({...v,record:R,framework:x,allRefused:y.allRefused===!0}):await pE({...v,...R===void 0?{}:{record:R}})),N=[w,b,T];return{kind:"checked",outcome:N.some(F=>F.status==="failed")?"failed":N.some(F=>F.status==="not-checked")?"incomplete":"passed",checkedAt:t,base:a,changes:u,gates:N}}import{createHash as U9}from"node:crypto";import{join as H9,relative as z9,sep as q9}from"node:path";var PE="kwikqa.config.json",G9=256*1024;async function EE(e,t){let n=await G(e,t,G9);if(n.kind==="unavailable")return{kind:"repair-config-missing",message:`Repair requires a reviewed ${t}; none was found in the workspace.`};if(n.kind!=="read")return{kind:"repair-config-invalid",message:`${t} could not be read: ${n.message}`};let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n.bytes))}catch{return{kind:"repair-config-invalid",message:`${t} is not valid UTF-8 JSON.`}}let s=cr(r);return s.kind!=="valid"?{kind:"repair-config-invalid",message:s.issues.join(" ")}:{...s,bytes:n.bytes}}async function Wi(e,t=PE){let n=await EE(e,t);return n.kind==="valid"?n.config.ci?.fix:void 0}async function K9(e,t,n,r){if(e.ci===void 0)return{};if(t.config.ci?.fix===void 0)return{refusal:{outcome:"operation-failed",reasonCode:"ci-fix-policy-missing",message:`\`kwikqa fix\` needs a terminal, unless ${r} has a committed ci.fix policy, which lets it validate a repair on this runner and open a draft pull request.`}};let s=z9(n.gitRoot,H9(n.workspaceRoot,r)).split(q9).join("/");return await jT(n.gitRoot,s,t.bytes)?{approver:{kind:"ci-policy",...e.ci,policyHash:U9("sha256").update(t.bytes).digest("hex")}}:{refusal:{outcome:"operation-failed",reasonCode:"ci-fix-policy-uncommitted",message:`${r} differs from its committed version, so its ci.fix policy wasn't reviewed; a fix in CI runs only under the committed policy.`}}}function W9(e,t,n){let r=new Set(n.map(o=>o.toLocaleLowerCase("en-US"))),s=new Set;for(let o of e.evidence){if(o.locator.type!=="source-range")continue;let a=o.locator.path;pi(a,t.editablePaths)!==void 0&&!Sn(a,t)&&!Zn(a)&&!r.has(a.toLocaleLowerCase("en-US"))&&s.add(a)}return[...s].sort()}async function vp(e){let t=e.now??(()=>new Date().toISOString()),n=await $r(e.workspaceRoot);if(n.kind==="unavailable")return{outcome:"operation-failed",reasonCode:"repository-status-unavailable",message:n.message};let{workspaceRoot:r,gitRoot:s,dirtyPaths:o,pristine:a}=n.status,d=e.configPath??PE,l=await EE(r,d);if(l.kind!=="valid")return{outcome:"operation-failed",reasonCode:l.kind,message:l.message};let c=l.config,u=await K9(e,l,{workspaceRoot:r,gitRoot:s},d);if("refusal"in u)return u.refusal;let{approver:p}=u;if(e.retryRepairSessionId!==void 0&&(await Ar(r,e.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 f=await Od({...e,workspaceRoot:r,gitRoot:s,repairableOnly:!0},t);if(f.kind==="unreadable")return{outcome:f.outcome,reasonCode:f.reasonCode,message:f.message};let{stage:m}=f,h={workspaceRoot:r,gitRoot:s,dirtyPaths:o},g=(x,T=[],N)=>(U,F={})=>tp(x,ep(x,"fix",T.length===0?U:{...U,message:`${T.join(" ")} ${U.message}`},t,{repository:{pristine:a,dirtyPaths:o},...F}),e.persist!==!1).then(I=>N===void 0?I:{...I,fixGroups:N}),y=Z9(m,e);if("refusal"in y)return g(m)(y.refusal);let w=e.oneGroup===void 0?void 0:nK(m);if(y.groups.length===0&&e.oneGroup!==void 0)return g(m,[],{groups:w??[]})({outcome:"abstained-from-repair",reasonCode:"group-not-repairable",message:tK(e.oneGroup)});if(y.groups.length===0){let{packet:x}=m,{diagnosis:T,grading:N}=m.result;return m.result.outcome!=="diagnosed"||x===void 0||T===void 0||N===void 0?g(m)(m.result):AE(e,m,{packet:x,diagnosis:T,grading:N},c,t,g(m),h,p)}let b=(m.clusterStages??[]).flatMap(x=>x.refusal===void 0?[]:[x.refusal.message]),v=[],R=new Map;for(let x of y.groups){let T=await e.fixInReview?.(x.cluster.signals);T===void 0?v.push(x):(R.set(x.representativeId,T),b.push(`Failure group ${jw(m,x)}: ${T.reason}.`))}if(v.length===0)return g(m,[],w===void 0?void 0:{groups:rK(w,R)})({outcome:"abstained-from-repair",reasonCode:"fix-in-review",message:b.join(" ")});await e.repairSession?.open(v.length);try{let x;for(let T of v){let N=Q9(m,T),{packet:U}=N,{diagnosis:F,grading:I}=T.result;if(U===void 0||F===void 0||I===void 0)continue;let C=w===void 0?void 0:{groups:w,attempted:T.representativeId},A=`Failure group ${jw(m,T)}`,M=g(N,b,C),$;if(x=await AE(e,N,{packet:U,diagnosis:F,grading:I},c,t,(j,O)=>($=j.message,M(b.length===0?j:{...j,message:`${A}: ${j.message}`},O)),h,p),!X9(x))return x;b.push(`${A}: ${$??x.message}`)}return x??g(m)(m.result)}finally{await e.repairSession?.close()}}var J9=3,Y9=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 X9(e){return e.outcome==="abstained-from-repair"?Y9.has(e.reasonCode):e.outcome==="validation-unavailable"&&e.record?.application.status==="not-run"}function jw(e,t){return(e.clusterStages??[]).indexOf(t)+1}function Q9(e,t){return{...e,...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,...(e.clusterStages??[]).filter(n=>n!==t)],representativeId:t.representativeId}}function Z9(e,t){let n=e.clusterStages??[];if(t.group!==void 0){let o=n[t.group-1];return o===void 0?{refusal:{outcome:"operation-failed",reasonCode:"group-not-found",message:`There is no failure group ${t.group}; this run has ${n.length}.`}}:o.refusal!==void 0?{refusal:{outcome:"abstained-from-repair",reasonCode:"not-a-browser-test",message:o.refusal.message}}:ho([o]).includes(o)?{groups:[o]}:{refusal:{outcome:"abstained-from-repair",reasonCode:"group-not-repairable",message:`Failure group ${t.group} is not diagnosed as the test's fault (${o.result.reasonCode}); KwikQA repairs only test-side causes.`}}}let r=ho(n);if(t.oneGroup!==void 0)return{groups:eK(r,t.oneGroup)};let s=t.repairSession===void 0||t.retryRepairSessionId!==void 0?1:J9;return{groups:r.slice(0,s)}}function eK(e,t){let{retryOf:n}=t,r=n===void 0?e.find(s=>!t.tried.includes(s.representativeId)):e.find(s=>s.cluster.logicalTestIds.includes(n));return r===void 0?[]:[r]}function tK(e){return e.retryOf===void 0?"No repair-eligible failure group is left to try, so no repair was requested.":"The failure group whose validation failed is no longer repair-eligible in the retry's report, so no repair was requested."}function nK(e){let t=e.clusterStages??[],n=new Set(ho(t));return t.map(r=>({number:jw(e,r),representativeId:r.representativeId,logicalTestIds:r.cluster.logicalTestIds,repairable:n.has(r),reasonCode:r.result.reasonCode,message:r.result.message}))}function rK(e,t){return e.map(n=>{let r=t.get(n.representativeId);return r===void 0?n:{...n,inReview:r}})}async function iK(e,t){let{interaction:n}=e;if(n.confirmFailure===void 0||e.retryRepairSessionId!==void 0)return;let r=t.clusterStages?.[0]?.cluster.logicalTestIds??t.failing,s=t.representativeId??r[0];if(s===void 0)return;let o=await n.confirmFailure(t.run,r);if(o.kind==="declined")return{status:"declined",logicalTestIds:r,message:"The developer chose not to re-run the failing tests first."};if(o.kind==="unavailable")return{status:"unavailable",logicalTestIds:r,message:o.message};let a=r.filter(l=>o.failedAgain.includes(l));if(a.includes(s))return{status:"reproduced",logicalTestIds:r,failedAgain:a};let d=t.run.logicalTests.find(l=>l.logicalTestId===s)?.title;return{status:"not-reproduced",logicalTestIds:r,failedAgain:a,message:`${d===void 0?"The failing test":`"${d}"`} 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 AE(e,t,n,r,s,o,a,d){let{packet:l,diagnosis:c,grading:u}=n,p=[...c.hypotheses].sort((b,v)=>b.rank-v.rank)[0],f=e.repairCaps??e.remote.caps,m=await qy({packet:l,diagnosis:c,grading:u,hypothesisId:p?.hypothesisId??"",editablePaths:W9(l,r,a.dirtyPaths),budgets:r.budgets,model:e.repairModel??e.remote.model,caps:f,transport:e.remote.transport,now:s()});if(m.kind!=="preview-ready"){let b=m.reasonCode==="repair-not-eligible"&&p?.probableOwner!=="test-support"?Zu(c):m.reasonCode,v=m.reasonCode==="repair-not-eligible"||Qu.has(m.reasonCode);return o({outcome:v?"abstained-from-repair":"operation-failed",reasonCode:b,message:m.message},{proposal:{status:v?"not-eligible":"failed"},repairAudit:m.audit})}let h=await iK(e,t),g=(b,v={})=>o(b,{...h===void 0?{}:{confirmation:h},...v});if(h?.status==="not-reproduced")return g({outcome:"abstained-from-repair",reasonCode:"failure-not-reproduced",message:h.message??"The failing test passed when re-run."},{proposal:{status:"not-eligible"}});if(!await e.interaction.approveRepairRequest(m.prepared.preview))return g({outcome:"repair-declined",reasonCode:"remote-consent-declined",message:"The developer declined the repair-proposal request; no evidence was sent."},{proposal:{status:"declined"}});let y=await Gy({prepared:m.prepared,authorization:{bindingHash:m.prepared.authorizationBindingHash,mode:"interactive",authorizedAt:s(),authorizationId:mo()},authorizationStore:e.authorizationStore??new $i,transport:e.remote.transport,now:s()});if(y.kind==="declined")return g({outcome:"abstained-from-repair",reasonCode:y.reasonCode,message:y.message},{proposal:{status:"not-eligible"},repairAudit:y.audit});if(y.kind!=="proposed")return g({outcome:"operation-failed",reasonCode:y.reasonCode,message:y.message},{proposal:{status:"failed"},repairAudit:y.audit});let w=await Pw({packet:l,diagnosis:c,grading:u,config:r,snapshot:{workspaceRoot:a.workspaceRoot,gitRoot:a.gitRoot,dirtyPaths:a.dirtyPaths,validation:[]},intent:y.draft.intent,replacements:y.draft.replacements});if(w.kind==="rejected"){let[b]=w.reasons;return g({outcome:"abstained-from-repair",reasonCode:b?.code??"invalid-replacement",message:w.reasons.map(v=>v.message).join(" ")},{proposal:{status:"not-eligible"},repairAudit:y.audit,proposalRejections:w.reasons})}return e.proposeOnly===!0?g({outcome:"proposal-ready",reasonCode:"test-support-owned",message:"A policy-checked proposal is ready for review; nothing was applied."},{proposal:{status:"ready"},repairAudit:y.audit,repairProposal:w.proposal}):lE({input:e,now:s,run:t.run,packet:l,diagnosis:c,...t.representativeId===void 0?{}:{representativeId:t.representativeId},...t.clusterStages?.[0]===void 0?{}:{memberIds:t.clusterStages[0].cluster.logicalTestIds},proposal:w.proposal,config:r,repository:a,diagnosisAudit:t.result.audit,repairAudit:y.audit,caps:f,...e.retryRepairSessionId===void 0?{}:{retry:{repairSessionId:e.retryRepairSessionId}},...d===void 0?{}:{ciApprover:d},finish:g})}import{randomUUID as sK}from"node:crypto";import{realpath as oK}from"node:fs/promises";import{join as NE,relative as aK,sep as Bw}from"node:path";var dK={maxStreamBytes:4*1024*1024,maxTotalStreamBytes:16*1024*1024,terminationGraceMs:5e3},lK=32*1024*1024,cK=new Set(["applied","validating"]);function uK(){return`vld_${sK().replaceAll("-","").slice(0,24)}`}function pK(e){return{config:e.config,snapshot:{workspaceRoot:e.workspace.workspaceRoot,gitRoot:e.workspace.gitRoot,dirtyPaths:[],validation:[]},workspace:e.workspace,maxTargetBytes:e.maxTargetBytes}}function fK(e,t,n){let r=s=>aK(e,`${t}${Bw}${s.split("/").join(Bw)}`).split(Bw).join("/");for(let s of n.commandRecords){let o=s.artifacts.find(l=>l.path.endsWith("/report.json"));if(o!==void 0)return r(o.path);let d=s.artifacts.filter(l=>Ql.test(l.path.split("/").at(-1)??""))[0];if(d!==void 0)return r(d.path.split("/").slice(0,-1).join("/"))}}var CE={parse:"parse check",format:"format check",typecheck:"type check",lint:"lint check"};async function mK(e,t,n,r){let s=h=>[...new Set(e.classifications.filter(g=>g.classification===h).flatMap(g=>g.logicalTestId===void 0?[]:[g.logicalTestId]))],o=s("still-failing-target"),a=s("newly-introduced-failure"),d=s("unchanged-pre-existing-failure"),l=[...new Set(e.commandRecords.filter(h=>h.status==="failed"&&CE[h.kind]).map(h=>CE[h.kind]))],c=t===void 0||o.length+a.length===0?void 0:await ht(NE(r,t),{workspaceRoot:r,gitRoot:n.workspace.gitRoot,...n.group?.framework===void 0?{}:{framework:n.group.framework}}),u=c?.kind==="parsed"?c.run:void 0,p=h=>`"${u?.logicalTests.find(g=>g.logicalTestId===h)?.title??h}"`,f=h=>{let y=[...u?.logicalTests.find(x=>x.logicalTestId===h)?.attempts??[]].reverse().find(x=>x.status!=="passed"&&x.errors.length>0),w=y?.errors[0];if(y===void 0||w===void 0)return"";let b=y.errorLocation??w.location,v=b===void 0?"":`, at ${b.file}:${b.line}`,R=(w.message??w.name??"").split(`
|
|
264
|
-
`)[0]?.trim().slice(0,200)??"";return`${v}${R===""?"":`: ${R}`}`},m=[...o.map(h=>`the repaired test ${p(h)} still failed${f(h)}`),...a.length===0?[]:[`${a.length===1?"a test that passed before now fails":`${a.length} tests that passed before now fail`}: ${a.map(p).join(", ")}`],...d.length===0?[]:[`${d.length===1?"a test":`${d.length} tests`} the change touches failed before it and still ${d.length===1?"fails":"fail"}`],...l.map(h=>`the ${h} failed`)];return m.length===0?void 0:m.join("; ")}async function hK(e,t,n){let r=t.group;if(r===void 0||r.logicalTestIds.length===0||e.checkGroup===void 0)return;let{logicalTestIds:s}=r,o=`${s.length} other test${s.length===1?"":"s"}`,a=await ht(NE(n,r.reportPath),{workspaceRoot:n,gitRoot:t.workspace.gitRoot,...r.framework===void 0?{}:{framework:r.framework}}),d=a.kind==="parsed"?new Set(a.run.logicalTests.map(p=>p.logicalTestId)):void 0;if(a.kind!=="parsed"||!s.every(p=>d?.has(p)))return{status:"unavailable",logicalTestIds:s,message:`The report fix read has changed, so the group's ${o} were not re-run.`};let l=await e.checkGroup(a.run,s);if(l.kind==="declined")return{status:"declined",logicalTestIds:s,message:`The group's ${o} were not re-run.`};if(l.kind==="unavailable")return{status:"unavailable",logicalTestIds:s,message:l.message};let c=s.filter(p=>l.failedAgain.includes(p)),u=c.map(p=>a.run.logicalTests.find(f=>f.logicalTestId===p)?.title??p).map(p=>`"${p}"`).join(", ");return{status:"rerun",logicalTestIds:s,stillFailing:c,message:c.length===0?`The group's ${o} pass now as well.`:`${c.length} of the group's ${o} still fail${c.length===1?"s":""}: ${u}. The patch stays; run \`kwikqa fix\` again for them.`}}async function Ud(e){let t=e.now??(()=>new Date().toISOString()),n=()=>new Date().toISOString(),r=await oK(e.workspaceRoot),s=await Vh(r);if(s.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-recovery-required",message:s.reasons.map(C=>C.message).join(" ")};let o=s.transactions.filter(C=>cK.has(C.phase));if(o.length!==1||o[0]===void 0)return{outcome:"operation-failed",reasonCode:"no-pending-repair",message:o.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 Ne(r,o[0].transactionId),d=a.manifest.preview.authoritativeValidation,l=await iE(r,d.repairSessionId,d.attemptOrdinal);if(l.transactionId!==a.manifest.transactionId)throw new Error("Repair attempt state does not belong to the pending transaction.");if(l.plan.planHash!==d.planHash)throw new Error("Saved validation plan does not match the approved plan.");let c=pK(l),u=l.transactionId,p=l.plan,f=[],m;if(a.state.phase==="validating"){let C=a.state.history.findLast(A=>A.type==="validation-started");if(C?.validationRunId===void 0)throw new Error("Validating transaction has no started validation run.");m=C.validationRunId}else{m=uK();let C=await pw({context:c,transactionId:u,planHash:p.planHash,validationRunId:m,now:n()});if(C.kind==="rejected"||C.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-rejected",message:C.reasons.map(A=>A.message).join(" ")};for(let A of p.commands)if(!(!A.required||A.timing!=="post-patch")){if(e.signal?.aborted===!0)break;await Jr({workspaceRoot:r,repositoryRoot:l.workspace.gitRoot,transactionId:u,validationRunId:m,plan:p,commandId:A.commandId,limits:dK,...e.signal===void 0?{}:{signal:e.signal}}).catch(M=>{Wr(A.kind)&&f.push(Uo(M))})}}let h=await zm({workspaceRoot:r,gitRoot:l.workspace.gitRoot,transactionId:u,validationRunId:m,plan:p,...l.baseline===void 0?{}:{baseline:l.baseline},reportMaxBytes:lK,completedAt:n()}),g=h.manifest,y={repairSessionId:l.repairSessionId,attempt:l.attempt,transactionId:u,planHash:p.planHash,validationRunId:m,validationManifestHash:g.manifestHash},w;if(g.status==="passed"){let C=await fw({context:c,transactionId:u,planHash:p.planHash,validationRunId:m,validationManifestHash:g.manifestHash,now:n(),approvedCommands:p.commands.map(A=>({commandId:A.commandId,executable:A.executable}))});if(C.kind==="completed"){await Va({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,validationRunId:m,now:t()});let A=await hK(e,l,r);return Vw(e,l,t,{outcome:"repaired",reasonCode:"validation-passed",message:`Every required validation check passed; the repair is complete.${A?.message===void 0?"":` ${A.message}`}`,application:"applied",validation:"passed",repair:y,...A===void 0?{}:{groupCheck:A}})}w="reasons"in C?C.reasons.map(A=>A.message).join(" "):"KwikQA couldn't complete the validation."}w===void 0&&await Va({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,validationRunId:m,now:t()});let b=await Uh(c,u,n());w!==void 0&&await Va({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,validationRunId:m,now:t()});let v=w!==void 0?"unavailable":g.status==="passed"?"incomplete":g.status,R=v==="failed"?"validation-failed":v==="unavailable"?"validation-unavailable":"validation-incomplete";if(b.kind!=="rolled-back")return Vw(e,l,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:v==="blocked"?"incomplete":v,repair:y});let T=(await Jh({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,proof:{transactionId:u,phase:"rolled-back",transactionRevision:b.transaction.revision},now:t()})).retry!==void 0,N=fK(r,h.directory,g),U=T?N:void 0,F=v==="failed"?await mK(g,N,l,r).catch(()=>{}):void 0,I=F===void 0?"Validation did not pass, so the patch was rolled back.":`Validation did not pass: ${F}. The patch was rolled back.`;return Vw(e,l,t,{outcome:"repair-failed",reasonCode:R,message:`${f.length===0?"":`KwikQA couldn't complete a command: ${f.join(" ")} `}${w===void 0?"":`${w} `}${I} ${T?"One retry is available.":"No retry remains."}`,application:"rolled-back",validation:v==="blocked"?"incomplete":v,repair:{...y,retryAvailable:T,...U===void 0?{}:{retryReportPath:U}}})}async function Vw(e,t,n,r){let s={schemaVersion:"1.5",recordId:Ju(),command:"validate",...t.record,recordedAt:n(),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(e.persist===!1)return{outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s};try{let o=await Cd(t.workspace.workspaceRoot,s);return{outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s,recordPath:o}}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}}}import{readFile as gK}from"node:fs/promises";var Hd="X-KwikQA-CI";function OE(e){let t=e?.trim().replace(/[^A-Za-z0-9._-]/g,"-").replace(/^[^A-Za-z0-9]+/,"");return t===void 0||t===""?void 0:t.slice(0,100)}function yK(e){let t=(e??"").split("/").map(n=>OE(n)).filter(n=>n!==void 0);return t.length===0?void 0:t.join("/").slice(0,200)}function Uw(e){try{return e===void 0||e===""?void 0:new URL(e).host.toLowerCase()}catch{return}}function $E(e){return e==="public"||e==="internal"||e==="private"?e:void 0}function kp(e,t){let n=yK(t.owner),r=OE(t.name);if(!(t.host===void 0||n===void 0||r===void 0))return{system:e,host:t.host,owner:n,name:r,...t.visibility===void 0?{}:{visibility:t.visibility}}}async function wK(e){let[t,n]=(e.GITHUB_REPOSITORY??"").split("/"),r={};try{e.GITHUB_EVENT_PATH!==void 0&&e.GITHUB_EVENT_PATH!==""&&(r=JSON.parse(await gK(e.GITHUB_EVENT_PATH,"utf8")))}catch{r={}}let s=r.repository,o=$E(s?.visibility)??(s?.private===!0?"private":s?.private===!1?"public":void 0);return kp("github",{host:Uw(e.GITHUB_SERVER_URL)??"github.com",owner:t,name:n,...o===void 0?{}:{visibility:o}})}function bK(e){let t=e.CI_PROJECT_PATH??"",n=t.lastIndexOf("/"),r=$E(e.CI_PROJECT_VISIBILITY);return kp("gitlab",{host:e.CI_SERVER_HOST?.toLowerCase()??Uw(e.CI_SERVER_URL),owner:n>0?t.slice(0,n):e.CI_PROJECT_NAMESPACE,name:n>0?t.slice(n+1):e.CI_PROJECT_NAME,...r===void 0?{}:{visibility:r}})}function vK(e){let t=e.SYSTEM_COLLECTIONURI??"",n;try{n=new URL(t).pathname.split("/").filter(Boolean)[0]}catch{n=void 0}return kp("azure",{host:Uw(t),owner:[n,e.SYSTEM_TEAMPROJECT].filter(Boolean).join("/"),name:e.BUILD_REPOSITORY_NAME})}function kK(e){let t=e.GIT_URL??e.CHANGE_URL??"",n=/^(?:https?:\/\/([^/]+)\/|git@([^:]+):)(.+?)\/([^/]+?)(?:\.git)?(?:\/(?:pull|-\/merge_requests)\/\d+)?\/?$/.exec(t),r=(n?.[1]??n?.[2])?.toLowerCase();return kp("jenkins",{host:r,owner:n?.[3],name:n?.[4]})}function Hw(e){if(e.GITHUB_ACTIONS==="true")return"github";if(e.TF_BUILD==="True")return"azure";if(e.GITLAB_CI==="true")return"gitlab";if(e.JENKINS_URL!==void 0||e.JENKINS_HOME!==void 0)return"jenkins"}async function ME(e){switch(Hw(e)){case"github":return wK(e);case"azure":return vK(e);case"gitlab":return bK(e);case"jenkins":return kK(e);default:return}}function LE(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function DE(e){let t=l=>{let c=e[l]?.trim();return c===void 0||c===""?void 0:c},n=t("KWIKQA_SHARD"),r,s;if(e.GITHUB_ACTIONS==="true"){let l=t("GITHUB_RUN_ID");r=l===void 0?void 0:`${l}-${t("GITHUB_RUN_ATTEMPT")??"1"}`,s=[t("GITHUB_JOB"),t("RUNNER_NAME")].filter(Boolean).join(":")||void 0}else if(e.TF_BUILD==="True"){let l=t("BUILD_BUILDID");r=l===void 0?void 0:`${l}-${t("SYSTEM_JOBATTEMPT")??"1"}`,s=t("SYSTEM_JOBID")}else e.GITLAB_CI==="true"?(r=t("CI_PIPELINE_ID"),s=t("CI_JOB_ID")):(e.JENKINS_URL!==void 0||e.JENKINS_HOME!==void 0)&&(r=t("BUILD_TAG"),s=[t("STAGE_NAME"),t("NODE_NAME"),t("EXECUTOR_NUMBER")].filter(Boolean).join(":")||void 0);s=n??s;let o=l=>l===void 0?void 0:l.replace(/[^A-Za-z0-9._:/-]/g,"-").slice(0,200),a=o(r),d=o(s);return a===void 0||d===void 0?void 0:{run:a,job:d}}var RK="X-KwikQA-CI-Identity",xK="https://kwikqa.com",_K=6e4,IK=6e4,SK=1e4;function TK(e){try{let t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));return typeof t.exp=="number"?t.exp*1e3:void 0}catch{return}}function AK(e,t,n,r){let s,o=0;return{token:async()=>{if(s!==void 0&&s.until>r())return s.value;if(!(o>r()))try{let a=new URL(e);if(a.protocol!=="https:")return;a.searchParams.set("audience",xK);let d=await n(a,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(SK)}),l=await d.json();if(!d.ok||typeof l.value!="string"||l.value==="")throw new Error("no token");let c=TK(l.value)??r()+5*6e4;return s={value:l.value,until:c-_K},l.value}catch{s=void 0,o=r()+IK;return}}}}function FE(e,t,n=Date.now){let r=e.KWIKQA_ID_TOKEN?.trim();if(r!==void 0&&r!=="")return{token:async()=>r};let s=e.ACTIONS_ID_TOKEN_REQUEST_URL,o=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(e.GITHUB_ACTIONS==="true"&&s&&o)return AK(s,o,t,n)}function jE(e,t){return t===void 0?e:(async(n,r)=>{let s=new Headers(r?.headers);if(!s.has(Hd))return e(n,r);let o=await t.token();return o!==void 0&&s.set(RK,o),e(n,{...r,headers:s})})}var PK=1200*1e3,EK=10,CK=1e3,NK=15e3,OK=3e3,$K=6e4,BE=3e4,MK=2;function qw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function UE(e){try{let t=await e.json();return qw(t)?t:void 0}catch{return}}async function LK(e){return await UE(e)??{}}function VE(e){return typeof e=="number"&&Number.isFinite(e)?Math.min(NK,Math.max(CK,e)):OK}function zw(e){let t=qw(e.error)?e.error:void 0;return typeof t?.message=="string"?t.message:void 0}var Rp=class{constructor(t){this.options=t}options;preflight(t){return this.options.preflight.preflight(t)}async complete(t){let n=performance.now(),r=()=>performance.now()-n;for(let s=0;;s+=1){let o=await this.#e(t,r);if(o!=="interrupted")return o;if(s===MK)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,n){let r=(p,f)=>({kind:"failed",code:p,message:f,elapsedMs:n()}),s=Tt(t);if(s!==void 0)return{kind:"failed",code:"invalid-request",message:s,elapsedMs:0};let o;try{o=await this.#n("POST","/v1/jobs",$K,{headers:{...this.options.headers(t.body),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(t.body)})}catch(p){return r("network-error",`The model request could not reach the KwikQA service (${Li(p)}).`)}let a=await LK(o);if(o.status!==202){let p=mu(a);return{kind:"failed",code:"http-error",message:zw(a)??"The KwikQA service refused the model request.",httpStatus:o.status,...p===void 0?{}:{providerCode:p},elapsedMs:n()}}let d=a.jobId;if(typeof d!="string"||d==="")return r("invalid-json","The KwikQA service did not name the job it started.");let l=this.options.sleep??(p=>new Promise(f=>setTimeout(f,p))),c=VE(a.pollAfterMs),u=0;for(;;){if(n()>(this.options.maxWaitMs??PK))return await this.#t(d),r("timeout","The model did not answer in time; nothing was charged.");await l(c);let p;try{p=await this.#n("GET",`/v1/jobs/${d}`,BE)}catch{p=new Response(null,{status:599})}let f=p.status>=500?void 0:await UE(p);if(p.status===404)return"interrupted";if(p.status<500&&!p.ok)return{kind:"failed",code:"http-error",message:zw(f??{})??"The KwikQA service refused to report the job.",httpStatus:p.status,elapsedMs:n()};if(f===void 0){if(u+=1,u>EK)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(u=0,f.status==="running"){this.options.onProgress?.(n()),c=VE(f.pollAfterMs);continue}if(f.status==="failed")return qw(f.error)&&f.error.code==="job-interrupted"?"interrupted":{kind:"failed",code:"http-error",message:zw(f)??"The model request was interrupted; nothing was charged.",httpStatus:503,elapsedMs:n()};if(f.status!=="answered")return r("invalid-json","The KwikQA service reported a job state the CLI does not know.");await this.#t(d);let m=typeof f.httpStatus=="number"?f.httpStatus:502,h=f.result,g=m>=200&&m<300;if(!g||xd(h)){let y=mu(h),w=g?y??502:m;return{kind:"failed",code:"http-error",message:vy(w,h),httpStatus:w,...y===void 0?{}:{providerCode:y},elapsedMs:n()}}return this.options.onCompletionBody?.(h),{kind:"response",httpStatus:m,body:h,elapsedMs:n()}}}async#t(t){try{await this.#n("DELETE",`/v1/jobs/${t}`,BE)}catch{}}#n(t,n,r,s={}){return this.options.fetch(`${this.options.baseUrl}${n}`,{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 Ji="0.10.0";var DK="https://api.kwikqa.com",Ln="https://kwikqa.com/dashboard/";function HE(e){return e.hosted??!(e.plan==="byo"||e.plan==="byo-team"||e.plan==="byo-enterprise")}function FK(e){return e?.response_format?.json_schema?.name==="kwikqa_diagnosis"}var nt=class extends Error{constructor(n,r,s,o){super(s);this.status=n;this.code=r;this.retryAfterSeconds=o}status;code;retryAfterSeconds};function jK(e,t){let n=e?.error?.retryAfter,r=typeof n=="number"?n:Number(t??Number.NaN);return Number.isFinite(r)&&r>0&&r<=3600?r:void 0}function pr(e,t){return(e.KWIKQA_API_URL??(t===void 0||t===""?DK:t)).replace(/\/+$/,"")}function zE(e){let t=e?.messages;if(!Array.isArray(t))return;let n=t.find(r=>typeof r=="object"&&r!==null&&r.role==="user"&&typeof r.content=="string");if(n!==void 0)try{let r=JSON.parse(n.content).framework;return r==="playwright"||r==="cypress"||r==="webdriverio"?r:void 0}catch{return}}var BK=`kwikqa/${Ji}`;function VK(e){return((t,n)=>{let r=new Headers(n?.headers);return r.set("User-Agent",BK),e(t,{...n,headers:r})})}var Ht=class{constructor(t,n,r=fetch,s,o){this.baseUrl=t;this.token=n;this.ciContext=s;this.fetchImpl=VK(jE(r,o))}baseUrl;token;ciContext;fetchImpl;async#e(t,n,r,s,o){let a=()=>this.fetchImpl(`${this.baseUrl}${n}`,{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},...o===void 0?{}:{"X-KwikQA-Session":o},...this.ciContext===void 0?{}:{[Hd]:this.ciContext}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error"}),d;try{d=await a().catch(c=>{if(t==="GET")return a();throw c})}catch(c){throw new nt(0,"network-error",`Could not reach the KwikQA service at ${this.baseUrl} (${Li(c)}).`)}let l;try{l=await d.json()}catch{l=void 0}if(!d.ok){let c=l?.error;throw new nt(d.status,c?.code??"http-error",c?.message??`The KwikQA service returned HTTP ${d.status}.`,jK(l,d.headers.get("Retry-After")))}return l}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,n){return this.#e("POST","/v1/billing/checkout",{plan:t,...n})}billingPortal(){return this.#e("POST","/v1/billing/portal")}reserveUsage(t,n,r){return this.#e("POST","/v1/usage/reserve",t,n,r)}openSession(t,n="diagnosis"){return this.#e("POST","/v1/usage/session",n==="diagnosis"?{requests:t}:{requests:t,kind:n})}async claimGroups(t,n,r){let s=await this.#e("POST","/v1/ci/groups",{run:t,job:n,groups:r});return new Map((s.groups??[]).flatMap(o=>typeof o.group=="string"&&(o.diagnosedBy==="this-job"||o.diagnosedBy==="another-job")?[[o.group,o.diagnosedBy]]:[]))}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})}reportResults(t){return this.#e("POST","/v1/results",{events:t})}releaseUsage(t,n){return this.#e("POST","/v1/usage/release",{id:t,status:n})}logout(){return this.#e("POST","/v1/auth/logout")}transport(t){let n=o=>{let a=zE(o),d=FK(o)?t.session?.():t.repairSession?.();return{...t.retryTicket===void 0?{}:{"X-KwikQA-Retry-Ticket":t.retryTicket},...d===void 0?{}:{"X-KwikQA-Session":d},...a===void 0?{}:{"X-KwikQA-Framework":a},...this.ciContext===void 0?{}:{[Hd]:this.ciContext}}},r=o=>{let a=o?.kwikqa?.retryTicket;typeof a=="string"&&a!==""&&t.onRetryTicket?.(a)},s=new Mi({apiRoot:`${this.baseUrl}/v1/openrouter`,credentialName:"A KwikQA login (run `npx kwikqa login`)",readApiKey:()=>this.token,fetch:this.fetchImpl,timeoutMs:6e5,extraHeaders:n,onCompletionBody:r});return t.jobs!==!0||this.token===void 0?s:new Rp({baseUrl:this.baseUrl,token:this.token,fetch:this.fetchImpl,preflight:s,headers:n,onCompletionBody:r,...t.onProgress===void 0?{}:{onProgress:t.onProgress},...t.onRestart===void 0?{}:{onRestart:t.onRestart},...t.sleep===void 0?{}:{sleep:t.sleep}})}},xp=class{constructor(t,n,r={}){this.inner=t;this.client=n;this.options=r}inner;client;options;get routing(){return this.inner.routing??"router"}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=zE(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 nt))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 o=await this.inner.complete(t);return o.kind!=="response"&&await this.client.releaseUsage(s.id,o.httpStatus??599).catch(()=>{}),o}};var UK={npm:"npx",pnpm:"pnpm exec",yarn:"yarn",bun:"bunx"},HK={npm:"npm i -D",pnpm:"pnpm add -D",yarn:"yarn add -D",bun:"bun add -d"};function qE(e){let t=(e.npm_config_user_agent??"").split("/")[0];return t==="pnpm"||t==="yarn"||t==="bun"?t:"npm"}function bt(e){return`${UK[qE(e)]} kwikqa`}function Gw(e,t){return`${HK[qE(e)]} ${t}`}var z={ok:0,failed:1,usage:2,account:3};function zd(e){return`Not signed in. Run \`${bt(e.env)} login\` first.`}function Br(e,t){for(let n of t.messages)e.io.error(n);return t.exit}function GE(e){return e==="repair-failed"||e==="validation-unavailable"||e==="operation-failed"?z.failed:z.ok}async function zt(e,t){try{return await t()}catch(n){if(n instanceof nt)return e.io.error(n.message),[401,402,403,409].includes(n.status)?z.account:z.failed;throw n}}function wo(e){return e.sleep??(t=>new Promise(n=>setTimeout(n,t)))}function KE(e,t){let n=(e.env.CI??"").trim().toLowerCase();return t&&e.io.interactive&&(n===""||n==="false"||n==="0")}import{spawn as zK}from"node:child_process";function WE(e,t=process.platform){let n;try{n=new URL(e)}catch{return Promise.resolve(!1)}if(n.protocol!=="https:"&&n.protocol!=="http:")return Promise.resolve(!1);let[r,s]=t==="darwin"?["open",[n.href]]:t==="win32"?["explorer.exe",[n.href]]:["xdg-open",[n.href]];return new Promise(o=>{try{let a=zK(r,s,{stdio:"ignore",detached:!0});a.once("error",()=>o(!1)),a.once("spawn",()=>{a.unref(),o(!0)})}catch{o(!1)}})}import{mkdir as qK,readFile as GK,rm as KK,writeFile as WK}from"node:fs/promises";import{homedir as JE}from"node:os";import{join as qd}from"node:path";function YE(e){return e.KWIKQA_CONFIG_DIR!==void 0&&e.KWIKQA_CONFIG_DIR!==""?e.KWIKQA_CONFIG_DIR:process.platform==="win32"?qd(e.APPDATA??qd(JE(),"AppData","Roaming"),"kwikqa"):qd(e.XDG_CONFIG_HOME??qd(JE(),".config"),"kwikqa")}function Kw(e){return qd(YE(e),"credentials.json")}async function Dn(e){if(e.KWIKQA_TOKEN!==void 0&&e.KWIKQA_TOKEN.trim()!=="")return{token:e.KWIKQA_TOKEN.trim(),login:"(KWIKQA_TOKEN)",apiUrl:""};try{let t=JSON.parse(await GK(Kw(e),"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 XE(e,t){await qK(YE(e),{recursive:!0,mode:448}),await WK(Kw(e),`${JSON.stringify(t)}
|
|
265
|
-
`,{mode:384})}async function QE(e){await KK(Kw(e),{force:!0})}import{createHash as JK}from"node:crypto";var ZE=20,YK=4,XK=/^[a-z][a-z0-9-]{0,59}$/,QK=new Set(Gs);function Ww(e){return["off","0","false","no"].includes((e.KWIKQA_RESULTS??"").trim().toLowerCase())}function Yi(e){return e!==void 0&&XK.test(e)?e:void 0}function Jw(e){if(!(Yi(e.outcome)===void 0||Yi(e.reason)===void 0))return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ZK(e){return JK("sha256").update(`kwikqa-result-run:${e.runId}`).digest("hex").slice(0,32)}function Yw(e){let t=e.diagnosis,n=e.repairProposal?.acceptedHypothesisId,r=t?.hypotheses.find(a=>a.hypothesisId===n)??[...t?.hypotheses??[]].sort((a,d)=>a.rank-d.rank)[0],s=e.clusters?.[0],o=s?.symptomCategory??s?.signals.find(a=>a.kind==="symptom-category")?.value;return{symptom:Yi(o),owner:Yi(r?.probableOwner),cause:r!==void 0&&QK.has(r.causalCategory)?r.causalCategory:void 0,evidence:Yi(r?.evidenceGrade),target:Yi(e.repairProposal?.targets[0]?.class)}}function Xw(e,t){return{run:ZK(e),outcome:e.outcome,reason:e.reasonCode,framework:Yi(e.framework??e.inputs?.framework),ci:Hw(t)}}function e0(e){let t=[...new Set(e??[])].filter(n=>/^[0-9a-f]{64}$/.test(n));return t.length===0?void 0:t.slice(0,YK)}function _p(e,t,n){if(e!==void 0)return Jw({stage:"analysis",...Xw(e,t),...Yw(e),target:void 0,sessions:e0(n),groups:e.clusters?.length??e.symptoms?.clusters,failed:e.failingLogicalTestIds.length,flaky:e.outcomes?.filter(r=>r.status==="flaky").length})}function Vr(e,t,n,r){if(t!==void 0)return Jw({stage:e,...Xw(t,n),...Yw(t),sessions:e==="fix"?e0(r):void 0,attempt:t.repair?.attempt,changedFiles:t.repairProposal?.changedFiles,changedLines:t.repairProposal?.changedLines})}function Qw(e,t,n){return Jw({stage:"pull-request",...Xw(e,n),...Yw(e),outcome:t?"opened":"not-opened",reason:t?"pull-request-opened":"pull-request-not-opened",changedFiles:e.repairProposal?.changedFiles,changedLines:e.repairProposal?.changedLines})}function eW(e,t){return e?.results?.share===!0&&!Ww(t)}async function Gd(e,t,n,r){let s=r.filter(o=>o!==void 0);if(!(s.length===0||!eW(t,n)))for(let o=0;o<s.length;o+=ZE)try{await e.reportResults(s.slice(o,o+ZE))}catch{return}}async function Zw(e,t={browser:!0}){return zt(e,async()=>{let n=new Ht(pr(e.env),void 0,e.fetch),r=await n.startDeviceLogin();if(e.io.print(`Open ${r.verificationUri} and enter the code: ${r.userCode}`),KE(e,t.browser)){let d=r.verificationUriComplete??r.verificationUri;await(e.openBrowser??WE)(d)&&e.io.print("Opened that page in your browser, with the code filled in. Check it matches, then approve it.")}let s=wo(e),o=Math.max(1,r.interval),a=Date.now()+r.expiresIn*1e3;for(;Date.now()<a;){await s(o*1e3);let d=await n.pollDeviceLogin(r.deviceCode);if(d.status==="complete"){await XE(e.env,{token:d.token,login:d.login,apiUrl:n.baseUrl}),e.io.print(`Signed in as ${d.login}.`);let l=await new Ht(n.baseUrl,d.token,e.fetch).status().catch(()=>{}),c=l===void 0?void 0:tb(l,e.env);return c!==void 0&&e.io.print(c),z.ok}if(d.status==="slow_down"&&(o+=5),d.status==="expired"||d.status==="denied")return e.io.error(d.status==="denied"?"Sign-in was denied.":"The code expired."),z.account}return e.io.error("The code expired before sign-in finished."),z.account})}async function eb(e){let t=(e.env.KWIKQA_TOKEN??"").trim()!=="",n=t?void 0:await Dn(e.env);if(n!==void 0)try{await new Ht(pr(e.env,n.apiUrl),n.token,e.fetch).logout()}catch{e.io.error(`Could not reach the KwikQA service to revoke this token; revoke it at ${Ln}account/.`)}return await QE(e.env),e.io.print("Signed out."),t&&e.io.print("KWIKQA_TOKEN is still set in this environment; unset it to stop using it."),z.ok}function t0(e){let t=[...e.interval===void 0?[]:[e.interval==="year"?"billed yearly":"billed monthly"]];return`on the ${e.plan} plan${t.length===0?"":` (${t.join(", ")})`}`}function i0(e){let t=e.organization;return t.kind==="personal"?[`Signed in as ${e.login} ${t0(e)}.`,...t.insights?["Insights: on. Test names and fix outcomes from your runs are shared with your insights."]:[]]:[`${e.login==="CI"?`Signed in with a CI token of ${t.name}`:`Signed in as ${e.login}, ${t.role==="admin"?"an admin":"a member"} of ${t.name},`} ${t0(e)}.`,...t.status==="pending"?[`${t.name} has no plan yet: an admin chooses one at ${Ln}billing/.`]:[],t.team===void 0?`Team: none; usage below is ${t.name}'s shared pool.`:`Team: ${t.team.name}; usage below is ${t.name}'s shared pool, and counts toward ${t.team.name}.`,t.insights?`Insights: on. Test names and fix outcomes from your runs are shared with ${t.name}.`:"Insights: off."]}function tb(e,t){let n=e.results;if(n!==void 0)return n.off==="organization"?`Result counts: off for everyone in ${e.organization.name}, by its admins.`:n.off==="you"?`Result counts: off. Turn them on at ${Ln}account/.`:Ww(t)?"Result counts: off for this run (KWIKQA_RESULTS).":`Result counts: on. Each result is reported as codes and counts, never test names or code. Turn them off at ${Ln}account/, or for a run with KWIKQA_RESULTS=off.`}async function nb(e){return zt(e,async()=>{let t=await Dn(e.env);if(t===void 0)return e.io.print(zd(e)),z.account;let r=await new Ht(pr(e.env,t.apiUrl),t.token,e.fetch).status(),s=(a,d)=>d===void 0?`${a} (unlimited)`:`${a} of ${d}`;for(let a of i0(r))e.io.print(a);e.io.print(`Analyses this period: ${s(r.usage.analyses.used,r.usage.analyses.limit)}`),e.io.print(`Fixes this period: ${s(r.usage.repairs.used,r.usage.repairs.limit)}`),e.io.print(`Period ends: ${r.periodEnd.slice(0,10)}`);let o=tb(r,e.env);return o!==void 0&&e.io.print(o),e.io.print(`Manage your account, team, and tokens: ${Ln}`),z.ok})}async function s0(e){let t=await Dn(e.env);if(t===void 0){e.io.error(zd(e));return}return new Ht(pr(e.env,t.apiUrl),t.token,e.fetch)}var Ip=e=>`$${e.toLocaleString("en-US")}`,n0="sales@kwikqa.com";function r0(e){let t=e.annualMonthlyUsd??e.annualUsd/12,n=`${Ip(e.annualUsd)}/yr (${Ip(t)}/mo)`,r=e.monthlyUsd===0&&e.annualUsd===0?"$0":e.sales===!0?`from ${n}, through KwikQA's sales`:`${Ip(e.monthlyUsd)}/mo, or ${n}`,s=e.audience==="organization"?", shared by the organization":"",o=e.analyses===void 0?"unlimited analyses and fixes":`${e.analyses.toLocaleString("en-US")} analyses and ${(e.repairs??0).toLocaleString("en-US")} fixes a month${s}`;return{price:r,limits:e.hosted?o:`${o} (your own model key)`}}async function rb(e,t,n={annual:!1}){return zt(e,async()=>{let r=await Dn(e.env),s=await new Ht(pr(e.env,r?.apiUrl),void 0,e.fetch).plans(),o=s.paidPlansOpen!==!1,d=s.plans.filter(m=>m.id!=="free").find(m=>m.id===t);if(d===void 0||!o){t!==void 0&&d===void 0&&e.io.error(`Unknown plan: ${t}`);let m=Math.max(0,...s.plans.map(g=>g.annualSavingPercent??0));e.io.print(`Plans, priced per account or organization (monthly, or yearly${m>0?`, which saves up to ${m}%`:""}):`);let h=Math.max(...s.plans.map(g=>g.id.length));for(let g of s.plans){let{price:y,limits:w}=r0(g);e.io.print(` ${g.id.padEnd(h)} ${y}: ${w}`)}if(o)e.io.print(`Run \`${bt(e.env)} upgrade <plan> [--annual]\` to get a checkout link. Enterprise is arranged with KwikQA's sales: ${n0}.`);else{let g=s.plans.find(y=>y.id==="free")?.name??"the free plan";if(e.io.print(`Paid plans are coming soon. Until they open, every account uses ${g}.`),d!==void 0)return z.account}return t===void 0?z.ok:z.usage}if(d.sales===!0)return e.io.print(`${d.name} is arranged with KwikQA's sales, ${r0(d).price.replace(/, through KwikQA's sales$/,"")}: write to ${n0}.`),z.ok;let l=n.annual?"year":"month";if(d.intervals!==void 0&&!d.intervals.includes(l))return e.io.error(`${d.name} is billed ${d.intervals.join(" or ")}ly.`),z.usage;let c=await s0(e);if(c===void 0)return z.account;let u=await c.status();if(u.organization.kind==="company"&&u.organization.role!=="admin")return e.io.print(`${u.organization.name}'s admins manage its plan and billing.`),z.ok;if(u.plan!=="free")return e.io.print(`You're on the ${u.plan} plan. Change plans or billing period in Billing, where you see the charge before you confirm:`),e.io.print(`${Ln}billing/`),z.ok;let p=await c.checkout(d.id,{interval:l}),f=n.annual?d.annualUsd:d.monthlyUsd;return e.io.print(`Open this link to subscribe to ${d.name} for ${Ip(f)} a ${n.annual?"year":"month"}:`),e.io.print(p.url),z.ok})}async function ib(e){return zt(e,async()=>{let t=await s0(e);if(t===void 0)return z.account;try{let{url:n}=await t.billingPortal();return e.io.print("Open this link to update your payment method or download invoices:"),e.io.print(n),e.io.print(`To change or cancel your plan: ${Ln}billing/`),z.ok}catch(n){if(n instanceof nt&&n.code==="no-billing-account")return e.io.print("You don't have a paid subscription yet."),e.io.print(`Run \`${bt(e.env)} upgrade <plan>\` to choose one.`),z.ok;if(n instanceof nt&&n.code==="team-member")return e.io.print(n.message),z.ok;throw n}})}import{appendFile as WW,readFile as JW,realpath as YW,writeFile as XW}from"node:fs/promises";import{join as nC}from"node:path";import{createHash as gb}from"node:crypto";import{access as FW,mkdir as jW,readdir as BW,readFile as yb,stat as q0,writeFile as VW}from"node:fs/promises";import{isAbsolute as G0,join as Fn,relative as K0,resolve as W0}from"node:path";import{mkdir as RW,writeFile as xW}from"node:fs/promises";import{join as T0}from"node:path";import{readFile as rW,realpath as iW}from"node:fs/promises";import{createRequire as sW}from"node:module";import{delimiter as oW,dirname as u0,isAbsolute as aW,join as Xi}from"node:path";import{spawn as l0}from"node:child_process";var o0=256*1024,tW=8e3;function Sp(e,t={}){let n={...e,...t};for(let r of df(e))delete n[r];return n}function a0(e){return e.pid===void 0||e.exitCode!==null||e.signalCode!==null}function d0(e,t){if(e.pid!==void 0)try{process.kill(-e.pid,t)}catch{e.kill(t)}}async function nW(e,t){if(!a0(e)){if(process.platform==="win32"){await new Promise(n=>{let r=l0("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});r.on("exit",()=>n()),r.on("error",()=>n())});return}d0(e,"SIGINT"),await Promise.race([t,new Promise(n=>setTimeout(n,tW))]),a0(e)||d0(e,"SIGKILL")}}function sb(e,t,n){let r=l0(e,[...t],{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),s="",o=d=>{s+=d.toString("utf8"),s.length>o0&&(s=s.slice(-o0))};r.stdout?.on("data",o),r.stderr?.on("data",o);let a=new Promise(d=>{r.on("exit",l=>d(l??void 0)),r.on("error",()=>d(void 0))});return{child:r,output:()=>s,exited:a,stop:async()=>{await nW(r,a),await Promise.race([a,new Promise(d=>setTimeout(d,2e3))])}}}async function Tp(e,t,n){let r=sb(e,t,n),s=!1,o=setTimeout(()=>{s=!0,r.stop()},n.timeoutMs),a=await r.exited;return clearTimeout(o),{...a===void 0?{}:{exitCode:a},timedOut:s,output:r.output()}}async function c0(e,t,n){let r=Date.now()+n,s=!1;for(e.exited.then(()=>{s=!0});Date.now()<r;){let o=t.exec(e.output());if(o!==null)return o;if(s)return t.exec(e.output())??void 0;await new Promise(a=>setTimeout(a,100))}}var f0="1.0",ob=[1,59],dW=5,lW=6e4,cW=3e4,uW=12e4,pW=new Set(["generic","text","list","group","none","presentation"]),fW=new Set(["banner","navigation","main","contentinfo","complementary","region","form","search"]);function ab(e){let[t=0,n=0]=e.split(".").map(r=>Number.parseInt(r,10));return t>ob[0]||t===ob[0]&&n>=ob[1]}async function p0(e){try{let t=JSON.parse(await rW(Xi(e,"package.json"),"utf8"));return t.name==="@playwright/cli"&&typeof t.version=="string"?t.version:void 0}catch{return}}async function m0(e,t){try{let r=sW(Xi(e,"package.json")).resolve("@playwright/cli/package.json"),s=u0(r),o=await p0(s);if(o!==void 0)return{entryPath:Xi(s,"playwright-cli.js"),version:o,source:"project"}}catch{}let n=process.platform==="win32"?["playwright-cli.cmd"]:["playwright-cli"];for(let r of(t.PATH??"").split(oW).filter(Boolean))for(let s of n){let o=Xi(r,s);try{let a=process.platform==="win32"?Xi(r,"node_modules","@playwright","cli"):u0(await iW(o)),d=await p0(a);if(d!==void 0)return{entryPath:Xi(a,"playwright-cli.js"),version:d,source:"path"}}catch{}}}function db(e){return e.split(/\r?\n/).filter(t=>!/[║╔╚═]/.test(t)).join(`
|
|
266
|
-
`)}function h0(e){return/```yaml\r?\n([\s\S]*?)\r?\n```/.exec(db(e))?.[1]?.split(/\r?\n/)}function g0(e){let t=db(e).split(/\r?\n/),n=t.findIndex(r=>r.trim()==="### Result");if(!(n<0))return t.slice(n+1).map(r=>r.trim()).find(r=>r!==""&&!r.startsWith("###"))}function
|
|
264
|
+
`)[0]?.trim().slice(0,200)??"";return`${v}${R===""?"":`: ${R}`}`},m=[...o.map(h=>`the repaired test ${p(h)} still failed${f(h)}`),...a.length===0?[]:[`${a.length===1?"a test that passed before now fails":`${a.length} tests that passed before now fail`}: ${a.map(p).join(", ")}`],...d.length===0?[]:[`${d.length===1?"a test":`${d.length} tests`} the change touches failed before it and still ${d.length===1?"fails":"fail"}`],...l.map(h=>`the ${h} failed`)];return m.length===0?void 0:m.join("; ")}async function hK(e,t,n){let r=t.group;if(r===void 0||r.logicalTestIds.length===0||e.checkGroup===void 0)return;let{logicalTestIds:s}=r,o=`${s.length} other test${s.length===1?"":"s"}`,a=await ht(NE(n,r.reportPath),{workspaceRoot:n,gitRoot:t.workspace.gitRoot,...r.framework===void 0?{}:{framework:r.framework}}),d=a.kind==="parsed"?new Set(a.run.logicalTests.map(p=>p.logicalTestId)):void 0;if(a.kind!=="parsed"||!s.every(p=>d?.has(p)))return{status:"unavailable",logicalTestIds:s,message:`The report fix read has changed, so the group's ${o} were not re-run.`};let l=await e.checkGroup(a.run,s);if(l.kind==="declined")return{status:"declined",logicalTestIds:s,message:`The group's ${o} were not re-run.`};if(l.kind==="unavailable")return{status:"unavailable",logicalTestIds:s,message:l.message};let c=s.filter(p=>l.failedAgain.includes(p)),u=c.map(p=>a.run.logicalTests.find(f=>f.logicalTestId===p)?.title??p).map(p=>`"${p}"`).join(", ");return{status:"rerun",logicalTestIds:s,stillFailing:c,message:c.length===0?`The group's ${o} pass now as well.`:`${c.length} of the group's ${o} still fail${c.length===1?"s":""}: ${u}. The patch stays; run \`kwikqa fix\` again for them.`}}async function Ud(e){let t=e.now??(()=>new Date().toISOString()),n=()=>new Date().toISOString(),r=await oK(e.workspaceRoot),s=await Vh(r);if(s.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-recovery-required",message:s.reasons.map(C=>C.message).join(" ")};let o=s.transactions.filter(C=>cK.has(C.phase));if(o.length!==1||o[0]===void 0)return{outcome:"operation-failed",reasonCode:"no-pending-repair",message:o.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 Ne(r,o[0].transactionId),d=a.manifest.preview.authoritativeValidation,l=await iE(r,d.repairSessionId,d.attemptOrdinal);if(l.transactionId!==a.manifest.transactionId)throw new Error("Repair attempt state does not belong to the pending transaction.");if(l.plan.planHash!==d.planHash)throw new Error("Saved validation plan does not match the approved plan.");let c=pK(l),u=l.transactionId,p=l.plan,f=[],m;if(a.state.phase==="validating"){let C=a.state.history.findLast(A=>A.type==="validation-started");if(C?.validationRunId===void 0)throw new Error("Validating transaction has no started validation run.");m=C.validationRunId}else{m=uK();let C=await pw({context:c,transactionId:u,planHash:p.planHash,validationRunId:m,now:n()});if(C.kind==="rejected"||C.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-rejected",message:C.reasons.map(A=>A.message).join(" ")};for(let A of p.commands)if(!(!A.required||A.timing!=="post-patch")){if(e.signal?.aborted===!0)break;await Jr({workspaceRoot:r,repositoryRoot:l.workspace.gitRoot,transactionId:u,validationRunId:m,plan:p,commandId:A.commandId,limits:dK,...e.signal===void 0?{}:{signal:e.signal}}).catch(M=>{Wr(A.kind)&&f.push(Uo(M))})}}let h=await zm({workspaceRoot:r,gitRoot:l.workspace.gitRoot,transactionId:u,validationRunId:m,plan:p,...l.baseline===void 0?{}:{baseline:l.baseline},reportMaxBytes:lK,completedAt:n()}),g=h.manifest,y={repairSessionId:l.repairSessionId,attempt:l.attempt,transactionId:u,planHash:p.planHash,validationRunId:m,validationManifestHash:g.manifestHash},w;if(g.status==="passed"){let C=await fw({context:c,transactionId:u,planHash:p.planHash,validationRunId:m,validationManifestHash:g.manifestHash,now:n(),approvedCommands:p.commands.map(A=>({commandId:A.commandId,executable:A.executable}))});if(C.kind==="completed"){await Va({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,validationRunId:m,now:t()});let A=await hK(e,l,r);return Vw(e,l,t,{outcome:"repaired",reasonCode:"validation-passed",message:`Every required validation check passed; the repair is complete.${A?.message===void 0?"":` ${A.message}`}`,application:"applied",validation:"passed",repair:y,...A===void 0?{}:{groupCheck:A}})}w="reasons"in C?C.reasons.map(A=>A.message).join(" "):"KwikQA couldn't complete the validation."}w===void 0&&await Va({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,validationRunId:m,now:t()});let b=await Uh(c,u,n());w!==void 0&&await Va({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,validationRunId:m,now:t()});let v=w!==void 0?"unavailable":g.status==="passed"?"incomplete":g.status,R=v==="failed"?"validation-failed":v==="unavailable"?"validation-unavailable":"validation-incomplete";if(b.kind!=="rolled-back")return Vw(e,l,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:v==="blocked"?"incomplete":v,repair:y});let T=(await Jh({workspaceRoot:r,repairSessionId:l.repairSessionId,ordinal:l.attempt,proof:{transactionId:u,phase:"rolled-back",transactionRevision:b.transaction.revision},now:t()})).retry!==void 0,N=fK(r,h.directory,g),U=T?N:void 0,F=v==="failed"?await mK(g,N,l,r).catch(()=>{}):void 0,I=F===void 0?"Validation did not pass, so the patch was rolled back.":`Validation did not pass: ${F}. The patch was rolled back.`;return Vw(e,l,t,{outcome:"repair-failed",reasonCode:R,message:`${f.length===0?"":`KwikQA couldn't complete a command: ${f.join(" ")} `}${w===void 0?"":`${w} `}${I} ${T?"One retry is available.":"No retry remains."}`,application:"rolled-back",validation:v==="blocked"?"incomplete":v,repair:{...y,retryAvailable:T,...U===void 0?{}:{retryReportPath:U}}})}async function Vw(e,t,n,r){let s={schemaVersion:"1.5",recordId:Ju(),command:"validate",...t.record,recordedAt:n(),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(e.persist===!1)return{outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s};try{let o=await Cd(t.workspace.workspaceRoot,s);return{outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s,recordPath:o}}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}}}import{readFile as gK}from"node:fs/promises";var Hd="X-KwikQA-CI";function OE(e){let t=e?.trim().replace(/[^A-Za-z0-9._-]/g,"-").replace(/^[^A-Za-z0-9]+/,"");return t===void 0||t===""?void 0:t.slice(0,100)}function yK(e){let t=(e??"").split("/").map(n=>OE(n)).filter(n=>n!==void 0);return t.length===0?void 0:t.join("/").slice(0,200)}function Uw(e){try{return e===void 0||e===""?void 0:new URL(e).host.toLowerCase()}catch{return}}function $E(e){return e==="public"||e==="internal"||e==="private"?e:void 0}function kp(e,t){let n=yK(t.owner),r=OE(t.name);if(!(t.host===void 0||n===void 0||r===void 0))return{system:e,host:t.host,owner:n,name:r,...t.visibility===void 0?{}:{visibility:t.visibility}}}async function wK(e){let[t,n]=(e.GITHUB_REPOSITORY??"").split("/"),r={};try{e.GITHUB_EVENT_PATH!==void 0&&e.GITHUB_EVENT_PATH!==""&&(r=JSON.parse(await gK(e.GITHUB_EVENT_PATH,"utf8")))}catch{r={}}let s=r.repository,o=$E(s?.visibility)??(s?.private===!0?"private":s?.private===!1?"public":void 0);return kp("github",{host:Uw(e.GITHUB_SERVER_URL)??"github.com",owner:t,name:n,...o===void 0?{}:{visibility:o}})}function bK(e){let t=e.CI_PROJECT_PATH??"",n=t.lastIndexOf("/"),r=$E(e.CI_PROJECT_VISIBILITY);return kp("gitlab",{host:e.CI_SERVER_HOST?.toLowerCase()??Uw(e.CI_SERVER_URL),owner:n>0?t.slice(0,n):e.CI_PROJECT_NAMESPACE,name:n>0?t.slice(n+1):e.CI_PROJECT_NAME,...r===void 0?{}:{visibility:r}})}function vK(e){let t=e.SYSTEM_COLLECTIONURI??"",n;try{n=new URL(t).pathname.split("/").filter(Boolean)[0]}catch{n=void 0}return kp("azure",{host:Uw(t),owner:[n,e.SYSTEM_TEAMPROJECT].filter(Boolean).join("/"),name:e.BUILD_REPOSITORY_NAME})}function kK(e){let t=e.GIT_URL??e.CHANGE_URL??"",n=/^(?:https?:\/\/([^/]+)\/|git@([^:]+):)(.+?)\/([^/]+?)(?:\.git)?(?:\/(?:pull|-\/merge_requests)\/\d+)?\/?$/.exec(t),r=(n?.[1]??n?.[2])?.toLowerCase();return kp("jenkins",{host:r,owner:n?.[3],name:n?.[4]})}function Hw(e){if(e.GITHUB_ACTIONS==="true")return"github";if(e.TF_BUILD==="True")return"azure";if(e.GITLAB_CI==="true")return"gitlab";if(e.JENKINS_URL!==void 0||e.JENKINS_HOME!==void 0)return"jenkins"}async function ME(e){switch(Hw(e)){case"github":return wK(e);case"azure":return vK(e);case"gitlab":return bK(e);case"jenkins":return kK(e);default:return}}function LE(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function DE(e){let t=l=>{let c=e[l]?.trim();return c===void 0||c===""?void 0:c},n=t("KWIKQA_SHARD"),r,s;if(e.GITHUB_ACTIONS==="true"){let l=t("GITHUB_RUN_ID");r=l===void 0?void 0:`${l}-${t("GITHUB_RUN_ATTEMPT")??"1"}`,s=[t("GITHUB_JOB"),t("RUNNER_NAME")].filter(Boolean).join(":")||void 0}else if(e.TF_BUILD==="True"){let l=t("BUILD_BUILDID");r=l===void 0?void 0:`${l}-${t("SYSTEM_JOBATTEMPT")??"1"}`,s=t("SYSTEM_JOBID")}else e.GITLAB_CI==="true"?(r=t("CI_PIPELINE_ID"),s=t("CI_JOB_ID")):(e.JENKINS_URL!==void 0||e.JENKINS_HOME!==void 0)&&(r=t("BUILD_TAG"),s=[t("STAGE_NAME"),t("NODE_NAME"),t("EXECUTOR_NUMBER")].filter(Boolean).join(":")||void 0);s=n??s;let o=l=>l===void 0?void 0:l.replace(/[^A-Za-z0-9._:/-]/g,"-").slice(0,200),a=o(r),d=o(s);return a===void 0||d===void 0?void 0:{run:a,job:d}}var RK="X-KwikQA-CI-Identity",xK="https://kwikqa.com",_K=6e4,IK=6e4,SK=1e4;function TK(e){try{let t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));return typeof t.exp=="number"?t.exp*1e3:void 0}catch{return}}function AK(e,t,n,r){let s,o=0;return{token:async()=>{if(s!==void 0&&s.until>r())return s.value;if(!(o>r()))try{let a=new URL(e);if(a.protocol!=="https:")return;a.searchParams.set("audience",xK);let d=await n(a,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(SK)}),l=await d.json();if(!d.ok||typeof l.value!="string"||l.value==="")throw new Error("no token");let c=TK(l.value)??r()+5*6e4;return s={value:l.value,until:c-_K},l.value}catch{s=void 0,o=r()+IK;return}}}}function FE(e,t,n=Date.now){let r=e.KWIKQA_ID_TOKEN?.trim();if(r!==void 0&&r!=="")return{token:async()=>r};let s=e.ACTIONS_ID_TOKEN_REQUEST_URL,o=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(e.GITHUB_ACTIONS==="true"&&s&&o)return AK(s,o,t,n)}function jE(e,t){return t===void 0?e:(async(n,r)=>{let s=new Headers(r?.headers);if(!s.has(Hd))return e(n,r);let o=await t.token();return o!==void 0&&s.set(RK,o),e(n,{...r,headers:s})})}var PK=1200*1e3,EK=10,CK=1e3,NK=15e3,OK=3e3,$K=6e4,BE=3e4,MK=2;function qw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function UE(e){try{let t=await e.json();return qw(t)?t:void 0}catch{return}}async function LK(e){return await UE(e)??{}}function VE(e){return typeof e=="number"&&Number.isFinite(e)?Math.min(NK,Math.max(CK,e)):OK}function zw(e){let t=qw(e.error)?e.error:void 0;return typeof t?.message=="string"?t.message:void 0}var Rp=class{constructor(t){this.options=t}options;preflight(t){return this.options.preflight.preflight(t)}async complete(t){let n=performance.now(),r=()=>performance.now()-n;for(let s=0;;s+=1){let o=await this.#e(t,r);if(o!=="interrupted")return o;if(s===MK)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,n){let r=(p,f)=>({kind:"failed",code:p,message:f,elapsedMs:n()}),s=Tt(t);if(s!==void 0)return{kind:"failed",code:"invalid-request",message:s,elapsedMs:0};let o;try{o=await this.#n("POST","/v1/jobs",$K,{headers:{...this.options.headers(t.body),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(t.body)})}catch(p){return r("network-error",`The model request could not reach the KwikQA service (${Li(p)}).`)}let a=await LK(o);if(o.status!==202){let p=mu(a);return{kind:"failed",code:"http-error",message:zw(a)??"The KwikQA service refused the model request.",httpStatus:o.status,...p===void 0?{}:{providerCode:p},elapsedMs:n()}}let d=a.jobId;if(typeof d!="string"||d==="")return r("invalid-json","The KwikQA service did not name the job it started.");let l=this.options.sleep??(p=>new Promise(f=>setTimeout(f,p))),c=VE(a.pollAfterMs),u=0;for(;;){if(n()>(this.options.maxWaitMs??PK))return await this.#t(d),r("timeout","The model did not answer in time; nothing was charged.");await l(c);let p;try{p=await this.#n("GET",`/v1/jobs/${d}`,BE)}catch{p=new Response(null,{status:599})}let f=p.status>=500?void 0:await UE(p);if(p.status===404)return"interrupted";if(p.status<500&&!p.ok)return{kind:"failed",code:"http-error",message:zw(f??{})??"The KwikQA service refused to report the job.",httpStatus:p.status,elapsedMs:n()};if(f===void 0){if(u+=1,u>EK)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(u=0,f.status==="running"){this.options.onProgress?.(n()),c=VE(f.pollAfterMs);continue}if(f.status==="failed")return qw(f.error)&&f.error.code==="job-interrupted"?"interrupted":{kind:"failed",code:"http-error",message:zw(f)??"The model request was interrupted; nothing was charged.",httpStatus:503,elapsedMs:n()};if(f.status!=="answered")return r("invalid-json","The KwikQA service reported a job state the CLI does not know.");await this.#t(d);let m=typeof f.httpStatus=="number"?f.httpStatus:502,h=f.result,g=m>=200&&m<300;if(!g||xd(h)){let y=mu(h),w=g?y??502:m;return{kind:"failed",code:"http-error",message:vy(w,h),httpStatus:w,...y===void 0?{}:{providerCode:y},elapsedMs:n()}}return this.options.onCompletionBody?.(h),{kind:"response",httpStatus:m,body:h,elapsedMs:n()}}}async#t(t){try{await this.#n("DELETE",`/v1/jobs/${t}`,BE)}catch{}}#n(t,n,r,s={}){return this.options.fetch(`${this.options.baseUrl}${n}`,{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 Ji="0.10.1";var DK="https://api.kwikqa.com",Ln="https://kwikqa.com/dashboard/";function HE(e){return e.hosted??!(e.plan==="byo"||e.plan==="byo-team"||e.plan==="byo-enterprise")}function FK(e){return e?.response_format?.json_schema?.name==="kwikqa_diagnosis"}var nt=class extends Error{constructor(n,r,s,o){super(s);this.status=n;this.code=r;this.retryAfterSeconds=o}status;code;retryAfterSeconds};function jK(e,t){let n=e?.error?.retryAfter,r=typeof n=="number"?n:Number(t??Number.NaN);return Number.isFinite(r)&&r>0&&r<=3600?r:void 0}function pr(e,t){return(e.KWIKQA_API_URL??(t===void 0||t===""?DK:t)).replace(/\/+$/,"")}function zE(e){let t=e?.messages;if(!Array.isArray(t))return;let n=t.find(r=>typeof r=="object"&&r!==null&&r.role==="user"&&typeof r.content=="string");if(n!==void 0)try{let r=JSON.parse(n.content).framework;return r==="playwright"||r==="cypress"||r==="webdriverio"?r:void 0}catch{return}}var BK=`kwikqa/${Ji}`;function VK(e){return((t,n)=>{let r=new Headers(n?.headers);return r.set("User-Agent",BK),e(t,{...n,headers:r})})}var Ht=class{constructor(t,n,r=fetch,s,o){this.baseUrl=t;this.token=n;this.ciContext=s;this.fetchImpl=VK(jE(r,o))}baseUrl;token;ciContext;fetchImpl;async#e(t,n,r,s,o){let a=()=>this.fetchImpl(`${this.baseUrl}${n}`,{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},...o===void 0?{}:{"X-KwikQA-Session":o},...this.ciContext===void 0?{}:{[Hd]:this.ciContext}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error"}),d;try{d=await a().catch(c=>{if(t==="GET")return a();throw c})}catch(c){throw new nt(0,"network-error",`Could not reach the KwikQA service at ${this.baseUrl} (${Li(c)}).`)}let l;try{l=await d.json()}catch{l=void 0}if(!d.ok){let c=l?.error;throw new nt(d.status,c?.code??"http-error",c?.message??`The KwikQA service returned HTTP ${d.status}.`,jK(l,d.headers.get("Retry-After")))}return l}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,n){return this.#e("POST","/v1/billing/checkout",{plan:t,...n})}billingPortal(){return this.#e("POST","/v1/billing/portal")}reserveUsage(t,n,r){return this.#e("POST","/v1/usage/reserve",t,n,r)}openSession(t,n="diagnosis"){return this.#e("POST","/v1/usage/session",n==="diagnosis"?{requests:t}:{requests:t,kind:n})}async claimGroups(t,n,r){let s=await this.#e("POST","/v1/ci/groups",{run:t,job:n,groups:r});return new Map((s.groups??[]).flatMap(o=>typeof o.group=="string"&&(o.diagnosedBy==="this-job"||o.diagnosedBy==="another-job")?[[o.group,o.diagnosedBy]]:[]))}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})}reportResults(t){return this.#e("POST","/v1/results",{events:t})}releaseUsage(t,n){return this.#e("POST","/v1/usage/release",{id:t,status:n})}logout(){return this.#e("POST","/v1/auth/logout")}transport(t){let n=o=>{let a=zE(o),d=FK(o)?t.session?.():t.repairSession?.();return{...t.retryTicket===void 0?{}:{"X-KwikQA-Retry-Ticket":t.retryTicket},...d===void 0?{}:{"X-KwikQA-Session":d},...a===void 0?{}:{"X-KwikQA-Framework":a},...this.ciContext===void 0?{}:{[Hd]:this.ciContext}}},r=o=>{let a=o?.kwikqa?.retryTicket;typeof a=="string"&&a!==""&&t.onRetryTicket?.(a)},s=new Mi({apiRoot:`${this.baseUrl}/v1/openrouter`,credentialName:"A KwikQA login (run `npx kwikqa login`)",readApiKey:()=>this.token,fetch:this.fetchImpl,timeoutMs:6e5,extraHeaders:n,onCompletionBody:r});return t.jobs!==!0||this.token===void 0?s:new Rp({baseUrl:this.baseUrl,token:this.token,fetch:this.fetchImpl,preflight:s,headers:n,onCompletionBody:r,...t.onProgress===void 0?{}:{onProgress:t.onProgress},...t.onRestart===void 0?{}:{onRestart:t.onRestart},...t.sleep===void 0?{}:{sleep:t.sleep}})}},xp=class{constructor(t,n,r={}){this.inner=t;this.client=n;this.options=r}inner;client;options;get routing(){return this.inner.routing??"router"}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=zE(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 nt))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 o=await this.inner.complete(t);return o.kind!=="response"&&await this.client.releaseUsage(s.id,o.httpStatus??599).catch(()=>{}),o}};var UK={npm:"npx",pnpm:"pnpm exec",yarn:"yarn",bun:"bunx"},HK={npm:"npm i -D",pnpm:"pnpm add -D",yarn:"yarn add -D",bun:"bun add -d"};function qE(e){let t=(e.npm_config_user_agent??"").split("/")[0];return t==="pnpm"||t==="yarn"||t==="bun"?t:"npm"}function bt(e){return`${UK[qE(e)]} kwikqa`}function Gw(e,t){return`${HK[qE(e)]} ${t}`}var z={ok:0,failed:1,usage:2,account:3};function zd(e){return`Not signed in. Run \`${bt(e.env)} login\` first.`}function Br(e,t){for(let n of t.messages)e.io.error(n);return t.exit}function GE(e){return e==="repair-failed"||e==="validation-unavailable"||e==="operation-failed"?z.failed:z.ok}async function zt(e,t){try{return await t()}catch(n){if(n instanceof nt)return e.io.error(n.message),[401,402,403,409].includes(n.status)?z.account:z.failed;throw n}}function wo(e){return e.sleep??(t=>new Promise(n=>setTimeout(n,t)))}function KE(e,t){let n=(e.env.CI??"").trim().toLowerCase();return t&&e.io.interactive&&(n===""||n==="false"||n==="0")}import{spawn as zK}from"node:child_process";function WE(e,t=process.platform){let n;try{n=new URL(e)}catch{return Promise.resolve(!1)}if(n.protocol!=="https:"&&n.protocol!=="http:")return Promise.resolve(!1);let[r,s]=t==="darwin"?["open",[n.href]]:t==="win32"?["explorer.exe",[n.href]]:["xdg-open",[n.href]];return new Promise(o=>{try{let a=zK(r,s,{stdio:"ignore",detached:!0});a.once("error",()=>o(!1)),a.once("spawn",()=>{a.unref(),o(!0)})}catch{o(!1)}})}import{mkdir as qK,readFile as GK,rm as KK,writeFile as WK}from"node:fs/promises";import{homedir as JE}from"node:os";import{join as qd}from"node:path";function YE(e){return e.KWIKQA_CONFIG_DIR!==void 0&&e.KWIKQA_CONFIG_DIR!==""?e.KWIKQA_CONFIG_DIR:process.platform==="win32"?qd(e.APPDATA??qd(JE(),"AppData","Roaming"),"kwikqa"):qd(e.XDG_CONFIG_HOME??qd(JE(),".config"),"kwikqa")}function Kw(e){return qd(YE(e),"credentials.json")}async function Dn(e){if(e.KWIKQA_TOKEN!==void 0&&e.KWIKQA_TOKEN.trim()!=="")return{token:e.KWIKQA_TOKEN.trim(),login:"(KWIKQA_TOKEN)",apiUrl:""};try{let t=JSON.parse(await GK(Kw(e),"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 XE(e,t){await qK(YE(e),{recursive:!0,mode:448}),await WK(Kw(e),`${JSON.stringify(t)}
|
|
265
|
+
`,{mode:384})}async function QE(e){await KK(Kw(e),{force:!0})}import{createHash as JK}from"node:crypto";var ZE=20,YK=4,XK=/^[a-z][a-z0-9-]{0,59}$/,QK=new Set(Gs);function Ww(e){return["off","0","false","no"].includes((e.KWIKQA_RESULTS??"").trim().toLowerCase())}function Yi(e){return e!==void 0&&XK.test(e)?e:void 0}function Jw(e){if(!(Yi(e.outcome)===void 0||Yi(e.reason)===void 0))return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ZK(e){return JK("sha256").update(`kwikqa-result-run:${e.runId}`).digest("hex").slice(0,32)}function Yw(e){let t=e.diagnosis,n=e.repairProposal?.acceptedHypothesisId,r=t?.hypotheses.find(a=>a.hypothesisId===n)??[...t?.hypotheses??[]].sort((a,d)=>a.rank-d.rank)[0],s=e.clusters?.[0],o=s?.symptomCategory??s?.signals.find(a=>a.kind==="symptom-category")?.value;return{symptom:Yi(o),owner:Yi(r?.probableOwner),cause:r!==void 0&&QK.has(r.causalCategory)?r.causalCategory:void 0,evidence:Yi(r?.evidenceGrade),target:Yi(e.repairProposal?.targets[0]?.class)}}function Xw(e,t){return{run:ZK(e),outcome:e.outcome,reason:e.reasonCode,framework:Yi(e.framework??e.inputs?.framework),ci:Hw(t)}}function e0(e){let t=[...new Set(e??[])].filter(n=>/^[0-9a-f]{64}$/.test(n));return t.length===0?void 0:t.slice(0,YK)}function _p(e,t,n){if(e!==void 0)return Jw({stage:"analysis",...Xw(e,t),...Yw(e),target:void 0,sessions:e0(n),groups:e.clusters?.length??e.symptoms?.clusters,failed:e.failingLogicalTestIds.length,flaky:e.outcomes?.filter(r=>r.status==="flaky").length})}function Vr(e,t,n,r){if(t!==void 0)return Jw({stage:e,...Xw(t,n),...Yw(t),sessions:e==="fix"?e0(r):void 0,attempt:t.repair?.attempt,changedFiles:t.repairProposal?.changedFiles,changedLines:t.repairProposal?.changedLines})}function Qw(e,t,n){return Jw({stage:"pull-request",...Xw(e,n),...Yw(e),outcome:t?"opened":"not-opened",reason:t?"pull-request-opened":"pull-request-not-opened",changedFiles:e.repairProposal?.changedFiles,changedLines:e.repairProposal?.changedLines})}function eW(e,t){return e?.results?.share===!0&&!Ww(t)}async function Gd(e,t,n,r){let s=r.filter(o=>o!==void 0);if(!(s.length===0||!eW(t,n)))for(let o=0;o<s.length;o+=ZE)try{await e.reportResults(s.slice(o,o+ZE))}catch{return}}async function Zw(e,t={browser:!0}){return zt(e,async()=>{let n=new Ht(pr(e.env),void 0,e.fetch),r=await n.startDeviceLogin();if(e.io.print(`Open ${r.verificationUri} and enter the code: ${r.userCode}`),KE(e,t.browser)){let d=r.verificationUriComplete??r.verificationUri;await(e.openBrowser??WE)(d)&&e.io.print("Opened that page in your browser, with the code filled in. Check it matches, then approve it.")}let s=wo(e),o=Math.max(1,r.interval),a=Date.now()+r.expiresIn*1e3;for(;Date.now()<a;){await s(o*1e3);let d=await n.pollDeviceLogin(r.deviceCode);if(d.status==="complete"){await XE(e.env,{token:d.token,login:d.login,apiUrl:n.baseUrl}),e.io.print(`Signed in as ${d.login}.`);let l=await new Ht(n.baseUrl,d.token,e.fetch).status().catch(()=>{}),c=l===void 0?void 0:tb(l,e.env);return c!==void 0&&e.io.print(c),z.ok}if(d.status==="slow_down"&&(o+=5),d.status==="expired"||d.status==="denied")return e.io.error(d.status==="denied"?"Sign-in was denied.":"The code expired."),z.account}return e.io.error("The code expired before sign-in finished."),z.account})}async function eb(e){let t=(e.env.KWIKQA_TOKEN??"").trim()!=="",n=t?void 0:await Dn(e.env);if(n!==void 0)try{await new Ht(pr(e.env,n.apiUrl),n.token,e.fetch).logout()}catch{e.io.error(`Could not reach the KwikQA service to revoke this token; revoke it at ${Ln}account/.`)}return await QE(e.env),e.io.print("Signed out."),t&&e.io.print("KWIKQA_TOKEN is still set in this environment; unset it to stop using it."),z.ok}function t0(e){let t=[...e.interval===void 0?[]:[e.interval==="year"?"billed yearly":"billed monthly"]];return`on the ${e.plan} plan${t.length===0?"":` (${t.join(", ")})`}`}function i0(e){let t=e.organization;return t.kind==="personal"?[`Signed in as ${e.login} ${t0(e)}.`,...t.insights?["Insights: on. Test names and fix outcomes from your runs are shared with your insights."]:[]]:[`${e.login==="CI"?`Signed in with a CI token of ${t.name}`:`Signed in as ${e.login}, ${t.role==="admin"?"an admin":"a member"} of ${t.name},`} ${t0(e)}.`,...t.status==="pending"?[`${t.name} has no plan yet: an admin chooses one at ${Ln}billing/.`]:[],t.team===void 0?`Team: none; usage below is ${t.name}'s shared pool.`:`Team: ${t.team.name}; usage below is ${t.name}'s shared pool, and counts toward ${t.team.name}.`,t.insights?`Insights: on. Test names and fix outcomes from your runs are shared with ${t.name}.`:"Insights: off."]}function tb(e,t){let n=e.results;if(n!==void 0)return n.off==="organization"?`Result counts: off for everyone in ${e.organization.name}, by its admins.`:n.off==="you"?`Result counts: off. Turn them on at ${Ln}account/.`:Ww(t)?"Result counts: off for this run (KWIKQA_RESULTS).":`Result counts: on. Each result is reported as codes and counts, never test names or code. Turn them off at ${Ln}account/, or for a run with KWIKQA_RESULTS=off.`}async function nb(e){return zt(e,async()=>{let t=await Dn(e.env);if(t===void 0)return e.io.print(zd(e)),z.account;let r=await new Ht(pr(e.env,t.apiUrl),t.token,e.fetch).status(),s=(c,u)=>u===void 0?`${c} (unlimited)`:`${c} of ${u}`;for(let c of i0(r))e.io.print(c);let o=r.contract===void 0?"this period":"this contract year",a=`Analyses ${o}:`,d=`Fixes ${o}:`.padEnd(a.length);e.io.print(`${a} ${s(r.usage.analyses.used,r.usage.analyses.limit)}`),e.io.print(`${d} ${s(r.usage.repairs.used,r.usage.repairs.limit)}`);for(let c of tW(r))e.io.print(c);r.contract===void 0?e.io.print(`Period ends: ${r.periodEnd.slice(0,10)}`):(e.io.print(`Contract year ends: ${r.contract.yearEndsAt.slice(0,10)}`),r.contract.endsAt!==r.contract.yearEndsAt&&e.io.print(`Contract ends: ${r.contract.endsAt.slice(0,10)}`));let l=tb(r,e.env);return l!==void 0&&e.io.print(l),e.io.print(`Manage your account, team, and tokens: ${Ln}`),z.ok})}function tW(e){let t=e.credits;if(t===void 0||t.analysesLeft+t.repairsLeft===0)return[];let n=t.items.map(r=>r.expiresAt).filter(r=>typeof r=="string").sort()[0];return[`Packs and grants: ${t.analysesLeft} analyses and ${t.repairsLeft} fixes left, used after the pool${n===void 0?"":`; the first expire ${n.slice(0,10)}`}.`]}async function s0(e){let t=await Dn(e.env);if(t===void 0){e.io.error(zd(e));return}return new Ht(pr(e.env,t.apiUrl),t.token,e.fetch)}var Ip=e=>`$${e.toLocaleString("en-US")}`,n0="sales@kwikqa.com";function r0(e){let t=e.annualMonthlyUsd??e.annualUsd/12,n=`${Ip(e.annualUsd)}/yr (${Ip(t)}/mo)`,r=e.monthlyUsd===0&&e.annualUsd===0?"$0":e.sales===!0?`from ${n}, through KwikQA's sales`:`${Ip(e.monthlyUsd)}/mo, or ${n}`,s=e.audience==="organization"?", shared by the organization":"",o=e.analyses===void 0?"unlimited analyses and fixes":`${e.analyses.toLocaleString("en-US")} analyses and ${(e.repairs??0).toLocaleString("en-US")} fixes a month${s}`;return{price:r,limits:e.hosted?o:`${o} (your own model key)`}}async function rb(e,t,n={annual:!1}){return zt(e,async()=>{let r=await Dn(e.env),s=await new Ht(pr(e.env,r?.apiUrl),void 0,e.fetch).plans(),o=s.paidPlansOpen!==!1,d=s.plans.filter(m=>m.id!=="free").find(m=>m.id===t);if(d===void 0||!o){t!==void 0&&d===void 0&&e.io.error(`Unknown plan: ${t}`);let m=Math.max(0,...s.plans.map(g=>g.annualSavingPercent??0));e.io.print(`Plans, priced per account or organization (monthly, or yearly${m>0?`, which saves up to ${m}%`:""}):`);let h=Math.max(...s.plans.map(g=>g.id.length));for(let g of s.plans){let{price:y,limits:w}=r0(g);e.io.print(` ${g.id.padEnd(h)} ${y}: ${w}`)}if(o)e.io.print(`Run \`${bt(e.env)} upgrade <plan> [--annual]\` to get a checkout link. Enterprise is arranged with KwikQA's sales: ${n0}.`);else{let g=s.plans.find(y=>y.id==="free")?.name??"the free plan";if(e.io.print(`Paid plans are coming soon. Until they open, every account uses ${g}.`),d!==void 0)return z.account}return t===void 0?z.ok:z.usage}if(d.sales===!0)return e.io.print(`${d.name} is arranged with KwikQA's sales, ${r0(d).price.replace(/, through KwikQA's sales$/,"")}: write to ${n0}.`),z.ok;let l=n.annual?"year":"month";if(d.intervals!==void 0&&!d.intervals.includes(l))return e.io.error(`${d.name} is billed ${d.intervals.join(" or ")}ly.`),z.usage;let c=await s0(e);if(c===void 0)return z.account;let u=await c.status();if(u.organization.kind==="company"&&u.organization.role!=="admin")return e.io.print(`${u.organization.name}'s admins manage its plan and billing.`),z.ok;if(u.plan!=="free")return e.io.print(`You're on the ${u.plan} plan. Change plans or billing period in Billing, where you see the charge before you confirm:`),e.io.print(`${Ln}billing/`),z.ok;let p=await c.checkout(d.id,{interval:l}),f=n.annual?d.annualUsd:d.monthlyUsd;return e.io.print(`Open this link to subscribe to ${d.name} for ${Ip(f)} a ${n.annual?"year":"month"}:`),e.io.print(p.url),z.ok})}async function ib(e){return zt(e,async()=>{let t=await s0(e);if(t===void 0)return z.account;try{let{url:n}=await t.billingPortal();return e.io.print("Open this link to update your payment method or download invoices:"),e.io.print(n),e.io.print(`To change or cancel your plan: ${Ln}billing/`),z.ok}catch(n){if(n instanceof nt&&n.code==="no-billing-account")return e.io.print("You don't have a paid subscription yet."),e.io.print(`Run \`${bt(e.env)} upgrade <plan>\` to choose one.`),z.ok;if(n instanceof nt&&n.code==="team-member")return e.io.print(n.message),z.ok;throw n}})}import{appendFile as JW,readFile as YW,realpath as XW,writeFile as QW}from"node:fs/promises";import{join as nC}from"node:path";import{createHash as gb}from"node:crypto";import{access as jW,mkdir as BW,readdir as VW,readFile as yb,stat as q0,writeFile as UW}from"node:fs/promises";import{isAbsolute as G0,join as Fn,relative as K0,resolve as W0}from"node:path";import{mkdir as xW,writeFile as _W}from"node:fs/promises";import{join as T0}from"node:path";import{readFile as iW,realpath as sW}from"node:fs/promises";import{createRequire as oW}from"node:module";import{delimiter as aW,dirname as u0,isAbsolute as dW,join as Xi}from"node:path";import{spawn as l0}from"node:child_process";var o0=256*1024,nW=8e3;function Sp(e,t={}){let n={...e,...t};for(let r of df(e))delete n[r];return n}function a0(e){return e.pid===void 0||e.exitCode!==null||e.signalCode!==null}function d0(e,t){if(e.pid!==void 0)try{process.kill(-e.pid,t)}catch{e.kill(t)}}async function rW(e,t){if(!a0(e)){if(process.platform==="win32"){await new Promise(n=>{let r=l0("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});r.on("exit",()=>n()),r.on("error",()=>n())});return}d0(e,"SIGINT"),await Promise.race([t,new Promise(n=>setTimeout(n,nW))]),a0(e)||d0(e,"SIGKILL")}}function sb(e,t,n){let r=l0(e,[...t],{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),s="",o=d=>{s+=d.toString("utf8"),s.length>o0&&(s=s.slice(-o0))};r.stdout?.on("data",o),r.stderr?.on("data",o);let a=new Promise(d=>{r.on("exit",l=>d(l??void 0)),r.on("error",()=>d(void 0))});return{child:r,output:()=>s,exited:a,stop:async()=>{await rW(r,a),await Promise.race([a,new Promise(d=>setTimeout(d,2e3))])}}}async function Tp(e,t,n){let r=sb(e,t,n),s=!1,o=setTimeout(()=>{s=!0,r.stop()},n.timeoutMs),a=await r.exited;return clearTimeout(o),{...a===void 0?{}:{exitCode:a},timedOut:s,output:r.output()}}async function c0(e,t,n){let r=Date.now()+n,s=!1;for(e.exited.then(()=>{s=!0});Date.now()<r;){let o=t.exec(e.output());if(o!==null)return o;if(s)return t.exec(e.output())??void 0;await new Promise(a=>setTimeout(a,100))}}var f0="1.0",ob=[1,59],lW=5,cW=6e4,uW=3e4,pW=12e4,fW=new Set(["generic","text","list","group","none","presentation"]),mW=new Set(["banner","navigation","main","contentinfo","complementary","region","form","search"]);function ab(e){let[t=0,n=0]=e.split(".").map(r=>Number.parseInt(r,10));return t>ob[0]||t===ob[0]&&n>=ob[1]}async function p0(e){try{let t=JSON.parse(await iW(Xi(e,"package.json"),"utf8"));return t.name==="@playwright/cli"&&typeof t.version=="string"?t.version:void 0}catch{return}}async function m0(e,t){try{let r=oW(Xi(e,"package.json")).resolve("@playwright/cli/package.json"),s=u0(r),o=await p0(s);if(o!==void 0)return{entryPath:Xi(s,"playwright-cli.js"),version:o,source:"project"}}catch{}let n=process.platform==="win32"?["playwright-cli.cmd"]:["playwright-cli"];for(let r of(t.PATH??"").split(aW).filter(Boolean))for(let s of n){let o=Xi(r,s);try{let a=process.platform==="win32"?Xi(r,"node_modules","@playwright","cli"):u0(await sW(o)),d=await p0(a);if(d!==void 0)return{entryPath:Xi(a,"playwright-cli.js"),version:d,source:"path"}}catch{}}}function db(e){return e.split(/\r?\n/).filter(t=>!/[║╔╚═]/.test(t)).join(`
|
|
266
|
+
`)}function h0(e){return/```yaml\r?\n([\s\S]*?)\r?\n```/.exec(db(e))?.[1]?.split(/\r?\n/)}function g0(e){let t=db(e).split(/\r?\n/),n=t.findIndex(r=>r.trim()==="### Result");if(!(n<0))return t.slice(n+1).map(r=>r.trim()).find(r=>r!==""&&!r.startsWith("###"))}function hW(e){return/getByRole\(\s*['"]([\w-]+)['"]/.exec(e??"")?.[1]?.toLowerCase()}function y0(e){return e.trim().replace(/^-\s+/,"").replace(/\s\[(?:ref|cursor)=[^\]]+\]/g,"").replace(/:$/,"").trim()}function w0(e,t,n=lW){let r=Vs(t??""),s=hW(t);return e.map((a,d)=>{let l=/\[ref=(e\d+)\]/.exec(a)?.[1],c=y0(a),u=/^([\w-]+)/.exec(c)?.[1]?.toLowerCase()??"";if(l===void 0||fW.has(u))return;let p=c.toLowerCase(),f=r.filter(m=>p.includes(m)).length*3+(s!==void 0&&u===s?2:0);if(!(mW.has(u)&&f===0))return{ref:l,element:c,score:f,order:d}}).filter(a=>a!==void 0).sort((a,d)=>d.score-a.score||a.order-d.order).slice(0,n).map(({ref:a,element:d})=>({ref:a,element:d}))}async function b0(e){let{target:t}=e,n=[],r={logicalTestId:t.logicalTestId,title:t.title,file:t.file,line:t.line,...t.failingLine===void 0?{}:{failingLine:t.failingLine},...t.locator===void 0?{}:{locator:t.locator}};if(t.failingLine===void 0)return{...r,candidates:[],issues:["The report does not say which line failed."]};let s=Sp(e.env,{PLAYWRIGHT_HTML_OPEN:"never"}),o=sb(e.playwright.executable,[...e.playwright.nodeArguments,"test",`${t.file}:${t.line}`,...t.project===void 0?[]:[`--project=${t.project}`],...e.configPath===void 0?[]:[`--config=${e.configPath}`],"--debug=cli","--timeout=0","--retries=0","--workers=1","--reporter=line"],{cwd:e.workspaceRoot,env:s}),a=(c,u=uW)=>Tp(process.execPath,[e.cli.entryPath,...c],{cwd:e.scratchDirectory,env:s,timeoutMs:u}),d,l=[];try{if(d=(await c0(o,/playwright-cli attach ([\w-]+)/,cW))?.[1],d===void 0)return n.push("The test did not stop in the debugger."),{...r,candidates:l,issues:n};if((await a(["attach",d])).exitCode!==0)return n.push("Playwright CLI could not attach to the paused test."),{...r,candidates:l,issues:n};let p=dW(t.file)?t.file:Xi(e.workspaceRoot,t.file),f=await a([`-s=${d}`,"pause-at",`${p}:${t.failingLine}`],pW);if(f.exitCode!==0||!/### Paused/.test(f.output))return n.push(`The test did not reach line ${t.failingLine}.`),{...r,candidates:l,issues:n};let m=h0((await a([`-s=${d}`,"snapshot"])).output);if(m===void 0)return n.push("Playwright CLI returned no page snapshot."),{...r,candidates:l,issues:n};for(let h of w0(m,t.locator)){let g=g0((await a([`-s=${d}`,"generate-locator",h.ref])).output);g!==void 0&&l.push({element:h.element,locator:g})}return l.length===0&&n.push("No locator could be generated for any candidate."),{...r,candidates:l,issues:n}}catch(c){return n.push(`The probe stopped: ${c instanceof Error?c.message:String(c)}`),{...r,candidates:l,issues:n}}finally{d!==void 0&&await a([`-s=${d}`,"detach"],1e4).catch(()=>{}),await o.stop()}}import{mkdir as R0,rm as v0}from"node:fs/promises";import{dirname as gW,join as bo,relative as yW,resolve as k0}from"node:path";var x0=".kwikqa/capture",wW=10*6e4,bW={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};function lb(e){let t=yW(e.workspaceRoot,e.tool.entryPath).replaceAll("\\","/"),n=e.workspaceRoot,r=e.args.map(s=>{let o=s===n?".":s.split(`${n}/`).join("").split(`${n}\\`).join("").replaceAll("\\","/");return/[\s"']/.test(o)?JSON.stringify(o):o});return`node ${t} ${r.join(" ")}`}async function _0(e){let t=e.targets[0];if(t===void 0)return{kind:"unavailable",message:"No failing tests to capture."};let n=Yt(e.run);if(n===void 0)return{kind:"unavailable",message:Wn(e.run)};if(!Nt(n))return{kind:"unavailable",message:"KwikQA captures pages only for Playwright, Cypress, and WebdriverIO runs. Java and Python runs can't be captured yet, so analyze them without --capture."};let r=bW[n],s=await Pa({workspaceRoot:e.workspaceRoot,...e.repositoryRoot===void 0?{}:{repositoryRoot:e.repositoryRoot},ownerPath:bo(e.workspaceRoot,t.file),packageName:r});if(s.kind!=="resolved")return{kind:"unavailable",message:s.reasons[0]?.message??`The project's ${r} could not be resolved; nothing was installed.`};let o=`${x0}/${e.captureId}`,a={framework:n,tool:s.tool,workspaceRoot:e.workspaceRoot,directory:o,targets:e.targets};if(n==="playwright"){let m=[...new Set(e.targets.map(w=>`${w.file}:${w.line}`))],h=[...new Set(e.targets.map(w=>w.project).filter(w=>w!==void 0))],g=bo(e.workspaceRoot,o,"report.json"),y=["test",...m,...h.map(w=>`--project=${w}`),...e.run.configFile===void 0?[]:[`--config=${e.run.configFile}`],"--trace=retain-on-failure","--retries=0","--max-failures=0","--reporter=json",`--output=${o}/results`];return{kind:"ready",plan:{...a,args:y,workingDirectory:e.workspaceRoot,environment:{PLAYWRIGHT_JSON_OUTPUT_NAME:g,PLAYWRIGHT_HTML_OPEN:"never"},reportPath:g,...e.run.configFile===void 0?{}:{configPath:e.run.configFile}}}}let d=[...new Set(e.targets.map(m=>m.file))],l=e.run.configFile??await zu(e.workspaceRoot,n,t.file),c=bo(e.workspaceRoot,o,"reports"),u=await $u(e.workspaceRoot);await R0(bo(e.workspaceRoot,o),{recursive:!0});let p=l===void 0?e.workspaceRoot:gW(k0(e.workspaceRoot,l));if(n==="cypress"){let m=await qu(e.workspaceRoot,l,d),h=await Du({workspaceRoot:e.workspaceRoot,runtime:u,...l===void 0?{}:{configFile:l},projectDirectory:m,specs:d,screenshotsDirectory:`${o}/screenshots`,noRetries:!0,capture:{directory:o,supportFile:await Gu(e.workspaceRoot,l,m)}});return{kind:"ready",plan:{...a,args:h.args,workingDirectory:k0(e.workspaceRoot,m),environment:{KWIKQA_REPORT_DIR:c},reportPath:c,...l===void 0?{}:{configPath:l}}}}if(l===void 0)return{kind:"unavailable",message:`No wdio.conf was found for ${t.file}; nothing was run.`};let f=await Fu({workspaceRoot:e.workspaceRoot,runtime:u,configFile:l,specs:d,directory:o,noRetries:!0,reportDirectory:`${o}/reports`,capture:!0});return{kind:"ready",plan:{...a,args:f.args,workingDirectory:p,environment:{KWIKQA_REPORT_DIR:c},reportPath:c,configPath:l}}}async function I0(e,t){let n=bo(e.workspaceRoot,e.directory);if(e.framework==="playwright")await v0(n,{recursive:!0,force:!0}),await R0(n,{recursive:!0});else for(let p of["reports","pages","screenshots"])await v0(bo(n,p),{recursive:!0,force:!0});let r=await Tp(e.tool.executable,[...e.tool.nodeArguments,...e.args],{cwd:e.workingDirectory,env:Sp(t.env,e.environment),timeoutMs:t.timeoutMs??wW}),s=await ht(e.reportPath,{workspaceRoot:e.workspaceRoot}),o=Hu[e.framework];if(s.kind!=="parsed"){let p=r.output.trim().split(`
|
|
267
267
|
`).slice(-5).join(`
|
|
268
268
|
`);return{kind:"failed",message:r.timedOut?`The capture run timed out before ${o} wrote its report.`:`${o} wrote no report.${p===""?"":`
|
|
269
|
-
${p}`}`,reproduced:0,passed:0}}let a=new Set(e.targets.map(p=>p.logicalTestId)),d=s.run.logicalTests.filter(p=>a.has(p.logicalTestId)),l=d.filter(p=>p.status==="unexpected"||p.status==="flaky").map(p=>p.logicalTestId),c=l.length,u=d.filter(p=>p.status==="expected").length;return{kind:"captured",reportPath:e.reportPath,reproduced:c,passed:u,failedAgain:l,message:c===0?`None of the ${e.targets.length} failing tests failed again, so the failure may be flaky or depend on state the re-run did not have.`:`Captured full evidence for ${c} failing test${c===1?"":"s"}${u>0?`; ${u} passed this time, which suggests flakiness`:""}.`}}var
|
|
270
|
-
${p.stack??""}`),l=(S0(o.errorLocation?.file,a)?o.errorLocation?.line:void 0)??o.errors.map(p=>S0(p.location?.file,a)?p.location?.line:
|
|
271
|
-
`),{outcome:n,probePath:c,probe:l}}var P0=["openrouter","anthropic","openai","azure-openai","bedrock","github-models"],
|
|
269
|
+
${p}`}`,reproduced:0,passed:0}}let a=new Set(e.targets.map(p=>p.logicalTestId)),d=s.run.logicalTests.filter(p=>a.has(p.logicalTestId)),l=d.filter(p=>p.status==="unexpected"||p.status==="flaky").map(p=>p.logicalTestId),c=l.length,u=d.filter(p=>p.status==="expected").length;return{kind:"captured",reportPath:e.reportPath,reproduced:c,passed:u,failedAgain:l,message:c===0?`None of the ${e.targets.length} failing tests failed again, so the failure may be flaky or depend on state the re-run did not have.`:`Captured full evidence for ${c} failing test${c===1?"":"s"}${u>0?`; ${u} passed this time, which suggests flakiness`:""}.`}}var vW=/\b(?:getBy\w+|locator|frameLocator)\((?:[^()]|\([^()]*\))*\)/;function kW(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function RW(e,t){if(e===void 0)return;let r=new RegExp(`${kW(t)}:(\\d+):\\d+`).exec(e.replaceAll("\\","/"));return r?.[1]===void 0?void 0:Number(r[1])}function S0(e,t){if(e===void 0)return!1;let n=e.replaceAll("\\","/");return n===t||n.endsWith(`/${t}`)}function Ap(e){let t=new Map(e.projects.map(r=>[r.projectId,r.name])),n=[];for(let r of e.logicalTests){let s=Hs(r),o=s.at(-1);if(o===void 0)continue;let a=r.location.file,d=o.errors.map(p=>`${p.message??""}
|
|
270
|
+
${p.stack??""}`),l=(S0(o.errorLocation?.file,a)?o.errorLocation?.line:void 0)??o.errors.map(p=>S0(p.location?.file,a)?p.location?.line:RW(p.stack,a)).find(p=>p!==void 0),c=d.map(p=>vW.exec(p)?.[0]).find(p=>p!==void 0),u=t.get(r.projectId);n.push({logicalTestId:r.logicalTestId,title:r.title,file:a,line:r.location.line??1,...u===void 0||u===""?{}:{project:u},...l===void 0?{}:{failingLine:l},...c===void 0?{}:{locator:c},hasTrace:s.some(p=>p.attachments.some(f=>f.name==="trace")),hasPageSnapshot:s.some(p=>p.attachments.some(f=>f.name==="error-context"))})}return n}var A0=3;async function cb(e){let t=Ap(e.run),n=await _0({run:e.run,workspaceRoot:e.workspaceRoot,...e.repositoryRoot===void 0?{}:{repositoryRoot:e.repositoryRoot},targets:t,captureId:e.captureId});if(n.kind!=="ready")return n;let{plan:r}=n,s,o,a=r.framework;e.probe&&a==="playwright"&&(ab(r.tool.packageVersion)?(s=await m0(e.workspaceRoot,e.env),s===void 0&&(o="Live probing needs Playwright CLI: add `@playwright/cli` to the project's dev dependencies (nothing was installed).")):o=`Live probing needs Playwright 1.59 or later; this project has ${r.tool.packageVersion}.`);let d=Hu[a],l=`${t.length} failing test${t.length===1?"":"s"}`,c=new Set(t.map(p=>p.file)).size,u=a==="playwright"?[`Re-run ${l} with full tracing, using this project's Playwright ${r.tool.packageVersion}:`,` ${lb(r)}`,...s===void 0?[]:[`Then pause up to ${A0} locator failures at their failing line and ask Playwright for locators, using Playwright CLI ${s.version} (${s.source==="project"?"project dependency":s.entryPath}).`],`Everything is written under ${r.directory}/. Your tests run on this machine, as they do in \`npx playwright test\`.`]:[`Re-run the ${c} spec file${c===1?"":"s"} with ${l}, using this project's ${d} ${r.tool.packageVersion} and its own config:`,` ${lb(r)}`,a==="cypress"?"KwikQA adds its reporter and a support file that loads its failure capture and then yours, and records each failed attempt's page: DOM, Cypress command log, console errors, and network.":"KwikQA adds its reporter and hooks after yours that record each failed attempt's page: DOM, screenshot, WebdriverIO commands, console, and network.",`Everything is written under ${r.directory}/. Your tests run on this machine, as they do in \`npx ${a==="cypress"?"cypress run":"wdio run"}\`.`];return{kind:"ready",prepared:{plan:r,...s===void 0?{}:{cli:s},...o===void 0?{}:{probeUnavailable:o},description:u}}}async function ub(e,t){let n=await I0(e.plan,{env:t});if(e.cli===void 0||n.reportPath===void 0||n.reproduced===0)return{outcome:n};let r=await ht(n.reportPath,{workspaceRoot:e.plan.workspaceRoot}),o=(r.kind==="parsed"?Ap(r.run):[]).filter(u=>u.locator!==void 0).slice(0,A0);if(o.length===0)return{outcome:n};let a=T0(e.plan.workspaceRoot,e.plan.directory,"probe");await xW(a,{recursive:!0});let d=[];for(let u of o)d.push(await b0({workspaceRoot:e.plan.workspaceRoot,playwright:e.plan.tool,cli:e.cli,target:u,...e.plan.configPath===void 0?{}:{configPath:e.plan.configPath},scratchDirectory:a,env:t}));let l={schemaVersion:f0,tool:{name:"@playwright/cli",version:e.cli.version,source:e.cli.source},playwrightVersion:e.plan.tool.packageVersion,results:d},c=T0(e.plan.workspaceRoot,e.plan.directory,"probe.json");return await _W(c,`${JSON.stringify(l,null,2)}
|
|
271
|
+
`),{outcome:n,probePath:c,probe:l}}var P0=["openrouter","anthropic","openai","azure-openai","bedrock","github-models"],IW="2024-10-21",SW=128e3,Xe=class extends Error{},vo="(KwikQA counts the request)";function Ge(e,t){let n=e[t]?.trim();return n===void 0||n===""?void 0:n}function Qi(e,t,n){let r=Ge(e,t);if(r===void 0)throw new Xe(`KWIKQA_ENDPOINT=${n} needs ${t} in the environment.`);return r}function E0(e,t){if(e===void 0)return{...t,evaluationStatus:"unverified-model"};let[n,r,s]=e.split("@");if(n===void 0||n===""||r===void 0||r==="")throw new Xe(`Model routes look like author/model@provider, not ${e}.`);if(s!==void 0)throw new Xe(`Model routes look like author/model@provider, not ${e}.`);return{modelId:n,providerId:r,evaluationStatus:"unverified-model"}}function TW(e,t,n){let r=Qi(e,"KWIKQA_DIAGNOSIS_MODEL",t),s=Ge(e,"KWIKQA_REPAIR_MODEL")??r;for(let a of[r,s])if(/\s|@/.test(a))throw new Xe(`With KWIKQA_ENDPOINT=${t}, a model is the endpoint's own model ID, such as ${AW[t]}, not ${a}.`);let o=a=>({modelId:a,providerId:n,evaluationStatus:"unverified-model"});return{diagnosis:o(r),repair:o(s)}}var AW={openrouter:"anthropic/claude-sonnet-4.5@anthropic",anthropic:"claude-sonnet-4-5",openai:"gpt-4.1","azure-openai":"your deployment's name",bedrock:"anthropic.claude-sonnet-4-5-20250929-v1:0","github-models":"openai/gpt-4.1"};function C0(e,t,n){let r=Ge(e,t);if(r===void 0)return n;let s=Number(r);if(!/^\d+$/.test(r)||!Number.isSafeInteger(s)||s<=0)throw new Xe(`${t} must be a positive whole number of tokens, not ${r}.`);return s}function PW(e){let t=Ge(e,"KWIKQA_MODEL_PRICING");if(t===void 0)return;let n=t.split(",").map(s=>s.trim()),r=n.map(Number);if(n.length!==2||n.some(s=>!/^\d+(\.\d+)?$/.test(s))||r.some(s=>!Number.isFinite(s)))throw new Xe(`KWIKQA_MODEL_PRICING is "prompt,completion" in USD per million tokens, such as 3,15, not ${t}.`);return{promptPerMillionTokens:r[0],completionPerMillionTokens:r[1]}}function EW(e,t){let n=Ge(e,t)?.toLowerCase();if(n===void 0||n==="0"||n==="false")return!1;if(n==="1"||n==="true")return!0;throw new Xe(`${t} is true or false, not ${n}.`)}function CW(e,t){let n;try{n=new URL(e)}catch{throw new Xe(`${t} must be an https URL, not ${e}.`)}if(n.protocol!=="https:")throw new Xe(`${t} must be an https URL.`);return n.host}var pb=class{constructor(t){this.byModel=t}byModel;routing="direct";preflight(t){let n=this.byModel.get(t.modelId);return n===void 0?Promise.resolve({kind:"unsupported",code:"model-mismatch",message:`The configured endpoint has no model ${t.modelId}.`}):n.preflight(t)}complete(t){let n=this.byModel.get(t.route.modelId);return n===void 0?Promise.resolve({kind:"failed",code:"invalid-request",message:`The configured endpoint has no model ${t.route.modelId}.`,elapsedMs:0}):n.complete(t)}};function NW(e){let t=Ge(e,"KWIKQA_ENDPOINT")?.toLowerCase()??"openrouter",n=P0.find(r=>r===t);if(n===void 0)throw new Xe(`KWIKQA_ENDPOINT is one of ${P0.join(", ")}, not ${t}.`);return n}function N0(e,t){let n=NW(e);if(n==="openrouter"){if(Ge(e,"OPENROUTER_API_KEY")===void 0)throw new Xe("The BYOK plans need OPENROUTER_API_KEY in the environment.");return{id:n,transport:new Mi({readApiKey:()=>e.OPENROUTER_API_KEY,fetch:t.fetch}),diagnosisModel:E0(Ge(e,"KWIKQA_DIAGNOSIS_MODEL"),t.diagnosis),repairModel:E0(Ge(e,"KWIKQA_REPAIR_MODEL"),t.repair),destination:`OpenRouter, with your own API key ${vo}`}}let r={contextLength:C0(e,"KWIKQA_MODEL_CONTEXT",SW),maxCompletionTokens:C0(e,"KWIKQA_MODEL_MAX_OUTPUT",t.maxOutputTokens)},s=PW(e),o={...r,...s===void 0?{}:{pricing:s}},a=EW(e,"KWIKQA_MODEL_REASONING"),d={fetch:t.fetch},l,c,u;switch(n){case"anthropic":{let m=Qi(e,"ANTHROPIC_API_KEY",n);l=Ui,c=`the Anthropic API, with your own API key ${vo}`,u=h=>Ru({apiKey:m,model:h,reasoning:a,...o},d);break}case"openai":{let m=Qi(e,"OPENAI_API_KEY",n),h=Ge(e,"OPENAI_ORG_ID"),g=Ge(e,"OPENAI_PROJECT_ID");l=dr,c=`the OpenAI API, with your own API key ${vo}`,u=y=>vu({apiKey:m,model:y,reasoning:a,...o,...h===void 0?{}:{organization:h},...g===void 0?{}:{project:g}},d);break}case"azure-openai":{let m=Qi(e,"AZURE_OPENAI_ENDPOINT",n),h=CW(m,"AZURE_OPENAI_ENDPOINT"),g=Qi(e,"AZURE_OPENAI_API_KEY",n),y=Ge(e,"AZURE_OPENAI_API_VERSION")??IW;l=ar,c=`Azure OpenAI at ${h}, with your own API key ${vo}`,u=w=>bu({endpoint:m,deployment:w,apiVersion:y,apiKey:g,reasoning:a,...o},d);break}case"bedrock":{let m=Ge(e,"AWS_REGION")??Ge(e,"AWS_DEFAULT_REGION")??Qi(e,"AWS_REGION",n),h=Ge(e,"AWS_BEARER_TOKEN_BEDROCK"),g=Ge(e,"AWS_ACCESS_KEY_ID"),y=Ge(e,"AWS_SECRET_ACCESS_KEY"),w=Ge(e,"AWS_SESSION_TOKEN");if(h===void 0&&(g===void 0||y===void 0))throw new Xe("KWIKQA_ENDPOINT=bedrock needs AWS_BEARER_TOKEN_BEDROCK, or AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, in the environment.");let b=h!==void 0?{kind:"bearer",token:h}:{kind:"keys",accessKeyId:g,secretAccessKey:y,...w===void 0?{}:{sessionToken:w}};l=Hi,c=`Amazon Bedrock in ${m}, with your own AWS credentials ${vo}`,u=v=>_u({region:m,modelId:v,credentials:b,...o},d);break}case"github-models":{let m=Qi(e,"GITHUB_TOKEN",n),h=Ge(e,"KWIKQA_GITHUB_MODELS_ORG");l=zi,c=`GitHub Models${h===void 0?"":` for ${h}`}, with your own token ${vo}`,u=g=>Iu({token:m,model:g,reasoning:a,...o,...h===void 0?{}:{organization:h}},d);break}}let p=TW(e,n,l),f=new Map;try{for(let m of[p.diagnosis.modelId,p.repair.modelId])f.has(m)||f.set(m,u(m))}catch(m){throw m instanceof Xe?m:new Xe(m instanceof Error?m.message:String(m))}return{id:n,transport:new pb(f),diagnosisModel:p.diagnosis,repairModel:p.repair,destination:c}}import{createHash as OW}from"node:crypto";import{basename as $W}from"node:path";var MW=100;function O0(e){return OW("sha256").update(e).digest("hex")}function $0(e,t){let n=e.projects.find(o=>o.projectId===t.projectId)?.name??"",r=t.location.file,s=t.titlePath.filter(o=>o!==""&&o!==r&&o!==$W(r));return{key:O0([n,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:n.slice(0,100)}}function M0(e){return e===void 0?void 0:O0(e).slice(0,32)}function Pp(e){if(e.run===void 0)return;let t=e.run,n=t.logicalTests.filter(r=>r.status==="unexpected"||r.status==="flaky").slice(0,MW).map(r=>({...$0(t,r),status:r.status==="flaky"?"flaky":"failed"}));return{kind:"analysis",outcome:e.outcome,reasonCode:e.reasonCode,framework:t.framework,tests:n}}function ko(e){let t=e.record,n=e.run===void 0||e.packet===void 0||t?.diagnosis===void 0?void 0:hp(e.run,t.diagnosis,e.packet,t.clusters?.[0]?.representativeId),r=M0(t?.repair?.repairSessionId);return{kind:"fix",outcome:e.outcome,reasonCode:e.reasonCode,...e.run===void 0?{}:{framework:e.run.framework},...r===void 0?{}:{session:r},...t?.repair?.attempt===void 0?{}:{attempt:t.repair.attempt},...n===void 0||e.run===void 0?{}:{test:$0(e.run,n)},...t?.repairProposal===void 0?{}:{changedFiles:t.repairProposal.changedFiles,changedLines:t.repairProposal.changedLines}}}function L0(e){let t=e.record?.repair,n=M0(t?.repairSessionId);if(!(n===void 0||t===void 0))return{kind:"validation",outcome:e.outcome,reasonCode:e.reasonCode,session:n,attempt:t.attempt}}async function D0(e,t,n,r){if(r===void 0||!n.organization.insights)return;try{await t.reportInsights([r])}catch{e.print("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";e.print(`Insights: shared ${s} with ${n.organization.name}.`)}import{basename as j0}from"node:path";function fr(e,t){return`${e} ${t}${e===1?"":"s"}`}function F0(e){return`$${e.toFixed(e<.1?4:2)}`}function LW(e){let t=e.evidence.flatMap(s=>s.locator.type==="diff-hunk"?[s.locator]:[]);if(t.length===0)return[];let n=new Set(t.flatMap(s=>s.commit===void 0?[]:[s.commit])),r=[...n.size===0?[]:[fr(n.size,"commit")],...t.some(s=>s.commit===void 0)?["uncommitted changes"]:[]].join(" and ");return[` Changes: ${fr(t.length,"changed hunk")} from ${r} that mention the failures (--no-changes leaves them out)`]}function Kd(e,t,n){let r=t.model.reasoningEffort===void 0?"":`, effort ${t.model.reasoningEffort}`,s=t.model.zeroDataRetention===!0?", zero data retention":"";return[`${e==="diagnosis"?"Diagnosis":"Repair proposal"} request -> ${n}`,` Model: ${t.model.modelId} via ${t.model.providerId}${r}${s}`,` Evidence: ${fr(t.evidence.length,"redacted item")} from ${t.channels.join(", ")||"the report"}`,` ${fr(t.redactionIds.length,"redaction")} applied, ${fr(t.omissionIds.length,"item")} withheld by policy`,...LW(t),` Estimate: at most ${t.estimate.estimatedInputTokens.toLocaleString("en-US")} input + ${t.estimate.estimatedOutputTokens.toLocaleString("en-US")} output tokens, at most ${F0(t.estimate.estimatedDollars)}`,` Caps: ${F0(t.caps.request.maxDollars)} per request`,` Payload: ${t.payloadManifestHash.slice(0,16)}... (exactly this redacted payload is sent)`]}function DW(e){switch(e.kind){case"build-executable":return"executable";case"jdk-launcher":return"JDK launcher";case"generated-init-script":return"init script";default:return j0(e.path)}}function FW(e){return[` in ${e.workingDirectory}`,...e.resolutionEvidence.flatMap(t=>t.sha256===void 0?[]:[` ${DW(t)}: sha256 ${t.sha256.slice(0,16)}... ${t.path}`])]}function Wd(e,t="post-patch"){let n=new Map;for(let r of e.commands.filter(s=>s.timing===t)){let s=Wr(r.kind),o=r.args.map(c=>/\s/.test(c)?JSON.stringify(c):c),a=` ${s?r.executable:j0(r.executable)} ${o.join(" ")}`,d=s?[a,...FW(r)]:[a],l=d.join(`
|
|
272
272
|
`);n.set(l,{lines:d,count:(n.get(l)?.count??0)+1})}return[...n.values()].flatMap(({lines:r,count:s})=>s===1?r:[`${r[0]??""} (${s} runs)`,...r.slice(1)])}function Ep(e,t,n={}){let r=e.proposal,s=["Proposed repair",` Intent: ${r.intent.statement}`,` Preserves: ${r.intent.preservedBehavior}`,` Changes: ${fr(r.changedFiles,"file")}, ${fr(r.changedLines,"line")}`,"",...r.diff.trimEnd().split(`
|
|
273
273
|
`),"",n.validatedNow===!0?"Validation commands (run next, on this runner):":"Validation commands (run later by `kwikqa validate`):"];return s.push(...Wd(t)),e.checkoutPristine||s.push("","Note: this checkout has other uncommitted changes; they are not touched."),s}function B0(e,t){let n=r=>t?.logicalTests.find(s=>s.logicalTestId===r)?.title;return e.flatMap((r,s)=>{let o=r.logicalTestIds.map(l=>n(l)??l),a=o.length<=3?o.join(", "):`${o.slice(0,3).join(", ")} and ${o.length-3} more`,d=`${o.length} test${o.length===1?"":"s"}`;return[`Failure group ${s+1} of ${e.length}: ${d} (${a})${r.escalated===!0?", answered by the stronger model":""}`,...r.diagnosis!==void 0&&r.diagnosis.hypotheses.length>0?fb(r.diagnosis):[` ${r.outcome} (${r.reasonCode}): ${r.message}`],...r.repairRefusal===void 0?[]:[` ${r.repairRefusal.message}`],""]})}function fb(e){if(e.hypotheses.length===0)return["No cause is supported by the evidence.",` Next: ${e.recommendedNextAction}`];let t=[];for(let n of[...e.hypotheses].sort((r,s)=>r.rank-s.rank))t.push(`#${n.rank} ${n.statement}`,` owner: ${n.probableOwner}${n.withheldOwner===void 0?"":` (leans ${n.withheldOwner}: no server error or crash shows it)`}, evidence: ${n.evidenceGrade}, cause: ${n.causalCategory}`);return t.push(` Next: ${e.recommendedNextAction}`),t}function V0(e,t,n,r,s={}){if(s.ciFix!=="running")switch(t){case"diagnosed":return r!==void 0&&Yt(r)===void 0?Wn(r):e?.repairRefusal!==void 0?e.repairRefusal.message:e?.diagnosis?.repairEligibility!=="eligible"?void 0:s.ci===!0&&s.ciFix==="policy"?`The committed ci.fix policy lets \`${n} fix\` repair it in this job and open a draft pull request.`:s.ci===!0?`To repair it, run \`${n} analyze\` and then \`${n} fix\` on your machine.`:`Run \`${n} fix\` to propose a repair.`;case"proposal-ready":return`Run \`${n} fix\` without --propose-only to review and apply it.`;case"awaiting-validation":return`Run \`${n} validate\` to verify the patch.`;case"repair-failed":return e?.repair?.retryAvailable===!0?`Run \`${n} fix --retry\` to re-diagnose from the validation evidence (one retry left).`:void 0;default:return}}function U0(e){if(e===void 0)return;let t=e.artifact.formatVersion===void 0?"":` ${e.artifact.formatVersion}`,n=e.artifact.format===void 0?void 0:Gn[e.artifact.format],r=e.logicalTests.filter(l=>l.status==="unexpected").length,s=e.logicalTests.filter(l=>l.status==="flaky").length,a=`Read a ${e.framework==="unknown"?"run from an unidentified framework":`${Jt[e.framework]}${t} run`}${n===void 0?"":` (${n})`}: ${fr(e.logicalTests.length,"test")}, ${r} failing${s===0?"":`, ${s} flaky`}.`;if(e.stop?.cause!=="max-failures")return a;let d=e.logicalTests.filter(l=>l.attempts.length===0).length;return`${a}
|
|
274
274
|
Playwright stopped it at its failure limit (maxFailures ${e.stop.limit}), so ${fr(d,"test")} ${d===1?"has":"have"} no result. KwikQA diagnoses the failures it finished.`}function H0(e,t){if(e===void 0)return;let n=Yt(e);if(n===void 0||!Nt(n))return;let r=e.framework==="playwright",s=r?"trace":"kwikqa-capture",o=0,a=0;for(let u of e.logicalTests)for(let p of Hs(u))o+=1,p.attachments.some(f=>f.name===s)&&(a+=1);if(o===0||a===o)return;let d=o-a;return[`Note: ${d===o?o===1?`The failing attempt has no ${r?"Playwright trace":"KwikQA failure capture"}`:`None of the ${o} failing attempts has ${r?"a Playwright trace":"a KwikQA failure capture"}`:`${d} of ${o} failing attempts have no ${r?"Playwright trace":"KwikQA failure capture"}`}, so browser actions, network, console, and DOM were not available to the diagnosis.`,r?` 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.`,...r?[' `use: { trace: "retain-on-failure" }` in playwright.config to keep traces of failures.']:[]].join(`
|
|
275
|
-
`)}var z0=["SIGINT","SIGTERM"];function mb(e,t=process,n=3e3){let r=()=>{for(let o of z0)t.off(o,s)};function s(o){r();let a,d=!1,l=()=>{d||(d=!0,clearTimeout(a),t.kill(t.pid,o))};a=setTimeout(l,n),e().then(l,l)}for(let o of z0)t.on(o,s);return r}var Ro=(()=>{let{workspaceRoot:e,...t}=$o;return{...t,maxPacketBytes:6e5}})(),
|
|
276
|
-
`,{mode:384})}async function Ur(e,t,n){if(n!==void 0)return G0(n)?n:W0(e.cwd,n);for(let r of[e.env.PLAYWRIGHT_JSON_OUTPUT_NAME,e.env.KWIKQA_REPORT_DIR])if(r!==void 0&&r!==""){let s=G0(r)?r:W0(t,r);if(await Zi(s))return s}for(let r of J0)if(await Zi(Fn(t,r)))return Fn(t,r);return Fn(t,J0[0]??"report.json")}async function Z0(e){try{if((await q0(e)).isDirectory()){let t=gb("sha256");for(let n of(await BW(e)).sort()){let r=Fn(e,n);(await q0(r)).isFile()&&t.update(`${n}\0`).update(await yb(r))}return t.digest("hex")}return gb("sha256").update(await yb(e)).digest("hex")}catch{return}}async function eC(e,t,n){let r=t.capture;if(r===void 0)return;let s=Fn(e,r.reportPath);if(await Z0(n)!==r.sourceSha256||!await Zi(s))return;let o=r.probePath===void 0?void 0:Fn(e,r.probePath);return{reportPath:s,...o!==void 0&&await Zi(o)?{probePath:o}:{}}}async function tC(e,t,n,r){let s=await ht(n,{workspaceRoot:t,...r.framework===void 0?{}:{framework:r.framework}});if(s.kind!=="parsed"){e.io.error(`Capture skipped: ${s.diagnostic.message}`);return}let o=s.run.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest",a=await cb({run:s.run,workspaceRoot:t,repositoryRoot:await an(t),captureId:o,env:e.env,probe:r.probe});if(a.kind!=="ready"){e.io.print(`Capture skipped: ${a.message}`);return}for(let c of a.prepared.description)e.io.print(c);if(a.prepared.probeUnavailable!==void 0&&e.io.print(`Note: ${a.prepared.probeUnavailable}`),r.yes)e.io.print("Run these tests? yes (--yes)");else if(!await e.io.confirm("Run these tests?")){e.io.print("Capture declined; analyzing the existing report.");return}let d=await ub(a.prepared,e.env);if(e.io.print(d.outcome.message),d.probe!==void 0){let c=d.probe.results.reduce((u,p)=>u+p.candidates.length,0);e.io.print(`Live probe: ${c} Playwright-generated locator${c===1?"":"s"} for ${d.probe.results.length} failing test${d.probe.results.length===1?"":"s"}.`)}if(d.outcome.reportPath===void 0||d.outcome.reproduced===0)return;let l=await Z0(n);if(l!==void 0){let c=await Jd(t);await Yd(t,{...c,capture:{sourceSha256:l,reportPath:K0(t,d.outcome.reportPath),...d.probePath===void 0?{}:{probePath:K0(t,d.probePath)}}})}return{reportPath:d.outcome.reportPath,...d.probePath===void 0?{}:{probePath:d.probePath}}}function HW(e,t){let n=e.entitlements?.ci;if(n==="none")return"Your plan analyzes CI runs locally, with nothing sent. Hosted analysis in CI comes with Pro and the team plans: see `npx kwikqa upgrade`.";if(n==="personal"&&t.owner.toLowerCase()!==e.login.toLowerCase())return`Your plan runs KwikQA in CI on a repository of your own. ${t.owner}/${t.name} belongs to someone else, so it needs a team plan: see \`npx kwikqa upgrade\`.`}function hb(e){return gb("sha256").update(e).digest("hex")}async function jn(e,t,n){let r=await Dn(e.env);if(r===void 0)return{exit:z.account,messages:[zd(e)]};let s=await ME(e.env),o=new Ht(pr(e.env,r.apiUrl),r.token,e.fetch,s===void 0?void 0:LE(s),s===void 0?void 0:FE(e.env,e.fetch)),a=await o.status(),d=s===void 0?void 0:HW(a,s);if(d!==void 0)return{exit:z.account,messages:[d],status:a};let l=await o.hostedConfig(),c=HE(a),u;if(!c)try{u=N0(e.env,{diagnosis:l.models.diagnosis,repair:l.models.repair,maxOutputTokens:Math.max(l.caps.diagnosis.request.maxOutputTokens,l.caps.repair.request.maxOutputTokens),fetch:e.fetch})}catch(O){if(!(O instanceof Xe))throw O;return{exit:z.account,messages:[O.message]}}let p=t==="analysis"?a.usage.analyses:a.usage.repairs;if(n===void 0&&p.limit!==void 0&&p.used>=p.limit){let O=t==="analysis"?"analyses":"fixes";return{exit:z.account,messages:[`You have used all ${p.limit} ${O} on the ${a.plan} plan until ${a.periodEnd.slice(0,10)}.`,a.organization.kind==="company"&&a.organization.role!=="admin"?`Ask an admin of ${a.organization.name} about more: a top-up pack, or a bigger plan.`:`Run \`${bt(e.env)} upgrade\` to see plans with more.`]}}let f,m=new Set,h=O=>{O===void 0||O.trim()===""||m.has(O)||(m.add(O),e.io.print(` KwikQA: ${O}`))},g=t==="analysis"&&s!==void 0?DE(e.env):void 0,y=g!==void 0&&a.entitlements?.shardDeduplication===!0?async O=>{let P=new Map(O.map(L=>[Or(L.signals),L.clusterId])),E=await o.claimGroups(g.run,g.job,[...P.keys()]);return new Set([...E].filter(([,L])=>L==="another-job").flatMap(([L])=>{let B=P.get(L);return B===void 0?[]:[B]}))}:void 0,w=new Set(n===void 0?[]:[hb(n)]),b,v,R=async()=>{v?.(),v=void 0;let O=b;b=void 0,O!==void 0&&await o.closeSession(O)},x=l.sessions===!0&&n===void 0?{open:async O=>{let P=await X0(e,()=>o.openSession(O));b=P.sessionTicket,v=mb(R),w.add(hb(P.sessionTicket)),h(P.notice)},close:R}:void 0,T,N,U=async()=>{N?.(),N=void 0;let O=T;if(T=void 0,O===void 0)return;let P=await o.closeSession(O);P.retryTicket!==void 0&&(f=P.retryTicket)},F=l.repairSessions===!0&&n===void 0?{open:async O=>{let P=await X0(e,()=>o.openSession(O,"repair"));T=P.sessionTicket,N=mb(U),w.add(hb(P.sessionTicket)),h(P.notice)},close:U}:void 0,I={...n===void 0?{}:{retryTicket:n},onRetryTicket:O=>{f=O},session:()=>b,repairSession:()=>T};if(u!==void 0){let O=new xp(u.transport,o,I);return{diagnosis:{model:u.diagnosisModel,caps:l.caps.diagnosis,transport:O,...x===void 0?{}:{session:x},...y===void 0?{}:{claim:y}},repairModel:u.repairModel,repairCaps:l.caps.repair,...F===void 0?{}:{repairSession:F},destination:u.destination,ticket:()=>f,sessions:()=>[...w],client:o,status:a}}let C=o.transport({...I,jobs:l.jobs===!0,onProgress:GW(e),onRestart:()=>e.io.print(" The KwikQA service restarted while the model was working; sending the request again (nothing was charged)."),...e.sleep===void 0?{}:{sleep:e.sleep}}),A=n!==void 0&&l.models.escalation!==void 0&&l.caps.escalation!==void 0,M=A?l.models.escalation:void 0,$=A?l.caps.escalation:void 0,j=!A&&x!==void 0&&l.models.escalation!==void 0&&l.caps.escalation!==void 0?{model:l.models.escalation,caps:l.caps.escalation}:void 0;return{diagnosis:{model:M??l.models.diagnosis,caps:$??l.caps.diagnosis,transport:C,...x===void 0?{}:{session:x},...j===void 0?{}:{escalation:j},...y===void 0?{}:{claim:y}},repairModel:M??l.models.repair,repairCaps:$??l.caps.repair,...F===void 0?{}:{repairSession:F},destination:"the KwikQA service, which forwards it to OpenRouter",ticket:()=>f,sessions:()=>[...w],client:o,status:a}}var zW=3e4;function qW(e){let t=Math.floor(e/1e3),n=Math.floor(t/60);return n===0?`${t}s`:`${n}m ${String(t%60).padStart(2,"0")}s`}function GW(e){let t=0;return n=>{let r=Math.floor(n/zW);r<=t||(t=r,e.io.print(` The model is still working (${qW(n)})\u2026`))}}function ts(e,t,n){let r=async(s,o)=>{for(let a of s)e.io.print(a);return n!==!1?(e.io.print(`${o} yes (${n===!0?"--yes":n})`),!0):e.io.confirm(o)};return{approveDiagnosis:s=>r(Kd("diagnosis",s,t),"Send this request?"),approveDiagnoses:s=>{let[o]=s;return s.length===1&&o!==void 0?r(Kd("diagnosis",o,t),"Send this request?"):r([`${s.length} diagnosis requests, one for each group of failures with a shared cause:`,...s.flatMap((a,d)=>["",`Request ${d+1} of ${s.length}`,...Kd("diagnosis",a,t)])],`Send these ${s.length} requests?`)},approveRepairRequest:s=>r(Kd("repair proposal",s,t),"Send this request?"),approveApplication:async(s,o)=>{for(let a of Ep(s,o))e.io.print(a);return e.io.confirm("Apply this patch?")},approveBaseline:s=>r(["This repair changes shared test support, so the tests that use it first run once on the current code. Validation then compares each with how it stood before the patch.",...Wd(s,"baseline")],"Run them now?")}}async function xo(e,t,n,r,s){let o=new Set(r),a=await cb({run:{...n,logicalTests:n.logicalTests.filter(l=>o.has(l.logicalTestId))},workspaceRoot:t,repositoryRoot:await an(t),captureId:`${s.purpose}-${n.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest"}`,env:e.env,probe:!1});if(a.kind!=="ready")return{kind:"unavailable",message:a.message};e.io.print(""),e.io.print(s.intro);for(let l of a.prepared.description)e.io.print(l);if(s.approvedBy!==void 0)e.io.print(`${s.question} yes (${s.approvedBy})`);else if(!await e.io.confirm(s.question))return{kind:"declined"};let d=await ub(a.prepared,e.env);return e.io.print(d.outcome.message),d.outcome.kind==="failed"?{kind:"unavailable",message:d.outcome.message}:{kind:"rerun",failedAgain:d.outcome.failedAgain??[]}}function rt(e,t,n={}){e.io.print("");let r=U0("run"in t?t.run:void 0);r!==void 0&&t.record?.command!=="validate"&&e.io.print(r);let s=t.record?.clusters??[];if(s.length>1&&t.record?.command!=="validate")for(let l of B0(s,"run"in t?t.run:void 0))e.io.print(l);else if(t.record?.diagnosis!==void 0&&t.record.command!=="validate"){for(let l of fb(t.record.diagnosis))e.io.print(l);e.io.print("")}e.io.print(`Result: ${t.outcome} (${t.reasonCode})`),e.io.print(t.message);let o=bt(e.env),a=H0("run"in t?t.run:void 0,o);a!==void 0&&e.io.print(a);let d=V0(t.record,t.outcome,o,"run"in t?t.run:void 0,n);return d!==void 0&&e.io.print(d),t.recordPath!==void 0&&e.io.print(`Record: ${t.recordPath}`),GE(t.outcome)}async function pn(e,t,n,r){await D0(e.io,t.client,t.status,n),await Gd(t.client,t.status,e.env,[r])}async function ns(e,t){let n=L0(t),r=await Dn(e.env);if(r===void 0)return;let s=new Ht(pr(e.env,r.apiUrl),r.token,e.fetch),o;try{o=await s.status()}catch{return}await pn(e,{client:s,status:o},n,Vr("validation",t.record,e.env))}var Y0=600;function KW(e){let t=e.KWIKQA_CI_WAIT_SECONDS?.trim();if(t===void 0||t==="")return Y0;let n=Number(t);return Number.isFinite(n)&&n>=0?Math.min(n,3600):Y0}async function X0(e,t){let n=wo(e),r=KW(e.env),s=0;for(;;)try{return await t()}catch(o){if(!(o instanceof nt)||o.code!=="ci-concurrency")throw o;let a=Math.min(o.retryAfterSeconds??30,300)+Math.floor(Math.random()*5);if(s+a>r)throw o;e.io.print(` KwikQA: ${o.message} Waiting ${a} seconds for a free CI slot.`),await n(a*1e3),s+=a}}async function wb(e){let t=await YW(e.cwd),n=nC(t,"kwikqa.config.json");if(await Zi(n))e.io.print("kwikqa.config.json already exists; review it to change what KwikQA may edit.");else{let f=hw({repositoryPaths:await cy(t)});e.io.print("Proposed kwikqa.config.json (what KwikQA may edit when repairing tests):");for(let m of f.canonicalContents.trimEnd().split(`
|
|
277
|
-
`))e.io.print(` ${m}`);for(let m of[...f.reasons,...f.ambiguities])e.io.print(` - ${m}`);await e.io.confirm("Write kwikqa.config.json?")&&(await
|
|
275
|
+
`)}var z0=["SIGINT","SIGTERM"];function mb(e,t=process,n=3e3){let r=()=>{for(let o of z0)t.off(o,s)};function s(o){r();let a,d=!1,l=()=>{d||(d=!0,clearTimeout(a),t.kill(t.pid,o))};a=setTimeout(l,n),e().then(l,l)}for(let o of z0)t.on(o,s);return r}var Ro=(()=>{let{workspaceRoot:e,...t}=$o;return{...t,maxPacketBytes:6e5}})(),HW=.85;function es(e){if(e===void 0)return Ro;let t=Math.min(e.diagnosis.caps.request.maxInputTokens,e.repairCaps.request.maxInputTokens);return{...Ro,maxPacketBytes:Math.min(Ro.maxPacketBytes,Math.floor(t*HW))}}var J0=["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"],Q0=Fn(".kwikqa","cli-state.json");async function Zi(e){return jW(e).then(()=>!0,()=>!1)}async function Jd(e){try{return JSON.parse(await yb(Fn(e,Q0),"utf8"))}catch{return{}}}async function Yd(e,t){await BW(Fn(e,".kwikqa"),{recursive:!0,mode:448}),await UW(Fn(e,Q0),`${JSON.stringify(t)}
|
|
276
|
+
`,{mode:384})}async function Ur(e,t,n){if(n!==void 0)return G0(n)?n:W0(e.cwd,n);for(let r of[e.env.PLAYWRIGHT_JSON_OUTPUT_NAME,e.env.KWIKQA_REPORT_DIR])if(r!==void 0&&r!==""){let s=G0(r)?r:W0(t,r);if(await Zi(s))return s}for(let r of J0)if(await Zi(Fn(t,r)))return Fn(t,r);return Fn(t,J0[0]??"report.json")}async function Z0(e){try{if((await q0(e)).isDirectory()){let t=gb("sha256");for(let n of(await VW(e)).sort()){let r=Fn(e,n);(await q0(r)).isFile()&&t.update(`${n}\0`).update(await yb(r))}return t.digest("hex")}return gb("sha256").update(await yb(e)).digest("hex")}catch{return}}async function eC(e,t,n){let r=t.capture;if(r===void 0)return;let s=Fn(e,r.reportPath);if(await Z0(n)!==r.sourceSha256||!await Zi(s))return;let o=r.probePath===void 0?void 0:Fn(e,r.probePath);return{reportPath:s,...o!==void 0&&await Zi(o)?{probePath:o}:{}}}async function tC(e,t,n,r){let s=await ht(n,{workspaceRoot:t,...r.framework===void 0?{}:{framework:r.framework}});if(s.kind!=="parsed"){e.io.error(`Capture skipped: ${s.diagnostic.message}`);return}let o=s.run.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest",a=await cb({run:s.run,workspaceRoot:t,repositoryRoot:await an(t),captureId:o,env:e.env,probe:r.probe});if(a.kind!=="ready"){e.io.print(`Capture skipped: ${a.message}`);return}for(let c of a.prepared.description)e.io.print(c);if(a.prepared.probeUnavailable!==void 0&&e.io.print(`Note: ${a.prepared.probeUnavailable}`),r.yes)e.io.print("Run these tests? yes (--yes)");else if(!await e.io.confirm("Run these tests?")){e.io.print("Capture declined; analyzing the existing report.");return}let d=await ub(a.prepared,e.env);if(e.io.print(d.outcome.message),d.probe!==void 0){let c=d.probe.results.reduce((u,p)=>u+p.candidates.length,0);e.io.print(`Live probe: ${c} Playwright-generated locator${c===1?"":"s"} for ${d.probe.results.length} failing test${d.probe.results.length===1?"":"s"}.`)}if(d.outcome.reportPath===void 0||d.outcome.reproduced===0)return;let l=await Z0(n);if(l!==void 0){let c=await Jd(t);await Yd(t,{...c,capture:{sourceSha256:l,reportPath:K0(t,d.outcome.reportPath),...d.probePath===void 0?{}:{probePath:K0(t,d.probePath)}}})}return{reportPath:d.outcome.reportPath,...d.probePath===void 0?{}:{probePath:d.probePath}}}function zW(e,t){let n=e.entitlements?.ci;if(n==="none")return"Your plan analyzes CI runs locally, with nothing sent. Hosted analysis in CI comes with Pro and the team plans: see `npx kwikqa upgrade`.";if(n==="personal"&&t.owner.toLowerCase()!==e.login.toLowerCase())return`Your plan runs KwikQA in CI on a repository of your own. ${t.owner}/${t.name} belongs to someone else, so it needs a team plan: see \`npx kwikqa upgrade\`.`}function hb(e){return gb("sha256").update(e).digest("hex")}async function jn(e,t,n){let r=await Dn(e.env);if(r===void 0)return{exit:z.account,messages:[zd(e)]};let s=await ME(e.env),o=new Ht(pr(e.env,r.apiUrl),r.token,e.fetch,s===void 0?void 0:LE(s),s===void 0?void 0:FE(e.env,e.fetch)),a=await o.status(),d=s===void 0?void 0:zW(a,s);if(d!==void 0)return{exit:z.account,messages:[d],status:a};let l=await o.hostedConfig(),c=HE(a),u;if(!c)try{u=N0(e.env,{diagnosis:l.models.diagnosis,repair:l.models.repair,maxOutputTokens:Math.max(l.caps.diagnosis.request.maxOutputTokens,l.caps.repair.request.maxOutputTokens),fetch:e.fetch})}catch(O){if(!(O instanceof Xe))throw O;return{exit:z.account,messages:[O.message]}}let p=t==="analysis"?a.usage.analyses:a.usage.repairs;if(n===void 0&&p.limit!==void 0&&p.used>=p.limit){let O=t==="analysis"?"analyses":"fixes";return{exit:z.account,messages:[`You have used all ${p.limit} ${O} on the ${a.plan} plan until ${a.periodEnd.slice(0,10)}.`,a.organization.kind==="company"&&a.organization.role!=="admin"?`Ask an admin of ${a.organization.name} about more: a top-up pack, or a bigger plan.`:`Run \`${bt(e.env)} upgrade\` to see plans with more.`]}}let f,m=new Set,h=O=>{O===void 0||O.trim()===""||m.has(O)||(m.add(O),e.io.print(` KwikQA: ${O}`))},g=t==="analysis"&&s!==void 0?DE(e.env):void 0,y=g!==void 0&&a.entitlements?.shardDeduplication===!0?async O=>{let P=new Map(O.map(L=>[Or(L.signals),L.clusterId])),E=await o.claimGroups(g.run,g.job,[...P.keys()]);return new Set([...E].filter(([,L])=>L==="another-job").flatMap(([L])=>{let B=P.get(L);return B===void 0?[]:[B]}))}:void 0,w=new Set(n===void 0?[]:[hb(n)]),b,v,R=async()=>{v?.(),v=void 0;let O=b;b=void 0,O!==void 0&&await o.closeSession(O)},x=l.sessions===!0&&n===void 0?{open:async O=>{let P=await X0(e,()=>o.openSession(O));b=P.sessionTicket,v=mb(R),w.add(hb(P.sessionTicket)),h(P.notice)},close:R}:void 0,T,N,U=async()=>{N?.(),N=void 0;let O=T;if(T=void 0,O===void 0)return;let P=await o.closeSession(O);P.retryTicket!==void 0&&(f=P.retryTicket)},F=l.repairSessions===!0&&n===void 0?{open:async O=>{let P=await X0(e,()=>o.openSession(O,"repair"));T=P.sessionTicket,N=mb(U),w.add(hb(P.sessionTicket)),h(P.notice)},close:U}:void 0,I={...n===void 0?{}:{retryTicket:n},onRetryTicket:O=>{f=O},session:()=>b,repairSession:()=>T};if(u!==void 0){let O=new xp(u.transport,o,I);return{diagnosis:{model:u.diagnosisModel,caps:l.caps.diagnosis,transport:O,...x===void 0?{}:{session:x},...y===void 0?{}:{claim:y}},repairModel:u.repairModel,repairCaps:l.caps.repair,...F===void 0?{}:{repairSession:F},destination:u.destination,ticket:()=>f,sessions:()=>[...w],client:o,status:a}}let C=o.transport({...I,jobs:l.jobs===!0,onProgress:KW(e),onRestart:()=>e.io.print(" The KwikQA service restarted while the model was working; sending the request again (nothing was charged)."),...e.sleep===void 0?{}:{sleep:e.sleep}}),A=n!==void 0&&l.models.escalation!==void 0&&l.caps.escalation!==void 0,M=A?l.models.escalation:void 0,$=A?l.caps.escalation:void 0,j=!A&&x!==void 0&&l.models.escalation!==void 0&&l.caps.escalation!==void 0?{model:l.models.escalation,caps:l.caps.escalation}:void 0;return{diagnosis:{model:M??l.models.diagnosis,caps:$??l.caps.diagnosis,transport:C,...x===void 0?{}:{session:x},...j===void 0?{}:{escalation:j},...y===void 0?{}:{claim:y}},repairModel:M??l.models.repair,repairCaps:$??l.caps.repair,...F===void 0?{}:{repairSession:F},destination:"the KwikQA service, which forwards it to OpenRouter",ticket:()=>f,sessions:()=>[...w],client:o,status:a}}var qW=3e4;function GW(e){let t=Math.floor(e/1e3),n=Math.floor(t/60);return n===0?`${t}s`:`${n}m ${String(t%60).padStart(2,"0")}s`}function KW(e){let t=0;return n=>{let r=Math.floor(n/qW);r<=t||(t=r,e.io.print(` The model is still working (${GW(n)})\u2026`))}}function ts(e,t,n){let r=async(s,o)=>{for(let a of s)e.io.print(a);return n!==!1?(e.io.print(`${o} yes (${n===!0?"--yes":n})`),!0):e.io.confirm(o)};return{approveDiagnosis:s=>r(Kd("diagnosis",s,t),"Send this request?"),approveDiagnoses:s=>{let[o]=s;return s.length===1&&o!==void 0?r(Kd("diagnosis",o,t),"Send this request?"):r([`${s.length} diagnosis requests, one for each group of failures with a shared cause:`,...s.flatMap((a,d)=>["",`Request ${d+1} of ${s.length}`,...Kd("diagnosis",a,t)])],`Send these ${s.length} requests?`)},approveRepairRequest:s=>r(Kd("repair proposal",s,t),"Send this request?"),approveApplication:async(s,o)=>{for(let a of Ep(s,o))e.io.print(a);return e.io.confirm("Apply this patch?")},approveBaseline:s=>r(["This repair changes shared test support, so the tests that use it first run once on the current code. Validation then compares each with how it stood before the patch.",...Wd(s,"baseline")],"Run them now?")}}async function xo(e,t,n,r,s){let o=new Set(r),a=await cb({run:{...n,logicalTests:n.logicalTests.filter(l=>o.has(l.logicalTestId))},workspaceRoot:t,repositoryRoot:await an(t),captureId:`${s.purpose}-${n.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest"}`,env:e.env,probe:!1});if(a.kind!=="ready")return{kind:"unavailable",message:a.message};e.io.print(""),e.io.print(s.intro);for(let l of a.prepared.description)e.io.print(l);if(s.approvedBy!==void 0)e.io.print(`${s.question} yes (${s.approvedBy})`);else if(!await e.io.confirm(s.question))return{kind:"declined"};let d=await ub(a.prepared,e.env);return e.io.print(d.outcome.message),d.outcome.kind==="failed"?{kind:"unavailable",message:d.outcome.message}:{kind:"rerun",failedAgain:d.outcome.failedAgain??[]}}function rt(e,t,n={}){e.io.print("");let r=U0("run"in t?t.run:void 0);r!==void 0&&t.record?.command!=="validate"&&e.io.print(r);let s=t.record?.clusters??[];if(s.length>1&&t.record?.command!=="validate")for(let l of B0(s,"run"in t?t.run:void 0))e.io.print(l);else if(t.record?.diagnosis!==void 0&&t.record.command!=="validate"){for(let l of fb(t.record.diagnosis))e.io.print(l);e.io.print("")}e.io.print(`Result: ${t.outcome} (${t.reasonCode})`),e.io.print(t.message);let o=bt(e.env),a=H0("run"in t?t.run:void 0,o);a!==void 0&&e.io.print(a);let d=V0(t.record,t.outcome,o,"run"in t?t.run:void 0,n);return d!==void 0&&e.io.print(d),t.recordPath!==void 0&&e.io.print(`Record: ${t.recordPath}`),GE(t.outcome)}async function pn(e,t,n,r){await D0(e.io,t.client,t.status,n),await Gd(t.client,t.status,e.env,[r])}async function ns(e,t){let n=L0(t),r=await Dn(e.env);if(r===void 0)return;let s=new Ht(pr(e.env,r.apiUrl),r.token,e.fetch),o;try{o=await s.status()}catch{return}await pn(e,{client:s,status:o},n,Vr("validation",t.record,e.env))}var Y0=600;function WW(e){let t=e.KWIKQA_CI_WAIT_SECONDS?.trim();if(t===void 0||t==="")return Y0;let n=Number(t);return Number.isFinite(n)&&n>=0?Math.min(n,3600):Y0}async function X0(e,t){let n=wo(e),r=WW(e.env),s=0;for(;;)try{return await t()}catch(o){if(!(o instanceof nt)||o.code!=="ci-concurrency")throw o;let a=Math.min(o.retryAfterSeconds??30,300)+Math.floor(Math.random()*5);if(s+a>r)throw o;e.io.print(` KwikQA: ${o.message} Waiting ${a} seconds for a free CI slot.`),await n(a*1e3),s+=a}}async function wb(e){let t=await XW(e.cwd),n=nC(t,"kwikqa.config.json");if(await Zi(n))e.io.print("kwikqa.config.json already exists; review it to change what KwikQA may edit.");else{let f=hw({repositoryPaths:await cy(t)});e.io.print("Proposed kwikqa.config.json (what KwikQA may edit when repairing tests):");for(let m of f.canonicalContents.trimEnd().split(`
|
|
277
|
+
`))e.io.print(` ${m}`);for(let m of[...f.reasons,...f.ambiguities])e.io.print(` - ${m}`);await e.io.confirm("Write kwikqa.config.json?")&&(await QW(n,f.canonicalContents,{flag:"wx"}),e.io.print("Wrote kwikqa.config.json. Commit it so the policy is reviewed like code."))}let r=nC(t,".gitignore"),s=await Zi(r)?await YW(r,"utf8"):"",o=f=>f.trim().replace(/^\//,"").replace(/\/$/,""),a=new Set(s.split(/\r?\n/).map(o)),d=[{entry:".kwikqa/",what:"local run records"},{entry:Ls,what:"the failure report"}].filter(f=>!a.has(o(f.entry))),l=d.map(f=>`${f.entry} (${f.what})`).join(" and ");d.length>0&&await e.io.confirm(`Add ${l} to .gitignore?`)&&await JW(r,`
|
|
278
278
|
${d.map(f=>f.entry).join(`
|
|
279
279
|
`)}
|
|
280
|
-
`);let c=new Set((await WA(t)).map(f=>f.framework)),u=f=>c.size===0||c.has(f),p=bt(e.env);return u("playwright")&&(e.io.print(""),e.io.print("Playwright: add a JSON reporter to playwright.config so KwikQA can read your runs:"),e.io.print(' reporter: [["list"], ["json", { outputFile: "test-results/kwikqa-report.json" }]],'),e.io.print(' use: { trace: "retain-on-failure" },')),u("cypress")&&(e.io.print(""),e.io.print(`Cypress: with kwikqa installed (${Gw(e.env,"kwikqa")}), set KwikQA's reporter in cypress.config`),e.io.print("so every attempt and its code frame is kept:"),e.io.print(' reporter: "node_modules/kwikqa/dist/cypress-reporter.cjs",'),e.io.print(` Mochawesome and JUnit reports work too: ${p} analyze --report mochawesome-report`)),u("webdriverio")&&(e.io.print(""),e.io.print(`WebdriverIO: with kwikqa installed (${Gw(e.env,"kwikqa")}), add KwikQA's reporter in wdio.conf:`),e.io.print(' import KwikqaReporter from "kwikqa/wdio-reporter";'),e.io.print(' reporters: ["spec", [KwikqaReporter, {}]],'),e.io.print(` @wdio/json-reporter and JUnit reports work too: ${p} analyze --report <directory>`)),(c.has("cypress")||c.has("webdriverio"))&&(e.io.print(""),e.io.print(`Then \`${p} analyze --capture\` re-runs failing specs and records each failure's page.`)),z.ok}import{realpath as iC}from"node:fs/promises";import{isAbsolute as QW,relative as sC,resolve as rC,sep as ZW}from"node:path";async function bb(e,t){return zt(e,async()=>{let n=await iC(e.cwd);if(t.output!==void 0&&t.html!==!0)return e.io.error("--output names where --html writes the report; add --html."),z.usage;let r=t.html===!0?await hi(n,t.output):void 0;if(r?.kind==="refused")return e.io.error(r.message),z.usage;let s=await Ur(e,n,t.report);if(t.capture===!0&&!e.io.interactive&&!t.yes)return e.io.error("Capturing re-runs your failing tests: run in a terminal, or pass --yes."),z.usage;let o=t.local?void 0:await jn(e,"analysis");if(o!==void 0&&"exit"in o)return Br(e,o);if(o!==void 0&&!e.io.interactive&&!t.yes)return e.io.error("Sending evidence needs approval: run in a terminal, or pass --yes, or use --local."),z.usage;let a=t.capture===!0?await tC(e,n,s,{yes:t.yes,probe:t.probe!==!1,...t.framework===void 0?{}:{framework:t.framework}}):void 0,d=a?.reportPath??s,l=await $r(n),c=await $d({reportPath:d,...t.framework===void 0?{}:{framework:t.framework},...a?.probePath===void 0?{}:{probePath:a.probePath},workspaceRoot:n,...l.kind==="read"?{gitRoot:l.status.gitRoot}:{},evidencePolicy:es(o),includeChangeHistory:t.changes!==!1,...o===void 0?{}:{remote:o.diagnosis},interaction:ts(e,o?.destination??"",t.yes)}),u=rt(e,c),p=r===void 0?u:await eJ(e,n,r.path,c,u);return o!==void 0&&await pn(e,o,Pp(c),_p(c.record,e.env,o.sessions())),p})}async function Cp(e,t,n,r){let s=await Qh(n,r);if(s.kind==="refused"){e.io.error(s.message);return}let o=sC(t,n),a=o.startsWith("..")||QW(o)?n:o;return e.io.print(`Report: ${a}`),a}async function eJ(e,t,n,r,s){if(r.run===void 0||r.record===void 0)return e.io.error("No failure report: the test report could not be read."),s;let o=Ms(vb(r.run,r.record,r));return await Cp(e,t,n,o)===void 0?z.usage:s}function vb(e,t,n){return iu({run:e,record:t,...n.detail===void 0?{}:{detail:n.detail},kwikqaVersion:Ji})}async function kb(e,t){let n=await iC(e.cwd),r=bt(e.env);if(t.run!==void 0&&!/^run_[a-f0-9]{24}$/.test(t.run))return e.io.error("--run takes a run id as named under .kwikqa/runs/, such as run_0123456789abcdef01234567."),z.usage;let s=await hi(n,t.output);if(s.kind==="refused")return e.io.error(s.message),z.usage;let o=t.run??await sw(n),a=o===void 0?[]:await Yu(n,o),d=h=>[...a].reverse().find(h),l=d(h=>h.command==="analyze")??d(h=>h.command==="fix"&&h.clusters!==void 0);if(l===void 0)return e.io.error(o===void 0?`No analysis is recorded here yet. Run \`${r} analyze\` first.`:`Run ${o} has no recorded analysis. Run \`${r} analyze\` first.`),z.usage;let c=d(h=>h.command!=="analyze"&&h.recordedAt>l.recordedAt),u=l.inputs??{report:sC(n,await Ur(e,n)).split(ZW).join("/"),changeHistory:!0,currentDiff:!1,maxPacketBytes:Ro.maxPacketBytes},p=await $r(n),f=await aw({reportPath:rC(n,u.report),...u.framework===void 0?{}:{framework:u.framework},workspaceRoot:n,...p.kind==="read"?{gitRoot:p.status.gitRoot}:{},evidencePolicy:{...Ro,maxPacketBytes:u.maxPacketBytes},includeChangeHistory:u.changeHistory,includeCurrentDiff:u.currentDiff,...u.probe===void 0?{}:{probePath:rC(n,u.probe)}},(l.clusters??[]).map(h=>h.clusterId));if(f.kind==="unreadable"||f.run.runId!==l.runId)return e.io.error(`The test report this analysis read (${u.report}) has changed or is gone, so its tests can't be shown. Run \`${r} analyze --html\` on the current report.`),z.failed;let m=Ms(iu({run:f.run,record:l,...f.detail===void 0?{}:{detail:f.detail},...c===void 0?{}:{repair:c},kwikqaVersion:Ji}));return await Cp(e,n,s.path,m)===void 0?z.usage:z.ok}import{realpath as tJ}from"node:fs/promises";import{sep as nJ}from"node:path";async function rJ(e,t,n,r){if(t)return{notDiagnosed:"--local analyzes without asking a model."};if(await Dn(e.env)===void 0)return{notDiagnosed:r?`${n==="gitlab"?"the merge request comes from a fork, whose pipeline gets none of this project's variables":n==="azure"?"the pull request comes from a fork, and Azure Pipelines gives a fork's build no secrets unless the pipeline allows it":"the pull request comes from a fork, and GitHub gives its workflows no secrets"}, so there is no KWIKQA_TOKEN.`:`there is no KwikQA token. Set KWIKQA_TOKEN${n==="azure"?", mapped in the step's env,":n==="jenkins"?", bound with withCredentials,":""} to a CI token from ${Ln}account/ to diagnose failures.`};try{let s=await jn(e,"analysis");return"exit"in s?{notDiagnosed:s.messages.join(" "),...s.status===void 0?{}:{status:s.status}}:{setup:s}}catch(s){if(s instanceof nt)return{notDiagnosed:s.message};throw s}}async function Rb(e,t){return zt(e,async()=>{let n=await tJ(e.cwd),r=await hi(n,t.output);if(r.kind==="refused")return e.io.error(r.message),z.usage;let s=await Ri(e.env),o=s===void 0?zr(e.env):void 0,a=s===void 0&&o===void 0?Ai(e.env):void 0,d=s===void 0&&o===void 0&&a===void 0?Ci(e.env):void 0,l=s??o??a??d,c=await Ur(e,n,t.report),u=await rJ(e,t.local,s!==void 0?"github":o!==void 0?"azure":a!==void 0?"gitlab":d!==void 0?"jenkins":void 0,l?.pullRequest?.fork===!0);u.notDiagnosed!==void 0&&e.io.print(`Not diagnosed: ${u.notDiagnosed} Analyzing locally.`);let p=await $r(n),f=await $d({reportPath:c,...t.framework===void 0?{}:{framework:t.framework},workspaceRoot:n,...p.kind==="read"?{gitRoot:p.status.gitRoot}:{},evidencePolicy:es(u.setup),includeChangeHistory:t.changes!==!1,...u.setup===void 0?{}:{remote:u.setup.diagnosis},interaction:ts(e,u.setup?.destination??"",!0)}),m=await Wi(n)===void 0?{}:{ciFix:"policy"},h=rt(e,f,{ci:!0,...m}),g=f.run===void 0||f.record===void 0?void 0:vb(f.run,f.record,f),y=g===void 0?void 0:await Cp(e,n,r.path,Ms(g));u.setup!==void 0&&await pn(e,u.setup,Pp(f),_p(f.record,e.env,u.setup.sessions()));let w=u.notDiagnosed??(u.setup!==void 0&&f.reasonCode==="session-unavailable"?f.message:void 0),b=f.record?.clusters?.filter(N=>N.reasonCode==="diagnosed-in-another-job").length??0,v=qg({model:g,message:f.message,...b===0?{}:{diagnosedElsewhere:b},...w===void 0?{}:{notDiagnosed:w},...y===void 0?{}:{reportFile:y.split(nJ).join("/")},...l?.runUrl===void 0?{}:{runUrl:l.runUrl}}),R=g?.run.counts.find(N=>N.label==="Failed")?.value??0,x=g===void 0||R>0;s!==void 0?await ld(e.io,e.fetch,s,v,{failures:x}):o!==void 0?await Io(e.io,e.fetch,o,v,{failures:x}):a!==void 0?await wd(e.io,e.fetch,a,v,{failures:x}):d!==void 0?await vd(e.io,e.fetch,d,v,{failures:x}):e.io.print("Not running in GitHub Actions, Azure Pipelines, GitLab CI/CD, or Jenkins, the CI systems supported so far: no summary or comment.");let T=Zg({model:g,message:f.message,...u.notDiagnosed===void 0?{}:{notDiagnosed:u.notDiagnosed},...l===void 0?{}:{run:l}});return(u.setup?.status??u.status)?.entitlements?.alerts===!1?e.io.print("No Slack or Teams alert: they come with the team plans. See `npx kwikqa upgrade`."):await ey(e.io,e.fetch,wo(e),e.env,T,{when:t.notify??"on-failure",failures:x}),h})}import{realpath as Op}from"node:fs/promises";import{isAbsolute as aJ,join as $p,relative as fC,sep as dJ}from"node:path";function xb(e,t){return e.find(n=>n.repairable&&!t.includes(n.representativeId))}function iJ(e,t=80){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function sJ(e,t){let n=t.get(e.representativeId),r=n===void 0?void 0:`"${iJ(n)}"`,s=e.logicalTestIds.length;return s===1?`Failure group ${e.number} (${r??"1 failing test"})`:`Failure group ${e.number} (${s} failing tests${r===void 0?"":`, starting with ${r}`})`}function Xd(e){return e.trim().replace(/[.;:\s]+$/,"")}function oJ(e){switch(e.kind){case"published":return`published as pull request #${e.pullRequest}${e.url===void 0?"":`: ${e.url}`}`;case"not-opened":return`validated, but no pull request was opened: ${Xd(e.reason)}`;case"rolled-back":return`failed validation, so its patch was rolled back${e.retried?" after a retry":""}`;case"duplicate":return`duplicate of pull request #${e.pullRequest}, noted there; not counted`;case"held":return`held back, not counted: ${Xd(e.reason)}`;case"not-repaired":return`not repaired: ${Xd(e.reason)}`;case"conflicted":return`stopped: ${Xd(e.reason)}`}}function oC(e){return e.groups.map(t=>{let n=e.ends.get(t.representativeId),r=sJ(t,e.titles);return n!==void 0?`${r}: ${oJ(n)}.`:t.repairable?`${r}: not tried: ${e.stopped??"no repair was requested"}.`:`${r}: not repaired: ${Xd(t.message)}.`})}import{appendFile as aC}from"node:fs/promises";function _b(e){return e.kind==="opened"?{kind:"opened",number:e.number,...e.url===void 0?{}:{url:e.url}}:{kind:"not-opened",reason:e.reason}}function it(e,t=!0){return{reason:e,misconfigured:t}}var lC={noun:"pull request",sigil:"#"},dC={noun:"merge request",sigil:"!"};async function Ib(e,t,n,r,s=lC){if(t.kind==="open")return await r(t.number),{reason:`fix ${s.noun} ${s.sigil}${t.number} is already open for it, so no repair was requested; this run is noted there`,pullRequest:t.number};if(t.kind==="branch")return{reason:`its fix branch ${on(n)} is left from an earlier fix, without an open ${s.noun}, so no repair was requested; delete the branch to let KwikQA open a new fix`};t.kind==="unknown"&&e.io.print(`Couldn't check for an open fix ${s.noun}: ${t.reason}.`)}function Sb(e,t,n,r=lC){let s=`Fix ${r.noun}`;t.kind==="opened"?e.io.print(`${s}: opened ${r.sigil}${t.number}, a draft into ${n}${t.url===void 0?"":`: ${t.url}`}.`):t.kind==="skipped"?e.io.print(`No fix ${r.noun}: ${t.reason}.`):e.io.error(`No fix ${r.noun}: ${t.reason}.`)}function Tb(e){return(e.fix.repairProposal?.targets??[]).map(t=>({path:t.path,sourceSha256:t.sourceSha256,resultSha256:t.resultSha256}))}function cC(e,t){let{repository:n,runId:r,runAttempt:s,commit:o}=t;if(n===void 0||r===void 0||s===void 0||o===void 0)return"`kwikqa fix` in CI needs GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT, and GITHUB_SHA as GitHub Actions sets them.";let a={system:"GitHub Actions",ci:{system:"github-actions",repository:n,runId:r,runAttempt:s,commit:o.sha},checkout:{variable:"GITHUB_WORKSPACE",path:e.env.GITHUB_WORKSPACE||void 0}},d=t.pullRequest;if(d?.fork===!0)return{...a,host:{reason:`the pull request comes from a fork, and GitHub gives its workflows a read-only token, so no fix pull request can be opened. A maintainer can check out the pull request (\`gh pr checkout ${d.number}\`) and run \`npx kwikqa fix\``,misconfigured:!1,note:async()=>{t.summaryPath!==void 0&&await aC(t.summaryPath,`
|
|
280
|
+
`);let c=new Set((await WA(t)).map(f=>f.framework)),u=f=>c.size===0||c.has(f),p=bt(e.env);return u("playwright")&&(e.io.print(""),e.io.print("Playwright: add a JSON reporter to playwright.config so KwikQA can read your runs:"),e.io.print(' reporter: [["list"], ["json", { outputFile: "test-results/kwikqa-report.json" }]],'),e.io.print(' use: { trace: "retain-on-failure" },')),u("cypress")&&(e.io.print(""),e.io.print(`Cypress: with kwikqa installed (${Gw(e.env,"kwikqa")}), set KwikQA's reporter in cypress.config`),e.io.print("so every attempt and its code frame is kept:"),e.io.print(' reporter: "node_modules/kwikqa/dist/cypress-reporter.cjs",'),e.io.print(` Mochawesome and JUnit reports work too: ${p} analyze --report mochawesome-report`)),u("webdriverio")&&(e.io.print(""),e.io.print(`WebdriverIO: with kwikqa installed (${Gw(e.env,"kwikqa")}), add KwikQA's reporter in wdio.conf:`),e.io.print(' import KwikqaReporter from "kwikqa/wdio-reporter";'),e.io.print(' reporters: ["spec", [KwikqaReporter, {}]],'),e.io.print(` @wdio/json-reporter and JUnit reports work too: ${p} analyze --report <directory>`)),(c.has("cypress")||c.has("webdriverio"))&&(e.io.print(""),e.io.print(`Then \`${p} analyze --capture\` re-runs failing specs and records each failure's page.`)),z.ok}import{realpath as iC}from"node:fs/promises";import{isAbsolute as ZW,relative as sC,resolve as rC,sep as eJ}from"node:path";async function bb(e,t){return zt(e,async()=>{let n=await iC(e.cwd);if(t.output!==void 0&&t.html!==!0)return e.io.error("--output names where --html writes the report; add --html."),z.usage;let r=t.html===!0?await hi(n,t.output):void 0;if(r?.kind==="refused")return e.io.error(r.message),z.usage;let s=await Ur(e,n,t.report);if(t.capture===!0&&!e.io.interactive&&!t.yes)return e.io.error("Capturing re-runs your failing tests: run in a terminal, or pass --yes."),z.usage;let o=t.local?void 0:await jn(e,"analysis");if(o!==void 0&&"exit"in o)return Br(e,o);if(o!==void 0&&!e.io.interactive&&!t.yes)return e.io.error("Sending evidence needs approval: run in a terminal, or pass --yes, or use --local."),z.usage;let a=t.capture===!0?await tC(e,n,s,{yes:t.yes,probe:t.probe!==!1,...t.framework===void 0?{}:{framework:t.framework}}):void 0,d=a?.reportPath??s,l=await $r(n),c=await $d({reportPath:d,...t.framework===void 0?{}:{framework:t.framework},...a?.probePath===void 0?{}:{probePath:a.probePath},workspaceRoot:n,...l.kind==="read"?{gitRoot:l.status.gitRoot}:{},evidencePolicy:es(o),includeChangeHistory:t.changes!==!1,...o===void 0?{}:{remote:o.diagnosis},interaction:ts(e,o?.destination??"",t.yes)}),u=rt(e,c),p=r===void 0?u:await tJ(e,n,r.path,c,u);return o!==void 0&&await pn(e,o,Pp(c),_p(c.record,e.env,o.sessions())),p})}async function Cp(e,t,n,r){let s=await Qh(n,r);if(s.kind==="refused"){e.io.error(s.message);return}let o=sC(t,n),a=o.startsWith("..")||ZW(o)?n:o;return e.io.print(`Report: ${a}`),a}async function tJ(e,t,n,r,s){if(r.run===void 0||r.record===void 0)return e.io.error("No failure report: the test report could not be read."),s;let o=Ms(vb(r.run,r.record,r));return await Cp(e,t,n,o)===void 0?z.usage:s}function vb(e,t,n){return iu({run:e,record:t,...n.detail===void 0?{}:{detail:n.detail},kwikqaVersion:Ji})}async function kb(e,t){let n=await iC(e.cwd),r=bt(e.env);if(t.run!==void 0&&!/^run_[a-f0-9]{24}$/.test(t.run))return e.io.error("--run takes a run id as named under .kwikqa/runs/, such as run_0123456789abcdef01234567."),z.usage;let s=await hi(n,t.output);if(s.kind==="refused")return e.io.error(s.message),z.usage;let o=t.run??await sw(n),a=o===void 0?[]:await Yu(n,o),d=h=>[...a].reverse().find(h),l=d(h=>h.command==="analyze")??d(h=>h.command==="fix"&&h.clusters!==void 0);if(l===void 0)return e.io.error(o===void 0?`No analysis is recorded here yet. Run \`${r} analyze\` first.`:`Run ${o} has no recorded analysis. Run \`${r} analyze\` first.`),z.usage;let c=d(h=>h.command!=="analyze"&&h.recordedAt>l.recordedAt),u=l.inputs??{report:sC(n,await Ur(e,n)).split(eJ).join("/"),changeHistory:!0,currentDiff:!1,maxPacketBytes:Ro.maxPacketBytes},p=await $r(n),f=await aw({reportPath:rC(n,u.report),...u.framework===void 0?{}:{framework:u.framework},workspaceRoot:n,...p.kind==="read"?{gitRoot:p.status.gitRoot}:{},evidencePolicy:{...Ro,maxPacketBytes:u.maxPacketBytes},includeChangeHistory:u.changeHistory,includeCurrentDiff:u.currentDiff,...u.probe===void 0?{}:{probePath:rC(n,u.probe)}},(l.clusters??[]).map(h=>h.clusterId));if(f.kind==="unreadable"||f.run.runId!==l.runId)return e.io.error(`The test report this analysis read (${u.report}) has changed or is gone, so its tests can't be shown. Run \`${r} analyze --html\` on the current report.`),z.failed;let m=Ms(iu({run:f.run,record:l,...f.detail===void 0?{}:{detail:f.detail},...c===void 0?{}:{repair:c},kwikqaVersion:Ji}));return await Cp(e,n,s.path,m)===void 0?z.usage:z.ok}import{realpath as nJ}from"node:fs/promises";import{sep as rJ}from"node:path";async function iJ(e,t,n,r){if(t)return{notDiagnosed:"--local analyzes without asking a model."};if(await Dn(e.env)===void 0)return{notDiagnosed:r?`${n==="gitlab"?"the merge request comes from a fork, whose pipeline gets none of this project's variables":n==="azure"?"the pull request comes from a fork, and Azure Pipelines gives a fork's build no secrets unless the pipeline allows it":"the pull request comes from a fork, and GitHub gives its workflows no secrets"}, so there is no KWIKQA_TOKEN.`:`there is no KwikQA token. Set KWIKQA_TOKEN${n==="azure"?", mapped in the step's env,":n==="jenkins"?", bound with withCredentials,":""} to a CI token from ${Ln}account/ to diagnose failures.`};try{let s=await jn(e,"analysis");return"exit"in s?{notDiagnosed:s.messages.join(" "),...s.status===void 0?{}:{status:s.status}}:{setup:s}}catch(s){if(s instanceof nt)return{notDiagnosed:s.message};throw s}}async function Rb(e,t){return zt(e,async()=>{let n=await nJ(e.cwd),r=await hi(n,t.output);if(r.kind==="refused")return e.io.error(r.message),z.usage;let s=await Ri(e.env),o=s===void 0?zr(e.env):void 0,a=s===void 0&&o===void 0?Ai(e.env):void 0,d=s===void 0&&o===void 0&&a===void 0?Ci(e.env):void 0,l=s??o??a??d,c=await Ur(e,n,t.report),u=await iJ(e,t.local,s!==void 0?"github":o!==void 0?"azure":a!==void 0?"gitlab":d!==void 0?"jenkins":void 0,l?.pullRequest?.fork===!0);u.notDiagnosed!==void 0&&e.io.print(`Not diagnosed: ${u.notDiagnosed} Analyzing locally.`);let p=await $r(n),f=await $d({reportPath:c,...t.framework===void 0?{}:{framework:t.framework},workspaceRoot:n,...p.kind==="read"?{gitRoot:p.status.gitRoot}:{},evidencePolicy:es(u.setup),includeChangeHistory:t.changes!==!1,...u.setup===void 0?{}:{remote:u.setup.diagnosis},interaction:ts(e,u.setup?.destination??"",!0)}),m=await Wi(n)===void 0?{}:{ciFix:"policy"},h=rt(e,f,{ci:!0,...m}),g=f.run===void 0||f.record===void 0?void 0:vb(f.run,f.record,f),y=g===void 0?void 0:await Cp(e,n,r.path,Ms(g));u.setup!==void 0&&await pn(e,u.setup,Pp(f),_p(f.record,e.env,u.setup.sessions()));let w=u.notDiagnosed??(u.setup!==void 0&&f.reasonCode==="session-unavailable"?f.message:void 0),b=f.record?.clusters?.filter(N=>N.reasonCode==="diagnosed-in-another-job").length??0,v=qg({model:g,message:f.message,...b===0?{}:{diagnosedElsewhere:b},...w===void 0?{}:{notDiagnosed:w},...y===void 0?{}:{reportFile:y.split(rJ).join("/")},...l?.runUrl===void 0?{}:{runUrl:l.runUrl}}),R=g?.run.counts.find(N=>N.label==="Failed")?.value??0,x=g===void 0||R>0;s!==void 0?await ld(e.io,e.fetch,s,v,{failures:x}):o!==void 0?await Io(e.io,e.fetch,o,v,{failures:x}):a!==void 0?await wd(e.io,e.fetch,a,v,{failures:x}):d!==void 0?await vd(e.io,e.fetch,d,v,{failures:x}):e.io.print("Not running in GitHub Actions, Azure Pipelines, GitLab CI/CD, or Jenkins, the CI systems supported so far: no summary or comment.");let T=Zg({model:g,message:f.message,...u.notDiagnosed===void 0?{}:{notDiagnosed:u.notDiagnosed},...l===void 0?{}:{run:l}});return(u.setup?.status??u.status)?.entitlements?.alerts===!1?e.io.print("No Slack or Teams alert: they come with the team plans. See `npx kwikqa upgrade`."):await ey(e.io,e.fetch,wo(e),e.env,T,{when:t.notify??"on-failure",failures:x}),h})}import{realpath as Op}from"node:fs/promises";import{isAbsolute as dJ,join as $p,relative as fC,sep as lJ}from"node:path";function xb(e,t){return e.find(n=>n.repairable&&!t.includes(n.representativeId))}function sJ(e,t=80){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function oJ(e,t){let n=t.get(e.representativeId),r=n===void 0?void 0:`"${sJ(n)}"`,s=e.logicalTestIds.length;return s===1?`Failure group ${e.number} (${r??"1 failing test"})`:`Failure group ${e.number} (${s} failing tests${r===void 0?"":`, starting with ${r}`})`}function Xd(e){return e.trim().replace(/[.;:\s]+$/,"")}function aJ(e){switch(e.kind){case"published":return`published as pull request #${e.pullRequest}${e.url===void 0?"":`: ${e.url}`}`;case"not-opened":return`validated, but no pull request was opened: ${Xd(e.reason)}`;case"rolled-back":return`failed validation, so its patch was rolled back${e.retried?" after a retry":""}`;case"duplicate":return`duplicate of pull request #${e.pullRequest}, noted there; not counted`;case"held":return`held back, not counted: ${Xd(e.reason)}`;case"not-repaired":return`not repaired: ${Xd(e.reason)}`;case"conflicted":return`stopped: ${Xd(e.reason)}`}}function oC(e){return e.groups.map(t=>{let n=e.ends.get(t.representativeId),r=oJ(t,e.titles);return n!==void 0?`${r}: ${aJ(n)}.`:t.repairable?`${r}: not tried: ${e.stopped??"no repair was requested"}.`:`${r}: not repaired: ${Xd(t.message)}.`})}import{appendFile as aC}from"node:fs/promises";function _b(e){return e.kind==="opened"?{kind:"opened",number:e.number,...e.url===void 0?{}:{url:e.url}}:{kind:"not-opened",reason:e.reason}}function it(e,t=!0){return{reason:e,misconfigured:t}}var lC={noun:"pull request",sigil:"#"},dC={noun:"merge request",sigil:"!"};async function Ib(e,t,n,r,s=lC){if(t.kind==="open")return await r(t.number),{reason:`fix ${s.noun} ${s.sigil}${t.number} is already open for it, so no repair was requested; this run is noted there`,pullRequest:t.number};if(t.kind==="branch")return{reason:`its fix branch ${on(n)} is left from an earlier fix, without an open ${s.noun}, so no repair was requested; delete the branch to let KwikQA open a new fix`};t.kind==="unknown"&&e.io.print(`Couldn't check for an open fix ${s.noun}: ${t.reason}.`)}function Sb(e,t,n,r=lC){let s=`Fix ${r.noun}`;t.kind==="opened"?e.io.print(`${s}: opened ${r.sigil}${t.number}, a draft into ${n}${t.url===void 0?"":`: ${t.url}`}.`):t.kind==="skipped"?e.io.print(`No fix ${r.noun}: ${t.reason}.`):e.io.error(`No fix ${r.noun}: ${t.reason}.`)}function Tb(e){return(e.fix.repairProposal?.targets??[]).map(t=>({path:t.path,sourceSha256:t.sourceSha256,resultSha256:t.resultSha256}))}function cC(e,t){let{repository:n,runId:r,runAttempt:s,commit:o}=t;if(n===void 0||r===void 0||s===void 0||o===void 0)return"`kwikqa fix` in CI needs GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT, and GITHUB_SHA as GitHub Actions sets them.";let a={system:"GitHub Actions",ci:{system:"github-actions",repository:n,runId:r,runAttempt:s,commit:o.sha},checkout:{variable:"GITHUB_WORKSPACE",path:e.env.GITHUB_WORKSPACE||void 0}},d=t.pullRequest;if(d?.fork===!0)return{...a,host:{reason:`the pull request comes from a fork, and GitHub gives its workflows a read-only token, so no fix pull request can be opened. A maintainer can check out the pull request (\`gh pr checkout ${d.number}\`) and run \`npx kwikqa fix\``,misconfigured:!1,note:async()=>{t.summaryPath!==void 0&&await aC(t.summaryPath,`
|
|
281
281
|
### KwikQA: no fix pull request for a fork
|
|
282
282
|
|
|
283
283
|
GitHub gives a fork's workflows a read-only token, so KwikQA can't open a fix pull request here. A maintainer can check out this pull request (\`gh pr checkout ${d.number}\`) and run \`npx kwikqa fix\` on their machine.
|
|
@@ -285,9 +285,9 @@ GitHub gives a fork's workflows a read-only token, so KwikQA can't open a fix pu
|
|
|
285
285
|
### KwikQA opened a fix
|
|
286
286
|
|
|
287
287
|
Draft pull request ${w}, into ${Re(l.branch)}, with a repair validated on this runner.
|
|
288
|
-
`).catch(()=>{})}return _b(y)}}}}function uC(e,t){let{projectId:n,repositoryId:r,buildId:s,jobAttempt:o,commit:a}=t;if(n===void 0||r===void 0||s===void 0||o===void 0||a===void 0)return"`kwikqa fix` in CI needs System.TeamProjectId, Build.Repository.ID, Build.BuildId, System.JobAttempt, and Build.SourceVersion as Azure Pipelines sets them.";let d={system:"Azure Pipelines",ci:{system:"azure-pipelines",repository:`${n}/${r}`,runId:s,runAttempt:o,commit:a.sha.toLowerCase()},checkout:{variable:"BUILD_SOURCESDIRECTORY",path:e.env.BUILD_SOURCESDIRECTORY||void 0}};if(t.provider!=="TfsGit")return{...d,host:it(`the repository is on ${t.provider||"another host"}, and from Azure Pipelines KwikQA opens fix pull requests only on Azure Repos`)};let l=t.pullRequest;if(l?.fork===!0)return{...d,host:it("the pull request comes from a fork, whose build gets no secrets by default, so no fix pull request is opened. A maintainer can check out its branch and run `npx kwikqa fix`",!1)};let c=l!==void 0?t.pullRequestHead===void 0?void 0:{branch:t.pullRequestHead.ref,commit:t.pullRequestHead.sha}:t.ref?.startsWith("refs/heads/")===!0?{branch:t.ref.slice(11),commit:a.sha.toLowerCase()}:void 0;if(c===void 0)return{...d,host:l===void 0?it("this build isn't on a branch, so there's no branch for a fix pull request",!1):it("the build doesn't name the pull request's source branch and commit (System.PullRequest.SourceBranch, System.PullRequest.SourceCommitId)")};if(t.token===void 0)return{...d,host:it("SYSTEM_ACCESSTOKEN isn't set; add `SYSTEM_ACCESSTOKEN: $(System.AccessToken)` to the step's env")};if(t.collectionUrl===void 0)return{...d,host:it("System.CollectionUri isn't what Azure Pipelines sets")};let u={collectionUrl:t.collectionUrl,projectId:n,repositoryId:r,token:t.token},p=t.runUrl===void 0?{}:{runUrl:t.runUrl};return{...d,host:{fixInReview:async f=>{let m=Or(f);return Ib(e,await Yg(e.fetch,u,m),m,h=>Xg(e.io,e.fetch,u,{number:h,fingerprint:m},{...p,commit:a.sha}))},publish:async(f,m,h)=>{let g=Tb(f);if(g.length===0)return e.io.print("No fix pull request: the fix's record names no repaired file."),{kind:"not-opened",reason:"the fix's record names no repaired file"};let y=ud(f.fix),w=await Qg(e.io,e.fetch,{...u,base:c,workspaceRoot:m.root,gitRoot:m.gitRoot,targets:g,fingerprint:y,title:Si(f.fix),description:fd({fix:f.fix,...f.validation===void 0?{}:{validation:f.validation},...f.plan===void 0?{}:{plan:f.plan},fingerprint:y,...p,commit:a.sha,host:"azure-repos",earlier:h}),commitMessage:pd(f.fix,y)});return Sb(e,w,c.branch),_b(w)}}}}function pC(e,t){let{repository:n,jobId:r,commit:s}=t;if(n===void 0||r===void 0||s===void 0)return"`kwikqa fix` in CI needs CI_PROJECT_PATH, CI_JOB_ID, and CI_COMMIT_SHA as GitLab CI/CD sets them.";let o={system:"GitLab CI/CD",ci:{system:"gitlab-ci",repository:n,runId:r,runAttempt:1,commit:s.sha},checkout:{variable:"CI_PROJECT_DIR",path:e.env.CI_PROJECT_DIR||void 0}},a="A maintainer can check out its branch and run `npx kwikqa fix` on their machine";if(t.pullRequest?.fork===!0)return{...o,host:it(`the merge request comes from a fork, whose pipeline gets none of this project's variables, so no fix merge request is opened. ${a}`,!1)};if(t.sourceInOtherProject===!0)return{...o,host:it(`the merge request's branch is in another project, such as a fork, which this project's token can't push to. ${a}`,!1)};let d=t.pullRequestHead!==void 0?{branch:t.pullRequestHead.ref,commit:t.pullRequestHead.sha}:t.commitBranch!==void 0?{branch:t.commitBranch,commit:s.sha}:void 0;if(d===void 0)return{...o,host:e.env.CI_MERGE_REQUEST_IID===void 0||e.env.CI_MERGE_REQUEST_IID===""?it("this pipeline isn't on a branch, so there's no branch for a fix merge request",!1):it("the pipeline doesn't name the merge request's source commit (CI_MERGE_REQUEST_SOURCE_BRANCH_SHA)")};if(t.token===void 0)return{...o,host:it("GITLAB_TOKEN isn't set; add a token with the `api` scope and at least the Developer role as a masked CI/CD variable")};if(t.apiUrl===void 0||t.projectId===void 0)return{...o,host:it("CI_API_V4_URL or the project isn't what GitLab sets")};let l={apiUrl:t.apiUrl,project:t.projectId,token:t.token},c=t.runUrl===void 0?{}:{runUrl:t.runUrl};return{...o,host:{fixInReview:async u=>{let p=Or(u);return Ib(e,await ry(e.fetch,l,p),p,f=>iy(e.io,e.fetch,l,{number:f,fingerprint:p},{...c,commit:s.sha}),dC)},publish:async(u,p,f)=>{let m=Tb(u);if(m.length===0)return e.io.print("No fix merge request: the fix's record names no repaired file."),{kind:"not-opened",reason:"the fix's record names no repaired file"};let h=ud(u.fix),g=await sy(e.io,e.fetch,{...l,base:d,workspaceRoot:p.root,gitRoot:p.gitRoot,targets:m,fingerprint:h,title:Si(u.fix),description:fd({fix:u.fix,...u.validation===void 0?{}:{validation:u.validation},...u.plan===void 0?{}:{plan:u.plan},fingerprint:h,...c,commit:s.sha,host:"gitlab",earlier:f}),commitMessage:pd(u.fix,h)});return Sb(e,g,d.branch,dC),_b(g)}}}}async function Pb(e,t){if(!e.io.interactive){let n=await Ri(e.env);if(n!==void 0)return Ab(e,t,cC(e,n));let r=zr(e.env);if(r!==void 0)return Ab(e,t,uC(e,r));let s=Ai(e.env);return s!==void 0?Ab(e,t,pC(e,s)):(e.io.error(Ci(e.env)===void 0?"`kwikqa fix` needs a terminal: every request and patch is approved by a person. In GitHub Actions, Azure Pipelines, and GitLab CI/CD, a committed ci.fix policy approves it instead.":"`kwikqa fix` needs a terminal on Jenkins: a committed ci.fix policy approves it only in GitHub Actions, Azure Pipelines, and GitLab CI/CD, so far."),z.usage)}return zt(e,async()=>{let n=await Op(e.cwd),r=await Jd(n),s=t.retry?r.pendingRetry:void 0;if(t.retry&&s===void 0)return e.io.error("There is no failed validation to retry."),z.usage;let o=s===void 0?void 0:r.tickets?.[s.repairSessionId],a=await jn(e,"repair",o);if("exit"in a)return Br(e,a);let d=s===void 0?await Ur(e,n,t.report):void 0,l=d===void 0?void 0:await eC(n,r,d);l!==void 0&&e.io.print(`Using the evidence captured by \`analyze --capture\`: ${fC(n,l.reportPath)}`);let c=await vp({reportPath:s===void 0?l?.reportPath??d??$p(n,"report.json"):$p(n,s.reportPath),...t.framework===void 0?{}:{framework:t.framework},...l?.probePath===void 0?{}:{probePath:l.probePath},workspaceRoot:n,evidencePolicy:es(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:{...ts(e,a.destination,!1),confirmFailure:(g,y)=>xo(e,n,g,y,{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}}),u=c.record?.repair?.repairSessionId,p=a.ticket(),{pendingRetry:f,...m}=r;await Yd(n,{...s===void 0?r:m,...u===void 0||p===void 0?{}:{tickets:{...r.tickets,[u]:p}}});let h=rt(e,c);return await pn(e,a,ko(c),Vr("fix",c.record,e.env,a.sessions())),h})}var Np="the committed ci.fix policy",Hr={ciFix:"running"};function lJ(e,t,n,r){return{...ts(e,t,Np),approveApplication:async(s,o)=>{for(let d of Ep(s,o,{validatedNow:!0}))e.io.print(d);let{approver:a}=s;return a.kind!=="ci-policy"?!1:(r(o,a),e.io.print(`Apply this patch? yes (${Np}, ${a.policyHash.slice(0,12)}, for run ${a.runId} attempt ${a.runAttempt}, on this runner's checkout)`),!0)},confirmFailure:(s,o)=>xo(e,n,s,o,{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?",approvedBy:Np})}}async function cJ(e,t){try{let n=fC(await Op(e),await Op(t));return n===""||!aJ(n)&&n!==".."&&!n.startsWith(`..${dJ}`)}catch{return!1}}function mC(e,t,n,r,s){let o={};return{approved:o,attempt:(a,d)=>vp({reportPath:d.reportPath,...t.framework===void 0?{}:{framework:t.framework},workspaceRoot:n,evidencePolicy:es(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:lJ(e,a.destination,n,(l,c)=>{o.plan=l,o.approver=c}),reuseDiagnosis:d.retryRepairSessionId===void 0,proposeOnly:t.proposeOnly,...d.retryRepairSessionId===void 0?{}:{retryRepairSessionId:d.retryRepairSessionId},...d.oneGroup===void 0?{}:{oneGroup:d.oneGroup},...d.reuse===void 0?{}:{reuseRecords:d.reuse},ci:r,fixInReview:l=>s.fixInReview(l)}),validate:()=>Ud({workspaceRoot:n,checkGroup:(a,d)=>xo(e,n,a,d,{purpose:"group",intro:`The repair passed. Re-run the ${d.length===1?"other test":`${d.length} other tests`} with the same cause once, to see whether the patch fixed ${d.length===1?"it":"them"} too. The patch stays either way.`,question:"Re-run them now?",approvedBy:Np})})}}async function uJ(e,t,n,r){let s=(await Wi(t))?.maxPullRequestsPerRun??1,o=Math.max(1,n.entitlements?.maxPullRequestsPerRun??1);return s>o&&e.io.print(`The ci.fix policy asks for up to ${s} fix pull requests a run, but this plan allows ${o}, so this run uses ${o}.`),r.group!==void 0||r.proposeOnly?1:Math.min(s,o)}async function Ab(e,t,n){if(t.retry)return e.io.error("In CI, the ci.fix policy's `retry` decides whether a failed validation is retried; --retry is for a terminal."),z.usage;if(typeof n=="string")return e.io.error(n),z.usage;let{ci:r,checkout:s,host:o}=n;if(s.path===void 0||!await cJ(s.path,e.cwd))return e.io.error(`\`kwikqa fix\` without a terminal patches only the runner's checkout, inside ${s.variable}.`),z.usage;if("reason"in o){let a=`No fix in CI: ${o.reason}.`;return o.misconfigured?(e.io.error(a),z.usage):(e.io.print(a),await o.note?.(),z.ok)}return zt(e,async()=>{let a=await Op(e.cwd),d=await jn(e,"repair");if("exit"in d)return Br(e,d);if(d.status.entitlements?.ciFix==="none")return e.io.error("Draft pull requests from CI come with Pro and the team plans, not this one: see `npx kwikqa upgrade`. Nothing was requested."),z.account;let l=await Ur(e,a,t.report),c=await uJ(e,a,d.status,t);if(c>1)return hJ(e,t,{root:a,reportPath:l,ci:r,host:o,limit:c});let u=mC(e,t,a,r,o),p=await u.attempt(d,{reportPath:l}),f=rt(e,p,Hr);if(await pn(e,d,ko(p),Vr("fix",p.record,e.env,d.sessions())),p.outcome!=="awaiting-validation")return f;let m=await u.validate();f=rt(e,m,Hr),await ns(e,m);let h=m.record?.repair;if(h?.retryAvailable===!0&&h.retryReportPath!==void 0){if((await Wi(a))?.retry!==!0)return e.io.print("The ci.fix policy doesn't retry a failed validation, so the patch was rolled back and nothing else was sent."),f;let g=d.ticket(),y=await jn(e,"repair",g);if("exit"in y)return Br(e,y);if(p=await u.attempt(y,{reportPath:$p(a,h.retryReportPath),retryRepairSessionId:h.repairSessionId}),f=rt(e,p,Hr),await pn(e,y,ko(p),Vr("fix",p.record,e.env,y.sessions())),p.outcome!=="awaiting-validation")return f;m=await u.validate(),f=rt(e,m,Hr),await ns(e,m)}if(m.outcome==="repaired"&&p.record!==void 0){let g=await o.publish({fix:p.record,...m.record===void 0?{}:{validation:m.record},...u.approved.plan===void 0?{}:{plan:u.approved.plan}},{root:a,gitRoot:await an(a)},[]);await Gd(d.client,d.status,e.env,[Qw(p.record,g.kind==="opened",e.env)])}return f})}function pJ(e){return e.reasonCode==="application-recovery-required"?{kind:"conflicted",reason:e.message}:{kind:"not-repaired",reason:e.message}}async function fJ(e,t,n,r,s){let o=await n.attempt(r,{reportPath:t.reportPath,oneGroup:{tried:s.tried},reuse:s.reuse}),a=rt(e,o,Hr);await pn(e,r,ko(o),Vr("fix",o.record,e.env,r.sessions()));let d=o.fixGroups?.groups,l=o.record,c=o.fixGroups?.attempted;if(o.outcome!=="awaiting-validation")return{groups:d,exit:a,...l===void 0?{}:{record:l},...c===void 0?{}:{attempted:{representative:c,end:pJ(o)}}};if(c===void 0)throw new Error("A repair was applied without the failure group it repaired.");let u=await n.validate();a=rt(e,u,Hr),await ns(e,u);let p=!1,f=u.record?.repair;if(f?.retryAvailable===!0&&f.retryReportPath!==void 0)if((await Wi(t.root))?.retry===!0){let v=await jn(e,"repair",r.ticket());if("exit"in v)return{groups:d,exit:a,record:l,attempted:{representative:c,end:{kind:"rolled-back",retried:!1}},refusal:Br(e,v)};if(p=!0,o=await n.attempt(v,{reportPath:$p(t.root,f.retryReportPath),retryRepairSessionId:f.repairSessionId,oneGroup:{tried:[],retryOf:c}}),a=rt(e,o,Hr),await pn(e,v,ko(o),Vr("fix",o.record,e.env,v.sessions())),o.outcome!=="awaiting-validation")return{groups:d,exit:a,record:o.record,attempted:{representative:c,end:{kind:"rolled-back",retried:p}}};u=await n.validate(),a=rt(e,u,Hr),await ns(e,u)}else e.io.print("The ci.fix policy doesn't retry a failed validation, so the patch was rolled back and nothing else was sent.");let m=u.record?.repair?.transactionId??o.record?.repair?.transactionId,h=n.approved.approver;if(u.reasonCode==="rollback-conflicted")return{groups:d,exit:a,attempted:{representative:c,end:{kind:"conflicted",reason:u.message}}};if(u.outcome!=="repaired"||o.record===void 0){let v=u.outcome==="repair-failed"?{kind:"rolled-back",retried:p}:{kind:"not-repaired",reason:u.message};return{groups:d,exit:a,record:l,attempted:{representative:c,end:v}}}if(m===void 0||h===void 0)return{groups:d,exit:a,attempted:{representative:c,end:{kind:"conflicted",reason:"the validated patch isn't recorded, so it can't be reverted"}}};let g=n.approved.plan,y=await t.host.publish({fix:o.record,...u.record===void 0?{}:{validation:u.record},...g===void 0?{}:{plan:g}},{root:t.root,gitRoot:await an(t.root)},s.earlier);await Gd(r.client,r.status,e.env,[Qw(o.record,y.kind==="opened",e.env)]);let w=(o.record.repairProposal?.targets??[]).map(v=>v.path),b=y.kind==="opened"?{kind:"published",pullRequest:y.number,...y.url===void 0?{}:{url:y.url}}:{kind:"not-opened",reason:y.reason};return{groups:d,exit:a,record:o.record,attempted:{representative:c,end:b},patch:{transactionId:m,approver:h,paths:w}}}function mJ(e){return e.published>0||e.eligible===0?z.ok:e.refusal!==void 0?e.refusal:e.conflicted?z.failed:e.exits.find(t=>t!==z.ok)??z.ok}async function hJ(e,t,n){let r=mC(e,t,n.root,n.ci,n.host),s=new Map,o=[],a=[],d,l=[],c=new Map,u=[],p=0,f,m=!1,h;for(;;){if(p>=n.limit){h=`the run's limit of ${n.limit} fix pull requests was reached`;break}if(d!==void 0&&xb(d,o)===void 0)break;let y=await jn(e,"repair");if("exit"in y){f=Br(e,y),h="the service refused the next fix";break}let w=o.length,b;try{b=await fJ(e,n,r,y,{tried:[...o],reuse:l,earlier:[...u]})}catch(v){if(!(v instanceof nt))throw v;e.io.error(v.message),f=[401,402,403,409].includes(v.status)?z.account:z.failed,h="the service refused the next fix";break}if(b.groups===void 0){if(d===void 0)return b.exit;f=b.exit===z.ok?z.failed:b.exit,h="the analysis didn't reach the failure groups";break}d=b.groups,a.push(b.exit),l.length===0&&b.record!==void 0&&(l=[b.record],c=new Map((b.record.failingTests??[]).map(v=>[v.logicalTestId,v.title])));for(let v of d){let R=v.inReview;R===void 0||s.has(v.representativeId)||(o.push(v.representativeId),s.set(v.representativeId,R.pullRequest===void 0?{kind:"held",reason:R.reason}:{kind:"duplicate",pullRequest:R.pullRequest}))}if(b.attempted!==void 0){o.push(b.attempted.representative),s.set(b.attempted.representative,b.attempted.end);let{end:v}=b.attempted;v.kind==="published"&&b.patch!==void 0&&(p+=1,u.push({number:v.pullRequest,...v.url===void 0?{}:{url:v.url},paths:b.patch.paths}))}if(b.refusal!==void 0){f=b.refusal,h="the service refused the next fix";break}if(b.attempted?.end.kind==="conflicted"){m=!0,h="an earlier patch couldn't be finished cleanly";break}if(o.length===w)break;if(b.patch!==void 0&&p<n.limit&&xb(d,o)!==void 0){let v=await lw({workspaceRoot:n.root,transactionId:b.patch.transactionId,approver:b.patch.approver,now:()=>new Date().toISOString()});if(v.kind!=="reverted"){e.io.print(`The patch couldn't be reverted: ${v.message}`),m=!0,h="an earlier patch couldn't be reverted";break}e.io.print(`Reverted the patch in ${v.reverted.length} file${v.reverted.length===1?"":"s"}, so the next group starts from the failing commit.`)}}if(d===void 0)return f??z.failed;e.io.print(""),e.io.print(`KwikQA fixes in this run, up to ${n.limit}:`);let g=oC({groups:d,ends:s,titles:c,...h===void 0?{}:{stopped:h}});for(let y of g)e.io.print(` ${y}`);return mJ({published:p,eligible:d.filter(y=>y.repairable).length,exits:a,...f===void 0?{}:{refusal:f},conflicted:m})}import{realpath as gJ}from"node:fs/promises";async function Eb(e){let t=await gJ(e.cwd),n=await Ud({workspaceRoot:t,checkGroup:(o,a)=>xo(e,t,o,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=n.record?.repair;if(r?.retryAvailable===!0&&r.retryReportPath!==void 0){let o=await Jd(t);await Yd(t,{...o,pendingRetry:{repairSessionId:r.repairSessionId,reportPath:r.retryReportPath}})}let s=rt(e,n);return await ns(e,n),s}var gC={"scope-and-policy":"Scope and policy",ownership:"Ownership",validation:"Validation"},wJ={passed:"passed",failed:"failed","not-checked":"not checked"};function bJ(e){let t=e.base.commit.slice(0,7),n=[e.base.revision==="HEAD"?`Checking your uncommitted changes against HEAD (${t}).`:`Checking the changes since this branch left ${e.base.revision} (${t}).`,"","Changed files:"],r=Math.max(...e.changes.map(s=>s.path.length));for(let s of e.changes){let o=s.scope==="outside"?"outside the editable test paths":`${s.scope}${s.changedLines===void 0?"":`, ${s.changedLines} line${s.changedLines===1?"":"s"}`}`;n.push(` ${s.change.padEnd(8)} ${s.path.padEnd(r)} ${o}`)}return e.gates.forEach((s,o)=>{if(n.push("",`${o+1}. ${gC[s.gate]}: ${wJ[s.status]}`),s.analysis!==void 0){let a=s.analysis.recordedAt.slice(0,16).replace("T"," ");n.push(` Judged by the analysis of ${s.analysis.runId}, recorded ${a} UTC.`)}for(let a of s.findings){let d=a.path===void 0?"":`${a.path}${a.line===void 0?"":`:${a.line}`}: `;n.push(` ${d}${a.message}`)}}),n.push("",e.outcome==="passed"?"Result: passed. Every gate passed.":e.outcome==="failed"?"Result: failed. Nothing was changed; the findings above name each problem.":"Result: incomplete. No gate found a problem, but not every gate could run, so this is not a pass."),n}async function yC(e,t){let n={approveValidation:async l=>{e.io.print("Validation re-runs the failing tests this change touches:");for(let{test:u,plan:p,covers:f}of l){let m=f??[u];e.io.print(m.length===1?` "${u.title}" in ${u.file}:`:` ${m.map(h=>`"${h.title}"`).join(", ")}, with every test that uses the changed code:`);for(let h of Wd(p))e.io.print(` ${h}`)}let c=t.yes===!0||await e.io.confirm("Run these commands?");return t.yes===!0&&e.io.print("Run these commands? yes (--yes)"),c&&e.io.print("Running the validation; this can take a few minutes."),e.io.print(""),c}},r=await yJ(e.cwd),s=await kJ(e),o=(l,c)=>RJ(e,s,l,c),a=await Fw({workspaceRoot:r,...t.base===void 0?{}:{base:t.base},...t.analysis===void 0?{}:{analysis:t.analysis},...e.io.interactive||t.yes===!0?{validation:n}:{}});if(a.kind==="unavailable")return e.io.error(a.message),await o(oy("not run",a.message),!0),a.reason==="unknown-base"||a.reason==="analysis-unreadable"?z.usage:z.failed;if(a.kind==="nothing-to-check")return e.io.print(a.message),await o(oy("nothing to check",a.message),!1),z.ok;for(let l of bJ(a))e.io.print(l);await o(AT({outcome:a.outcome,base:a.base,changedFiles:a.changes.length,gates:a.gates.map(l=>({title:gC[l.gate],status:l.status,findings:l.findings})),...s?.run.runUrl===void 0?{}:{runUrl:s.run.runUrl}}),a.outcome!=="passed");let d=e.io.interactive?zT(a):void 0;if(d!==void 0){e.io.print(""),e.io.print("KwikQA can put these files back as HEAD has them, keeping a copy of the change in .kwikqa/adopted/:");for(let l of d.files)e.io.print(` ${l}`);for(let l of d.skipped)e.io.print(` Not restored: ${l.path} (${l.reason})`);if(await e.io.confirm("Restore these files?")){let l=await qT({workspaceRoot:r,result:a,files:d.files});for(let c of vJ(l))e.io.print(c)}}return a.outcome==="passed"?z.ok:z.failed}function hC(e,t){return`${e} ${t}${e===1?"":"s"}`}function vJ(e){let t=[];switch(e.kind){case"restored":t.push(`Restored ${hC(e.restored.length,"file")} to HEAD. The change is kept in .kwikqa/adopted/${e.adoptedId}/results/.`);break;case"conflicted":t.push(`Restored ${hC(e.restored.length,"file")}, then stopped: ${e.path} changed while it was being restored, so it and the files after it were left as they are. The change is kept in .kwikqa/adopted/${e.adoptedId}/results/.`);break;case"failed":t.push(e.message);break;case"nothing":t.push("Nothing was restored.");break}return e.leftAlone.length>0&&t.push(`Left alone, because they changed after the check or HEAD has no copy: ${e.leftAlone.join(", ")}.`),t}async function kJ(e){let t=await Ri(e.env);if(t!==void 0)return{system:"github",run:t};let n=zr(e.env);if(n!==void 0)return{system:"azure",run:n};let r=Ai(e.env);if(r!==void 0)return{system:"gitlab",run:r};let s=Ci(e.env);return s===void 0?void 0:{system:"jenkins",run:s}}async function RJ(e,t,n,r){let s={failures:r,command:"check"};switch(t?.system){case"github":return ld(e.io,e.fetch,t.run,n,s);case"azure":return Io(e.io,e.fetch,t.run,n,s);case"gitlab":return wd(e.io,e.fetch,t.run,n,s);case"jenkins":return vd(e.io,e.fetch,t.run,n,s)}}import{createInterface as xJ}from"node:readline/promises";function wC(e){let t=n=>n.replace(/##vso\[/gi,"##vso [");return{interactive:e.interactive,print:(n="")=>e.print(t(n)),error:n=>e.error(t(n)),confirm:n=>e.confirm(t(n)),command:n=>e.print(n)}}function bC(){return{interactive:process.stdin.isTTY===!0,print:(e="")=>{process.stdout.write(`${e}
|
|
288
|
+
`).catch(()=>{})}return _b(y)}}}}function uC(e,t){let{projectId:n,repositoryId:r,buildId:s,jobAttempt:o,commit:a}=t;if(n===void 0||r===void 0||s===void 0||o===void 0||a===void 0)return"`kwikqa fix` in CI needs System.TeamProjectId, Build.Repository.ID, Build.BuildId, System.JobAttempt, and Build.SourceVersion as Azure Pipelines sets them.";let d={system:"Azure Pipelines",ci:{system:"azure-pipelines",repository:`${n}/${r}`,runId:s,runAttempt:o,commit:a.sha.toLowerCase()},checkout:{variable:"BUILD_SOURCESDIRECTORY",path:e.env.BUILD_SOURCESDIRECTORY||void 0}};if(t.provider!=="TfsGit")return{...d,host:it(`the repository is on ${t.provider||"another host"}, and from Azure Pipelines KwikQA opens fix pull requests only on Azure Repos`)};let l=t.pullRequest;if(l?.fork===!0)return{...d,host:it("the pull request comes from a fork, whose build gets no secrets by default, so no fix pull request is opened. A maintainer can check out its branch and run `npx kwikqa fix`",!1)};let c=l!==void 0?t.pullRequestHead===void 0?void 0:{branch:t.pullRequestHead.ref,commit:t.pullRequestHead.sha}:t.ref?.startsWith("refs/heads/")===!0?{branch:t.ref.slice(11),commit:a.sha.toLowerCase()}:void 0;if(c===void 0)return{...d,host:l===void 0?it("this build isn't on a branch, so there's no branch for a fix pull request",!1):it("the build doesn't name the pull request's source branch and commit (System.PullRequest.SourceBranch, System.PullRequest.SourceCommitId)")};if(t.token===void 0)return{...d,host:it("SYSTEM_ACCESSTOKEN isn't set; add `SYSTEM_ACCESSTOKEN: $(System.AccessToken)` to the step's env")};if(t.collectionUrl===void 0)return{...d,host:it("System.CollectionUri isn't what Azure Pipelines sets")};let u={collectionUrl:t.collectionUrl,projectId:n,repositoryId:r,token:t.token},p=t.runUrl===void 0?{}:{runUrl:t.runUrl};return{...d,host:{fixInReview:async f=>{let m=Or(f);return Ib(e,await Yg(e.fetch,u,m),m,h=>Xg(e.io,e.fetch,u,{number:h,fingerprint:m},{...p,commit:a.sha}))},publish:async(f,m,h)=>{let g=Tb(f);if(g.length===0)return e.io.print("No fix pull request: the fix's record names no repaired file."),{kind:"not-opened",reason:"the fix's record names no repaired file"};let y=ud(f.fix),w=await Qg(e.io,e.fetch,{...u,base:c,workspaceRoot:m.root,gitRoot:m.gitRoot,targets:g,fingerprint:y,title:Si(f.fix),description:fd({fix:f.fix,...f.validation===void 0?{}:{validation:f.validation},...f.plan===void 0?{}:{plan:f.plan},fingerprint:y,...p,commit:a.sha,host:"azure-repos",earlier:h}),commitMessage:pd(f.fix,y)});return Sb(e,w,c.branch),_b(w)}}}}function pC(e,t){let{repository:n,jobId:r,commit:s}=t;if(n===void 0||r===void 0||s===void 0)return"`kwikqa fix` in CI needs CI_PROJECT_PATH, CI_JOB_ID, and CI_COMMIT_SHA as GitLab CI/CD sets them.";let o={system:"GitLab CI/CD",ci:{system:"gitlab-ci",repository:n,runId:r,runAttempt:1,commit:s.sha},checkout:{variable:"CI_PROJECT_DIR",path:e.env.CI_PROJECT_DIR||void 0}},a="A maintainer can check out its branch and run `npx kwikqa fix` on their machine";if(t.pullRequest?.fork===!0)return{...o,host:it(`the merge request comes from a fork, whose pipeline gets none of this project's variables, so no fix merge request is opened. ${a}`,!1)};if(t.sourceInOtherProject===!0)return{...o,host:it(`the merge request's branch is in another project, such as a fork, which this project's token can't push to. ${a}`,!1)};let d=t.pullRequestHead!==void 0?{branch:t.pullRequestHead.ref,commit:t.pullRequestHead.sha}:t.commitBranch!==void 0?{branch:t.commitBranch,commit:s.sha}:void 0;if(d===void 0)return{...o,host:e.env.CI_MERGE_REQUEST_IID===void 0||e.env.CI_MERGE_REQUEST_IID===""?it("this pipeline isn't on a branch, so there's no branch for a fix merge request",!1):it("the pipeline doesn't name the merge request's source commit (CI_MERGE_REQUEST_SOURCE_BRANCH_SHA)")};if(t.token===void 0)return{...o,host:it("GITLAB_TOKEN isn't set; add a token with the `api` scope and at least the Developer role as a masked CI/CD variable")};if(t.apiUrl===void 0||t.projectId===void 0)return{...o,host:it("CI_API_V4_URL or the project isn't what GitLab sets")};let l={apiUrl:t.apiUrl,project:t.projectId,token:t.token},c=t.runUrl===void 0?{}:{runUrl:t.runUrl};return{...o,host:{fixInReview:async u=>{let p=Or(u);return Ib(e,await ry(e.fetch,l,p),p,f=>iy(e.io,e.fetch,l,{number:f,fingerprint:p},{...c,commit:s.sha}),dC)},publish:async(u,p,f)=>{let m=Tb(u);if(m.length===0)return e.io.print("No fix merge request: the fix's record names no repaired file."),{kind:"not-opened",reason:"the fix's record names no repaired file"};let h=ud(u.fix),g=await sy(e.io,e.fetch,{...l,base:d,workspaceRoot:p.root,gitRoot:p.gitRoot,targets:m,fingerprint:h,title:Si(u.fix),description:fd({fix:u.fix,...u.validation===void 0?{}:{validation:u.validation},...u.plan===void 0?{}:{plan:u.plan},fingerprint:h,...c,commit:s.sha,host:"gitlab",earlier:f}),commitMessage:pd(u.fix,h)});return Sb(e,g,d.branch,dC),_b(g)}}}}async function Pb(e,t){if(!e.io.interactive){let n=await Ri(e.env);if(n!==void 0)return Ab(e,t,cC(e,n));let r=zr(e.env);if(r!==void 0)return Ab(e,t,uC(e,r));let s=Ai(e.env);return s!==void 0?Ab(e,t,pC(e,s)):(e.io.error(Ci(e.env)===void 0?"`kwikqa fix` needs a terminal: every request and patch is approved by a person. In GitHub Actions, Azure Pipelines, and GitLab CI/CD, a committed ci.fix policy approves it instead.":"`kwikqa fix` needs a terminal on Jenkins: a committed ci.fix policy approves it only in GitHub Actions, Azure Pipelines, and GitLab CI/CD, so far."),z.usage)}return zt(e,async()=>{let n=await Op(e.cwd),r=await Jd(n),s=t.retry?r.pendingRetry:void 0;if(t.retry&&s===void 0)return e.io.error("There is no failed validation to retry."),z.usage;let o=s===void 0?void 0:r.tickets?.[s.repairSessionId],a=await jn(e,"repair",o);if("exit"in a)return Br(e,a);let d=s===void 0?await Ur(e,n,t.report):void 0,l=d===void 0?void 0:await eC(n,r,d);l!==void 0&&e.io.print(`Using the evidence captured by \`analyze --capture\`: ${fC(n,l.reportPath)}`);let c=await vp({reportPath:s===void 0?l?.reportPath??d??$p(n,"report.json"):$p(n,s.reportPath),...t.framework===void 0?{}:{framework:t.framework},...l?.probePath===void 0?{}:{probePath:l.probePath},workspaceRoot:n,evidencePolicy:es(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:{...ts(e,a.destination,!1),confirmFailure:(g,y)=>xo(e,n,g,y,{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}}),u=c.record?.repair?.repairSessionId,p=a.ticket(),{pendingRetry:f,...m}=r;await Yd(n,{...s===void 0?r:m,...u===void 0||p===void 0?{}:{tickets:{...r.tickets,[u]:p}}});let h=rt(e,c);return await pn(e,a,ko(c),Vr("fix",c.record,e.env,a.sessions())),h})}var Np="the committed ci.fix policy",Hr={ciFix:"running"};function cJ(e,t,n,r){return{...ts(e,t,Np),approveApplication:async(s,o)=>{for(let d of Ep(s,o,{validatedNow:!0}))e.io.print(d);let{approver:a}=s;return a.kind!=="ci-policy"?!1:(r(o,a),e.io.print(`Apply this patch? yes (${Np}, ${a.policyHash.slice(0,12)}, for run ${a.runId} attempt ${a.runAttempt}, on this runner's checkout)`),!0)},confirmFailure:(s,o)=>xo(e,n,s,o,{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?",approvedBy:Np})}}async function uJ(e,t){try{let n=fC(await Op(e),await Op(t));return n===""||!dJ(n)&&n!==".."&&!n.startsWith(`..${lJ}`)}catch{return!1}}function mC(e,t,n,r,s){let o={};return{approved:o,attempt:(a,d)=>vp({reportPath:d.reportPath,...t.framework===void 0?{}:{framework:t.framework},workspaceRoot:n,evidencePolicy:es(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:cJ(e,a.destination,n,(l,c)=>{o.plan=l,o.approver=c}),reuseDiagnosis:d.retryRepairSessionId===void 0,proposeOnly:t.proposeOnly,...d.retryRepairSessionId===void 0?{}:{retryRepairSessionId:d.retryRepairSessionId},...d.oneGroup===void 0?{}:{oneGroup:d.oneGroup},...d.reuse===void 0?{}:{reuseRecords:d.reuse},ci:r,fixInReview:l=>s.fixInReview(l)}),validate:()=>Ud({workspaceRoot:n,checkGroup:(a,d)=>xo(e,n,a,d,{purpose:"group",intro:`The repair passed. Re-run the ${d.length===1?"other test":`${d.length} other tests`} with the same cause once, to see whether the patch fixed ${d.length===1?"it":"them"} too. The patch stays either way.`,question:"Re-run them now?",approvedBy:Np})})}}async function pJ(e,t,n,r){let s=(await Wi(t))?.maxPullRequestsPerRun??1,o=Math.max(1,n.entitlements?.maxPullRequestsPerRun??1);return s>o&&e.io.print(`The ci.fix policy asks for up to ${s} fix pull requests a run, but this plan allows ${o}, so this run uses ${o}.`),r.group!==void 0||r.proposeOnly?1:Math.min(s,o)}async function Ab(e,t,n){if(t.retry)return e.io.error("In CI, the ci.fix policy's `retry` decides whether a failed validation is retried; --retry is for a terminal."),z.usage;if(typeof n=="string")return e.io.error(n),z.usage;let{ci:r,checkout:s,host:o}=n;if(s.path===void 0||!await uJ(s.path,e.cwd))return e.io.error(`\`kwikqa fix\` without a terminal patches only the runner's checkout, inside ${s.variable}.`),z.usage;if("reason"in o){let a=`No fix in CI: ${o.reason}.`;return o.misconfigured?(e.io.error(a),z.usage):(e.io.print(a),await o.note?.(),z.ok)}return zt(e,async()=>{let a=await Op(e.cwd),d=await jn(e,"repair");if("exit"in d)return Br(e,d);if(d.status.entitlements?.ciFix==="none")return e.io.error("Draft pull requests from CI come with Pro and the team plans, not this one: see `npx kwikqa upgrade`. Nothing was requested."),z.account;let l=await Ur(e,a,t.report),c=await pJ(e,a,d.status,t);if(c>1)return gJ(e,t,{root:a,reportPath:l,ci:r,host:o,limit:c});let u=mC(e,t,a,r,o),p=await u.attempt(d,{reportPath:l}),f=rt(e,p,Hr);if(await pn(e,d,ko(p),Vr("fix",p.record,e.env,d.sessions())),p.outcome!=="awaiting-validation")return f;let m=await u.validate();f=rt(e,m,Hr),await ns(e,m);let h=m.record?.repair;if(h?.retryAvailable===!0&&h.retryReportPath!==void 0){if((await Wi(a))?.retry!==!0)return e.io.print("The ci.fix policy doesn't retry a failed validation, so the patch was rolled back and nothing else was sent."),f;let g=d.ticket(),y=await jn(e,"repair",g);if("exit"in y)return Br(e,y);if(p=await u.attempt(y,{reportPath:$p(a,h.retryReportPath),retryRepairSessionId:h.repairSessionId}),f=rt(e,p,Hr),await pn(e,y,ko(p),Vr("fix",p.record,e.env,y.sessions())),p.outcome!=="awaiting-validation")return f;m=await u.validate(),f=rt(e,m,Hr),await ns(e,m)}if(m.outcome==="repaired"&&p.record!==void 0){let g=await o.publish({fix:p.record,...m.record===void 0?{}:{validation:m.record},...u.approved.plan===void 0?{}:{plan:u.approved.plan}},{root:a,gitRoot:await an(a)},[]);await Gd(d.client,d.status,e.env,[Qw(p.record,g.kind==="opened",e.env)])}return f})}function fJ(e){return e.reasonCode==="application-recovery-required"?{kind:"conflicted",reason:e.message}:{kind:"not-repaired",reason:e.message}}async function mJ(e,t,n,r,s){let o=await n.attempt(r,{reportPath:t.reportPath,oneGroup:{tried:s.tried},reuse:s.reuse}),a=rt(e,o,Hr);await pn(e,r,ko(o),Vr("fix",o.record,e.env,r.sessions()));let d=o.fixGroups?.groups,l=o.record,c=o.fixGroups?.attempted;if(o.outcome!=="awaiting-validation")return{groups:d,exit:a,...l===void 0?{}:{record:l},...c===void 0?{}:{attempted:{representative:c,end:fJ(o)}}};if(c===void 0)throw new Error("A repair was applied without the failure group it repaired.");let u=await n.validate();a=rt(e,u,Hr),await ns(e,u);let p=!1,f=u.record?.repair;if(f?.retryAvailable===!0&&f.retryReportPath!==void 0)if((await Wi(t.root))?.retry===!0){let v=await jn(e,"repair",r.ticket());if("exit"in v)return{groups:d,exit:a,record:l,attempted:{representative:c,end:{kind:"rolled-back",retried:!1}},refusal:Br(e,v)};if(p=!0,o=await n.attempt(v,{reportPath:$p(t.root,f.retryReportPath),retryRepairSessionId:f.repairSessionId,oneGroup:{tried:[],retryOf:c}}),a=rt(e,o,Hr),await pn(e,v,ko(o),Vr("fix",o.record,e.env,v.sessions())),o.outcome!=="awaiting-validation")return{groups:d,exit:a,record:o.record,attempted:{representative:c,end:{kind:"rolled-back",retried:p}}};u=await n.validate(),a=rt(e,u,Hr),await ns(e,u)}else e.io.print("The ci.fix policy doesn't retry a failed validation, so the patch was rolled back and nothing else was sent.");let m=u.record?.repair?.transactionId??o.record?.repair?.transactionId,h=n.approved.approver;if(u.reasonCode==="rollback-conflicted")return{groups:d,exit:a,attempted:{representative:c,end:{kind:"conflicted",reason:u.message}}};if(u.outcome!=="repaired"||o.record===void 0){let v=u.outcome==="repair-failed"?{kind:"rolled-back",retried:p}:{kind:"not-repaired",reason:u.message};return{groups:d,exit:a,record:l,attempted:{representative:c,end:v}}}if(m===void 0||h===void 0)return{groups:d,exit:a,attempted:{representative:c,end:{kind:"conflicted",reason:"the validated patch isn't recorded, so it can't be reverted"}}};let g=n.approved.plan,y=await t.host.publish({fix:o.record,...u.record===void 0?{}:{validation:u.record},...g===void 0?{}:{plan:g}},{root:t.root,gitRoot:await an(t.root)},s.earlier);await Gd(r.client,r.status,e.env,[Qw(o.record,y.kind==="opened",e.env)]);let w=(o.record.repairProposal?.targets??[]).map(v=>v.path),b=y.kind==="opened"?{kind:"published",pullRequest:y.number,...y.url===void 0?{}:{url:y.url}}:{kind:"not-opened",reason:y.reason};return{groups:d,exit:a,record:o.record,attempted:{representative:c,end:b},patch:{transactionId:m,approver:h,paths:w}}}function hJ(e){return e.published>0||e.eligible===0?z.ok:e.refusal!==void 0?e.refusal:e.conflicted?z.failed:e.exits.find(t=>t!==z.ok)??z.ok}async function gJ(e,t,n){let r=mC(e,t,n.root,n.ci,n.host),s=new Map,o=[],a=[],d,l=[],c=new Map,u=[],p=0,f,m=!1,h;for(;;){if(p>=n.limit){h=`the run's limit of ${n.limit} fix pull requests was reached`;break}if(d!==void 0&&xb(d,o)===void 0)break;let y=await jn(e,"repair");if("exit"in y){f=Br(e,y),h="the service refused the next fix";break}let w=o.length,b;try{b=await mJ(e,n,r,y,{tried:[...o],reuse:l,earlier:[...u]})}catch(v){if(!(v instanceof nt))throw v;e.io.error(v.message),f=[401,402,403,409].includes(v.status)?z.account:z.failed,h="the service refused the next fix";break}if(b.groups===void 0){if(d===void 0)return b.exit;f=b.exit===z.ok?z.failed:b.exit,h="the analysis didn't reach the failure groups";break}d=b.groups,a.push(b.exit),l.length===0&&b.record!==void 0&&(l=[b.record],c=new Map((b.record.failingTests??[]).map(v=>[v.logicalTestId,v.title])));for(let v of d){let R=v.inReview;R===void 0||s.has(v.representativeId)||(o.push(v.representativeId),s.set(v.representativeId,R.pullRequest===void 0?{kind:"held",reason:R.reason}:{kind:"duplicate",pullRequest:R.pullRequest}))}if(b.attempted!==void 0){o.push(b.attempted.representative),s.set(b.attempted.representative,b.attempted.end);let{end:v}=b.attempted;v.kind==="published"&&b.patch!==void 0&&(p+=1,u.push({number:v.pullRequest,...v.url===void 0?{}:{url:v.url},paths:b.patch.paths}))}if(b.refusal!==void 0){f=b.refusal,h="the service refused the next fix";break}if(b.attempted?.end.kind==="conflicted"){m=!0,h="an earlier patch couldn't be finished cleanly";break}if(o.length===w)break;if(b.patch!==void 0&&p<n.limit&&xb(d,o)!==void 0){let v=await lw({workspaceRoot:n.root,transactionId:b.patch.transactionId,approver:b.patch.approver,now:()=>new Date().toISOString()});if(v.kind!=="reverted"){e.io.print(`The patch couldn't be reverted: ${v.message}`),m=!0,h="an earlier patch couldn't be reverted";break}e.io.print(`Reverted the patch in ${v.reverted.length} file${v.reverted.length===1?"":"s"}, so the next group starts from the failing commit.`)}}if(d===void 0)return f??z.failed;e.io.print(""),e.io.print(`KwikQA fixes in this run, up to ${n.limit}:`);let g=oC({groups:d,ends:s,titles:c,...h===void 0?{}:{stopped:h}});for(let y of g)e.io.print(` ${y}`);return hJ({published:p,eligible:d.filter(y=>y.repairable).length,exits:a,...f===void 0?{}:{refusal:f},conflicted:m})}import{realpath as yJ}from"node:fs/promises";async function Eb(e){let t=await yJ(e.cwd),n=await Ud({workspaceRoot:t,checkGroup:(o,a)=>xo(e,t,o,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=n.record?.repair;if(r?.retryAvailable===!0&&r.retryReportPath!==void 0){let o=await Jd(t);await Yd(t,{...o,pendingRetry:{repairSessionId:r.repairSessionId,reportPath:r.retryReportPath}})}let s=rt(e,n);return await ns(e,n),s}var gC={"scope-and-policy":"Scope and policy",ownership:"Ownership",validation:"Validation"},bJ={passed:"passed",failed:"failed","not-checked":"not checked"};function vJ(e){let t=e.base.commit.slice(0,7),n=[e.base.revision==="HEAD"?`Checking your uncommitted changes against HEAD (${t}).`:`Checking the changes since this branch left ${e.base.revision} (${t}).`,"","Changed files:"],r=Math.max(...e.changes.map(s=>s.path.length));for(let s of e.changes){let o=s.scope==="outside"?"outside the editable test paths":`${s.scope}${s.changedLines===void 0?"":`, ${s.changedLines} line${s.changedLines===1?"":"s"}`}`;n.push(` ${s.change.padEnd(8)} ${s.path.padEnd(r)} ${o}`)}return e.gates.forEach((s,o)=>{if(n.push("",`${o+1}. ${gC[s.gate]}: ${bJ[s.status]}`),s.analysis!==void 0){let a=s.analysis.recordedAt.slice(0,16).replace("T"," ");n.push(` Judged by the analysis of ${s.analysis.runId}, recorded ${a} UTC.`)}for(let a of s.findings){let d=a.path===void 0?"":`${a.path}${a.line===void 0?"":`:${a.line}`}: `;n.push(` ${d}${a.message}`)}}),n.push("",e.outcome==="passed"?"Result: passed. Every gate passed.":e.outcome==="failed"?"Result: failed. Nothing was changed; the findings above name each problem.":"Result: incomplete. No gate found a problem, but not every gate could run, so this is not a pass."),n}async function yC(e,t){let n={approveValidation:async l=>{e.io.print("Validation re-runs the failing tests this change touches:");for(let{test:u,plan:p,covers:f}of l){let m=f??[u];e.io.print(m.length===1?` "${u.title}" in ${u.file}:`:` ${m.map(h=>`"${h.title}"`).join(", ")}, with every test that uses the changed code:`);for(let h of Wd(p))e.io.print(` ${h}`)}let c=t.yes===!0||await e.io.confirm("Run these commands?");return t.yes===!0&&e.io.print("Run these commands? yes (--yes)"),c&&e.io.print("Running the validation; this can take a few minutes."),e.io.print(""),c}},r=await wJ(e.cwd),s=await RJ(e),o=(l,c)=>xJ(e,s,l,c),a=await Fw({workspaceRoot:r,...t.base===void 0?{}:{base:t.base},...t.analysis===void 0?{}:{analysis:t.analysis},...e.io.interactive||t.yes===!0?{validation:n}:{}});if(a.kind==="unavailable")return e.io.error(a.message),await o(oy("not run",a.message),!0),a.reason==="unknown-base"||a.reason==="analysis-unreadable"?z.usage:z.failed;if(a.kind==="nothing-to-check")return e.io.print(a.message),await o(oy("nothing to check",a.message),!1),z.ok;for(let l of vJ(a))e.io.print(l);await o(AT({outcome:a.outcome,base:a.base,changedFiles:a.changes.length,gates:a.gates.map(l=>({title:gC[l.gate],status:l.status,findings:l.findings})),...s?.run.runUrl===void 0?{}:{runUrl:s.run.runUrl}}),a.outcome!=="passed");let d=e.io.interactive?zT(a):void 0;if(d!==void 0){e.io.print(""),e.io.print("KwikQA can put these files back as HEAD has them, keeping a copy of the change in .kwikqa/adopted/:");for(let l of d.files)e.io.print(` ${l}`);for(let l of d.skipped)e.io.print(` Not restored: ${l.path} (${l.reason})`);if(await e.io.confirm("Restore these files?")){let l=await qT({workspaceRoot:r,result:a,files:d.files});for(let c of kJ(l))e.io.print(c)}}return a.outcome==="passed"?z.ok:z.failed}function hC(e,t){return`${e} ${t}${e===1?"":"s"}`}function kJ(e){let t=[];switch(e.kind){case"restored":t.push(`Restored ${hC(e.restored.length,"file")} to HEAD. The change is kept in .kwikqa/adopted/${e.adoptedId}/results/.`);break;case"conflicted":t.push(`Restored ${hC(e.restored.length,"file")}, then stopped: ${e.path} changed while it was being restored, so it and the files after it were left as they are. The change is kept in .kwikqa/adopted/${e.adoptedId}/results/.`);break;case"failed":t.push(e.message);break;case"nothing":t.push("Nothing was restored.");break}return e.leftAlone.length>0&&t.push(`Left alone, because they changed after the check or HEAD has no copy: ${e.leftAlone.join(", ")}.`),t}async function RJ(e){let t=await Ri(e.env);if(t!==void 0)return{system:"github",run:t};let n=zr(e.env);if(n!==void 0)return{system:"azure",run:n};let r=Ai(e.env);if(r!==void 0)return{system:"gitlab",run:r};let s=Ci(e.env);return s===void 0?void 0:{system:"jenkins",run:s}}async function xJ(e,t,n,r){let s={failures:r,command:"check"};switch(t?.system){case"github":return ld(e.io,e.fetch,t.run,n,s);case"azure":return Io(e.io,e.fetch,t.run,n,s);case"gitlab":return wd(e.io,e.fetch,t.run,n,s);case"jenkins":return vd(e.io,e.fetch,t.run,n,s)}}import{createInterface as _J}from"node:readline/promises";function wC(e){let t=n=>n.replace(/##vso\[/gi,"##vso [");return{interactive:e.interactive,print:(n="")=>e.print(t(n)),error:n=>e.error(t(n)),confirm:n=>e.confirm(t(n)),command:n=>e.print(n)}}function bC(){return{interactive:process.stdin.isTTY===!0,print:(e="")=>{process.stdout.write(`${e}
|
|
289
289
|
`)},error:e=>{process.stderr.write(`${e}
|
|
290
|
-
`)},confirm:async e=>{if(process.stdin.isTTY!==!0)return!1;let t=
|
|
290
|
+
`)},confirm:async e=>{if(process.stdin.isTTY!==!0)return!1;let t=_J({input:process.stdin,output:process.stdout});try{let n=await t.question(`${e} [y/N] `);return/^y(?:es)?$/i.test(n.trim())}finally{t.close()}}}}var SJ=`KwikQA turns failed test runs into evidence-backed diagnoses and safe, validated test repairs.
|
|
291
291
|
|
|
292
292
|
Usage:
|
|
293
293
|
npx kwikqa init Create kwikqa.config.json and set up your reporter
|
|
@@ -326,8 +326,8 @@ Usage:
|
|
|
326
326
|
npx kwikqa logout Sign out and revoke this machine's token
|
|
327
327
|
|
|
328
328
|
Docs: https://kwikqa.com/docs/
|
|
329
|
-
Dashboard: https://kwikqa.com/dashboard/`;function vC(e){let t=bt(e),n=" ".repeat(t.length-10);return
|
|
329
|
+
Dashboard: https://kwikqa.com/dashboard/`;function vC(e){let t=bt(e),n=" ".repeat(t.length-10);return SJ.split(`
|
|
330
330
|
`).map(r=>r.startsWith(" npx kwikqa ")?r.replace("npx kwikqa",t):/^ +\[/.test(r)?`${n}${r}`:r).join(`
|
|
331
|
-
`)}async function
|
|
331
|
+
`)}async function TJ(e,t){let n=t.env.TF_BUILD==="True"?{...t,env:jp(t.env),io:wC(t.io)}:t,[r,...s]=e,o;try{o=IJ({args:[...s],allowPositionals:!0,strict:!0,options:{report:{type:"string"},framework:{type:"string"},local:{type:"boolean",default:!1},yes:{type:"boolean",default:!1},capture:{type:"boolean",default:!1},"no-probe":{type:"boolean",default:!1},"no-changes":{type:"boolean",default:!1},"no-browser":{type:"boolean",default:!1},group:{type:"string"},html:{type:"boolean",default:!1},output:{type:"string"},notify:{type:"string"},run:{type:"string"},base:{type:"string"},analysis:{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(u){return n.io.error(u.message),z.usage}let a=o.values;if(a.help||r===void 0||r==="help"||r==="--help")return n.io.print(vC(n.env)),z.ok;if(a.framework!==void 0&&!bn.includes(a.framework))return n.io.error(`--framework must be one of: ${bn.join(", ")}`),z.usage;let d=a.framework;if(a.notify!==void 0&&!ou.includes(a.notify))return n.io.error(`--notify must be one of: ${ou.join(", ")}`),z.usage;let l=a.notify,c=a.group===void 0?void 0:Number(a.group);if(c!==void 0&&!(Number.isInteger(c)&&c>=1))return n.io.error("--group takes a failure group's number as analyze printed it: 1, 2, ..."),z.usage;switch(r){case"--version":case"version":return n.io.print(Ji),z.ok;case"init":return wb(n);case"login":return Zw(n,{browser:!a["no-browser"]});case"logout":return eb(n);case"status":return nb(n);case"upgrade":return a.seats!==void 0&&n.io.error("--seats is no longer used: plans are priced per account or organization."),rb(n,o.positionals[0],{annual:a.annual});case"billing":return ib(n);case"analyze":return bb(n,{...a.report===void 0?{}:{report:a.report},...d===void 0?{}:{framework:d},local:a.local,yes:a.yes,capture:a.capture,probe:!a["no-probe"],changes:!a["no-changes"],html:a.html,...a.output===void 0?{}:{output:a.output}});case"ci":return Rb(n,{...a.report===void 0?{}:{report:a.report},...d===void 0?{}:{framework:d},local:a.local,changes:!a["no-changes"],...a.output===void 0?{}:{output:a.output},...l===void 0?{}:{notify:l}});case"report":return kb(n,{...a.run===void 0?{}:{run:a.run},...a.output===void 0?{}:{output:a.output}});case"fix":return Pb(n,{...a.report===void 0?{}:{report:a.report},...d===void 0?{}:{framework:d},retry:a.retry,proposeOnly:a["propose-only"],changes:!a["no-changes"],...c===void 0?{}:{group:c}});case"validate":return Eb(n);case"check":return yC(n,{...a.base===void 0?{}:{base:a.base},...a.analysis===void 0?{}:{analysis:a.analysis},yes:a.yes});default:return n.io.error(`Unknown command: ${r}
|
|
332
332
|
|
|
333
|
-
${vC(n.env)}`),z.usage}}async function kC(){let e=await
|
|
333
|
+
${vC(n.env)}`),z.usage}}async function kC(){let e=await TJ(process.argv.slice(2),{cwd:process.cwd(),env:process.env,io:bC(),fetch});process.exitCode=e}await kC();
|