mcp-claw 0.1.49 → 0.1.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bundle.js +1 -1
  2. package/package.json +1 -1
package/dist/bundle.js CHANGED
@@ -54,7 +54,7 @@ progress/lib/node-progress.js:
54
54
  * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
55
55
  * MIT Licensed
56
56
  *)
57
- */},43730:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{KeyParser:()=>KeyParser,ParserError:()=>ParserError,ariaNodesEqual:()=>ariaNodesEqual,findNewNode:()=>findNewNode,hasPointerCursor:()=>hasPointerCursor,parseAriaSnapshot:()=>parseAriaSnapshot,parseAriaSnapshotUnsafe:()=>parseAriaSnapshotUnsafe,textValue:()=>textValue});G.exports=__toCommonJS(Xe);function ariaNodesEqual(G,K){if(G.role!==K.role||G.name!==K.name)return false;if(!ariaPropsEqual(G,K)||hasPointerCursor(G)!==hasPointerCursor(K))return false;const je=Object.keys(G.props);const ze=Object.keys(K.props);return je.length===ze.length&&je.every((je=>G.props[je]===K.props[je]))}function hasPointerCursor(G){return G.box.cursor==="pointer"}function ariaPropsEqual(G,K){return G.active===K.active&&G.checked===K.checked&&G.disabled===K.disabled&&G.expanded===K.expanded&&G.selected===K.selected&&G.level===K.level&&G.pressed===K.pressed}function parseAriaSnapshotUnsafe(G,K,je={}){const ze=parseAriaSnapshot(G,K,je);if(ze.errors.length)throw new Error(ze.errors[0].message);return ze.fragment}function parseAriaSnapshot(G,K,je={}){const ze=new G.LineCounter;const We={keepSourceTokens:true,lineCounter:ze,...je};const Xe=G.parseDocument(K,We);const at=[];const convertRange=G=>[ze.linePos(G[0]),ze.linePos(G[1])];const addError=G=>{at.push({message:G.message,range:[ze.linePos(G.pos[0]),ze.linePos(G.pos[1])]})};const convertSeq=(K,je)=>{for(const ze of je.items){const Xe=ze instanceof G.Scalar&&typeof ze.value==="string";if(Xe){const G=KeyParser.parse(ze,We,at);if(G){K.children=K.children||[];K.children.push(G)}continue}const rt=ze instanceof G.YAMLMap;if(rt){convertMap(K,ze);continue}at.push({message:"Sequence items should be strings or maps",range:convertRange(ze.range||je.range)})}};const convertMap=(K,je)=>{for(const ze of je.items){K.children=K.children||[];const Xe=ze.key instanceof G.Scalar&&typeof ze.key.value==="string";if(!Xe){at.push({message:"Only string keys are supported",range:convertRange(ze.key.range||je.range)});continue}const rt=ze.key;const ft=ze.value;if(rt.value==="text"){const We=ft instanceof G.Scalar&&typeof ft.value==="string";if(!We){at.push({message:"Text value should be a string",range:convertRange(ze.value.range||je.range)});continue}K.children.push({kind:"text",text:textValue(ft.value)});continue}if(rt.value==="/children"){const We=ft instanceof G.Scalar&&typeof ft.value==="string";if(!We||ft.value!=="contain"&&ft.value!=="equal"&&ft.value!=="deep-equal"){at.push({message:'Strict value should be "contain", "equal" or "deep-equal"',range:convertRange(ze.value.range||je.range)});continue}K.containerMode=ft.value;continue}if(rt.value.startsWith("/")){const We=ft instanceof G.Scalar&&typeof ft.value==="string";if(!We){at.push({message:"Property value should be a string",range:convertRange(ze.value.range||je.range)});continue}K.props=K.props??{};K.props[rt.value.slice(1)]=textValue(ft.value);continue}const mt=KeyParser.parse(rt,We,at);if(!mt)continue;const vt=ft instanceof G.Scalar;if(vt){const G=typeof ft.value;if(G!=="string"&&G!=="number"&&G!=="boolean"){at.push({message:"Node value should be a string or a sequence",range:convertRange(ze.value.range||je.range)});continue}K.children.push({...mt,children:[{kind:"text",text:textValue(String(ft.value))}]});continue}const yt=ft instanceof G.YAMLSeq;if(yt){K.children.push(mt);convertSeq(mt,ft);continue}at.push({message:"Map values should be strings or sequences",range:convertRange(ze.value.range||je.range)})}};const ft={kind:"role",role:"fragment"};Xe.errors.forEach(addError);if(at.length)return{errors:at,fragment:ft};if(!(Xe.contents instanceof G.YAMLSeq)){at.push({message:'Aria snapshot must be a YAML sequence, elements starting with " -"',range:Xe.contents?convertRange(Xe.contents.range):[{line:0,col:0},{line:0,col:0}]})}if(at.length)return{errors:at,fragment:ft};convertSeq(ft,Xe.contents);if(at.length)return{errors:at,fragment:rt};if(ft.children?.length===1&&(!ft.containerMode||ft.containerMode==="contain"))return{fragment:ft.children[0],errors:[]};return{fragment:ft,errors:[]}}const rt={kind:"role",role:"fragment"};function normalizeWhitespace(G){return G.replace(/[\u200b\u00ad]/g,"").replace(/[\r\n\s\t]+/g," ").trim()}function textValue(G){return{raw:G,normalized:normalizeWhitespace(G)}}class KeyParser{static parse(G,K,je){try{return new KeyParser(G.value)._parse()}catch(ze){if(ze instanceof ParserError){const We=K.prettyErrors===false?ze.message:ze.message+":\n\n"+G.value+"\n"+" ".repeat(ze.pos)+"^\n";je.push({message:We,range:[K.lineCounter.linePos(G.range[0]),K.lineCounter.linePos(G.range[0]+ze.pos)]});return null}throw ze}}constructor(G){this._input=G;this._pos=0;this._length=G.length}_peek(){return this._input[this._pos]||""}_next(){if(this._pos<this._length)return this._input[this._pos++];return null}_eof(){return this._pos>=this._length}_isWhitespace(){return!this._eof()&&/\s/.test(this._peek())}_skipWhitespace(){while(this._isWhitespace())this._pos++}_readIdentifier(G){if(this._eof())this._throwError(`Unexpected end of input when expecting ${G}`);const K=this._pos;while(!this._eof()&&/[a-zA-Z]/.test(this._peek()))this._pos++;return this._input.slice(K,this._pos)}_readString(){let G="";let K=false;while(!this._eof()){const je=this._next();if(K){G+=je;K=false}else if(je==="\\"){K=true}else if(je==='"'){return G}else{G+=je}}this._throwError("Unterminated string")}_throwError(G,K=0){throw new ParserError(G,K||this._pos)}_readRegex(){let G="";let K=false;let je=false;while(!this._eof()){const ze=this._next();if(K){G+=ze;K=false}else if(ze==="\\"){K=true;G+=ze}else if(ze==="/"&&!je){return{pattern:G}}else if(ze==="["){je=true;G+=ze}else if(ze==="]"&&je){G+=ze;je=false}else{G+=ze}}this._throwError("Unterminated regex")}_readStringOrRegex(){const G=this._peek();if(G==='"'){this._next();return normalizeWhitespace(this._readString())}if(G==="/"){this._next();return this._readRegex()}return null}_readAttributes(G){let K=this._pos;while(true){this._skipWhitespace();if(this._peek()==="["){this._next();this._skipWhitespace();K=this._pos;const je=this._readIdentifier("attribute");this._skipWhitespace();let ze="";if(this._peek()==="="){this._next();this._skipWhitespace();K=this._pos;while(this._peek()!=="]"&&!this._isWhitespace()&&!this._eof())ze+=this._next()}this._skipWhitespace();if(this._peek()!=="]")this._throwError("Expected ]");this._next();this._applyAttribute(G,je,ze||"true",K)}else{break}}}_parse(){this._skipWhitespace();const G=this._readIdentifier("role");this._skipWhitespace();const K=this._readStringOrRegex()||"";const je={kind:"role",role:G,name:K};this._readAttributes(je);this._skipWhitespace();if(!this._eof())this._throwError("Unexpected input");return je}_applyAttribute(G,K,je,ze){if(K==="checked"){this._assert(je==="true"||je==="false"||je==="mixed",'Value of "checked" attribute must be a boolean or "mixed"',ze);G.checked=je==="true"?true:je==="false"?false:"mixed";return}if(K==="disabled"){this._assert(je==="true"||je==="false",'Value of "disabled" attribute must be a boolean',ze);G.disabled=je==="true";return}if(K==="expanded"){this._assert(je==="true"||je==="false",'Value of "expanded" attribute must be a boolean',ze);G.expanded=je==="true";return}if(K==="active"){this._assert(je==="true"||je==="false",'Value of "active" attribute must be a boolean',ze);G.active=je==="true";return}if(K==="level"){this._assert(!isNaN(Number(je)),'Value of "level" attribute must be a number',ze);G.level=Number(je);return}if(K==="pressed"){this._assert(je==="true"||je==="false"||je==="mixed",'Value of "pressed" attribute must be a boolean or "mixed"',ze);G.pressed=je==="true"?true:je==="false"?false:"mixed";return}if(K==="selected"){this._assert(je==="true"||je==="false",'Value of "selected" attribute must be a boolean',ze);G.selected=je==="true";return}this._assert(false,`Unsupported attribute [${K}]`,ze)}_assert(G,K,je){if(!G)this._throwError(K||"Assertion error",je)}}class ParserError extends Error{constructor(G,K){super(G);this.pos=K}}function findNewNode(G,K){function fillMap(G,K,je){let ze=1;let We=je+ze;for(const je of G.children||[]){if(typeof je==="string"){ze++;We++}else{ze+=fillMap(je,K,We);We+=ze}}if(!["none","presentation","fragment","iframe","generic"].includes(G.role)&&G.name){let We=K.get(G.role);if(!We){We=new Map;K.set(G.role,We)}const Xe=We.get(G.name);const rt=ze*100-je;if(!Xe||Xe.sizeAndPosition<rt)We.set(G.name,{node:G,sizeAndPosition:rt})}return ze}const je=new Map;if(G)fillMap(G,je,0);const ze=new Map;fillMap(K,ze,0);const We=[];for(const[G,K]of ze){for(const[ze,Xe]of K){const K=je.get(G)?.get(ze);if(!K)We.push(Xe)}}We.sort(((G,K)=>K.sizeAndPosition-G.sizeAndPosition));return We[0]?.node}0&&0},16353:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{assert:()=>assert});G.exports=__toCommonJS(Xe);function assert(G,K){if(!G)throw new Error(K||"Assertion error")}0&&0},38607:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{noColors:()=>at,webColors:()=>rt});G.exports=__toCommonJS(Xe);const rt={enabled:true,reset:G=>applyStyle(0,0,G),bold:G=>applyStyle(1,22,G),dim:G=>applyStyle(2,22,G),italic:G=>applyStyle(3,23,G),underline:G=>applyStyle(4,24,G),inverse:G=>applyStyle(7,27,G),hidden:G=>applyStyle(8,28,G),strikethrough:G=>applyStyle(9,29,G),black:G=>applyStyle(30,39,G),red:G=>applyStyle(31,39,G),green:G=>applyStyle(32,39,G),yellow:G=>applyStyle(33,39,G),blue:G=>applyStyle(34,39,G),magenta:G=>applyStyle(35,39,G),cyan:G=>applyStyle(36,39,G),white:G=>applyStyle(37,39,G),gray:G=>applyStyle(90,39,G),grey:G=>applyStyle(90,39,G)};const at={enabled:false,reset:G=>G,bold:G=>G,dim:G=>G,italic:G=>G,underline:G=>G,inverse:G=>G,hidden:G=>G,strikethrough:G=>G,black:G=>G,red:G=>G,green:G=>G,yellow:G=>G,blue:G=>G,magenta:G=>G,cyan:G=>G,white:G=>G,gray:G=>G,grey:G=>G};const applyStyle=(G,K,je)=>`[${G}m${je}[${K}m`;0&&0},59891:(G,K,je)=>{"use strict";var ze=Object.create;var We=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var at=Object.getPrototypeOf;var ft=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)We(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,ze)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let at of rt(K))if(!ft.call(G,at)&&at!==je)We(G,at,{get:()=>K[at],enumerable:!(ze=Xe(K,at))||ze.enumerable})}return G};var __toESM=(G,K,je)=>(je=G!=null?ze(at(G)):{},__copyProps(K||!G||!G.__esModule?We(je,"default",{value:G,enumerable:true}):je,G));var __toCommonJS=G=>__copyProps(We({},"__esModule",{value:true}),G);var mt={};__export(mt,{InvalidSelectorError:()=>InvalidSelectorError,isInvalidSelectorError:()=>isInvalidSelectorError,parseCSS:()=>parseCSS,serializeSelector:()=>serializeSelector});G.exports=__toCommonJS(mt);var vt=__toESM(je(6071));class InvalidSelectorError extends Error{}function isInvalidSelectorError(G){return G instanceof InvalidSelectorError}function parseCSS(G,K){let je;try{je=vt.tokenize(G);if(!(je[je.length-1]instanceof vt.EOFToken))je.push(new vt.EOFToken)}catch(K){const je=K.message+` while parsing css selector "${G}". Did you mean to CSS.escape it?`;const ze=(K.stack||"").indexOf(K.message);if(ze!==-1)K.stack=K.stack.substring(0,ze)+je+K.stack.substring(ze+K.message.length);K.message=je;throw K}const ze=je.find((G=>G instanceof vt.AtKeywordToken||G instanceof vt.BadStringToken||G instanceof vt.BadURLToken||G instanceof vt.ColumnToken||G instanceof vt.CDOToken||G instanceof vt.CDCToken||G instanceof vt.SemicolonToken||G instanceof vt.OpenCurlyToken||G instanceof vt.CloseCurlyToken||G instanceof vt.URLToken||G instanceof vt.PercentageToken));if(ze)throw new InvalidSelectorError(`Unsupported token "${ze.toSource()}" while parsing css selector "${G}". Did you mean to CSS.escape it?`);let We=0;const Xe=new Set;function unexpected(){return new InvalidSelectorError(`Unexpected token "${je[We].toSource()}" while parsing css selector "${G}". Did you mean to CSS.escape it?`)}function skipWhitespace(){while(je[We]instanceof vt.WhitespaceToken)We++}function isIdent(G=We){return je[G]instanceof vt.IdentToken}function isString(G=We){return je[G]instanceof vt.StringToken}function isNumber(G=We){return je[G]instanceof vt.NumberToken}function isComma(G=We){return je[G]instanceof vt.CommaToken}function isOpenParen(G=We){return je[G]instanceof vt.OpenParenToken}function isCloseParen(G=We){return je[G]instanceof vt.CloseParenToken}function isFunction(G=We){return je[G]instanceof vt.FunctionToken}function isStar(G=We){return je[G]instanceof vt.DelimToken&&je[G].value==="*"}function isEOF(G=We){return je[G]instanceof vt.EOFToken}function isClauseCombinator(G=We){return je[G]instanceof vt.DelimToken&&[">","+","~"].includes(je[G].value)}function isSelectorClauseEnd(G=We){return isComma(G)||isCloseParen(G)||isEOF(G)||isClauseCombinator(G)||je[G]instanceof vt.WhitespaceToken}function consumeFunctionArguments(){const G=[consumeArgument()];while(true){skipWhitespace();if(!isComma())break;We++;G.push(consumeArgument())}return G}function consumeArgument(){skipWhitespace();if(isNumber())return je[We++].value;if(isString())return je[We++].value;return consumeComplexSelector()}function consumeComplexSelector(){const G={simples:[]};skipWhitespace();if(isClauseCombinator()){G.simples.push({selector:{functions:[{name:"scope",args:[]}]},combinator:""})}else{G.simples.push({selector:consumeSimpleSelector(),combinator:""})}while(true){skipWhitespace();if(isClauseCombinator()){G.simples[G.simples.length-1].combinator=je[We++].value;skipWhitespace()}else if(isSelectorClauseEnd()){break}G.simples.push({combinator:"",selector:consumeSimpleSelector()})}return G}function consumeSimpleSelector(){let G="";const ze=[];while(!isSelectorClauseEnd()){if(isIdent()||isStar()){G+=je[We++].toSource()}else if(je[We]instanceof vt.HashToken){G+=je[We++].toSource()}else if(je[We]instanceof vt.DelimToken&&je[We].value==="."){We++;if(isIdent())G+="."+je[We++].toSource();else throw unexpected()}else if(je[We]instanceof vt.ColonToken){We++;if(isIdent()){if(!K.has(je[We].value.toLowerCase())){G+=":"+je[We++].toSource()}else{const G=je[We++].value.toLowerCase();ze.push({name:G,args:[]});Xe.add(G)}}else if(isFunction()){const rt=je[We++].value.toLowerCase();if(!K.has(rt)){G+=`:${rt}(${consumeBuiltinFunctionArguments()})`}else{ze.push({name:rt,args:consumeFunctionArguments()});Xe.add(rt)}skipWhitespace();if(!isCloseParen())throw unexpected();We++}else{throw unexpected()}}else if(je[We]instanceof vt.OpenSquareToken){G+="[";We++;while(!(je[We]instanceof vt.CloseSquareToken)&&!isEOF())G+=je[We++].toSource();if(!(je[We]instanceof vt.CloseSquareToken))throw unexpected();G+="]";We++}else{throw unexpected()}}if(!G&&!ze.length)throw unexpected();return{css:G||void 0,functions:ze}}function consumeBuiltinFunctionArguments(){let G="";let K=1;while(!isEOF()){if(isOpenParen()||isFunction())K++;if(isCloseParen())K--;if(!K)break;G+=je[We++].toSource()}return G}const rt=consumeFunctionArguments();if(!isEOF())throw unexpected();if(rt.some((G=>typeof G!=="object"||!("simples"in G))))throw new InvalidSelectorError(`Error while parsing css selector "${G}". Did you mean to CSS.escape it?`);return{selector:rt,names:Array.from(Xe)}}function serializeSelector(G){return G.map((G=>{if(typeof G==="string")return`"${G}"`;if(typeof G==="number")return String(G);return G.simples.map((({selector:G,combinator:K})=>{let je=G.css||"";je=je+G.functions.map((G=>`:${G.name}(${serializeSelector(G.args)})`)).join("");if(K)je+=" "+K;return je})).join(" ")})).join(", ")}0&&0},6071:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{AtKeywordToken:()=>AtKeywordToken,BadStringToken:()=>BadStringToken,BadURLToken:()=>BadURLToken,CDCToken:()=>CDCToken,CDOToken:()=>CDOToken,CSSParserToken:()=>CSSParserToken,CloseCurlyToken:()=>CloseCurlyToken,CloseParenToken:()=>CloseParenToken,CloseSquareToken:()=>CloseSquareToken,ColonToken:()=>ColonToken,ColumnToken:()=>ColumnToken,CommaToken:()=>CommaToken,DashMatchToken:()=>DashMatchToken,DelimToken:()=>DelimToken,DimensionToken:()=>DimensionToken,EOFToken:()=>EOFToken,FunctionToken:()=>FunctionToken,GroupingToken:()=>GroupingToken,HashToken:()=>HashToken,IdentToken:()=>IdentToken,IncludeMatchToken:()=>IncludeMatchToken,InvalidCharacterError:()=>InvalidCharacterError,NumberToken:()=>NumberToken,OpenCurlyToken:()=>OpenCurlyToken,OpenParenToken:()=>OpenParenToken,OpenSquareToken:()=>OpenSquareToken,PercentageToken:()=>PercentageToken,PrefixMatchToken:()=>PrefixMatchToken,SemicolonToken:()=>SemicolonToken,StringToken:()=>StringToken,StringValuedToken:()=>StringValuedToken,SubstringMatchToken:()=>SubstringMatchToken,SuffixMatchToken:()=>SuffixMatchToken,URLToken:()=>URLToken,WhitespaceToken:()=>WhitespaceToken,tokenize:()=>tokenize});G.exports=__toCommonJS(Xe);const between=function(G,K,je){return G>=K&&G<=je};function digit(G){return between(G,48,57)}function hexdigit(G){return digit(G)||between(G,65,70)||between(G,97,102)}function uppercaseletter(G){return between(G,65,90)}function lowercaseletter(G){return between(G,97,122)}function letter(G){return uppercaseletter(G)||lowercaseletter(G)}function nonascii(G){return G>=128}function namestartchar(G){return letter(G)||nonascii(G)||G===95}function namechar(G){return namestartchar(G)||digit(G)||G===45}function nonprintable(G){return between(G,0,8)||G===11||between(G,14,31)||G===127}function newline(G){return G===10}function whitespace(G){return newline(G)||G===9||G===32}const rt=1114111;class InvalidCharacterError extends Error{constructor(G){super(G);this.name="InvalidCharacterError"}}function preprocess(G){const K=[];for(let je=0;je<G.length;je++){let ze=G.charCodeAt(je);if(ze===13&&G.charCodeAt(je+1)===10){ze=10;je++}if(ze===13||ze===12)ze=10;if(ze===0)ze=65533;if(between(ze,55296,56319)&&between(G.charCodeAt(je+1),56320,57343)){const K=ze-55296;const We=G.charCodeAt(je+1)-56320;ze=Math.pow(2,16)+K*Math.pow(2,10)+We;je++}K.push(ze)}return K}function stringFromCode(G){if(G<=65535)return String.fromCharCode(G);G-=Math.pow(2,16);const K=Math.floor(G/Math.pow(2,10))+55296;const je=G%Math.pow(2,10)+56320;return String.fromCharCode(K)+String.fromCharCode(je)}function tokenize(G){const K=preprocess(G);let je=-1;const ze=[];let We;let Xe=0;let at=0;let ft=0;const incrLineno=function(){Xe+=1;ft=at;at=0};const mt={line:Xe,column:at};const codepoint=function(G){if(G>=K.length)return-1;return K[G]};const next=function(G){if(G===void 0)G=1;if(G>3)throw"Spec Error: no more than three codepoints of lookahead.";return codepoint(je+G)};const consume=function(G){if(G===void 0)G=1;je+=G;We=codepoint(je);if(newline(We))incrLineno();else at+=G;return true};const reconsume=function(){je-=1;if(newline(We)){Xe-=1;at=ft}else{at-=1}mt.line=Xe;mt.column=at;return true};const eof=function(G){if(G===void 0)G=We;return G===-1};const donothing=function(){};const parseerror=function(){};const consumeAToken=function(){consumeComments();consume();if(whitespace(We)){while(whitespace(next()))consume();return new WhitespaceToken}else if(We===34){return consumeAStringToken()}else if(We===35){if(namechar(next())||areAValidEscape(next(1),next(2))){const G=new HashToken("");if(wouldStartAnIdentifier(next(1),next(2),next(3)))G.type="id";G.value=consumeAName();return G}else{return new DelimToken(We)}}else if(We===36){if(next()===61){consume();return new SuffixMatchToken}else{return new DelimToken(We)}}else if(We===39){return consumeAStringToken()}else if(We===40){return new OpenParenToken}else if(We===41){return new CloseParenToken}else if(We===42){if(next()===61){consume();return new SubstringMatchToken}else{return new DelimToken(We)}}else if(We===43){if(startsWithANumber()){reconsume();return consumeANumericToken()}else{return new DelimToken(We)}}else if(We===44){return new CommaToken}else if(We===45){if(startsWithANumber()){reconsume();return consumeANumericToken()}else if(next(1)===45&&next(2)===62){consume(2);return new CDCToken}else if(startsWithAnIdentifier()){reconsume();return consumeAnIdentlikeToken()}else{return new DelimToken(We)}}else if(We===46){if(startsWithANumber()){reconsume();return consumeANumericToken()}else{return new DelimToken(We)}}else if(We===58){return new ColonToken}else if(We===59){return new SemicolonToken}else if(We===60){if(next(1)===33&&next(2)===45&&next(3)===45){consume(3);return new CDOToken}else{return new DelimToken(We)}}else if(We===64){if(wouldStartAnIdentifier(next(1),next(2),next(3)))return new AtKeywordToken(consumeAName());else return new DelimToken(We)}else if(We===91){return new OpenSquareToken}else if(We===92){if(startsWithAValidEscape()){reconsume();return consumeAnIdentlikeToken()}else{parseerror();return new DelimToken(We)}}else if(We===93){return new CloseSquareToken}else if(We===94){if(next()===61){consume();return new PrefixMatchToken}else{return new DelimToken(We)}}else if(We===123){return new OpenCurlyToken}else if(We===124){if(next()===61){consume();return new DashMatchToken}else if(next()===124){consume();return new ColumnToken}else{return new DelimToken(We)}}else if(We===125){return new CloseCurlyToken}else if(We===126){if(next()===61){consume();return new IncludeMatchToken}else{return new DelimToken(We)}}else if(digit(We)){reconsume();return consumeANumericToken()}else if(namestartchar(We)){reconsume();return consumeAnIdentlikeToken()}else if(eof()){return new EOFToken}else{return new DelimToken(We)}};const consumeComments=function(){while(next(1)===47&&next(2)===42){consume(2);while(true){consume();if(We===42&&next()===47){consume();break}else if(eof()){parseerror();return}}}};const consumeANumericToken=function(){const G=consumeANumber();if(wouldStartAnIdentifier(next(1),next(2),next(3))){const K=new DimensionToken;K.value=G.value;K.repr=G.repr;K.type=G.type;K.unit=consumeAName();return K}else if(next()===37){consume();const K=new PercentageToken;K.value=G.value;K.repr=G.repr;return K}else{const K=new NumberToken;K.value=G.value;K.repr=G.repr;K.type=G.type;return K}};const consumeAnIdentlikeToken=function(){const G=consumeAName();if(G.toLowerCase()==="url"&&next()===40){consume();while(whitespace(next(1))&&whitespace(next(2)))consume();if(next()===34||next()===39)return new FunctionToken(G);else if(whitespace(next())&&(next(2)===34||next(2)===39))return new FunctionToken(G);else return consumeAURLToken()}else if(next()===40){consume();return new FunctionToken(G)}else{return new IdentToken(G)}};const consumeAStringToken=function(G){if(G===void 0)G=We;let K="";while(consume()){if(We===G||eof()){return new StringToken(K)}else if(newline(We)){parseerror();reconsume();return new BadStringToken}else if(We===92){if(eof(next()))donothing();else if(newline(next()))consume();else K+=stringFromCode(consumeEscape())}else{K+=stringFromCode(We)}}throw new Error("Internal error")};const consumeAURLToken=function(){const G=new URLToken("");while(whitespace(next()))consume();if(eof(next()))return G;while(consume()){if(We===41||eof()){return G}else if(whitespace(We)){while(whitespace(next()))consume();if(next()===41||eof(next())){consume();return G}else{consumeTheRemnantsOfABadURL();return new BadURLToken}}else if(We===34||We===39||We===40||nonprintable(We)){parseerror();consumeTheRemnantsOfABadURL();return new BadURLToken}else if(We===92){if(startsWithAValidEscape()){G.value+=stringFromCode(consumeEscape())}else{parseerror();consumeTheRemnantsOfABadURL();return new BadURLToken}}else{G.value+=stringFromCode(We)}}throw new Error("Internal error")};const consumeEscape=function(){consume();if(hexdigit(We)){const G=[We];for(let K=0;K<5;K++){if(hexdigit(next())){consume();G.push(We)}else{break}}if(whitespace(next()))consume();let K=parseInt(G.map((function(G){return String.fromCharCode(G)})).join(""),16);if(K>rt)K=65533;return K}else if(eof()){return 65533}else{return We}};const areAValidEscape=function(G,K){if(G!==92)return false;if(newline(K))return false;return true};const startsWithAValidEscape=function(){return areAValidEscape(We,next())};const wouldStartAnIdentifier=function(G,K,je){if(G===45)return namestartchar(K)||K===45||areAValidEscape(K,je);else if(namestartchar(G))return true;else if(G===92)return areAValidEscape(G,K);else return false};const startsWithAnIdentifier=function(){return wouldStartAnIdentifier(We,next(1),next(2))};const wouldStartANumber=function(G,K,je){if(G===43||G===45){if(digit(K))return true;if(K===46&&digit(je))return true;return false}else if(G===46){if(digit(K))return true;return false}else if(digit(G)){return true}else{return false}};const startsWithANumber=function(){return wouldStartANumber(We,next(1),next(2))};const consumeAName=function(){let G="";while(consume()){if(namechar(We)){G+=stringFromCode(We)}else if(startsWithAValidEscape()){G+=stringFromCode(consumeEscape())}else{reconsume();return G}}throw new Error("Internal parse error")};const consumeANumber=function(){let G="";let K="integer";if(next()===43||next()===45){consume();G+=stringFromCode(We)}while(digit(next())){consume();G+=stringFromCode(We)}if(next(1)===46&&digit(next(2))){consume();G+=stringFromCode(We);consume();G+=stringFromCode(We);K="number";while(digit(next())){consume();G+=stringFromCode(We)}}const je=next(1),ze=next(2),Xe=next(3);if((je===69||je===101)&&digit(ze)){consume();G+=stringFromCode(We);consume();G+=stringFromCode(We);K="number";while(digit(next())){consume();G+=stringFromCode(We)}}else if((je===69||je===101)&&(ze===43||ze===45)&&digit(Xe)){consume();G+=stringFromCode(We);consume();G+=stringFromCode(We);consume();G+=stringFromCode(We);K="number";while(digit(next())){consume();G+=stringFromCode(We)}}const rt=convertAStringToANumber(G);return{type:K,value:rt,repr:G}};const convertAStringToANumber=function(G){return+G};const consumeTheRemnantsOfABadURL=function(){while(consume()){if(We===41||eof()){return}else if(startsWithAValidEscape()){consumeEscape();donothing()}else{donothing()}}};let vt=0;while(!eof(next())){ze.push(consumeAToken());vt++;if(vt>K.length*2)throw new Error("I'm infinite-looping!")}return ze}class CSSParserToken{constructor(){this.tokenType=""}toJSON(){return{token:this.tokenType}}toString(){return this.tokenType}toSource(){return""+this}}class BadStringToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="BADSTRING"}}class BadURLToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="BADURL"}}class WhitespaceToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="WHITESPACE"}toString(){return"WS"}toSource(){return" "}}class CDOToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="CDO"}toSource(){return"\x3c!--"}}class CDCToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="CDC"}toSource(){return"--\x3e"}}class ColonToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType=":"}}class SemicolonToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType=";"}}class CommaToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType=","}}class GroupingToken extends CSSParserToken{constructor(){super(...arguments);this.value="";this.mirror=""}}class OpenCurlyToken extends GroupingToken{constructor(){super();this.tokenType="{";this.value="{";this.mirror="}"}}class CloseCurlyToken extends GroupingToken{constructor(){super();this.tokenType="}";this.value="}";this.mirror="{"}}class OpenSquareToken extends GroupingToken{constructor(){super();this.tokenType="[";this.value="[";this.mirror="]"}}class CloseSquareToken extends GroupingToken{constructor(){super();this.tokenType="]";this.value="]";this.mirror="["}}class OpenParenToken extends GroupingToken{constructor(){super();this.tokenType="(";this.value="(";this.mirror=")"}}class CloseParenToken extends GroupingToken{constructor(){super();this.tokenType=")";this.value=")";this.mirror="("}}class IncludeMatchToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="~="}}class DashMatchToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="|="}}class PrefixMatchToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="^="}}class SuffixMatchToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="$="}}class SubstringMatchToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="*="}}class ColumnToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="||"}}class EOFToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="EOF"}toSource(){return""}}class DelimToken extends CSSParserToken{constructor(G){super();this.tokenType="DELIM";this.value="";this.value=stringFromCode(G)}toString(){return"DELIM("+this.value+")"}toJSON(){const G=this.constructor.prototype.constructor.prototype.toJSON.call(this);G.value=this.value;return G}toSource(){if(this.value==="\\")return"\\\n";else return this.value}}class StringValuedToken extends CSSParserToken{constructor(){super(...arguments);this.value=""}ASCIIMatch(G){return this.value.toLowerCase()===G.toLowerCase()}toJSON(){const G=this.constructor.prototype.constructor.prototype.toJSON.call(this);G.value=this.value;return G}}class IdentToken extends StringValuedToken{constructor(G){super();this.tokenType="IDENT";this.value=G}toString(){return"IDENT("+this.value+")"}toSource(){return escapeIdent(this.value)}}class FunctionToken extends StringValuedToken{constructor(G){super();this.tokenType="FUNCTION";this.value=G;this.mirror=")"}toString(){return"FUNCTION("+this.value+")"}toSource(){return escapeIdent(this.value)+"("}}class AtKeywordToken extends StringValuedToken{constructor(G){super();this.tokenType="AT-KEYWORD";this.value=G}toString(){return"AT("+this.value+")"}toSource(){return"@"+escapeIdent(this.value)}}class HashToken extends StringValuedToken{constructor(G){super();this.tokenType="HASH";this.value=G;this.type="unrestricted"}toString(){return"HASH("+this.value+")"}toJSON(){const G=this.constructor.prototype.constructor.prototype.toJSON.call(this);G.value=this.value;G.type=this.type;return G}toSource(){if(this.type==="id")return"#"+escapeIdent(this.value);else return"#"+escapeHash(this.value)}}class StringToken extends StringValuedToken{constructor(G){super();this.tokenType="STRING";this.value=G}toString(){return'"'+escapeString(this.value)+'"'}}class URLToken extends StringValuedToken{constructor(G){super();this.tokenType="URL";this.value=G}toString(){return"URL("+this.value+")"}toSource(){return'url("'+escapeString(this.value)+'")'}}class NumberToken extends CSSParserToken{constructor(){super();this.tokenType="NUMBER";this.type="integer";this.repr=""}toString(){if(this.type==="integer")return"INT("+this.value+")";return"NUMBER("+this.value+")"}toJSON(){const G=super.toJSON();G.value=this.value;G.type=this.type;G.repr=this.repr;return G}toSource(){return this.repr}}class PercentageToken extends CSSParserToken{constructor(){super();this.tokenType="PERCENTAGE";this.repr=""}toString(){return"PERCENTAGE("+this.value+")"}toJSON(){const G=this.constructor.prototype.constructor.prototype.toJSON.call(this);G.value=this.value;G.repr=this.repr;return G}toSource(){return this.repr+"%"}}class DimensionToken extends CSSParserToken{constructor(){super();this.tokenType="DIMENSION";this.type="integer";this.repr="";this.unit=""}toString(){return"DIM("+this.value+","+this.unit+")"}toJSON(){const G=this.constructor.prototype.constructor.prototype.toJSON.call(this);G.value=this.value;G.type=this.type;G.repr=this.repr;G.unit=this.unit;return G}toSource(){const G=this.repr;let K=escapeIdent(this.unit);if(K[0].toLowerCase()==="e"&&(K[1]==="-"||between(K.charCodeAt(1),48,57))){K="\\65 "+K.slice(1,K.length)}return G+K}}function escapeIdent(G){G=""+G;let K="";const je=G.charCodeAt(0);for(let ze=0;ze<G.length;ze++){const We=G.charCodeAt(ze);if(We===0)throw new InvalidCharacterError("Invalid character: the input contains U+0000.");if(between(We,1,31)||We===127||ze===0&&between(We,48,57)||ze===1&&between(We,48,57)&&je===45)K+="\\"+We.toString(16)+" ";else if(We>=128||We===45||We===95||between(We,48,57)||between(We,65,90)||between(We,97,122))K+=G[ze];else K+="\\"+G[ze]}return K}function escapeHash(G){G=""+G;let K="";for(let je=0;je<G.length;je++){const ze=G.charCodeAt(je);if(ze===0)throw new InvalidCharacterError("Invalid character: the input contains U+0000.");if(ze>=128||ze===45||ze===95||between(ze,48,57)||between(ze,65,90)||between(ze,97,122))K+=G[je];else K+="\\"+ze.toString(16)+" "}return K}function escapeString(G){G=""+G;let K="";for(let je=0;je<G.length;je++){const ze=G.charCodeAt(je);if(ze===0)throw new InvalidCharacterError("Invalid character: the input contains U+0000.");if(between(ze,1,31)||ze===127)K+="\\"+ze.toString(16)+" ";else if(ze===34||ze===92)K+="\\"+G[je];else K+=G[je]}return K}0&&0},71761:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{headersArrayToObject:()=>headersArrayToObject,headersObjectToArray:()=>headersObjectToArray});G.exports=__toCommonJS(Xe);function headersObjectToArray(G,K,je){if(!je)je=K;const ze=[];for(const We in G){const Xe=G[We];if(Xe===void 0)continue;if(K){const G=We.toLowerCase()==="set-cookie"?je:K;for(const K of Xe.split(G))ze.push({name:We,value:K.trim()})}else{ze.push({name:We,value:Xe})}}return ze}function headersArrayToObject(G,K){const je={};for(const{name:ze,value:We}of G)je[K?ze.toLowerCase():ze]=We;return je}0&&0},78359:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{CSharpLocatorFactory:()=>CSharpLocatorFactory,JavaLocatorFactory:()=>JavaLocatorFactory,JavaScriptLocatorFactory:()=>JavaScriptLocatorFactory,JsonlLocatorFactory:()=>JsonlLocatorFactory,PythonLocatorFactory:()=>PythonLocatorFactory,asLocator:()=>asLocator,asLocatorDescription:()=>asLocatorDescription,asLocators:()=>asLocators,locatorCustomDescription:()=>locatorCustomDescription});G.exports=__toCommonJS(at);var ft=je(37673);var mt=je(70017);function asLocatorDescription(G,K){try{const je=(0,ft.parseSelector)(K);const ze=parseCustomDescription(je);if(ze)return ze;return innerAsLocators(new vt[G],je,false,1)[0]}catch(G){return K}}function locatorCustomDescription(G){try{const K=(0,ft.parseSelector)(G);return parseCustomDescription(K)}catch(G){return void 0}}function parseCustomDescription(G){const K=G.parts[G.parts.length-1];if(K?.name==="internal:describe"){const G=JSON.parse(K.body);if(typeof G==="string")return G}return void 0}function asLocator(G,K,je=false){return asLocators(G,K,je,1)[0]}function asLocators(G,K,je=false,ze=20,We){try{return innerAsLocators(new vt[G](We),(0,ft.parseSelector)(K),je,ze)}catch(G){return[K]}}function innerAsLocators(G,K,je=false,ze=20){const We=[...K.parts];const Xe=[];let rt=je?"frame-locator":"page";for(let K=0;K<We.length;K++){const je=We[K];const at=rt;rt="locator";if(je.name==="internal:describe")continue;if(je.name==="nth"){if(je.body==="0")Xe.push([G.generateLocator(at,"first",""),G.generateLocator(at,"nth","0")]);else if(je.body==="-1")Xe.push([G.generateLocator(at,"last",""),G.generateLocator(at,"nth","-1")]);else Xe.push([G.generateLocator(at,"nth",je.body)]);continue}if(je.name==="visible"){Xe.push([G.generateLocator(at,"visible",je.body),G.generateLocator(at,"default",`visible=${je.body}`)]);continue}if(je.name==="internal:text"){const{exact:K,text:ze}=detectExact(je.body);Xe.push([G.generateLocator(at,"text",ze,{exact:K})]);continue}if(je.name==="internal:has-text"){const{exact:K,text:ze}=detectExact(je.body);if(!K){Xe.push([G.generateLocator(at,"has-text",ze,{exact:K})]);continue}}if(je.name==="internal:has-not-text"){const{exact:K,text:ze}=detectExact(je.body);if(!K){Xe.push([G.generateLocator(at,"has-not-text",ze,{exact:K})]);continue}}if(je.name==="internal:has"){const K=innerAsLocators(G,je.body.parsed,false,ze);Xe.push(K.map((K=>G.generateLocator(at,"has",K))));continue}if(je.name==="internal:has-not"){const K=innerAsLocators(G,je.body.parsed,false,ze);Xe.push(K.map((K=>G.generateLocator(at,"hasNot",K))));continue}if(je.name==="internal:and"){const K=innerAsLocators(G,je.body.parsed,false,ze);Xe.push(K.map((K=>G.generateLocator(at,"and",K))));continue}if(je.name==="internal:or"){const K=innerAsLocators(G,je.body.parsed,false,ze);Xe.push(K.map((K=>G.generateLocator(at,"or",K))));continue}if(je.name==="internal:chain"){const K=innerAsLocators(G,je.body.parsed,false,ze);Xe.push(K.map((K=>G.generateLocator(at,"chain",K))));continue}if(je.name==="internal:label"){const{exact:K,text:ze}=detectExact(je.body);Xe.push([G.generateLocator(at,"label",ze,{exact:K})]);continue}if(je.name==="internal:role"){const K=(0,ft.parseAttributeSelector)(je.body,true);const ze={attrs:[]};for(const G of K.attributes){if(G.name==="name"){ze.exact=G.caseSensitive;ze.name=G.value}else{if(G.name==="level"&&typeof G.value==="string")G.value=+G.value;ze.attrs.push({name:G.name==="include-hidden"?"includeHidden":G.name,value:G.value})}}Xe.push([G.generateLocator(at,"role",K.name,ze)]);continue}if(je.name==="internal:testid"){const K=(0,ft.parseAttributeSelector)(je.body,true);const{value:ze}=K.attributes[0];Xe.push([G.generateLocator(at,"test-id",ze)]);continue}if(je.name==="internal:attr"){const K=(0,ft.parseAttributeSelector)(je.body,true);const{name:ze,value:We,caseSensitive:rt}=K.attributes[0];const mt=We;const vt=!!rt;if(ze==="placeholder"){Xe.push([G.generateLocator(at,"placeholder",mt,{exact:vt})]);continue}if(ze==="alt"){Xe.push([G.generateLocator(at,"alt",mt,{exact:vt})]);continue}if(ze==="title"){Xe.push([G.generateLocator(at,"title",mt,{exact:vt})]);continue}}if(je.name==="internal:control"&&je.body==="enter-frame"){const je=Xe[Xe.length-1];const ze=We[K-1];const mt=je.map((K=>G.chainLocators([K,G.generateLocator(at,"frame","")])));if(["xpath","css"].includes(ze.name)){mt.push(G.generateLocator(at,"frame-locator",(0,ft.stringifySelector)({parts:[ze]})),G.generateLocator(at,"frame-locator",(0,ft.stringifySelector)({parts:[ze]},true)))}je.splice(0,je.length,...mt);rt="frame-locator";continue}const mt=We[K+1];const vt=(0,ft.stringifySelector)({parts:[je]});const yt=G.generateLocator(at,"default",vt);if(mt&&["internal:has-text","internal:has-not-text"].includes(mt.name)){const{exact:je,text:ze}=detectExact(mt.body);if(!je){const We=G.generateLocator("locator",mt.name==="internal:has-text"?"has-text":"has-not-text",ze,{exact:je});const rt={};if(mt.name==="internal:has-text")rt.hasText=ze;else rt.hasNotText=ze;const ft=G.generateLocator(at,"default",vt,rt);Xe.push([G.chainLocators([yt,We]),ft]);K++;continue}}let wt;if(["xpath","css"].includes(je.name)){const K=(0,ft.stringifySelector)({parts:[je]},true);wt=G.generateLocator(at,"default",K)}Xe.push([yt,wt].filter(Boolean))}return combineTokens(G,Xe,ze)}function combineTokens(G,K,je){const ze=K.map((()=>""));const We=[];const visit=Xe=>{if(Xe===K.length){We.push(G.chainLocators(ze));return We.length<je}for(const G of K[Xe]){ze[Xe]=G;if(!visit(Xe+1))return false}return true};visit(0);return We}function detectExact(G){let K=false;const je=G.match(/^\/(.*)\/([igm]*)$/);if(je)return{text:new RegExp(je[1],je[2])};if(G.endsWith('"')){G=JSON.parse(G);K=true}else if(G.endsWith('"s')){G=JSON.parse(G.substring(0,G.length-1));K=true}else if(G.endsWith('"i')){G=JSON.parse(G.substring(0,G.length-1));K=false}return{exact:K,text:G}}class JavaScriptLocatorFactory{constructor(G){this.preferredQuote=G}generateLocator(G,K,je,ze={}){switch(K){case"default":if(ze.hasText!==void 0)return`locator(${this.quote(je)}, { hasText: ${this.toHasText(ze.hasText)} })`;if(ze.hasNotText!==void 0)return`locator(${this.quote(je)}, { hasNotText: ${this.toHasText(ze.hasNotText)} })`;return`locator(${this.quote(je)})`;case"frame-locator":return`frameLocator(${this.quote(je)})`;case"frame":return`contentFrame()`;case"nth":return`nth(${je})`;case"first":return`first()`;case"last":return`last()`;case"visible":return`filter({ visible: ${je==="true"?"true":"false"} })`;case"role":const G=[];if(isRegExp(ze.name)){G.push(`name: ${this.regexToSourceString(ze.name)}`)}else if(typeof ze.name==="string"){G.push(`name: ${this.quote(ze.name)}`);if(ze.exact)G.push(`exact: true`)}for(const{name:K,value:je}of ze.attrs)G.push(`${K}: ${typeof je==="string"?this.quote(je):je}`);const We=G.length?`, { ${G.join(", ")} }`:"";return`getByRole(${this.quote(je)}${We})`;case"has-text":return`filter({ hasText: ${this.toHasText(je)} })`;case"has-not-text":return`filter({ hasNotText: ${this.toHasText(je)} })`;case"has":return`filter({ has: ${je} })`;case"hasNot":return`filter({ hasNot: ${je} })`;case"and":return`and(${je})`;case"or":return`or(${je})`;case"chain":return`locator(${je})`;case"test-id":return`getByTestId(${this.toTestIdValue(je)})`;case"text":return this.toCallWithExact("getByText",je,!!ze.exact);case"alt":return this.toCallWithExact("getByAltText",je,!!ze.exact);case"placeholder":return this.toCallWithExact("getByPlaceholder",je,!!ze.exact);case"label":return this.toCallWithExact("getByLabel",je,!!ze.exact);case"title":return this.toCallWithExact("getByTitle",je,!!ze.exact);default:throw new Error("Unknown selector kind "+K)}}chainLocators(G){return G.join(".")}regexToSourceString(G){return(0,mt.normalizeEscapedRegexQuotes)(String(G))}toCallWithExact(G,K,je){if(isRegExp(K))return`${G}(${this.regexToSourceString(K)})`;return je?`${G}(${this.quote(K)}, { exact: true })`:`${G}(${this.quote(K)})`}toHasText(G){if(isRegExp(G))return this.regexToSourceString(G);return this.quote(G)}toTestIdValue(G){if(isRegExp(G))return this.regexToSourceString(G);return this.quote(G)}quote(G){return(0,mt.escapeWithQuotes)(G,this.preferredQuote??"'")}}class PythonLocatorFactory{generateLocator(G,K,je,ze={}){switch(K){case"default":if(ze.hasText!==void 0)return`locator(${this.quote(je)}, has_text=${this.toHasText(ze.hasText)})`;if(ze.hasNotText!==void 0)return`locator(${this.quote(je)}, has_not_text=${this.toHasText(ze.hasNotText)})`;return`locator(${this.quote(je)})`;case"frame-locator":return`frame_locator(${this.quote(je)})`;case"frame":return`content_frame`;case"nth":return`nth(${je})`;case"first":return`first`;case"last":return`last`;case"visible":return`filter(visible=${je==="true"?"True":"False"})`;case"role":const G=[];if(isRegExp(ze.name)){G.push(`name=${this.regexToString(ze.name)}`)}else if(typeof ze.name==="string"){G.push(`name=${this.quote(ze.name)}`);if(ze.exact)G.push(`exact=True`)}for(const{name:K,value:je}of ze.attrs){let ze=typeof je==="string"?this.quote(je):je;if(typeof je==="boolean")ze=je?"True":"False";G.push(`${(0,mt.toSnakeCase)(K)}=${ze}`)}const We=G.length?`, ${G.join(", ")}`:"";return`get_by_role(${this.quote(je)}${We})`;case"has-text":return`filter(has_text=${this.toHasText(je)})`;case"has-not-text":return`filter(has_not_text=${this.toHasText(je)})`;case"has":return`filter(has=${je})`;case"hasNot":return`filter(has_not=${je})`;case"and":return`and_(${je})`;case"or":return`or_(${je})`;case"chain":return`locator(${je})`;case"test-id":return`get_by_test_id(${this.toTestIdValue(je)})`;case"text":return this.toCallWithExact("get_by_text",je,!!ze.exact);case"alt":return this.toCallWithExact("get_by_alt_text",je,!!ze.exact);case"placeholder":return this.toCallWithExact("get_by_placeholder",je,!!ze.exact);case"label":return this.toCallWithExact("get_by_label",je,!!ze.exact);case"title":return this.toCallWithExact("get_by_title",je,!!ze.exact);default:throw new Error("Unknown selector kind "+K)}}chainLocators(G){return G.join(".")}regexToString(G){const K=G.flags.includes("i")?", re.IGNORECASE":"";return`re.compile(r"${(0,mt.normalizeEscapedRegexQuotes)(G.source).replace(/\\\//,"/").replace(/"/g,'\\"')}"${K})`}toCallWithExact(G,K,je){if(isRegExp(K))return`${G}(${this.regexToString(K)})`;if(je)return`${G}(${this.quote(K)}, exact=True)`;return`${G}(${this.quote(K)})`}toHasText(G){if(isRegExp(G))return this.regexToString(G);return`${this.quote(G)}`}toTestIdValue(G){if(isRegExp(G))return this.regexToString(G);return this.quote(G)}quote(G){return(0,mt.escapeWithQuotes)(G,'"')}}class JavaLocatorFactory{generateLocator(G,K,je,ze={}){let We;switch(G){case"page":We="Page";break;case"frame-locator":We="FrameLocator";break;case"locator":We="Locator";break}switch(K){case"default":if(ze.hasText!==void 0)return`locator(${this.quote(je)}, new ${We}.LocatorOptions().setHasText(${this.toHasText(ze.hasText)}))`;if(ze.hasNotText!==void 0)return`locator(${this.quote(je)}, new ${We}.LocatorOptions().setHasNotText(${this.toHasText(ze.hasNotText)}))`;return`locator(${this.quote(je)})`;case"frame-locator":return`frameLocator(${this.quote(je)})`;case"frame":return`contentFrame()`;case"nth":return`nth(${je})`;case"first":return`first()`;case"last":return`last()`;case"visible":return`filter(new ${We}.FilterOptions().setVisible(${je==="true"?"true":"false"}))`;case"role":const G=[];if(isRegExp(ze.name)){G.push(`.setName(${this.regexToString(ze.name)})`)}else if(typeof ze.name==="string"){G.push(`.setName(${this.quote(ze.name)})`);if(ze.exact)G.push(`.setExact(true)`)}for(const{name:K,value:je}of ze.attrs)G.push(`.set${(0,mt.toTitleCase)(K)}(${typeof je==="string"?this.quote(je):je})`);const Xe=G.length?`, new ${We}.GetByRoleOptions()${G.join("")}`:"";return`getByRole(AriaRole.${(0,mt.toSnakeCase)(je).toUpperCase()}${Xe})`;case"has-text":return`filter(new ${We}.FilterOptions().setHasText(${this.toHasText(je)}))`;case"has-not-text":return`filter(new ${We}.FilterOptions().setHasNotText(${this.toHasText(je)}))`;case"has":return`filter(new ${We}.FilterOptions().setHas(${je}))`;case"hasNot":return`filter(new ${We}.FilterOptions().setHasNot(${je}))`;case"and":return`and(${je})`;case"or":return`or(${je})`;case"chain":return`locator(${je})`;case"test-id":return`getByTestId(${this.toTestIdValue(je)})`;case"text":return this.toCallWithExact(We,"getByText",je,!!ze.exact);case"alt":return this.toCallWithExact(We,"getByAltText",je,!!ze.exact);case"placeholder":return this.toCallWithExact(We,"getByPlaceholder",je,!!ze.exact);case"label":return this.toCallWithExact(We,"getByLabel",je,!!ze.exact);case"title":return this.toCallWithExact(We,"getByTitle",je,!!ze.exact);default:throw new Error("Unknown selector kind "+K)}}chainLocators(G){return G.join(".")}regexToString(G){const K=G.flags.includes("i")?", Pattern.CASE_INSENSITIVE":"";return`Pattern.compile(${this.quote((0,mt.normalizeEscapedRegexQuotes)(G.source))}${K})`}toCallWithExact(G,K,je,ze){if(isRegExp(je))return`${K}(${this.regexToString(je)})`;if(ze)return`${K}(${this.quote(je)}, new ${G}.${(0,mt.toTitleCase)(K)}Options().setExact(true))`;return`${K}(${this.quote(je)})`}toHasText(G){if(isRegExp(G))return this.regexToString(G);return this.quote(G)}toTestIdValue(G){if(isRegExp(G))return this.regexToString(G);return this.quote(G)}quote(G){return(0,mt.escapeWithQuotes)(G,'"')}}class CSharpLocatorFactory{generateLocator(G,K,je,ze={}){switch(K){case"default":if(ze.hasText!==void 0)return`Locator(${this.quote(je)}, new() { ${this.toHasText(ze.hasText)} })`;if(ze.hasNotText!==void 0)return`Locator(${this.quote(je)}, new() { ${this.toHasNotText(ze.hasNotText)} })`;return`Locator(${this.quote(je)})`;case"frame-locator":return`FrameLocator(${this.quote(je)})`;case"frame":return`ContentFrame`;case"nth":return`Nth(${je})`;case"first":return`First`;case"last":return`Last`;case"visible":return`Filter(new() { Visible = ${je==="true"?"true":"false"} })`;case"role":const G=[];if(isRegExp(ze.name)){G.push(`NameRegex = ${this.regexToString(ze.name)}`)}else if(typeof ze.name==="string"){G.push(`Name = ${this.quote(ze.name)}`);if(ze.exact)G.push(`Exact = true`)}for(const{name:K,value:je}of ze.attrs)G.push(`${(0,mt.toTitleCase)(K)} = ${typeof je==="string"?this.quote(je):je}`);const We=G.length?`, new() { ${G.join(", ")} }`:"";return`GetByRole(AriaRole.${(0,mt.toTitleCase)(je)}${We})`;case"has-text":return`Filter(new() { ${this.toHasText(je)} })`;case"has-not-text":return`Filter(new() { ${this.toHasNotText(je)} })`;case"has":return`Filter(new() { Has = ${je} })`;case"hasNot":return`Filter(new() { HasNot = ${je} })`;case"and":return`And(${je})`;case"or":return`Or(${je})`;case"chain":return`Locator(${je})`;case"test-id":return`GetByTestId(${this.toTestIdValue(je)})`;case"text":return this.toCallWithExact("GetByText",je,!!ze.exact);case"alt":return this.toCallWithExact("GetByAltText",je,!!ze.exact);case"placeholder":return this.toCallWithExact("GetByPlaceholder",je,!!ze.exact);case"label":return this.toCallWithExact("GetByLabel",je,!!ze.exact);case"title":return this.toCallWithExact("GetByTitle",je,!!ze.exact);default:throw new Error("Unknown selector kind "+K)}}chainLocators(G){return G.join(".")}regexToString(G){const K=G.flags.includes("i")?", RegexOptions.IgnoreCase":"";return`new Regex(${this.quote((0,mt.normalizeEscapedRegexQuotes)(G.source))}${K})`}toCallWithExact(G,K,je){if(isRegExp(K))return`${G}(${this.regexToString(K)})`;if(je)return`${G}(${this.quote(K)}, new() { Exact = true })`;return`${G}(${this.quote(K)})`}toHasText(G){if(isRegExp(G))return`HasTextRegex = ${this.regexToString(G)}`;return`HasText = ${this.quote(G)}`}toTestIdValue(G){if(isRegExp(G))return this.regexToString(G);return this.quote(G)}toHasNotText(G){if(isRegExp(G))return`HasNotTextRegex = ${this.regexToString(G)}`;return`HasNotText = ${this.quote(G)}`}quote(G){return(0,mt.escapeWithQuotes)(G,'"')}}class JsonlLocatorFactory{generateLocator(G,K,je,ze={}){return JSON.stringify({kind:K,body:je,options:ze})}chainLocators(G){const K=G.map((G=>JSON.parse(G)));for(let G=0;G<K.length-1;++G)K[G].next=K[G+1];return JSON.stringify(K[0])}}const vt={javascript:JavaScriptLocatorFactory,python:PythonLocatorFactory,java:JavaLocatorFactory,csharp:CSharpLocatorFactory,jsonl:JsonlLocatorFactory};function isRegExp(G){return G instanceof RegExp}0&&0},32930:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{locatorOrSelectorAsSelector:()=>locatorOrSelectorAsSelector,unsafeLocatorOrSelectorAsSelector:()=>unsafeLocatorOrSelectorAsSelector});G.exports=__toCommonJS(at);var ft=je(78359);var mt=je(37673);var vt=je(70017);function parseLocator(G,K){G=G.replace(/AriaRole\s*\.\s*([\w]+)/g,((G,K)=>K.toLowerCase())).replace(/(get_by_role|getByRole)\s*\(\s*(?:["'`])([^'"`]+)['"`]/g,((G,K,je)=>`${K}(${je.toLowerCase()}`));const je=[];let ze="";for(let K=0;K<G.length;++K){const We=G[K];if(We!=='"'&&We!=="'"&&We!=="`"&&We!=="/"){ze+=We;continue}const Xe=G[K-1]==="r"||G[K]==="/";++K;let rt="";while(K<G.length){if(G[K]==="\\"){if(Xe){if(G[K+1]!==We)rt+=G[K];++K;rt+=G[K]}else{++K;if(G[K]==="n")rt+="\n";else if(G[K]==="r")rt+="\r";else if(G[K]==="t")rt+="\t";else rt+=G[K]}++K;continue}if(G[K]!==We){rt+=G[K++];continue}break}je.push({quote:We,text:rt});ze+=(We==="/"?"r":"")+"$"+je.length}ze=ze.toLowerCase().replace(/get_by_alt_text/g,"getbyalttext").replace(/get_by_test_id/g,"getbytestid").replace(/get_by_([\w]+)/g,"getby$1").replace(/has_not_text/g,"hasnottext").replace(/has_text/g,"hastext").replace(/has_not/g,"hasnot").replace(/frame_locator/g,"framelocator").replace(/content_frame/g,"contentframe").replace(/[{}\s]/g,"").replace(/new\(\)/g,"").replace(/new[\w]+\.[\w]+options\(\)/g,"").replace(/\.set/g,",set").replace(/\.or_\(/g,"or(").replace(/\.and_\(/g,"and(").replace(/:/g,"=").replace(/,re\.ignorecase/g,"i").replace(/,pattern.case_insensitive/g,"i").replace(/,regexoptions.ignorecase/g,"i").replace(/re.compile\(([^)]+)\)/g,"$1").replace(/pattern.compile\(([^)]+)\)/g,"r$1").replace(/newregex\(([^)]+)\)/g,"r$1").replace(/string=/g,"=").replace(/regex=/g,"=").replace(/,,/g,",").replace(/,\)/g,")");const We=je.map((G=>G.quote)).filter((G=>"'\"`".includes(G)))[0];return{selector:transform(ze,je,K),preferredQuote:We}}function countParams(G){return[...G.matchAll(/\$\d+/g)].length}function shiftParams(G,K){return G.replace(/\$(\d+)/g,((G,je)=>`$${je-K}`))}function transform(G,K,je){while(true){const ze=G.match(/filter\(,?(has=|hasnot=|sethas\(|sethasnot\()/);if(!ze)break;const We=ze.index+ze[0].length;let Xe=0;let rt=We;for(;rt<G.length;rt++){if(G[rt]==="(")Xe++;else if(G[rt]===")")Xe--;if(Xe<0)break}let at=G.substring(0,We);let ft=0;if(["sethas(","sethasnot("].includes(ze[1])){ft=1;at=at.replace(/sethas\($/,"has=").replace(/sethasnot\($/,"hasnot=")}const mt=countParams(G.substring(0,We));const vt=shiftParams(G.substring(We,rt),mt);const yt=countParams(vt);const wt=K.slice(mt,mt+yt);const lr=JSON.stringify(transform(vt,wt,je));G=at.replace(/=$/,"2=")+`$${mt+1}`+shiftParams(G.substring(rt+ft),yt-1);const Er=K.slice(0,mt);const Rr=K.slice(mt+yt);K=Er.concat([{quote:'"',text:lr}]).concat(Rr)}G=G.replace(/\,set([\w]+)\(([^)]+)\)/g,((G,K,je)=>","+K.toLowerCase()+"="+je.toLowerCase())).replace(/framelocator\(([^)]+)\)/g,"$1.internal:control=enter-frame").replace(/contentframe(\(\))?/g,"internal:control=enter-frame").replace(/locator\(([^)]+),hastext=([^),]+)\)/g,"locator($1).internal:has-text=$2").replace(/locator\(([^)]+),hasnottext=([^),]+)\)/g,"locator($1).internal:has-not-text=$2").replace(/locator\(([^)]+),hastext=([^),]+)\)/g,"locator($1).internal:has-text=$2").replace(/locator\(([^)]+)\)/g,"$1").replace(/getbyrole\(([^)]+)\)/g,"internal:role=$1").replace(/getbytext\(([^)]+)\)/g,"internal:text=$1").replace(/getbylabel\(([^)]+)\)/g,"internal:label=$1").replace(/getbytestid\(([^)]+)\)/g,`internal:testid=[${je}=$1]`).replace(/getby(placeholder|alt|title)(?:text)?\(([^)]+)\)/g,"internal:attr=[$1=$2]").replace(/first(\(\))?/g,"nth=0").replace(/last(\(\))?/g,"nth=-1").replace(/nth\(([^)]+)\)/g,"nth=$1").replace(/filter\(,?visible=true\)/g,"visible=true").replace(/filter\(,?visible=false\)/g,"visible=false").replace(/filter\(,?hastext=([^)]+)\)/g,"internal:has-text=$1").replace(/filter\(,?hasnottext=([^)]+)\)/g,"internal:has-not-text=$1").replace(/filter\(,?has2=([^)]+)\)/g,"internal:has=$1").replace(/filter\(,?hasnot2=([^)]+)\)/g,"internal:has-not=$1").replace(/,exact=false/g,"").replace(/,exact=true/g,"s").replace(/,includehidden=/g,",include-hidden=").replace(/\,/g,"][");const ze=G.split(".");for(let G=0;G<ze.length-1;G++){if(ze[G]==="internal:control=enter-frame"&&ze[G+1].startsWith("nth=")){const[K]=ze.splice(G,1);ze.splice(G+1,0,K)}}return ze.map((G=>{if(!G.startsWith("internal:")||G==="internal:control")return G.replace(/\$(\d+)/g,((G,je)=>{const ze=K[+je-1];return ze.text}));G=G.includes("[")?G.replace(/\]/,"")+"]":G;G=G.replace(/(?:r)\$(\d+)(i)?/g,((je,ze,We)=>{const Xe=K[+ze-1];if(G.startsWith("internal:attr")||G.startsWith("internal:testid")||G.startsWith("internal:role"))return(0,vt.escapeForAttributeSelector)(new RegExp(Xe.text),false)+(We||"");return(0,vt.escapeForTextSelector)(new RegExp(Xe.text,We),false)})).replace(/\$(\d+)(i|s)?/g,((je,ze,We)=>{const Xe=K[+ze-1];if(G.startsWith("internal:has=")||G.startsWith("internal:has-not="))return Xe.text;if(G.startsWith("internal:testid"))return(0,vt.escapeForAttributeSelector)(Xe.text,true);if(G.startsWith("internal:attr")||G.startsWith("internal:role"))return(0,vt.escapeForAttributeSelector)(Xe.text,We==="s");return(0,vt.escapeForTextSelector)(Xe.text,We==="s")}));return G})).join(" >> ")}function locatorOrSelectorAsSelector(G,K,je){try{return unsafeLocatorOrSelectorAsSelector(G,K,je)}catch(G){return""}}function unsafeLocatorOrSelectorAsSelector(G,K,je){try{(0,mt.parseSelector)(K);return K}catch(G){}const{selector:ze,preferredQuote:We}=parseLocator(K,je);const Xe=(0,ft.asLocators)(G,ze,void 0,void 0,We);const rt=digestForComparison(G,K);if(Xe.some((K=>digestForComparison(G,K)===rt)))return ze;return""}function digestForComparison(G,K){K=K.replace(/\s/g,"");if(G==="javascript")K=K.replace(/\\?["`]/g,"'").replace(/,{}/g,"");return K}0&&0},25880:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{getByAltTextSelector:()=>getByAltTextSelector,getByLabelSelector:()=>getByLabelSelector,getByPlaceholderSelector:()=>getByPlaceholderSelector,getByRoleSelector:()=>getByRoleSelector,getByTestIdSelector:()=>getByTestIdSelector,getByTextSelector:()=>getByTextSelector,getByTitleSelector:()=>getByTitleSelector});G.exports=__toCommonJS(at);var ft=je(70017);function getByAttributeTextSelector(G,K,je){return`internal:attr=[${G}=${(0,ft.escapeForAttributeSelector)(K,je?.exact||false)}]`}function getByTestIdSelector(G,K){return`internal:testid=[${G}=${(0,ft.escapeForAttributeSelector)(K,true)}]`}function getByLabelSelector(G,K){return"internal:label="+(0,ft.escapeForTextSelector)(G,!!K?.exact)}function getByAltTextSelector(G,K){return getByAttributeTextSelector("alt",G,K)}function getByTitleSelector(G,K){return getByAttributeTextSelector("title",G,K)}function getByPlaceholderSelector(G,K){return getByAttributeTextSelector("placeholder",G,K)}function getByTextSelector(G,K){return"internal:text="+(0,ft.escapeForTextSelector)(G,!!K?.exact)}function getByRoleSelector(G,K={}){const je=[];if(K.checked!==void 0)je.push(["checked",String(K.checked)]);if(K.disabled!==void 0)je.push(["disabled",String(K.disabled)]);if(K.selected!==void 0)je.push(["selected",String(K.selected)]);if(K.expanded!==void 0)je.push(["expanded",String(K.expanded)]);if(K.includeHidden!==void 0)je.push(["include-hidden",String(K.includeHidden)]);if(K.level!==void 0)je.push(["level",String(K.level)]);if(K.name!==void 0)je.push(["name",(0,ft.escapeForAttributeSelector)(K.name,!!K.exact)]);if(K.pressed!==void 0)je.push(["pressed",String(K.pressed)]);return`internal:role=${G}${je.map((([G,K])=>`[${G}=${K}]`)).join("")}`}0&&0},28040:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{LongStandingScope:()=>LongStandingScope,ManualPromise:()=>ManualPromise});G.exports=__toCommonJS(at);var ft=je(46662);class ManualPromise extends Promise{constructor(){let G;let K;super(((je,ze)=>{G=je;K=ze}));this._isDone=false;this._resolve=G;this._reject=K}isDone(){return this._isDone}resolve(G){this._isDone=true;this._resolve(G)}reject(G){this._isDone=true;this._reject(G)}static get[Symbol.species](){return Promise}get[Symbol.toStringTag](){return"ManualPromise"}}class LongStandingScope{constructor(){this._terminatePromises=new Map;this._isClosed=false}reject(G){this._isClosed=true;this._terminateError=G;for(const K of this._terminatePromises.keys())K.resolve(G)}close(G){this._isClosed=true;this._closeError=G;for(const[K,je]of this._terminatePromises)K.resolve(cloneError(G,je))}isClosed(){return this._isClosed}static async raceMultiple(G,K){return Promise.race(G.map((G=>G.race(K))))}async race(G){return this._race(Array.isArray(G)?G:[G],false)}async safeRace(G,K){return this._race([G],true,K)}async _race(G,K,je){const ze=new ManualPromise;const We=(0,ft.captureRawStack)();if(this._terminateError)ze.resolve(this._terminateError);if(this._closeError)ze.resolve(cloneError(this._closeError,We));this._terminatePromises.set(ze,We);try{return await Promise.race([ze.then((G=>K?je:Promise.reject(G))),...G])}finally{this._terminatePromises.delete(ze)}}}function cloneError(G,K){const je=new Error;je.name=G.name;je.message=G.message;je.stack=[G.name+":"+G.message,...K].join("\n");return je}0&&0},22467:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{getMimeTypeForPath:()=>getMimeTypeForPath,isJsonMimeType:()=>isJsonMimeType,isTextualMimeType:()=>isTextualMimeType});G.exports=__toCommonJS(Xe);function isJsonMimeType(G){return!!G.match(/^(application\/json|application\/.*?\+json|text\/(x-)?json)(;\s*charset=.*)?$/)}function isTextualMimeType(G){return!!G.match(/^(text\/.*?|application\/(json|(x-)?javascript|xml.*?|ecmascript|graphql|x-www-form-urlencoded)|image\/svg(\+xml)?|application\/.*?(\+json|\+xml))(;\s*charset=.*)?$/)}function getMimeTypeForPath(G){const K=G.lastIndexOf(".");if(K===-1)return null;const je=G.substring(K+1);return rt.get(je)||null}const rt=new Map([["ez","application/andrew-inset"],["aw","application/applixware"],["atom","application/atom+xml"],["atomcat","application/atomcat+xml"],["atomdeleted","application/atomdeleted+xml"],["atomsvc","application/atomsvc+xml"],["dwd","application/atsc-dwd+xml"],["held","application/atsc-held+xml"],["rsat","application/atsc-rsat+xml"],["bdoc","application/bdoc"],["xcs","application/calendar+xml"],["ccxml","application/ccxml+xml"],["cdfx","application/cdfx+xml"],["cdmia","application/cdmi-capability"],["cdmic","application/cdmi-container"],["cdmid","application/cdmi-domain"],["cdmio","application/cdmi-object"],["cdmiq","application/cdmi-queue"],["cu","application/cu-seeme"],["mpd","application/dash+xml"],["davmount","application/davmount+xml"],["dbk","application/docbook+xml"],["dssc","application/dssc+der"],["xdssc","application/dssc+xml"],["ecma","application/ecmascript"],["es","application/ecmascript"],["emma","application/emma+xml"],["emotionml","application/emotionml+xml"],["epub","application/epub+zip"],["exi","application/exi"],["exp","application/express"],["fdt","application/fdt+xml"],["pfr","application/font-tdpfr"],["geojson","application/geo+json"],["gml","application/gml+xml"],["gpx","application/gpx+xml"],["gxf","application/gxf"],["gz","application/gzip"],["hjson","application/hjson"],["stk","application/hyperstudio"],["ink","application/inkml+xml"],["inkml","application/inkml+xml"],["ipfix","application/ipfix"],["its","application/its+xml"],["ear","application/java-archive"],["jar","application/java-archive"],["war","application/java-archive"],["ser","application/java-serialized-object"],["class","application/java-vm"],["js","application/javascript"],["mjs","application/javascript"],["json","application/json"],["map","application/json"],["json5","application/json5"],["jsonml","application/jsonml+json"],["jsonld","application/ld+json"],["lgr","application/lgr+xml"],["lostxml","application/lost+xml"],["hqx","application/mac-binhex40"],["cpt","application/mac-compactpro"],["mads","application/mads+xml"],["webmanifest","application/manifest+json"],["mrc","application/marc"],["mrcx","application/marcxml+xml"],["ma","application/mathematica"],["mb","application/mathematica"],["nb","application/mathematica"],["mathml","application/mathml+xml"],["mbox","application/mbox"],["mscml","application/mediaservercontrol+xml"],["metalink","application/metalink+xml"],["meta4","application/metalink4+xml"],["mets","application/mets+xml"],["maei","application/mmt-aei+xml"],["musd","application/mmt-usd+xml"],["mods","application/mods+xml"],["m21","application/mp21"],["mp21","application/mp21"],["m4p","application/mp4"],["mp4s","application/mp4"],["doc","application/msword"],["dot","application/msword"],["mxf","application/mxf"],["nq","application/n-quads"],["nt","application/n-triples"],["cjs","application/node"],["bin","application/octet-stream"],["bpk","application/octet-stream"],["buffer","application/octet-stream"],["deb","application/octet-stream"],["deploy","application/octet-stream"],["dist","application/octet-stream"],["distz","application/octet-stream"],["dll","application/octet-stream"],["dmg","application/octet-stream"],["dms","application/octet-stream"],["dump","application/octet-stream"],["elc","application/octet-stream"],["exe","application/octet-stream"],["img","application/octet-stream"],["iso","application/octet-stream"],["lrf","application/octet-stream"],["mar","application/octet-stream"],["msi","application/octet-stream"],["msm","application/octet-stream"],["msp","application/octet-stream"],["pkg","application/octet-stream"],["so","application/octet-stream"],["oda","application/oda"],["opf","application/oebps-package+xml"],["ogx","application/ogg"],["omdoc","application/omdoc+xml"],["onepkg","application/onenote"],["onetmp","application/onenote"],["onetoc","application/onenote"],["onetoc2","application/onenote"],["oxps","application/oxps"],["relo","application/p2p-overlay+xml"],["xer","application/patch-ops-error+xml"],["pdf","application/pdf"],["pgp","application/pgp-encrypted"],["asc","application/pgp-signature"],["sig","application/pgp-signature"],["prf","application/pics-rules"],["p10","application/pkcs10"],["p7c","application/pkcs7-mime"],["p7m","application/pkcs7-mime"],["p7s","application/pkcs7-signature"],["p8","application/pkcs8"],["ac","application/pkix-attr-cert"],["cer","application/pkix-cert"],["crl","application/pkix-crl"],["pkipath","application/pkix-pkipath"],["pki","application/pkixcmp"],["pls","application/pls+xml"],["ai","application/postscript"],["eps","application/postscript"],["ps","application/postscript"],["provx","application/provenance+xml"],["pskcxml","application/pskc+xml"],["raml","application/raml+yaml"],["owl","application/rdf+xml"],["rdf","application/rdf+xml"],["rif","application/reginfo+xml"],["rnc","application/relax-ng-compact-syntax"],["rl","application/resource-lists+xml"],["rld","application/resource-lists-diff+xml"],["rs","application/rls-services+xml"],["rapd","application/route-apd+xml"],["sls","application/route-s-tsid+xml"],["rusd","application/route-usd+xml"],["gbr","application/rpki-ghostbusters"],["mft","application/rpki-manifest"],["roa","application/rpki-roa"],["rsd","application/rsd+xml"],["rss","application/rss+xml"],["rtf","application/rtf"],["sbml","application/sbml+xml"],["scq","application/scvp-cv-request"],["scs","application/scvp-cv-response"],["spq","application/scvp-vp-request"],["spp","application/scvp-vp-response"],["sdp","application/sdp"],["senmlx","application/senml+xml"],["sensmlx","application/sensml+xml"],["setpay","application/set-payment-initiation"],["setreg","application/set-registration-initiation"],["shf","application/shf+xml"],["sieve","application/sieve"],["siv","application/sieve"],["smi","application/smil+xml"],["smil","application/smil+xml"],["rq","application/sparql-query"],["srx","application/sparql-results+xml"],["gram","application/srgs"],["grxml","application/srgs+xml"],["sru","application/sru+xml"],["ssdl","application/ssdl+xml"],["ssml","application/ssml+xml"],["swidtag","application/swid+xml"],["tei","application/tei+xml"],["teicorpus","application/tei+xml"],["tfi","application/thraud+xml"],["tsd","application/timestamped-data"],["toml","application/toml"],["trig","application/trig"],["ttml","application/ttml+xml"],["ubj","application/ubjson"],["rsheet","application/urc-ressheet+xml"],["td","application/urc-targetdesc+xml"],["vxml","application/voicexml+xml"],["wasm","application/wasm"],["wgt","application/widget"],["hlp","application/winhlp"],["wsdl","application/wsdl+xml"],["wspolicy","application/wspolicy+xml"],["xaml","application/xaml+xml"],["xav","application/xcap-att+xml"],["xca","application/xcap-caps+xml"],["xdf","application/xcap-diff+xml"],["xel","application/xcap-el+xml"],["xns","application/xcap-ns+xml"],["xenc","application/xenc+xml"],["xht","application/xhtml+xml"],["xhtml","application/xhtml+xml"],["xlf","application/xliff+xml"],["rng","application/xml"],["xml","application/xml"],["xsd","application/xml"],["xsl","application/xml"],["dtd","application/xml-dtd"],["xop","application/xop+xml"],["xpl","application/xproc+xml"],["*xsl","application/xslt+xml"],["xslt","application/xslt+xml"],["xspf","application/xspf+xml"],["mxml","application/xv+xml"],["xhvml","application/xv+xml"],["xvm","application/xv+xml"],["xvml","application/xv+xml"],["yang","application/yang"],["yin","application/yin+xml"],["zip","application/zip"],["*3gpp","audio/3gpp"],["adp","audio/adpcm"],["amr","audio/amr"],["au","audio/basic"],["snd","audio/basic"],["kar","audio/midi"],["mid","audio/midi"],["midi","audio/midi"],["rmi","audio/midi"],["mxmf","audio/mobile-xmf"],["*mp3","audio/mp3"],["m4a","audio/mp4"],["mp4a","audio/mp4"],["m2a","audio/mpeg"],["m3a","audio/mpeg"],["mp2","audio/mpeg"],["mp2a","audio/mpeg"],["mp3","audio/mpeg"],["mpga","audio/mpeg"],["oga","audio/ogg"],["ogg","audio/ogg"],["opus","audio/ogg"],["spx","audio/ogg"],["s3m","audio/s3m"],["sil","audio/silk"],["wav","audio/wav"],["*wav","audio/wave"],["weba","audio/webm"],["xm","audio/xm"],["ttc","font/collection"],["otf","font/otf"],["ttf","font/ttf"],["woff","font/woff"],["woff2","font/woff2"],["exr","image/aces"],["apng","image/apng"],["avif","image/avif"],["bmp","image/bmp"],["cgm","image/cgm"],["drle","image/dicom-rle"],["emf","image/emf"],["fits","image/fits"],["g3","image/g3fax"],["gif","image/gif"],["heic","image/heic"],["heics","image/heic-sequence"],["heif","image/heif"],["heifs","image/heif-sequence"],["hej2","image/hej2k"],["hsj2","image/hsj2"],["ief","image/ief"],["jls","image/jls"],["jp2","image/jp2"],["jpg2","image/jp2"],["jpe","image/jpeg"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["jph","image/jph"],["jhc","image/jphc"],["jpm","image/jpm"],["jpf","image/jpx"],["jpx","image/jpx"],["jxr","image/jxr"],["jxra","image/jxra"],["jxrs","image/jxrs"],["jxs","image/jxs"],["jxsc","image/jxsc"],["jxsi","image/jxsi"],["jxss","image/jxss"],["ktx","image/ktx"],["ktx2","image/ktx2"],["png","image/png"],["sgi","image/sgi"],["svg","image/svg+xml"],["svgz","image/svg+xml"],["t38","image/t38"],["tif","image/tiff"],["tiff","image/tiff"],["tfx","image/tiff-fx"],["webp","image/webp"],["wmf","image/wmf"],["disposition-notification","message/disposition-notification"],["u8msg","message/global"],["u8dsn","message/global-delivery-status"],["u8mdn","message/global-disposition-notification"],["u8hdr","message/global-headers"],["eml","message/rfc822"],["mime","message/rfc822"],["3mf","model/3mf"],["gltf","model/gltf+json"],["glb","model/gltf-binary"],["iges","model/iges"],["igs","model/iges"],["mesh","model/mesh"],["msh","model/mesh"],["silo","model/mesh"],["mtl","model/mtl"],["obj","model/obj"],["stpx","model/step+xml"],["stpz","model/step+zip"],["stpxz","model/step-xml+zip"],["stl","model/stl"],["vrml","model/vrml"],["wrl","model/vrml"],["*x3db","model/x3d+binary"],["x3dbz","model/x3d+binary"],["x3db","model/x3d+fastinfoset"],["*x3dv","model/x3d+vrml"],["x3dvz","model/x3d+vrml"],["x3d","model/x3d+xml"],["x3dz","model/x3d+xml"],["x3dv","model/x3d-vrml"],["appcache","text/cache-manifest"],["manifest","text/cache-manifest"],["ics","text/calendar"],["ifb","text/calendar"],["coffee","text/coffeescript"],["litcoffee","text/coffeescript"],["css","text/css"],["csv","text/csv"],["htm","text/html"],["html","text/html"],["shtml","text/html"],["jade","text/jade"],["jsx","text/jsx"],["less","text/less"],["markdown","text/markdown"],["md","text/markdown"],["mml","text/mathml"],["mdx","text/mdx"],["n3","text/n3"],["conf","text/plain"],["def","text/plain"],["in","text/plain"],["ini","text/plain"],["list","text/plain"],["log","text/plain"],["text","text/plain"],["txt","text/plain"],["rtx","text/richtext"],["*rtf","text/rtf"],["sgm","text/sgml"],["sgml","text/sgml"],["shex","text/shex"],["slim","text/slim"],["slm","text/slim"],["spdx","text/spdx"],["styl","text/stylus"],["stylus","text/stylus"],["tsv","text/tab-separated-values"],["man","text/troff"],["me","text/troff"],["ms","text/troff"],["roff","text/troff"],["t","text/troff"],["tr","text/troff"],["ttl","text/turtle"],["uri","text/uri-list"],["uris","text/uri-list"],["urls","text/uri-list"],["vcard","text/vcard"],["vtt","text/vtt"],["*xml","text/xml"],["yaml","text/yaml"],["yml","text/yaml"],["3gp","video/3gpp"],["3gpp","video/3gpp"],["3g2","video/3gpp2"],["h261","video/h261"],["h263","video/h263"],["h264","video/h264"],["m4s","video/iso.segment"],["jpgv","video/jpeg"],["jpm","video/jpm"],["jpgm","video/jpm"],["mj2","video/mj2"],["mjp2","video/mj2"],["ts","application/typescript"],["mp4","video/mp4"],["mp4v","video/mp4"],["mpg4","video/mp4"],["m1v","video/mpeg"],["m2v","video/mpeg"],["mpe","video/mpeg"],["mpeg","video/mpeg"],["mpg","video/mpeg"],["ogv","video/ogg"],["mov","video/quicktime"],["qt","video/quicktime"],["webm","video/webm"]]);0&&0},27094:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{MultiMap:()=>MultiMap});G.exports=__toCommonJS(Xe);class MultiMap{constructor(){this._map=new Map}set(G,K){let je=this._map.get(G);if(!je){je=[];this._map.set(G,je)}je.push(K)}get(G){return this._map.get(G)||[]}has(G){return this._map.has(G)}delete(G,K){const je=this._map.get(G);if(!je)return;if(je.includes(K))this._map.set(G,je.filter((G=>K!==G)))}deleteAll(G){this._map.delete(G)}hasValue(G,K){const je=this._map.get(G);if(!je)return false;return je.includes(K)}get size(){return this._map.size}[Symbol.iterator](){return this._map[Symbol.iterator]()}keys(){return this._map.keys()}values(){const G=[];for(const K of this.keys())G.push(...this.get(K));return G}clear(){this._map.clear()}}0&&0},13601:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{formatProtocolParam:()=>formatProtocolParam,getActionGroup:()=>getActionGroup,renderTitleForCall:()=>renderTitleForCall});G.exports=__toCommonJS(at);var ft=je(81438);function formatProtocolParam(G,K){return _formatProtocolParam(G,K)?.replaceAll("\n","\\n")}function _formatProtocolParam(G,K){if(!G)return void 0;for(const je of K.split("|")){if(je==="url"){try{const K=new URL(G[je]);if(K.protocol==="data:")return K.protocol;if(K.protocol==="about:")return G[je];return K.pathname+K.search}catch(K){if(G[je]!==void 0)return G[je]}}if(je==="timeNumber"&&G[je]!==void 0){return new Date(G[je]).toString()}const K=deepParam(G,je);if(K!==void 0)return K}}function deepParam(G,K){const je=K.split(".");let ze=G;for(const G of je){if(typeof ze!=="object"||ze===null)return void 0;ze=ze[G]}if(ze===void 0)return void 0;return String(ze)}function renderTitleForCall(G){const K=G.title??ft.methodMetainfo.get(G.type+"."+G.method)?.title??G.method;return K.replace(/\{([^}]+)\}/g,((K,je)=>formatProtocolParam(G.params,je)??K))}function getActionGroup(G){return ft.methodMetainfo.get(G.type+"."+G.method)?.group}0&&0},81438:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{methodMetainfo:()=>rt});G.exports=__toCommonJS(Xe);const rt=new Map([["APIRequestContext.fetch",{title:'{method} "{url}"'}],["APIRequestContext.fetchResponseBody",{title:"Get response body",group:"getter"}],["APIRequestContext.fetchLog",{internal:true}],["APIRequestContext.storageState",{title:"Get storage state"}],["APIRequestContext.disposeAPIResponse",{internal:true}],["APIRequestContext.dispose",{internal:true}],["LocalUtils.zip",{internal:true}],["LocalUtils.harOpen",{internal:true}],["LocalUtils.harLookup",{internal:true}],["LocalUtils.harClose",{internal:true}],["LocalUtils.harUnzip",{internal:true}],["LocalUtils.connect",{internal:true}],["LocalUtils.tracingStarted",{internal:true}],["LocalUtils.addStackToTracingNoReply",{internal:true}],["LocalUtils.traceDiscarded",{internal:true}],["LocalUtils.globToRegex",{internal:true}],["Root.initialize",{internal:true}],["Playwright.newRequest",{title:"Create request context"}],["DebugController.initialize",{internal:true}],["DebugController.setReportStateChanged",{internal:true}],["DebugController.setRecorderMode",{internal:true}],["DebugController.highlight",{internal:true}],["DebugController.hideHighlight",{internal:true}],["DebugController.resume",{internal:true}],["DebugController.kill",{internal:true}],["SocksSupport.socksConnected",{internal:true}],["SocksSupport.socksFailed",{internal:true}],["SocksSupport.socksData",{internal:true}],["SocksSupport.socksError",{internal:true}],["SocksSupport.socksEnd",{internal:true}],["BrowserType.launch",{title:"Launch browser"}],["BrowserType.launchPersistentContext",{title:"Launch persistent context"}],["BrowserType.connectOverCDP",{title:"Connect over CDP"}],["Browser.close",{title:"Close browser",pausesBeforeAction:true}],["Browser.killForTests",{internal:true}],["Browser.defaultUserAgentForTest",{internal:true}],["Browser.newContext",{title:"Create context"}],["Browser.newContextForReuse",{internal:true}],["Browser.disconnectFromReusedContext",{internal:true}],["Browser.newBrowserCDPSession",{title:"Create CDP session",group:"configuration"}],["Browser.startTracing",{title:"Start browser tracing",group:"configuration"}],["Browser.stopTracing",{title:"Stop browser tracing",group:"configuration"}],["EventTarget.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["BrowserContext.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["Page.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["Worker.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["WebSocket.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["ElectronApplication.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["AndroidDevice.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["PageAgent.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["BrowserContext.addCookies",{title:"Add cookies",group:"configuration"}],["BrowserContext.addInitScript",{title:"Add init script",group:"configuration"}],["BrowserContext.clearCookies",{title:"Clear cookies",group:"configuration"}],["BrowserContext.clearPermissions",{title:"Clear permissions",group:"configuration"}],["BrowserContext.close",{title:"Close context",pausesBeforeAction:true}],["BrowserContext.cookies",{title:"Get cookies",group:"getter"}],["BrowserContext.exposeBinding",{title:"Expose binding",group:"configuration"}],["BrowserContext.grantPermissions",{title:"Grant permissions",group:"configuration"}],["BrowserContext.newPage",{title:"Create page"}],["BrowserContext.registerSelectorEngine",{internal:true}],["BrowserContext.setTestIdAttributeName",{internal:true}],["BrowserContext.setExtraHTTPHeaders",{title:"Set extra HTTP headers",group:"configuration"}],["BrowserContext.setGeolocation",{title:"Set geolocation",group:"configuration"}],["BrowserContext.setHTTPCredentials",{title:"Set HTTP credentials",group:"configuration"}],["BrowserContext.setNetworkInterceptionPatterns",{title:"Route requests",group:"route"}],["BrowserContext.setWebSocketInterceptionPatterns",{title:"Route WebSockets",group:"route"}],["BrowserContext.setOffline",{title:"Set offline mode"}],["BrowserContext.storageState",{title:"Get storage state"}],["BrowserContext.pause",{title:"Pause"}],["BrowserContext.enableRecorder",{internal:true}],["BrowserContext.disableRecorder",{internal:true}],["BrowserContext.exposeConsoleApi",{internal:true}],["BrowserContext.newCDPSession",{title:"Create CDP session",group:"configuration"}],["BrowserContext.harStart",{internal:true}],["BrowserContext.harExport",{internal:true}],["BrowserContext.createTempFiles",{internal:true}],["BrowserContext.updateSubscription",{internal:true}],["BrowserContext.clockFastForward",{title:'Fast forward clock "{ticksNumber|ticksString}"'}],["BrowserContext.clockInstall",{title:'Install clock "{timeNumber|timeString}"'}],["BrowserContext.clockPauseAt",{title:'Pause clock "{timeNumber|timeString}"'}],["BrowserContext.clockResume",{title:"Resume clock"}],["BrowserContext.clockRunFor",{title:'Run clock "{ticksNumber|ticksString}"'}],["BrowserContext.clockSetFixedTime",{title:'Set fixed time "{timeNumber|timeString}"'}],["BrowserContext.clockSetSystemTime",{title:'Set system time "{timeNumber|timeString}"'}],["Page.addInitScript",{title:"Add init script",group:"configuration"}],["Page.close",{title:"Close page",pausesBeforeAction:true}],["Page.consoleMessages",{title:"Get console messages",group:"getter"}],["Page.emulateMedia",{title:"Emulate media",snapshot:true,pausesBeforeAction:true}],["Page.exposeBinding",{title:"Expose binding",group:"configuration"}],["Page.goBack",{title:"Go back",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.goForward",{title:"Go forward",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.requestGC",{title:"Request garbage collection",group:"configuration"}],["Page.registerLocatorHandler",{title:"Register locator handler"}],["Page.resolveLocatorHandlerNoReply",{internal:true}],["Page.unregisterLocatorHandler",{title:"Unregister locator handler"}],["Page.reload",{title:"Reload",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.expectScreenshot",{title:"Expect screenshot",snapshot:true,pausesBeforeAction:true}],["Page.screenshot",{title:"Screenshot",snapshot:true,pausesBeforeAction:true}],["Page.setExtraHTTPHeaders",{title:"Set extra HTTP headers",group:"configuration"}],["Page.setNetworkInterceptionPatterns",{title:"Route requests",group:"route"}],["Page.setWebSocketInterceptionPatterns",{title:"Route WebSockets",group:"route"}],["Page.setViewportSize",{title:"Set viewport size",snapshot:true,pausesBeforeAction:true}],["Page.keyboardDown",{title:'Key down "{key}"',slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.keyboardUp",{title:'Key up "{key}"',slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.keyboardInsertText",{title:'Insert "{text}"',slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.keyboardType",{title:'Type "{text}"',slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.keyboardPress",{title:'Press "{key}"',slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.mouseMove",{title:"Mouse move",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.mouseDown",{title:"Mouse down",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.mouseUp",{title:"Mouse up",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.mouseClick",{title:"Click",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.mouseWheel",{title:"Mouse wheel",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.touchscreenTap",{title:"Tap",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.pageErrors",{title:"Get page errors",group:"getter"}],["Page.pdf",{title:"PDF"}],["Page.requests",{title:"Get network requests",group:"getter"}],["Page.snapshotForAI",{internal:true}],["Page.startJSCoverage",{title:"Start JS coverage",group:"configuration"}],["Page.stopJSCoverage",{title:"Stop JS coverage",group:"configuration"}],["Page.startCSSCoverage",{title:"Start CSS coverage",group:"configuration"}],["Page.stopCSSCoverage",{title:"Stop CSS coverage",group:"configuration"}],["Page.bringToFront",{title:"Bring to front"}],["Page.updateSubscription",{internal:true}],["Page.agent",{internal:true}],["Frame.evalOnSelector",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["Frame.evalOnSelectorAll",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["Frame.addScriptTag",{title:"Add script tag",snapshot:true,pausesBeforeAction:true}],["Frame.addStyleTag",{title:"Add style tag",snapshot:true,pausesBeforeAction:true}],["Frame.ariaSnapshot",{title:"Aria snapshot",snapshot:true,pausesBeforeAction:true}],["Frame.blur",{title:"Blur",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Frame.check",{title:"Check",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.click",{title:"Click",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.content",{title:"Get content",snapshot:true,pausesBeforeAction:true}],["Frame.dragAndDrop",{title:"Drag and drop",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.dblclick",{title:"Double click",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.dispatchEvent",{title:'Dispatch "{type}"',slowMo:true,snapshot:true,pausesBeforeAction:true}],["Frame.evaluateExpression",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["Frame.evaluateExpressionHandle",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["Frame.fill",{title:'Fill "{value}"',slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.focus",{title:"Focus",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Frame.frameElement",{title:"Get frame element",group:"getter"}],["Frame.resolveSelector",{internal:true}],["Frame.highlight",{title:"Highlight element",group:"configuration"}],["Frame.getAttribute",{title:'Get attribute "{name}"',snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.goto",{title:'Navigate to "{url}"',slowMo:true,snapshot:true,pausesBeforeAction:true}],["Frame.hover",{title:"Hover",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.innerHTML",{title:"Get HTML",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.innerText",{title:"Get inner text",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.inputValue",{title:"Get input value",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.isChecked",{title:"Is checked",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.isDisabled",{title:"Is disabled",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.isEnabled",{title:"Is enabled",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.isHidden",{title:"Is hidden",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.isVisible",{title:"Is visible",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.isEditable",{title:"Is editable",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.press",{title:'Press "{key}"',slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.querySelector",{title:"Query selector",snapshot:true}],["Frame.querySelectorAll",{title:"Query selector all",snapshot:true}],["Frame.queryCount",{title:"Query count",snapshot:true,pausesBeforeAction:true}],["Frame.selectOption",{title:"Select option",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.setContent",{title:"Set content",snapshot:true,pausesBeforeAction:true}],["Frame.setInputFiles",{title:"Set input files",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.tap",{title:"Tap",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.textContent",{title:"Get text content",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.title",{title:"Get page title",group:"getter"}],["Frame.type",{title:'Type "{text}"',slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.uncheck",{title:"Uncheck",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.waitForTimeout",{title:"Wait for timeout",snapshot:true}],["Frame.waitForFunction",{title:"Wait for function",snapshot:true,pausesBeforeAction:true}],["Frame.waitForSelector",{title:"Wait for selector",snapshot:true}],["Frame.expect",{title:'Expect "{expression}"',snapshot:true,pausesBeforeAction:true}],["Worker.evaluateExpression",{title:"Evaluate"}],["Worker.evaluateExpressionHandle",{title:"Evaluate"}],["Worker.updateSubscription",{internal:true}],["JSHandle.dispose",{internal:true}],["ElementHandle.dispose",{internal:true}],["JSHandle.evaluateExpression",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["ElementHandle.evaluateExpression",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["JSHandle.evaluateExpressionHandle",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["ElementHandle.evaluateExpressionHandle",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["JSHandle.getPropertyList",{title:"Get property list",group:"getter"}],["ElementHandle.getPropertyList",{title:"Get property list",group:"getter"}],["JSHandle.getProperty",{title:"Get JS property",group:"getter"}],["ElementHandle.getProperty",{title:"Get JS property",group:"getter"}],["JSHandle.jsonValue",{title:"Get JSON value",group:"getter"}],["ElementHandle.jsonValue",{title:"Get JSON value",group:"getter"}],["ElementHandle.evalOnSelector",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["ElementHandle.evalOnSelectorAll",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["ElementHandle.boundingBox",{title:"Get bounding box",snapshot:true,pausesBeforeAction:true}],["ElementHandle.check",{title:"Check",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.click",{title:"Click",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.contentFrame",{title:"Get content frame",group:"getter"}],["ElementHandle.dblclick",{title:"Double click",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.dispatchEvent",{title:"Dispatch event",slowMo:true,snapshot:true,pausesBeforeAction:true}],["ElementHandle.fill",{title:'Fill "{value}"',slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.focus",{title:"Focus",slowMo:true,snapshot:true,pausesBeforeAction:true}],["ElementHandle.getAttribute",{title:"Get attribute",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.hover",{title:"Hover",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.innerHTML",{title:"Get HTML",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.innerText",{title:"Get inner text",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.inputValue",{title:"Get input value",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.isChecked",{title:"Is checked",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.isDisabled",{title:"Is disabled",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.isEditable",{title:"Is editable",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.isEnabled",{title:"Is enabled",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.isHidden",{title:"Is hidden",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.isVisible",{title:"Is visible",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.ownerFrame",{title:"Get owner frame",group:"getter"}],["ElementHandle.press",{title:'Press "{key}"',slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.querySelector",{title:"Query selector",snapshot:true}],["ElementHandle.querySelectorAll",{title:"Query selector all",snapshot:true}],["ElementHandle.screenshot",{title:"Screenshot",snapshot:true,pausesBeforeAction:true}],["ElementHandle.scrollIntoViewIfNeeded",{title:"Scroll into view",slowMo:true,snapshot:true,pausesBeforeAction:true}],["ElementHandle.selectOption",{title:"Select option",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.selectText",{title:"Select text",slowMo:true,snapshot:true,pausesBeforeAction:true}],["ElementHandle.setInputFiles",{title:"Set input files",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.tap",{title:"Tap",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.textContent",{title:"Get text content",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.type",{title:"Type",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.uncheck",{title:"Uncheck",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.waitForElementState",{title:"Wait for state",snapshot:true,pausesBeforeAction:true}],["ElementHandle.waitForSelector",{title:"Wait for selector",snapshot:true}],["Request.response",{internal:true}],["Request.rawRequestHeaders",{internal:true}],["Route.redirectNavigationRequest",{internal:true}],["Route.abort",{title:"Abort request",group:"route"}],["Route.continue",{title:"Continue request",group:"route"}],["Route.fulfill",{title:"Fulfill request",group:"route"}],["WebSocketRoute.connect",{title:"Connect WebSocket to server",group:"route"}],["WebSocketRoute.ensureOpened",{internal:true}],["WebSocketRoute.sendToPage",{title:"Send WebSocket message",group:"route"}],["WebSocketRoute.sendToServer",{title:"Send WebSocket message",group:"route"}],["WebSocketRoute.closePage",{internal:true}],["WebSocketRoute.closeServer",{internal:true}],["Response.body",{title:"Get response body",group:"getter"}],["Response.securityDetails",{internal:true}],["Response.serverAddr",{internal:true}],["Response.rawResponseHeaders",{internal:true}],["Response.sizes",{internal:true}],["BindingCall.reject",{internal:true}],["BindingCall.resolve",{internal:true}],["Dialog.accept",{title:"Accept dialog"}],["Dialog.dismiss",{title:"Dismiss dialog"}],["Tracing.tracingStart",{title:"Start tracing",group:"configuration"}],["Tracing.tracingStartChunk",{title:"Start tracing",group:"configuration"}],["Tracing.tracingGroup",{title:'Trace "{name}"'}],["Tracing.tracingGroupEnd",{title:"Group end"}],["Tracing.tracingStopChunk",{title:"Stop tracing",group:"configuration"}],["Tracing.tracingStop",{title:"Stop tracing",group:"configuration"}],["Artifact.pathAfterFinished",{internal:true}],["Artifact.saveAs",{internal:true}],["Artifact.saveAsStream",{internal:true}],["Artifact.failure",{internal:true}],["Artifact.stream",{internal:true}],["Artifact.cancel",{internal:true}],["Artifact.delete",{internal:true}],["Stream.read",{internal:true}],["Stream.close",{internal:true}],["WritableStream.write",{internal:true}],["WritableStream.close",{internal:true}],["CDPSession.send",{title:"Send CDP command",group:"configuration"}],["CDPSession.detach",{title:"Detach CDP session",group:"configuration"}],["Electron.launch",{title:"Launch electron"}],["ElectronApplication.browserWindow",{internal:true}],["ElectronApplication.evaluateExpression",{title:"Evaluate"}],["ElectronApplication.evaluateExpressionHandle",{title:"Evaluate"}],["ElectronApplication.updateSubscription",{internal:true}],["Android.devices",{internal:true}],["AndroidSocket.write",{internal:true}],["AndroidSocket.close",{internal:true}],["AndroidDevice.wait",{title:"Wait"}],["AndroidDevice.fill",{title:'Fill "{text}"'}],["AndroidDevice.tap",{title:"Tap"}],["AndroidDevice.drag",{title:"Drag"}],["AndroidDevice.fling",{title:"Fling"}],["AndroidDevice.longTap",{title:"Long tap"}],["AndroidDevice.pinchClose",{title:"Pinch close"}],["AndroidDevice.pinchOpen",{title:"Pinch open"}],["AndroidDevice.scroll",{title:"Scroll"}],["AndroidDevice.swipe",{title:"Swipe"}],["AndroidDevice.info",{internal:true}],["AndroidDevice.screenshot",{title:"Screenshot"}],["AndroidDevice.inputType",{title:"Type"}],["AndroidDevice.inputPress",{title:"Press"}],["AndroidDevice.inputTap",{title:"Tap"}],["AndroidDevice.inputSwipe",{title:"Swipe"}],["AndroidDevice.inputDrag",{title:"Drag"}],["AndroidDevice.launchBrowser",{title:"Launch browser"}],["AndroidDevice.open",{title:"Open app"}],["AndroidDevice.shell",{title:"Execute shell command",group:"configuration"}],["AndroidDevice.installApk",{title:"Install apk"}],["AndroidDevice.push",{title:"Push"}],["AndroidDevice.connectToWebView",{title:"Connect to Web View"}],["AndroidDevice.close",{internal:true}],["JsonPipe.send",{internal:true}],["JsonPipe.close",{internal:true}],["PageAgent.perform",{title:'Perform "{task}"'}],["PageAgent.expect",{title:'Expect "{expectation}"'}],["PageAgent.extract",{title:'Extract "{query}"'}],["PageAgent.dispose",{internal:true}],["PageAgent.usage",{title:"Get agent usage",group:"configuration"}]]);0&&0},96298:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{isError:()=>isError,isObject:()=>isObject,isRegExp:()=>isRegExp,isString:()=>ft.isString});G.exports=__toCommonJS(at);var ft=je(70017);function isRegExp(G){return G instanceof RegExp||Object.prototype.toString.call(G)==="[object RegExp]"}function isObject(G){return typeof G==="object"&&G!==null}function isError(G){return G instanceof Error||G&&Object.getPrototypeOf(G)?.name==="Error"}0&&0},37673:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{InvalidSelectorError:()=>mt.InvalidSelectorError,customCSSNames:()=>wt,isInvalidSelectorError:()=>mt.isInvalidSelectorError,parseAttributeSelector:()=>parseAttributeSelector,parseSelector:()=>parseSelector,splitSelectorByFrame:()=>splitSelectorByFrame,stringifySelector:()=>stringifySelector,visitAllSelectorParts:()=>visitAllSelectorParts});G.exports=__toCommonJS(at);var ft=je(59891);var mt=je(59891);const vt=new Set(["internal:has","internal:has-not","internal:and","internal:or","internal:chain","left-of","right-of","above","below","near"]);const yt=new Set(["left-of","right-of","above","below","near"]);const wt=new Set(["not","is","where","has","scope","light","visible","text","text-matches","text-is","has-text","above","below","right-of","left-of","near","nth-match"]);function parseSelector(G){const K=parseSelectorString(G);const je=[];for(const G of K.parts){if(G.name==="css"||G.name==="css:light"){if(G.name==="css:light")G.body=":light("+G.body+")";const K=(0,ft.parseCSS)(G.body,wt);je.push({name:"css",body:K.selector,source:G.body});continue}if(vt.has(G.name)){let K;let ze;try{const je=JSON.parse("["+G.body+"]");if(!Array.isArray(je)||je.length<1||je.length>2||typeof je[0]!=="string")throw new ft.InvalidSelectorError(`Malformed selector: ${G.name}=`+G.body);K=je[0];if(je.length===2){if(typeof je[1]!=="number"||!yt.has(G.name))throw new ft.InvalidSelectorError(`Malformed selector: ${G.name}=`+G.body);ze=je[1]}}catch(K){throw new ft.InvalidSelectorError(`Malformed selector: ${G.name}=`+G.body)}const We={name:G.name,source:G.body,body:{parsed:parseSelector(K),distance:ze}};const Xe=[...We.body.parsed.parts].reverse().find((G=>G.name==="internal:control"&&G.body==="enter-frame"));const rt=Xe?We.body.parsed.parts.indexOf(Xe):-1;if(rt!==-1&&selectorPartsEqual(We.body.parsed.parts.slice(0,rt+1),je.slice(0,rt+1)))We.body.parsed.parts.splice(0,rt+1);je.push(We);continue}je.push({...G,source:G.body})}if(vt.has(je[0].name))throw new ft.InvalidSelectorError(`"${je[0].name}" selector cannot be first`);return{capture:K.capture,parts:je}}function splitSelectorByFrame(G){const K=parseSelector(G);const je=[];let ze={parts:[]};let We=0;for(let G=0;G<K.parts.length;++G){const Xe=K.parts[G];if(Xe.name==="internal:control"&&Xe.body==="enter-frame"){if(!ze.parts.length)throw new ft.InvalidSelectorError("Selector cannot start with entering frame, select the iframe first");je.push(ze);ze={parts:[]};We=G+1;continue}if(K.capture===G)ze.capture=G-We;ze.parts.push(Xe)}if(!ze.parts.length)throw new ft.InvalidSelectorError(`Selector cannot end with entering frame, while parsing selector ${G}`);je.push(ze);if(typeof K.capture==="number"&&typeof je[je.length-1].capture!=="number")throw new ft.InvalidSelectorError(`Can not capture the selector before diving into the frame. Only use * after the last frame has been selected`);return je}function selectorPartsEqual(G,K){return stringifySelector({parts:G})===stringifySelector({parts:K})}function stringifySelector(G,K){if(typeof G==="string")return G;return G.parts.map(((je,ze)=>{let We=true;if(!K&&ze!==G.capture){if(je.name==="css")We=false;else if(je.name==="xpath"&&je.source.startsWith("//")||je.source.startsWith(".."))We=false}const Xe=We?je.name+"=":"";return`${ze===G.capture?"*":""}${Xe}${je.source}`})).join(" >> ")}function visitAllSelectorParts(G,K){const visit=(G,je)=>{for(const ze of G.parts){K(ze,je);if(vt.has(ze.name))visit(ze.body.parsed,true)}};visit(G,false)}function parseSelectorString(G){let K=0;let je;let ze=0;const We={parts:[]};const append=()=>{const je=G.substring(ze,K).trim();const Xe=je.indexOf("=");let rt;let at;if(Xe!==-1&&je.substring(0,Xe).trim().match(/^[a-zA-Z_0-9-+:*]+$/)){rt=je.substring(0,Xe).trim();at=je.substring(Xe+1)}else if(je.length>1&&je[0]==='"'&&je[je.length-1]==='"'){rt="text";at=je}else if(je.length>1&&je[0]==="'"&&je[je.length-1]==="'"){rt="text";at=je}else if(/^\(*\/\//.test(je)||je.startsWith("..")){rt="xpath";at=je}else{rt="css";at=je}let mt=false;if(rt[0]==="*"){mt=true;rt=rt.substring(1)}We.parts.push({name:rt,body:at});if(mt){if(We.capture!==void 0)throw new ft.InvalidSelectorError(`Only one of the selectors can capture using * modifier`);We.capture=We.parts.length-1}};if(!G.includes(">>")){K=G.length;append();return We}const shouldIgnoreTextSelectorQuote=()=>{const je=G.substring(ze,K);const We=je.match(/^\s*text\s*=(.*)$/);return!!We&&!!We[1]};while(K<G.length){const We=G[K];if(We==="\\"&&K+1<G.length){K+=2}else if(We===je){je=void 0;K++}else if(!je&&(We==='"'||We==="'"||We==="`")&&!shouldIgnoreTextSelectorQuote()){je=We;K++}else if(!je&&We===">"&&G[K+1]===">"){append();K+=2;ze=K}else{K++}}append();return We}function parseAttributeSelector(G,K){let je=0;let ze=G.length===0;const next=()=>G[je]||"";const eat1=()=>{const K=next();++je;ze=je>=G.length;return K};const syntaxError=K=>{if(ze)throw new ft.InvalidSelectorError(`Unexpected end of selector while parsing selector \`${G}\``);throw new ft.InvalidSelectorError(`Error while parsing selector \`${G}\` - unexpected symbol "${next()}" at position ${je}`+(K?" during "+K:""))};function skipSpaces(){while(!ze&&/\s/.test(next()))eat1()}function isCSSNameChar(G){return G>="€"||G>="0"&&G<="9"||G>="A"&&G<="Z"||G>="a"&&G<="z"||G>="0"&&G<="9"||G==="_"||G==="-"}function readIdentifier(){let G="";skipSpaces();while(!ze&&isCSSNameChar(next()))G+=eat1();return G}function readQuotedString(G){let K=eat1();if(K!==G)syntaxError("parsing quoted string");while(!ze&&next()!==G){if(next()==="\\")eat1();K+=eat1()}if(next()!==G)syntaxError("parsing quoted string");K+=eat1();return K}function readRegularExpression(){if(eat1()!=="/")syntaxError("parsing regular expression");let K="";let je=false;while(!ze){if(next()==="\\"){K+=eat1();if(ze)syntaxError("parsing regular expression")}else if(je&&next()==="]"){je=false}else if(!je&&next()==="["){je=true}else if(!je&&next()==="/"){break}K+=eat1()}if(eat1()!=="/")syntaxError("parsing regular expression");let We="";while(!ze&&next().match(/[dgimsuy]/))We+=eat1();try{return new RegExp(K,We)}catch(K){throw new ft.InvalidSelectorError(`Error while parsing selector \`${G}\`: ${K.message}`)}}function readAttributeToken(){let G="";skipSpaces();if(next()===`'`||next()===`"`)G=readQuotedString(next()).slice(1,-1);else G=readIdentifier();if(!G)syntaxError("parsing property path");return G}function readOperator(){skipSpaces();let G="";if(!ze)G+=eat1();if(!ze&&G!=="=")G+=eat1();if(!["=","*=","^=","$=","|=","~="].includes(G))syntaxError("parsing operator");return G}function readAttribute(){eat1();const je=[];je.push(readAttributeToken());skipSpaces();while(next()==="."){eat1();je.push(readAttributeToken());skipSpaces()}if(next()==="]"){eat1();return{name:je.join("."),jsonPath:je,op:"<truthy>",value:null,caseSensitive:false}}const We=readOperator();let Xe=void 0;let rt=true;skipSpaces();if(next()==="/"){if(We!=="=")throw new ft.InvalidSelectorError(`Error while parsing selector \`${G}\` - cannot use ${We} in attribute with regular expression`);Xe=readRegularExpression()}else if(next()===`'`||next()===`"`){Xe=readQuotedString(next()).slice(1,-1);skipSpaces();if(next()==="i"||next()==="I"){rt=false;eat1()}else if(next()==="s"||next()==="S"){rt=true;eat1()}}else{Xe="";while(!ze&&(isCSSNameChar(next())||next()==="+"||next()==="."))Xe+=eat1();if(Xe==="true"){Xe=true}else if(Xe==="false"){Xe=false}else{if(!K){Xe=+Xe;if(Number.isNaN(Xe))syntaxError("parsing attribute value")}}}skipSpaces();if(next()!=="]")syntaxError("parsing attribute value");eat1();if(We!=="="&&typeof Xe!=="string")throw new ft.InvalidSelectorError(`Error while parsing selector \`${G}\` - cannot use ${We} in attribute with non-string matching value - ${Xe}`);return{name:je.join("."),jsonPath:je,op:We,value:Xe,caseSensitive:rt}}const We={name:"",attributes:[]};We.name=readIdentifier();skipSpaces();while(next()==="["){We.attributes.push(readAttribute());skipSpaces()}if(!ze)syntaxError(void 0);if(!We.name&&!We.attributes.length)throw new ft.InvalidSelectorError(`Error while parsing selector \`${G}\` - selector cannot be empty`);return We}0&&0},26265:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{Semaphore:()=>Semaphore});G.exports=__toCommonJS(at);var ft=je(28040);class Semaphore{constructor(G){this._acquired=0;this._queue=[];this._max=G}setMax(G){this._max=G}acquire(){const G=new ft.ManualPromise;this._queue.push(G);this._flush();return G}release(){--this._acquired;this._flush()}_flush(){while(this._acquired<this._max&&this._queue.length){++this._acquired;this._queue.shift().resolve()}}}0&&0},46662:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{captureRawStack:()=>captureRawStack,parseErrorStack:()=>parseErrorStack,parseStackFrame:()=>parseStackFrame,rewriteErrorMessage:()=>rewriteErrorMessage,splitErrorMessage:()=>splitErrorMessage,stringifyStackFrames:()=>stringifyStackFrames});G.exports=__toCommonJS(Xe);function captureRawStack(){const G=Error.stackTraceLimit;Error.stackTraceLimit=50;const K=new Error;const je=K.stack||"";Error.stackTraceLimit=G;return je.split("\n")}function parseStackFrame(G,K,je){const ze=G&&G.match(rt);if(!ze)return null;let We=ze[2];let Xe=ze[7];if(!Xe)return null;if(!je&&(Xe.startsWith("internal")||Xe.startsWith("node:")))return null;const ft=ze[8];const mt=ze[9];const vt=ze[11]===")";const yt={file:"",line:0,column:0};if(ft)yt.line=Number(ft);if(mt)yt.column=Number(mt);if(vt&&Xe){let G=0;for(let K=Xe.length-1;K>0;K--){if(Xe.charAt(K)===")"){G++}else if(Xe.charAt(K)==="("&&Xe.charAt(K-1)===" "){G--;if(G===-1&&Xe.charAt(K-1)===" "){const G=Xe.slice(0,K-1);const je=Xe.slice(K+1);Xe=je;We+=` (${G}`;break}}}}if(We){const G=We.match(at);if(G)We=G[1]}if(Xe){if(Xe.startsWith("file://"))Xe=fileURLToPath(Xe,K);yt.file=Xe}if(We)yt.function=We;return yt}function rewriteErrorMessage(G,K){const je=(G.stack?.split("\n")||[]).filter((G=>G.startsWith(" at ")));G.message=K;const ze=`${G.name}: ${G.message}`;if(je.length)G.stack=`${ze}\n${je.join("\n")}`;return G}function stringifyStackFrames(G){const K=[];for(const je of G){if(je.function)K.push(` at ${je.function} (${je.file}:${je.line}:${je.column})`);else K.push(` at ${je.file}:${je.line}:${je.column}`)}return K}function splitErrorMessage(G){const K=G.indexOf(":");return{name:K!==-1?G.slice(0,K):"",message:K!==-1&&K+2<=G.length?G.substring(K+2):G}}function parseErrorStack(G,K,je=false){const ze=G.split("\n");let We=ze.findIndex((G=>G.startsWith(" at ")));if(We===-1)We=ze.length;const Xe=ze.slice(0,We).join("\n");const rt=ze.slice(We);let at;for(const G of rt){const ze=parseStackFrame(G,K,je);if(!ze||!ze.file)continue;if(belongsToNodeModules(ze.file,K))continue;at={file:ze.file,column:ze.column||0,line:ze.line||0};break}return{message:Xe,stackLines:rt,location:at}}function belongsToNodeModules(G,K){return G.includes(`${K}node_modules${K}`)}const rt=new RegExp("^(?:\\s*at )?(?:(new) )?(?:(.*?) \\()?(?:eval at ([^ ]+) \\((.+?):(\\d+):(\\d+)\\), )?(?:(.+?):(\\d+):(\\d+)|(native))(\\)?)$");const at=/^(.*?) \[as (.*?)\]$/;function fileURLToPath(G,K){if(!G.startsWith("file://"))return G;let je=decodeURIComponent(G.slice(7));if(je.startsWith("/")&&/^[a-zA-Z]:/.test(je.slice(1)))je=je.slice(1);return je.replace(/\//g,K)}0&&0},70017:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{ansiRegex:()=>ft,cacheNormalizedWhitespaces:()=>cacheNormalizedWhitespaces,escapeForAttributeSelector:()=>escapeForAttributeSelector,escapeForTextSelector:()=>escapeForTextSelector,escapeHTML:()=>escapeHTML,escapeHTMLAttribute:()=>escapeHTMLAttribute,escapeRegExp:()=>escapeRegExp,escapeTemplateString:()=>escapeTemplateString,escapeWithQuotes:()=>escapeWithQuotes,formatObject:()=>formatObject,formatObjectOrVoid:()=>formatObjectOrVoid,isString:()=>isString,longestCommonSubstring:()=>longestCommonSubstring,normalizeEscapedRegexQuotes:()=>normalizeEscapedRegexQuotes,normalizeWhiteSpace:()=>normalizeWhiteSpace,parseRegex:()=>parseRegex,quoteCSSAttributeValue:()=>quoteCSSAttributeValue,stripAnsiEscapes:()=>stripAnsiEscapes,toSnakeCase:()=>toSnakeCase,toTitleCase:()=>toTitleCase,trimString:()=>trimString,trimStringWithEllipsis:()=>trimStringWithEllipsis});G.exports=__toCommonJS(Xe);function escapeWithQuotes(G,K="'"){const je=JSON.stringify(G);const ze=je.substring(1,je.length-1).replace(/\\"/g,'"');if(K==="'")return K+ze.replace(/[']/g,"\\'")+K;if(K==='"')return K+ze.replace(/["]/g,'\\"')+K;if(K==="`")return K+ze.replace(/[`]/g,"\\`")+K;throw new Error("Invalid escape char")}function escapeTemplateString(G){return G.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function isString(G){return typeof G==="string"||G instanceof String}function toTitleCase(G){return G.charAt(0).toUpperCase()+G.substring(1)}function toSnakeCase(G){return G.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function formatObject(G,K=" ",je="multiline"){if(typeof G==="string")return escapeWithQuotes(G,"'");if(Array.isArray(G))return`[${G.map((G=>formatObject(G))).join(", ")}]`;if(typeof G==="object"){const ze=Object.keys(G).filter((K=>G[K]!==void 0)).sort();if(!ze.length)return"{}";const We=[];for(const K of ze)We.push(`${K}: ${formatObject(G[K])}`);if(je==="multiline")return`{\n${We.join(`,\n${K}`)}\n}`;return`{ ${We.join(", ")} }`}return String(G)}function formatObjectOrVoid(G,K=" "){const je=formatObject(G,K);return je==="{}"?"":je}function quoteCSSAttributeValue(G){return`"${G.replace(/["\\]/g,(G=>"\\"+G))}"`}let rt;function cacheNormalizedWhitespaces(){rt=new Map}function normalizeWhiteSpace(G){let K=rt?.get(G);if(K===void 0){K=G.replace(/[\u200b\u00ad]/g,"").trim().replace(/\s+/g," ");rt?.set(G,K)}return K}function normalizeEscapedRegexQuotes(G){return G.replace(/(^|[^\\])(\\\\)*\\(['"`])/g,"$1$2$3")}function escapeRegexForSelector(G){if(G.unicode||G.unicodeSets)return String(G);return String(G).replace(/(^|[^\\])(\\\\)*(["'`])/g,"$1$2\\$3").replace(/>>/g,"\\>\\>")}function escapeForTextSelector(G,K){if(typeof G!=="string")return escapeRegexForSelector(G);return`${JSON.stringify(G)}${K?"s":"i"}`}function escapeForAttributeSelector(G,K){if(typeof G!=="string")return escapeRegexForSelector(G);return`"${G.replace(/\\/g,"\\\\").replace(/["]/g,'\\"')}"${K?"s":"i"}`}function trimString(G,K,je=""){if(G.length<=K)return G;const ze=[...G];if(ze.length>K)return ze.slice(0,K-je.length).join("")+je;return ze.join("")}function trimStringWithEllipsis(G,K){return trimString(G,K,"…")}function escapeRegExp(G){return G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const at={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function escapeHTMLAttribute(G){return G.replace(/[&<>"']/gu,(G=>at[G]))}function escapeHTML(G){return G.replace(/[&<]/gu,(G=>at[G]))}function longestCommonSubstring(G,K){const je=G.length;const ze=K.length;let We=0;let Xe=0;const rt=Array(je+1).fill(null).map((()=>Array(ze+1).fill(0)));for(let at=1;at<=je;at++){for(let je=1;je<=ze;je++){if(G[at-1]===K[je-1]){rt[at][je]=rt[at-1][je-1]+1;if(rt[at][je]>We){We=rt[at][je];Xe=at}}}}return G.slice(Xe-We,Xe)}function parseRegex(G){if(G[0]!=="/")throw new Error(`Invalid regex, must start with '/': ${G}`);const K=G.lastIndexOf("/");if(K<=0)throw new Error(`Invalid regex, must end with '/' followed by optional flags: ${G}`);const je=G.slice(1,K);const ze=G.slice(K+1);return new RegExp(je,ze)}const ft=new RegExp("([\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~])))","g");function stripAnsiEscapes(G){return G.replace(ft,"")}0&&0},29166:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT:()=>mt,DEFAULT_PLAYWRIGHT_TIMEOUT:()=>ft,monotonicTime:()=>monotonicTime,setTimeOrigin:()=>setTimeOrigin,timeOrigin:()=>timeOrigin});G.exports=__toCommonJS(Xe);let rt=performance.timeOrigin;let at=0;function setTimeOrigin(G){rt=G;at=performance.timeOrigin-G}function timeOrigin(){return rt}function monotonicTime(){return Math.floor((performance.now()+at)*1e3)/1e3}const ft=3e4;const mt=3*60*1e3;0&&0},44782:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{pollAgainstDeadline:()=>pollAgainstDeadline,raceAgainstDeadline:()=>raceAgainstDeadline});G.exports=__toCommonJS(at);var ft=je(29166);async function raceAgainstDeadline(G,K){let je;return Promise.race([G().then((G=>({result:G,timedOut:false}))),new Promise((G=>{const ze=2147483647;const We=(K||ze)-(0,ft.monotonicTime)();je=setTimeout((()=>G({timedOut:true})),We)}))]).finally((()=>{clearTimeout(je)}))}async function pollAgainstDeadline(G,K,je=[100,250,500,1e3]){const ze=je.pop()??1e3;let We;const wrappedCallback=()=>Promise.resolve().then(G);while(true){const G=(0,ft.monotonicTime)();if(K&&G>=K)break;const Xe=await raceAgainstDeadline(wrappedCallback,K);if(Xe.timedOut)break;We=Xe.result.result;if(!Xe.result.continuePolling)return{result:We,timedOut:false};const rt=je.shift()??ze;if(K&&K<=(0,ft.monotonicTime)()+rt)break;await new Promise((G=>setTimeout(G,rt)))}return{timedOut:true,result:We}}0&&0},69985:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{parseClientSideCallMetadata:()=>parseClientSideCallMetadata,serializeClientSideCallMetadata:()=>serializeClientSideCallMetadata});G.exports=__toCommonJS(Xe);function parseClientSideCallMetadata(G){const K=new Map;const{files:je,stacks:ze}=G;for(const G of ze){const[ze,We]=G;K.set(`call@${ze}`,We.map((G=>({file:je[G[0]],line:G[1],column:G[2],function:G[3]}))))}return K}function serializeClientSideCallMetadata(G){const K=new Map;const je=[];for(const ze of G){if(!ze.stack||!ze.stack.length)continue;const G=[];for(const je of ze.stack){let ze=K.get(je.file);if(typeof ze!=="number"){ze=K.size;K.set(je.file,ze)}const We=[ze,je.line||0,je.column||0,je.function||""];G.push(We)}je.push([ze.id,G])}return{files:[...K.keys()],stacks:je}}0&&0},78185:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{constructURLBasedOnBaseURL:()=>constructURLBasedOnBaseURL,globToRegexPattern:()=>globToRegexPattern,resolveGlobToRegexPattern:()=>resolveGlobToRegexPattern,urlMatches:()=>urlMatches,urlMatchesEqual:()=>urlMatchesEqual});G.exports=__toCommonJS(at);var ft=je(70017);const mt=new Set(["$","^","+",".","*","(",")","|","\\","?","{","}","[","]"]);function globToRegexPattern(G){const K=["^"];let je=false;for(let ze=0;ze<G.length;++ze){const We=G[ze];if(We==="\\"&&ze+1<G.length){const je=G[++ze];K.push(mt.has(je)?"\\"+je:je);continue}if(We==="*"){const je=G[ze-1];let We=1;while(G[ze+1]==="*"){We++;ze++}if(We>1){const We=G[ze+1];if(We==="/"){if(je==="/")K.push("((.+/)|)");else K.push("(.*/)");++ze}else{K.push("(.*)")}}else{K.push("([^/]*)")}continue}switch(We){case"{":je=true;K.push("(");break;case"}":je=false;K.push(")");break;case",":if(je){K.push("|");break}K.push("\\"+We);break;default:K.push(mt.has(We)?"\\"+We:We)}}K.push("$");return K.join("")}function isRegExp(G){return G instanceof RegExp||Object.prototype.toString.call(G)==="[object RegExp]"}function urlMatchesEqual(G,K){if(isRegExp(G)&&isRegExp(K))return G.source===K.source&&G.flags===K.flags;return G===K}function urlMatches(G,K,je,ze){if(je===void 0||je==="")return true;if((0,ft.isString)(je))je=new RegExp(resolveGlobToRegexPattern(G,je,ze));if(isRegExp(je)){const G=je.test(K);return G}const We=parseURL(K);if(!We)return false;if(typeof je!=="function")throw new Error("url parameter should be string, RegExp or function");return je(We)}function resolveGlobToRegexPattern(G,K,je){if(je)G=toWebSocketBaseUrl(G);K=resolveGlobBase(G,K);return globToRegexPattern(K)}function toWebSocketBaseUrl(G){if(G&&/^https?:\/\//.test(G))G=G.replace(/^http/,"ws");return G}function resolveGlobBase(G,K){if(!K.startsWith("*")){let mapToken2=function(G,K){if(G.length===0)return"";ze.set(K,G);return K};var je=mapToken2;const ze=new Map;K=K.replaceAll(/\\\\\?/g,"?");if(K.startsWith("about:")||K.startsWith("data:")||K.startsWith("chrome:")||K.startsWith("edge:")||K.startsWith("file:"))return K;const We=K.split("/").map(((G,K)=>{if(G==="."||G===".."||G==="")return G;if(K===0&&G.endsWith(":")){if(G.indexOf("*")!==-1||G.indexOf("{")!==-1)return mapToken2(G,"http:");return G}const je=G.indexOf("?");if(je===-1)return mapToken2(G,`$_${K}_$`);const ze=mapToken2(G.substring(0,je),`$_${K}_$`);const We=mapToken2(G.substring(je),`?$_${K}_$`);return ze+We})).join("/");const Xe=resolveBaseURL(G,We);let rt=Xe.resolved;for(const[G,K]of ze){const je=Xe.caseInsensitivePart?.includes(G);rt=rt.replace(G,je?K.toLowerCase():K)}K=rt}return K}function parseURL(G){try{return new URL(G)}catch(G){return null}}function constructURLBasedOnBaseURL(G,K){try{return resolveBaseURL(G,K).resolved}catch(G){return K}}function resolveBaseURL(G,K){try{const je=new URL(K,G);const ze=je.toString();const We=je.origin;return{resolved:ze,caseInsensitivePart:We}}catch(G){return{resolved:K}}}0&&0},29127:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{parseEvaluationResultValue:()=>parseEvaluationResultValue,serializeAsCallArgument:()=>serializeAsCallArgument});G.exports=__toCommonJS(Xe);function isRegExp(G){try{return G instanceof RegExp||Object.prototype.toString.call(G)==="[object RegExp]"}catch(G){return false}}function isDate(G){try{return G instanceof Date||Object.prototype.toString.call(G)==="[object Date]"}catch(G){return false}}function isURL(G){try{return G instanceof URL||Object.prototype.toString.call(G)==="[object URL]"}catch(G){return false}}function isError(G){try{return G instanceof Error||G&&Object.getPrototypeOf(G)?.name==="Error"}catch(G){return false}}function isTypedArray(G,K){try{return G instanceof K||Object.prototype.toString.call(G)===`[object ${K.name}]`}catch(G){return false}}const rt={i8:Int8Array,ui8:Uint8Array,ui8c:Uint8ClampedArray,i16:Int16Array,ui16:Uint16Array,i32:Int32Array,ui32:Uint32Array,f32:Float32Array,f64:Float64Array,bi64:BigInt64Array,bui64:BigUint64Array};function typedArrayToBase64(G){if("toBase64"in G)return G.toBase64();const K=Array.from(new Uint8Array(G.buffer,G.byteOffset,G.byteLength)).map((G=>String.fromCharCode(G))).join("");return btoa(K)}function base64ToTypedArray(G,K){const je=atob(G);const ze=new Uint8Array(je.length);for(let G=0;G<je.length;G++)ze[G]=je.charCodeAt(G);return new K(ze.buffer)}function parseEvaluationResultValue(G,K=[],je=new Map){if(Object.is(G,void 0))return void 0;if(typeof G==="object"&&G){if("ref"in G)return je.get(G.ref);if("v"in G){if(G.v==="undefined")return void 0;if(G.v==="null")return null;if(G.v==="NaN")return NaN;if(G.v==="Infinity")return Infinity;if(G.v==="-Infinity")return-Infinity;if(G.v==="-0")return-0;return void 0}if("d"in G){return new Date(G.d)}if("u"in G)return new URL(G.u);if("bi"in G)return BigInt(G.bi);if("e"in G){const K=new Error(G.e.m);K.name=G.e.n;K.stack=G.e.s;return K}if("r"in G)return new RegExp(G.r.p,G.r.f);if("a"in G){const ze=[];je.set(G.id,ze);for(const We of G.a)ze.push(parseEvaluationResultValue(We,K,je));return ze}if("o"in G){const ze={};je.set(G.id,ze);for(const{k:We,v:Xe}of G.o){if(We==="__proto__")continue;ze[We]=parseEvaluationResultValue(Xe,K,je)}return ze}if("h"in G)return K[G.h];if("ta"in G)return base64ToTypedArray(G.ta.b,rt[G.ta.k])}return G}function serializeAsCallArgument(G,K){return serialize(G,K,{visited:new Map,lastId:0})}function serialize(G,K,je){if(G&&typeof G==="object"){if(typeof globalThis.Window==="function"&&G instanceof globalThis.Window)return"ref: <Window>";if(typeof globalThis.Document==="function"&&G instanceof globalThis.Document)return"ref: <Document>";if(typeof globalThis.Node==="function"&&G instanceof globalThis.Node)return"ref: <Node>"}return innerSerialize(G,K,je)}function innerSerialize(G,K,je){const ze=K(G);if("fallThrough"in ze)G=ze.fallThrough;else return ze;if(typeof G==="symbol")return{v:"undefined"};if(Object.is(G,void 0))return{v:"undefined"};if(Object.is(G,null))return{v:"null"};if(Object.is(G,NaN))return{v:"NaN"};if(Object.is(G,Infinity))return{v:"Infinity"};if(Object.is(G,-Infinity))return{v:"-Infinity"};if(Object.is(G,-0))return{v:"-0"};if(typeof G==="boolean")return G;if(typeof G==="number")return G;if(typeof G==="string")return G;if(typeof G==="bigint")return{bi:G.toString()};if(isError(G)){let K;if(G.stack?.startsWith(G.name+": "+G.message)){K=G.stack}else{K=`${G.name}: ${G.message}\n${G.stack}`}return{e:{n:G.name,m:G.message,s:K}}}if(isDate(G))return{d:G.toJSON()};if(isURL(G))return{u:G.toJSON()};if(isRegExp(G))return{r:{p:G.source,f:G.flags}};for(const[K,je]of Object.entries(rt)){if(isTypedArray(G,je))return{ta:{b:typedArrayToBase64(G),k:K}}}const We=je.visited.get(G);if(We)return{ref:We};if(Array.isArray(G)){const ze=[];const We=++je.lastId;je.visited.set(G,We);for(let We=0;We<G.length;++We)ze.push(serialize(G[We],K,je));return{a:ze,id:We}}if(typeof G==="object"){const ze=[];const We=++je.lastId;je.visited.set(G,We);for(const We of Object.keys(G)){let Xe;try{Xe=G[We]}catch(G){continue}if(We==="toJSON"&&typeof Xe==="function")ze.push({k:We,v:{o:[],id:0}});else ze.push({k:We,v:serialize(Xe,K,je)})}let Xe;try{if(ze.length===0&&G.toJSON&&typeof G.toJSON==="function")Xe={value:G.toJSON()}}catch(G){}if(Xe)return innerSerialize(Xe.value,K,je);return{o:ze,id:We}}}0&&0},83432:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{yamlEscapeKeyIfNeeded:()=>yamlEscapeKeyIfNeeded,yamlEscapeValueIfNeeded:()=>yamlEscapeValueIfNeeded});G.exports=__toCommonJS(Xe);function yamlEscapeKeyIfNeeded(G){if(!yamlStringNeedsQuotes(G))return G;return`'`+G.replace(/'/g,`''`)+`'`}function yamlEscapeValueIfNeeded(G){if(!yamlStringNeedsQuotes(G))return G;return'"'+G.replace(/[\\"\x00-\x1f\x7f-\x9f]/g,(G=>{switch(G){case"\\":return"\\\\";case'"':return'\\"';case"\b":return"\\b";case"\f":return"\\f";case"\n":return"\\n";case"\r":return"\\r";case"\t":return"\\t";default:const K=G.charCodeAt(0);return"\\x"+K.toString(16).padStart(2,"0")}}))+'"'}function yamlStringNeedsQuotes(G){if(G.length===0)return true;if(/^\s|\s$/.test(G))return true;if(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/.test(G))return true;if(/^-/.test(G))return true;if(/[\n:](\s|$)/.test(G))return true;if(/\s#/.test(G))return true;if(/[\n\r]/.test(G))return true;if(/^[&*\],?!>|@"'#%]/.test(G))return true;if(/[{}`]/.test(G))return true;if(/^\[/.test(G))return true;if(!isNaN(Number(G))||["y","n","yes","no","true","false","on","off","null"].includes(G.toLowerCase()))return true;return false}0&&0},45392:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{extract:()=>vt,yauzl:()=>mt,yazl:()=>ft});G.exports=__toCommonJS(at);const ft=je(15070).yazl;const mt=je(15070).yauzl;const vt=je(15070).extract;0&&0},15070:(G,K,je)=>{"use strict";var ze=Object.create;var We=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var at=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var v=(G,K)=>()=>(K||G((K={exports:{}}).exports,K),K.exports),Ct=(G,K)=>{for(var je in K)We(G,je,{get:K[je],enumerable:!0})},or=(G,K,je,ze)=>{if(K&&typeof K=="object"||typeof K=="function")for(let at of rt(K))!ft.call(G,at)&&at!==je&&We(G,at,{get:()=>K[at],enumerable:!(ze=Xe(K,at))||ze.enumerable});return G};var sr=(G,K,je)=>(je=G!=null?ze(at(G)):{},or(K||!G||!G.__esModule?We(je,"default",{value:G,enumerable:!0}):je,G)),bt=G=>or(We({},"__esModule",{value:!0}),G);var mt=v(((G,K)=>{var ze=je(20181).Buffer,We=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];typeof Int32Array!="undefined"&&(We=new Int32Array(We));function fr(G){if(ze.isBuffer(G))return G;var K=typeof ze.alloc=="function"&&typeof ze.from=="function";if(typeof G=="number")return K?ze.alloc(G):new ze(G);if(typeof G=="string")return K?ze.from(G):new ze(G);throw new Error("input must be buffer, number, or string, received "+typeof G)}function Ft(G){var K=fr(4);return K.writeInt32BE(G,0),K}function Ue(G,K){G=fr(G),ze.isBuffer(K)&&(K=K.readUInt32BE(0));for(var je=~~K^-1,Xe=0;Xe<G.length;Xe++)je=We[(je^G[Xe])&255]^je>>>8;return je^-1}function Te(){return Ft(Ue.apply(null,arguments))}Te.signed=function(){return Ue.apply(null,arguments)};Te.unsigned=function(){return Ue.apply(null,arguments)>>>0};K.exports=Te}));var vt=v((G=>{var K=je(79896),ze=je(2203).Transform,We=je(2203).PassThrough,Xe=je(43106),rt=je(39023),at=je(24434).EventEmitter,ft=mt();G.ZipFile=P;G.dateToDosDateTime=br;rt.inherits(P,at);function P(){this.outputStream=new We,this.entries=[],this.outputStreamCursor=0,this.ended=!1,this.allDone=!1,this.forceZip64Eocd=!1}P.prototype.addFile=function(G,je,ze){var We=this;je=de(je,!1),ze==null&&(ze={});var Xe=new m(je,!1,ze);We.entries.push(Xe),K.stat(G,(function(je,rt){if(je)return We.emit("error",je);if(!rt.isFile())return We.emit("error",new Error("not a file: "+G));Xe.uncompressedSize=rt.size,ze.mtime==null&&Xe.setLastModDate(rt.mtime),ze.mode==null&&Xe.setFileAttributesMode(rt.mode),Xe.setFileDataPumpFunction((function(){var je=K.createReadStream(G);Xe.state=m.FILE_DATA_IN_PROGRESS,je.on("error",(function(G){We.emit("error",G)})),hr(We,Xe,je)})),N(We)}))};P.prototype.addReadStream=function(G,K,je){var ze=this;K=de(K,!1),je==null&&(je={});var We=new m(K,!1,je);ze.entries.push(We),We.setFileDataPumpFunction((function(){We.state=m.FILE_DATA_IN_PROGRESS,hr(ze,We,G)})),N(ze)};P.prototype.addBuffer=function(G,K,je){var ze=this;if(K=de(K,!1),G.length>1073741823)throw new Error("buffer too large: "+G.length+" > 1073741823");if(je==null&&(je={}),je.size!=null)throw new Error("options.size not allowed");var We=new m(K,!1,je);We.uncompressedSize=G.length,We.crc32=ft.unsigned(G),We.crcAndFileSizeKnown=!0,ze.entries.push(We),We.compress?Xe.deflateRaw(G,(function(G,K){s(K)})):s(G);function s(G){We.compressedSize=G.length,We.setFileDataPumpFunction((function(){q(ze,G),q(ze,We.getDataDescriptor()),We.state=m.FILE_DATA_DONE,setImmediate((function(){N(ze)}))})),N(ze)}};P.prototype.addEmptyDirectory=function(G,K){var je=this;if(G=de(G,!0),K==null&&(K={}),K.size!=null)throw new Error("options.size not allowed");if(K.compress!=null)throw new Error("options.compress not allowed");var ze=new m(G,!0,K);je.entries.push(ze),ze.setFileDataPumpFunction((function(){q(je,ze.getDataDescriptor()),ze.state=m.FILE_DATA_DONE,N(je)})),N(je)};var vt=T([80,75,5,6]);P.prototype.end=function(G,K){if(typeof G=="function"&&(K=G,G=null),G==null&&(G={}),!this.ended){if(this.ended=!0,this.finalSizeCallback=K,this.forceZip64Eocd=!!G.forceZip64Format,G.comment){if(typeof G.comment=="string"?this.comment=zt(G.comment):this.comment=G.comment,this.comment.length>65535)throw new Error("comment is too large");if(J(this.comment,vt))throw new Error("comment contains end of central directory record signature")}else this.comment=Er;N(this)}};function q(G,K){G.outputStream.write(K),G.outputStreamCursor+=K.length}function hr(G,K,je){var ze=new Ze,rt=new ue,at=K.compress?new Xe.DeflateRaw:new We,ft=new ue;je.pipe(ze).pipe(rt).pipe(at).pipe(ft).pipe(G.outputStream,{end:!1}),ft.on("end",(function(){if(K.crc32=ze.crc32,K.uncompressedSize==null)K.uncompressedSize=rt.byteCount;else if(K.uncompressedSize!==rt.byteCount)return G.emit("error",new Error("file data stream has unexpected number of bytes"));K.compressedSize=ft.byteCount,G.outputStreamCursor+=K.compressedSize,q(G,K.getDataDescriptor()),K.state=m.FILE_DATA_DONE,N(G)}))}function N(G){if(G.allDone)return;if(G.ended&&G.finalSizeCallback!=null){var K=Lt(G);K!=null&&(G.finalSizeCallback(K),G.finalSizeCallback=null)}var je=n();function n(){for(var K=0;K<G.entries.length;K++){var je=G.entries[K];if(je.state<m.FILE_DATA_DONE)return je}return null}if(je!=null){if(je.state<m.READY_TO_PUMP_FILE_DATA||je.state===m.FILE_DATA_IN_PROGRESS)return;je.relativeOffsetOfLocalHeader=G.outputStreamCursor;var ze=je.getLocalFileHeader();q(G,ze),je.doFileDataPump()}else G.ended&&(G.offsetOfStartOfCentralDirectory=G.outputStreamCursor,G.entries.forEach((function(K){var je=K.getCentralDirectoryRecord();q(G,je)})),q(G,Ot(G)),G.outputStream.end(),G.allDone=!0)}function Lt(G){for(var K=0,je=0,ze=0;ze<G.entries.length;ze++){var We=G.entries[ze];if(We.compress)return-1;if(We.state>=m.READY_TO_PUMP_FILE_DATA){if(We.uncompressedSize==null)return-1}else if(We.uncompressedSize==null)return null;We.relativeOffsetOfLocalHeader=K;var Xe=We.useZip64Format();K+=Rr+We.utf8FileName.length,K+=We.uncompressedSize,We.crcAndFileSizeKnown||(Xe?K+=Ei:K+=Si),je+=ki+We.utf8FileName.length+We.fileComment.length,Xe&&(je+=Ci)}var rt=0;return(G.forceZip64Eocd||G.entries.length>=65535||je>=65535||K>=4294967295)&&(rt+=yt+wt),rt+=lr+G.comment.length,K+je+rt}var yt=56,wt=20,lr=22;function Ot(G,K){var je=!1,ze=G.entries.length;(G.forceZip64Eocd||G.entries.length>=65535)&&(ze=65535,je=!0);var We=G.outputStreamCursor-G.offsetOfStartOfCentralDirectory,Xe=We;(G.forceZip64Eocd||We>=4294967295)&&(Xe=4294967295,je=!0);var rt=G.offsetOfStartOfCentralDirectory;if((G.forceZip64Eocd||G.offsetOfStartOfCentralDirectory>=4294967295)&&(rt=4294967295,je=!0),K)return je?yt+wt+lr:lr;var at=g(lr+G.comment.length);if(at.writeUInt32LE(101010256,0),at.writeUInt16LE(0,4),at.writeUInt16LE(0,6),at.writeUInt16LE(ze,8),at.writeUInt16LE(ze,10),at.writeUInt32LE(Xe,12),at.writeUInt32LE(rt,16),at.writeUInt16LE(G.comment.length,20),G.comment.copy(at,22),!je)return at;var ft=g(yt);ft.writeUInt32LE(101075792,0),I(ft,yt-12,4),ft.writeUInt16LE(fi,12),ft.writeUInt16LE(zr,14),ft.writeUInt32LE(0,16),ft.writeUInt32LE(0,20),I(ft,G.entries.length,24),I(ft,G.entries.length,32),I(ft,We,40),I(ft,G.offsetOfStartOfCentralDirectory,48);var mt=g(wt);return mt.writeUInt32LE(117853008,0),mt.writeUInt32LE(0,4),I(mt,G.outputStreamCursor,8),mt.writeUInt32LE(1,16),Buffer.concat([ft,mt,at])}function de(G,K){if(G==="")throw new Error("empty metadataPath");if(G=G.replace(/\\/g,"/"),/^[a-zA-Z]:/.test(G)||/^\//.test(G))throw new Error("absolute path: "+G);if(G.split("/").indexOf("..")!==-1)throw new Error("invalid relative path: "+G);var je=/\/$/.test(G);if(K)je||(G+="/");else if(je)throw new Error("file path cannot end with '/': "+G);return G}var Er=g(0);function m(G,K,je){if(this.utf8FileName=T(G),this.utf8FileName.length>65535)throw new Error("utf8 file name too long. "+utf8FileName.length+" > 65535");if(this.isDirectory=K,this.state=m.WAITING_FOR_METADATA,this.setLastModDate(je.mtime!=null?je.mtime:new Date),je.mode!=null?this.setFileAttributesMode(je.mode):this.setFileAttributesMode(K?16893:33204),K?(this.crcAndFileSizeKnown=!0,this.crc32=0,this.uncompressedSize=0,this.compressedSize=0):(this.crcAndFileSizeKnown=!1,this.crc32=null,this.uncompressedSize=null,this.compressedSize=null,je.size!=null&&(this.uncompressedSize=je.size)),K?this.compress=!1:(this.compress=!0,je.compress!=null&&(this.compress=!!je.compress)),this.forceZip64Format=!!je.forceZip64Format,je.fileComment){if(typeof je.fileComment=="string"?this.fileComment=T(je.fileComment,"utf-8"):this.fileComment=je.fileComment,this.fileComment.length>65535)throw new Error("fileComment is too large")}else this.fileComment=Er}m.WAITING_FOR_METADATA=0;m.READY_TO_PUMP_FILE_DATA=1;m.FILE_DATA_IN_PROGRESS=2;m.FILE_DATA_DONE=3;m.prototype.setLastModDate=function(G){var K=br(G);this.lastModFileTime=K.time,this.lastModFileDate=K.date};m.prototype.setFileAttributesMode=function(G){if((G&65535)!==G)throw new Error("invalid mode. expected: 0 <= "+G+" <= 65535");this.externalFileAttributes=G<<16>>>0};m.prototype.setFileDataPumpFunction=function(G){this.doFileDataPump=G,this.state=m.READY_TO_PUMP_FILE_DATA};m.prototype.useZip64Format=function(){return this.forceZip64Format||this.uncompressedSize!=null&&this.uncompressedSize>4294967294||this.compressedSize!=null&&this.compressedSize>4294967294||this.relativeOffsetOfLocalHeader!=null&&this.relativeOffsetOfLocalHeader>4294967294};var Rr=30,jr=20,zr=45,fi=831,mi=2048,bi=8;m.prototype.getLocalFileHeader=function(){var G=0,K=0,je=0;this.crcAndFileSizeKnown&&(G=this.crc32,K=this.compressedSize,je=this.uncompressedSize);var ze=g(Rr),We=mi;return this.crcAndFileSizeKnown||(We|=bi),ze.writeUInt32LE(67324752,0),ze.writeUInt16LE(jr,4),ze.writeUInt16LE(We,6),ze.writeUInt16LE(this.getCompressionMethod(),8),ze.writeUInt16LE(this.lastModFileTime,10),ze.writeUInt16LE(this.lastModFileDate,12),ze.writeUInt32LE(G,14),ze.writeUInt32LE(K,18),ze.writeUInt32LE(je,22),ze.writeUInt16LE(this.utf8FileName.length,26),ze.writeUInt16LE(0,28),Buffer.concat([ze,this.utf8FileName])};var Si=16,Ei=24;m.prototype.getDataDescriptor=function(){if(this.crcAndFileSizeKnown)return Er;if(this.useZip64Format()){var G=g(Ei);return G.writeUInt32LE(134695760,0),G.writeUInt32LE(this.crc32,4),I(G,this.compressedSize,8),I(G,this.uncompressedSize,16),G}else{var G=g(Si);return G.writeUInt32LE(134695760,0),G.writeUInt32LE(this.crc32,4),G.writeUInt32LE(this.compressedSize,8),G.writeUInt32LE(this.uncompressedSize,12),G}};var ki=46,Ci=28;m.prototype.getCentralDirectoryRecord=function(){var G=g(ki),K=mi;this.crcAndFileSizeKnown||(K|=bi);var je=this.compressedSize,ze=this.uncompressedSize,We=this.relativeOffsetOfLocalHeader,Xe,rt;return this.useZip64Format()?(je=4294967295,ze=4294967295,We=4294967295,Xe=zr,rt=g(Ci),rt.writeUInt16LE(1,0),rt.writeUInt16LE(Ci-4,2),I(rt,this.uncompressedSize,4),I(rt,this.compressedSize,12),I(rt,this.relativeOffsetOfLocalHeader,20)):(Xe=jr,rt=Er),G.writeUInt32LE(33639248,0),G.writeUInt16LE(fi,4),G.writeUInt16LE(Xe,6),G.writeUInt16LE(K,8),G.writeUInt16LE(this.getCompressionMethod(),10),G.writeUInt16LE(this.lastModFileTime,12),G.writeUInt16LE(this.lastModFileDate,14),G.writeUInt32LE(this.crc32,16),G.writeUInt32LE(je,20),G.writeUInt32LE(ze,24),G.writeUInt16LE(this.utf8FileName.length,28),G.writeUInt16LE(rt.length,30),G.writeUInt16LE(this.fileComment.length,32),G.writeUInt16LE(0,34),G.writeUInt16LE(0,36),G.writeUInt32LE(this.externalFileAttributes,38),G.writeUInt32LE(We,42),Buffer.concat([G,this.utf8FileName,rt,this.fileComment])};m.prototype.getCompressionMethod=function(){var G=0,K=8;return this.compress?K:G};function br(G){var K=0;K|=G.getDate()&31,K|=(G.getMonth()+1&15)<<5,K|=(G.getFullYear()-1980&127)<<9;var je=0;return je|=Math.floor(G.getSeconds()/2),je|=(G.getMinutes()&63)<<5,je|=(G.getHours()&31)<<11,{date:K,time:je}}function I(G,K,je){var ze=Math.floor(K/4294967296),We=K%4294967296;G.writeUInt32LE(We,je),G.writeUInt32LE(ze,je+4)}rt.inherits(ue,ze);function ue(G){ze.call(this,G),this.byteCount=0}ue.prototype._transform=function(G,K,je){this.byteCount+=G.length,je(null,G)};rt.inherits(Ze,ze);function Ze(G){ze.call(this,G),this.crc32=0}Ze.prototype._transform=function(G,K,je){this.crc32=ft.unsigned(G,this.crc32),je(null,G)};var Ti="\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ";if(Ti.length!==256)throw new Error("assertion failure");var Pi=null;function zt(G){if(/^[\x20-\x7e]*$/.test(G))return T(G,"utf-8");if(Pi==null){Pi={};for(var K=0;K<Ti.length;K++)Pi[Ti[K]]=K}for(var je=g(G.length),K=0;K<G.length;K++){var ze=Pi[G[K]];if(ze==null)throw new Error("character not encodable in CP437: "+JSON.stringify(G[K]));je[K]=ze}return je}function g(G){g=r;try{return g(G)}catch{return g=t,g(G)}function r(G){return Buffer.allocUnsafe(G)}function t(G){return new Buffer(G)}}function T(G,K){T=t;try{return T(G,K)}catch{return T=n,T(G,K)}function t(G,K){return Buffer.from(G,K)}function n(G,K){return new Buffer(G,K)}}function J(G,K){J=t;try{return J(G,K)}catch{return J=n,J(G,K)}function t(G,K){return G.includes(K)}function n(G,K){for(var je=0;je<=G.length-K.length;je++)for(var ze=0;;ze++){if(ze===K.length)return!0;if(G[je+ze]!==K[ze])break}return!1}}}));var yt=v(((G,K)=>{K.exports=he;function he(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}he.prototype.go=function(G){this.pending<this.max?Sr(this,G):this.waiting.push(G)};he.prototype.wait=function(G){this.pending===0?G(this.error):this.listeners.push(G)};he.prototype.hold=function(){return Ir(this)};function Ir(G){G.pending+=1;var K=!1;return t;function t(je){if(K)throw new Error("callback called twice");if(K=!0,G.error=G.error||je,G.pending-=1,G.waiting.length>0&&G.pending<G.max)Sr(G,G.waiting.shift());else if(G.pending===0){var ze=G.listeners;G.listeners=[],ze.forEach(n)}}function n(K){K(G.error)}}function Sr(G,K){K(Ir(G))}}));var wt=v((G=>{var K=je(79896),ze=je(39023),We=je(2203),Xe=We.Readable,rt=We.Writable,at=We.PassThrough,ft=yt(),mt=je(24434).EventEmitter;G.createFromBuffer=Dt;G.createFromFd=At;G.BufferSlicer=D;G.FdSlicer=R;ze.inherits(R,mt);function R(G,K){K=K||{},mt.call(this),this.fd=G,this.pend=new ft,this.pend.max=1,this.refCount=0,this.autoClose=!!K.autoClose}R.prototype.read=function(G,je,ze,We,Xe){var rt=this;rt.pend.go((function(at){K.read(rt.fd,G,je,ze,We,(function(G,K,je){at(),Xe(G,K,je)}))}))};R.prototype.write=function(G,je,ze,We,Xe){var rt=this;rt.pend.go((function(at){K.write(rt.fd,G,je,ze,We,(function(G,K,je){at(),Xe(G,K,je)}))}))};R.prototype.createReadStream=function(G){return new xe(this,G)};R.prototype.createWriteStream=function(G){return new Ee(this,G)};R.prototype.ref=function(){this.refCount+=1};R.prototype.unref=function(){var G=this;if(G.refCount-=1,G.refCount>0)return;if(G.refCount<0)throw new Error("invalid unref");G.autoClose&&K.close(G.fd,r);function r(K){K?G.emit("error",K):G.emit("close")}};ze.inherits(xe,Xe);function xe(G,K){K=K||{},Xe.call(this,K),this.context=G,this.context.ref(),this.start=K.start||0,this.endOffset=K.end,this.pos=this.start,this.destroyed=!1}xe.prototype._read=function(G){var je=this;if(!je.destroyed){var ze=Math.min(je._readableState.highWaterMark,G);if(je.endOffset!=null&&(ze=Math.min(ze,je.endOffset-je.pos)),ze<=0){je.destroyed=!0,je.push(null),je.context.unref();return}je.context.pend.go((function(G){if(je.destroyed)return G();var We=Buffer.allocUnsafe(ze);K.read(je.context.fd,We,0,ze,je.pos,(function(K,ze){K?je.destroy(K):ze===0?(je.destroyed=!0,je.push(null),je.context.unref()):(je.pos+=ze,je.push(We.slice(0,ze))),G()}))}))}};xe.prototype.destroy=function(G){this.destroyed||(G=G||new Error("stream destroyed"),this.destroyed=!0,this.emit("error",G),this.context.unref())};ze.inherits(Ee,rt);function Ee(G,K){K=K||{},rt.call(this,K),this.context=G,this.context.ref(),this.start=K.start||0,this.endOffset=K.end==null?1/0:+K.end,this.bytesWritten=0,this.pos=this.start,this.destroyed=!1,this.on("finish",this.destroy.bind(this))}Ee.prototype._write=function(G,je,ze){var We=this;if(!We.destroyed){if(We.pos+G.length>We.endOffset){var Xe=new Error("maximum file length exceeded");Xe.code="ETOOBIG",We.destroy(),ze(Xe);return}We.context.pend.go((function(je){if(We.destroyed)return je();K.write(We.context.fd,G,0,G.length,We.pos,(function(G,K){G?(We.destroy(),je(),ze(G)):(We.bytesWritten+=K,We.pos+=K,We.emit("progress"),je(),ze())}))}))}};Ee.prototype.destroy=function(){this.destroyed||(this.destroyed=!0,this.context.unref())};ze.inherits(D,mt);function D(G,K){mt.call(this),K=K||{},this.refCount=0,this.buffer=G,this.maxChunkSize=K.maxChunkSize||Number.MAX_SAFE_INTEGER}D.prototype.read=function(G,K,je,ze,We){if(!(0<=K&&K<=G.length))throw new RangeError("offset outside buffer: 0 <= "+K+" <= "+G.length);if(ze<0)throw new RangeError("position is negative: "+ze);if(K+je>G.length&&(je=G.length-K),ze+je>this.buffer.length&&(je=this.buffer.length-ze),je<=0){setImmediate((function(){We(null,0)}));return}this.buffer.copy(G,K,ze,ze+je),setImmediate((function(){We(null,je)}))};D.prototype.write=function(G,K,je,ze,We){G.copy(this.buffer,ze,K,K+je),setImmediate((function(){We(null,je,G)}))};D.prototype.createReadStream=function(G){G=G||{};var K=new at(G);K.destroyed=!1,K.start=G.start||0,K.endOffset=G.end,K.pos=K.endOffset||this.buffer.length;for(var je=this.buffer.slice(K.start,K.pos),ze=0;;){var We=ze+this.maxChunkSize;if(We>=je.length){ze<je.length&&K.write(je.slice(ze,je.length));break}K.write(je.slice(ze,We)),ze=We}return K.end(),K.destroy=function(){K.destroyed=!0},K};D.prototype.createWriteStream=function(G){var K=this;G=G||{};var je=new rt(G);return je.start=G.start||0,je.endOffset=G.end==null?this.buffer.length:+G.end,je.bytesWritten=0,je.pos=je.start,je.destroyed=!1,je._write=function(G,ze,We){if(!je.destroyed){var Xe=je.pos+G.length;if(Xe>je.endOffset){var rt=new Error("maximum file length exceeded");rt.code="ETOOBIG",je.destroyed=!0,We(rt);return}G.copy(K.buffer,je.pos,0,G.length),je.bytesWritten+=G.length,je.pos=Xe,je.emit("progress"),We()}},je.destroy=function(){je.destroyed=!0},je};D.prototype.ref=function(){this.refCount+=1};D.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw new Error("invalid unref")};function Dt(G,K){return new D(G,K)}function At(G,K){return new R(G,K)}}));var lr=v((G=>{var K=je(79896),ze=je(43106),We=wt(),Xe=mt(),rt=je(39023),at=je(24434).EventEmitter,ft=je(2203).Transform,vt=je(2203).PassThrough,yt=je(2203).Writable;G.open=Mt;G.fromFd=Ar;G.fromBuffer=Bt;G.fromRandomAccessReader=Ve;G.dosDateTimeToDate=Nr;G.getFileNameLowLevel=Mr;G.validateFileName=Br;G.parseExtraFields=qr;G.ZipFile=_;G.Entry=ee;G.LocalFileHeader=Tr;G.RandomAccessReader=M;function Mt(G,je,ze){typeof je=="function"&&(ze=je,je=null),je==null&&(je={}),je.autoClose==null&&(je.autoClose=!0),je.lazyEntries==null&&(je.lazyEntries=!1),je.decodeStrings==null&&(je.decodeStrings=!0),je.validateEntrySizes==null&&(je.validateEntrySizes=!0),je.strictFileNames==null&&(je.strictFileNames=!1),ze==null&&(ze=we),K.open(G,"r",(function(G,We){if(G)return ze(G);Ar(We,je,(function(G,je){G&&K.close(We,we),ze(G,je)}))}))}function Ar(G,je,ze){typeof je=="function"&&(ze=je,je=null),je==null&&(je={}),je.autoClose==null&&(je.autoClose=!1),je.lazyEntries==null&&(je.lazyEntries=!1),je.decodeStrings==null&&(je.decodeStrings=!0),je.validateEntrySizes==null&&(je.validateEntrySizes=!0),je.strictFileNames==null&&(je.strictFileNames=!1),ze==null&&(ze=we),K.fstat(G,(function(K,Xe){if(K)return ze(K);var rt=We.createFromFd(G,{autoClose:!0});Ve(rt,Xe.size,je,ze)}))}function Bt(G,K,je){typeof K=="function"&&(je=K,K=null),K==null&&(K={}),K.autoClose=!1,K.lazyEntries==null&&(K.lazyEntries=!1),K.decodeStrings==null&&(K.decodeStrings=!0),K.validateEntrySizes==null&&(K.validateEntrySizes=!0),K.strictFileNames==null&&(K.strictFileNames=!1);var ze=We.createFromBuffer(G,{maxChunkSize:65536});Ve(ze,G.length,K,je)}function Ve(G,K,je,ze){typeof je=="function"&&(ze=je,je=null),je==null&&(je={}),je.autoClose==null&&(je.autoClose=!0),je.lazyEntries==null&&(je.lazyEntries=!1),je.decodeStrings==null&&(je.decodeStrings=!0);var We=!!je.decodeStrings;if(je.validateEntrySizes==null&&(je.validateEntrySizes=!0),je.strictFileNames==null&&(je.strictFileNames=!1),ze==null&&(ze=we),typeof K!="number")throw new Error("expected totalSize parameter to be a number");if(K>Number.MAX_SAFE_INTEGER)throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");G.ref();var Xe=22,rt=20,at=65535,ft=Math.min(rt+Xe+at,K),mt=Er(ft),vt=K-mt.length;j(G,mt,0,ft,vt,(function(at){if(at)return ze(at);for(var vt=ft-Xe;vt>=0;vt-=1)if(mt.readUInt32LE(vt)===101010256){var yt=mt.subarray(vt),wt=yt.readUInt16LE(4),lr=yt.readUInt16LE(10),Rr=yt.readUInt32LE(16),jr=yt.readUInt16LE(20),zr=yt.length-Xe;if(jr!==zr)return ze(new Error("Invalid comment length. Expected: "+zr+". Found: "+jr+". Are there extra bytes at the end of the file? Or is the end of central dir signature `PK☺☻` in the comment?"));var fi=We?ve(yt.subarray(22),!1):yt.subarray(22);if(vt-rt>=0&&mt.readUInt32LE(vt-rt)===117853008){var mi=mt.subarray(vt-rt,vt-rt+rt),bi=Y(mi,8),Si=Er(56);return j(G,Si,0,Si.length,bi,(function(Xe){return Xe?ze(Xe):Si.readUInt32LE(0)!==101075792?ze(new Error("invalid zip64 end of central directory record signature")):(wt=Si.readUInt32LE(16),wt!==0?ze(new Error("multi-disk zip files are not supported: found disk number: "+wt)):(lr=Y(Si,32),Rr=Y(Si,48),ze(null,new _(G,Rr,K,lr,fi,je.autoClose,je.lazyEntries,We,je.validateEntrySizes,je.strictFileNames))))}))}return wt!==0?ze(new Error("multi-disk zip files are not supported: found disk number: "+wt)):ze(null,new _(G,Rr,K,lr,fi,je.autoClose,je.lazyEntries,We,je.validateEntrySizes,je.strictFileNames))}ze(new Error("End of central directory record signature not found. Either not a zip file, or file is truncated."))}))}rt.inherits(_,at);function _(G,K,je,ze,We,Xe,rt,ft,mt,vt){var yt=this;at.call(yt),yt.reader=G,yt.reader.on("error",(function(G){Ur(yt,G)})),yt.reader.once("close",(function(){yt.emit("close")})),yt.readEntryCursor=K,yt.fileSize=je,yt.entryCount=ze,yt.comment=We,yt.entriesRead=0,yt.autoClose=!!Xe,yt.lazyEntries=!!rt,yt.decodeStrings=!!ft,yt.validateEntrySizes=!!mt,yt.strictFileNames=!!vt,yt.isOpen=!0,yt.emittedError=!1,yt.lazyEntries||yt._readEntry()}_.prototype.close=function(){this.isOpen&&(this.isOpen=!1,this.reader.unref())};function z(G,K){G.autoClose&&G.close(),Ur(G,K)}function Ur(G,K){G.emittedError||(G.emittedError=!0,G.emit("error",K))}_.prototype.readEntry=function(){if(!this.lazyEntries)throw new Error("readEntry() called without lazyEntries:true");this._readEntry()};_.prototype._readEntry=function(){var G=this;if(G.entryCount===G.entriesRead){setImmediate((function(){G.autoClose&&G.close(),!G.emittedError&&G.emit("end")}));return}if(!G.emittedError){var K=Er(46);j(G.reader,K,0,K.length,G.readEntryCursor,(function(je){if(je)return z(G,je);if(!G.emittedError){var ze=new ee,We=K.readUInt32LE(0);if(We!==33639248)return z(G,new Error("invalid central directory file header signature: 0x"+We.toString(16)));if(ze.versionMadeBy=K.readUInt16LE(4),ze.versionNeededToExtract=K.readUInt16LE(6),ze.generalPurposeBitFlag=K.readUInt16LE(8),ze.compressionMethod=K.readUInt16LE(10),ze.lastModFileTime=K.readUInt16LE(12),ze.lastModFileDate=K.readUInt16LE(14),ze.crc32=K.readUInt32LE(16),ze.compressedSize=K.readUInt32LE(20),ze.uncompressedSize=K.readUInt32LE(24),ze.fileNameLength=K.readUInt16LE(28),ze.extraFieldLength=K.readUInt16LE(30),ze.fileCommentLength=K.readUInt16LE(32),ze.internalFileAttributes=K.readUInt16LE(36),ze.externalFileAttributes=K.readUInt32LE(38),ze.relativeOffsetOfLocalHeader=K.readUInt32LE(42),ze.generalPurposeBitFlag&64)return z(G,new Error("strong encryption is not supported"));G.readEntryCursor+=46,K=Er(ze.fileNameLength+ze.extraFieldLength+ze.fileCommentLength),j(G.reader,K,0,K.length,G.readEntryCursor,(function(je){if(je)return z(G,je);if(!G.emittedError){ze.fileNameRaw=K.subarray(0,ze.fileNameLength);var We=ze.fileNameLength+ze.extraFieldLength;ze.extraFieldRaw=K.subarray(ze.fileNameLength,We),ze.fileCommentRaw=K.subarray(We,We+ze.fileCommentLength);try{ze.extraFields=qr(ze.extraFieldRaw)}catch(K){return z(G,K)}if(G.decodeStrings){var Xe=(ze.generalPurposeBitFlag&2048)!==0;ze.fileComment=ve(ze.fileCommentRaw,Xe),ze.fileName=Mr(ze.generalPurposeBitFlag,ze.fileNameRaw,ze.extraFields,G.strictFileNames);var rt=Br(ze.fileName);if(rt!=null)return z(G,new Error(rt))}else ze.fileComment=ze.fileCommentRaw,ze.fileName=ze.fileNameRaw;ze.comment=ze.fileComment,G.readEntryCursor+=K.length,G.entriesRead+=1;for(var at=0;at<ze.extraFields.length;at++){var ft=ze.extraFields[at];if(ft.id===1){var mt=ft.data,vt=0;if(ze.uncompressedSize===4294967295){if(vt+8>mt.length)return z(G,new Error("zip64 extended information extra field does not include uncompressed size"));ze.uncompressedSize=Y(mt,vt),vt+=8}if(ze.compressedSize===4294967295){if(vt+8>mt.length)return z(G,new Error("zip64 extended information extra field does not include compressed size"));ze.compressedSize=Y(mt,vt),vt+=8}if(ze.relativeOffsetOfLocalHeader===4294967295){if(vt+8>mt.length)return z(G,new Error("zip64 extended information extra field does not include relative header offset"));ze.relativeOffsetOfLocalHeader=Y(mt,vt),vt+=8}break}}if(G.validateEntrySizes&&ze.compressionMethod===0){var yt=ze.uncompressedSize;if(ze.isEncrypted()&&(yt+=12),ze.compressedSize!==yt){var wt="compressed/uncompressed size mismatch for stored file: "+ze.compressedSize+" != "+ze.uncompressedSize;return z(G,new Error(wt))}}G.emit("entry",ze),G.lazyEntries||G._readEntry()}}))}}))}};_.prototype.openReadStream=function(G,K,je){var ze=this,We=0,Xe=G.compressedSize;if(je==null&&(je=K,K=null),K==null)K={};else{if(K.decrypt!=null){if(!G.isEncrypted())throw new Error("options.decrypt can only be specified for encrypted entries");if(K.decrypt!==!1)throw new Error("invalid options.decrypt value: "+K.decrypt);if(G.isCompressed()&&K.decompress!==!1)throw new Error("entry is encrypted and compressed, and options.decompress !== false")}if(K.decompress!=null){if(!G.isCompressed())throw new Error("options.decompress can only be specified for compressed entries");if(!(K.decompress===!1||K.decompress===!0))throw new Error("invalid options.decompress value: "+K.decompress)}if(K.start!=null||K.end!=null){if(G.isCompressed()&&K.decompress!==!1)throw new Error("start/end range not allowed for compressed entry without options.decompress === false");if(G.isEncrypted()&&K.decrypt!==!1)throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false")}if(K.start!=null){if(We=K.start,We<0)throw new Error("options.start < 0");if(We>G.compressedSize)throw new Error("options.start > entry.compressedSize")}if(K.end!=null){if(Xe=K.end,Xe<0)throw new Error("options.end < 0");if(Xe>G.compressedSize)throw new Error("options.end > entry.compressedSize");if(Xe<We)throw new Error("options.end < options.start")}}if(!ze.isOpen)return je(new Error("closed"));if(G.isEncrypted()&&K.decrypt!==!1)return je(new Error("entry is encrypted, and options.decrypt !== false"));var rt;if(G.compressionMethod===0)rt=!1;else if(G.compressionMethod===8)rt=K.decompress!=null?K.decompress:!0;else return je(new Error("unsupported compression method: "+G.compressionMethod));ze.readLocalFileHeader(G,{minimal:!0},(function(K,at){if(K)return je(K);ze.openReadStreamLowLevel(at.fileDataStart,G.compressedSize,We,Xe,rt,G.uncompressedSize,je)}))};_.prototype.openReadStreamLowLevel=function(G,K,je,We,Xe,rt,at){var ft=this,mt=G+K,vt=ft.reader.createReadStream({start:G+je,end:G+We}),yt=vt;if(Xe){var wt=!1,lr=ze.createInflateRaw();vt.on("error",(function(G){setImmediate((function(){wt||lr.emit("error",G)}))})),vt.pipe(lr),ft.validateEntrySizes?(yt=new re(rt),lr.on("error",(function(G){setImmediate((function(){wt||yt.emit("error",G)}))})),lr.pipe(yt)):yt=lr,He(yt,(function(){wt=!0,lr!==yt&&lr.unpipe(yt),vt.unpipe(lr),vt.destroy()}))}at(null,yt)};_.prototype.readLocalFileHeader=function(G,K,je){var ze=this;je==null&&(je=K,K=null),K==null&&(K={}),ze.reader.ref();var We=Er(30);j(ze.reader,We,0,We.length,G.relativeOffsetOfLocalHeader,(function(Xe){try{if(Xe)return je(Xe);var rt=We.readUInt32LE(0);if(rt!==67324752)return je(new Error("invalid local file header signature: 0x"+rt.toString(16)));var at=We.readUInt16LE(26),ft=We.readUInt16LE(28),mt=G.relativeOffsetOfLocalHeader+30+at+ft;if(mt+G.compressedSize>ze.fileSize)return je(new Error("file data overflows file bounds: "+mt+" + "+G.compressedSize+" > "+ze.fileSize));if(K.minimal)return je(null,{fileDataStart:mt});var vt=new Tr;vt.fileDataStart=mt,vt.versionNeededToExtract=We.readUInt16LE(4),vt.generalPurposeBitFlag=We.readUInt16LE(6),vt.compressionMethod=We.readUInt16LE(8),vt.lastModFileTime=We.readUInt16LE(10),vt.lastModFileDate=We.readUInt16LE(12),vt.crc32=We.readUInt32LE(14),vt.compressedSize=We.readUInt32LE(18),vt.uncompressedSize=We.readUInt32LE(22),vt.fileNameLength=at,vt.extraFieldLength=ft,We=Er(at+ft),ze.reader.ref(),j(ze.reader,We,0,We.length,G.relativeOffsetOfLocalHeader+30,(function(G){try{return G?je(G):(vt.fileName=We.subarray(0,at),vt.extraField=We.subarray(at),je(null,vt))}finally{ze.reader.unref()}}))}finally{ze.reader.unref()}}))};function ee(){}ee.prototype.getLastModDate=function(G){if(G==null&&(G={}),!G.forceDosFormat)for(var K=0;K<this.extraFields.length;K++){var je=this.extraFields[K];if(je.id===21589){var ze=je.data;if(ze.length<5)continue;var We=ze[0],Xe=1;if(!(We&Xe))continue;var rt=ze.readInt32LE(1);return new Date(rt*1e3)}else if(je.id===10)for(var ze=je.data,at=4;at<ze.length+4;){var ft=ze.readUInt16LE(at);at+=2;var mt=ze.readUInt16LE(at);if(at+=2,ft!==1){at+=mt;continue}if(mt<8||at+mt>ze.length)break;var vt=4294967296*ze.readInt32LE(at+4)+ze.readUInt32LE(at),yt=vt/1e4-116444736e5;return new Date(yt)}}return Nr(this.lastModFileDate,this.lastModFileTime,G.timezone)};ee.prototype.isEncrypted=function(){return(this.generalPurposeBitFlag&1)!==0};ee.prototype.isCompressed=function(){return this.compressionMethod===8};function Tr(){}function Nr(G,K,je){var ze=G&31,We=(G>>5&15)-1,Xe=(G>>9&127)+1980,rt=0,at=(K&31)*2,ft=K>>5&63,mt=K>>11&31;if(je==null||je==="local")return new Date(Xe,We,ze,mt,ft,at,rt);if(je==="UTC")return new Date(Date.UTC(Xe,We,ze,mt,ft,at,rt));throw new Error("unrecognized options.timezone: "+options.timezone)}function Mr(G,K,je,ze){for(var We=null,rt=0;rt<je.length;rt++){var at=je[rt];if(at.id===28789){if(at.data.length<6||at.data.readUInt8(0)!==1)continue;var ft=at.data.readUInt32LE(1);if(Xe.unsigned(K)!==ft)continue;We=ve(at.data.subarray(5),!0);break}}if(We==null){var mt=(G&2048)!==0;We=ve(K,mt)}return ze||(We=We.replace(/\\/g,"/")),We}function Br(G){return G.indexOf("\\")!==-1?"invalid characters in fileName: "+G:/^[a-zA-Z]:/.test(G)||/^\//.test(G)?"absolute path: "+G:G.split("/").indexOf("..")!==-1?"invalid relative path: "+G:null}function qr(G){for(var K=[],je=0;je<G.length-3;){var ze=G.readUInt16LE(je+0),We=G.readUInt16LE(je+2),Xe=je+4,rt=Xe+We;if(rt>G.length)throw new Error("extra field length exceeds extra field buffer size");var at=G.subarray(Xe,rt);K.push({id:ze,data:at}),je=rt}return K}function j(G,K,je,ze,We,Xe){if(ze===0)return setImmediate((function(){Xe(null,Er(0))}));G.read(K,je,ze,We,(function(G,K){if(G)return Xe(G);if(K<ze)return Xe(new Error("unexpected EOF"));Xe()}))}rt.inherits(re,ft);function re(G){ft.call(this),this.actualByteCount=0,this.expectedByteCount=G}re.prototype._transform=function(G,K,je){if(this.actualByteCount+=G.length,this.actualByteCount>this.expectedByteCount){var ze="too many bytes in the stream. expected "+this.expectedByteCount+". got at least "+this.actualByteCount;return je(new Error(ze))}je(null,G)};re.prototype._flush=function(G){if(this.actualByteCount<this.expectedByteCount){var K="not enough bytes in the stream. expected "+this.expectedByteCount+". got only "+this.actualByteCount;return G(new Error(K))}G()};rt.inherits(M,at);function M(){at.call(this),this.refCount=0}M.prototype.ref=function(){this.refCount+=1};M.prototype.unref=function(){var G=this;if(G.refCount-=1,G.refCount>0)return;if(G.refCount<0)throw new Error("invalid unref");G.close(r);function r(K){if(K)return G.emit("error",K);G.emit("close")}};M.prototype.createReadStream=function(G){G==null&&(G={});var K=G.start,je=G.end;if(K===je){var ze=new vt;return setImmediate((function(){ze.end()})),ze}var We=this._readStreamForRange(K,je),Xe=!1,rt=new Ce(this);We.on("error",(function(G){setImmediate((function(){Xe||rt.emit("error",G)}))})),He(rt,(function(){We.unpipe(rt),rt.unref(),We.destroy()}));var at=new re(je-K);return rt.on("error",(function(G){setImmediate((function(){Xe||at.emit("error",G)}))})),He(at,(function(){Xe=!0,rt.unpipe(at),rt.destroy()})),We.pipe(rt).pipe(at)};M.prototype._readStreamForRange=function(G,K){throw new Error("not implemented")};M.prototype.read=function(G,K,je,ze,We){var Xe=this.createReadStream({start:ze,end:ze+je}),rt=new yt,at=0;rt._write=function(je,ze,We){je.copy(G,K+at,0,je.length),at+=je.length,We()},rt.on("finish",We),Xe.on("error",(function(G){We(G)})),Xe.pipe(rt)};M.prototype.close=function(G){setImmediate(G)};rt.inherits(Ce,vt);function Ce(G){vt.call(this),this.context=G,this.context.ref(),this.unreffedYet=!1}Ce.prototype._flush=function(G){this.unref(),G()};Ce.prototype.unref=function(G){this.unreffedYet||(this.unreffedYet=!0,this.context.unref())};var lr="\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ";function ve(G,K){if(K)return G.toString("utf8");for(var je="",ze=0;ze<G.length;ze++)je+=lr[G[ze]];return je}function Y(G,K){var je=G.readUInt32LE(K),ze=G.readUInt32LE(K+4);return ze*4294967296+je}var Er;typeof Buffer.allocUnsafe=="function"?Er=function(G){return Buffer.allocUnsafe(G)}:Er=function(G){return new Buffer(G)};function He(G,K){typeof G.destroy=="function"?G._destroy=function(G,je){K(),je!=null&&je(G)}:G.destroy=K}function we(G){if(G)throw G}}));var Er=v(((G,K)=>{var je=1e3,ze=je*60,We=ze*60,Xe=We*24,rt=Xe*7,at=Xe*365.25;K.exports=function(G,K){K=K||{};var je=typeof G;if(je==="string"&&G.length>0)return Wt(G);if(je==="number"&&isFinite(G))return K.long?Yt(G):Gt(G);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(G))};function Wt(G){if(G=String(G),!(G.length>100)){var K=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(G);if(K){var ft=parseFloat(K[1]),mt=(K[2]||"ms").toLowerCase();switch(mt){case"years":case"year":case"yrs":case"yr":case"y":return ft*at;case"weeks":case"week":case"w":return ft*rt;case"days":case"day":case"d":return ft*Xe;case"hours":case"hour":case"hrs":case"hr":case"h":return ft*We;case"minutes":case"minute":case"mins":case"min":case"m":return ft*ze;case"seconds":case"second":case"secs":case"sec":case"s":return ft*je;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return ft;default:return}}}}function Gt(G){var K=Math.abs(G);return K>=Xe?Math.round(G/Xe)+"d":K>=We?Math.round(G/We)+"h":K>=ze?Math.round(G/ze)+"m":K>=je?Math.round(G/je)+"s":G+"ms"}function Yt(G){var K=Math.abs(G);return K>=Xe?be(G,K,Xe,"day"):K>=We?be(G,K,We,"hour"):K>=ze?be(G,K,ze,"minute"):K>=je?be(G,K,je,"second"):G+" ms"}function be(G,K,je,ze){var We=K>=je*1.5;return Math.round(G/je)+" "+ze+(We?"s":"")}}));var Rr=v(((G,K)=>{function jt(G){t.debug=t,t.default=t,t.coerce=u,t.disable=o,t.enable=i,t.enabled=f,t.humanize=Er(),t.destroy=l,Object.keys(G).forEach((K=>{t[K]=G[K]})),t.names=[],t.skips=[],t.formatters={};function r(G){let K=0;for(let je=0;je<G.length;je++)K=(K<<5)-K+G.charCodeAt(je),K|=0;return t.colors[Math.abs(K)%t.colors.length]}t.selectColor=r;function t(G){let K,je=null,ze,We;function p(...G){if(!p.enabled)return;let je=p,ze=Number(new Date),We=ze-(K||ze);je.diff=We,je.prev=K,je.curr=ze,K=ze,G[0]=t.coerce(G[0]),typeof G[0]!="string"&&G.unshift("%O");let Xe=0;G[0]=G[0].replace(/%([a-zA-Z%])/g,((K,ze)=>{if(K==="%%")return"%";Xe++;let We=t.formatters[ze];if(typeof We=="function"){let ze=G[Xe];K=We.call(je,ze),G.splice(Xe,1),Xe--}return K})),t.formatArgs.call(je,G),(je.log||t.log).apply(je,G)}return p.namespace=G,p.useColors=t.useColors(),p.color=t.selectColor(G),p.extend=n,p.destroy=t.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>je!==null?je:(ze!==t.namespaces&&(ze=t.namespaces,We=t.enabled(G)),We),set:G=>{je=G}}),typeof t.init=="function"&&t.init(p),p}function n(G,K){let je=t(this.namespace+(typeof K=="undefined"?":":K)+G);return je.log=this.log,je}function i(G){t.save(G),t.namespaces=G,t.names=[],t.skips=[];let K=(typeof G=="string"?G:"").trim().replace(" ",",").split(",").filter(Boolean);for(let G of K)G[0]==="-"?t.skips.push(G.slice(1)):t.names.push(G)}function s(G,K){let je=0,ze=0,We=-1,Xe=0;for(;je<G.length;)if(ze<K.length&&(K[ze]===G[je]||K[ze]==="*"))K[ze]==="*"?(We=ze,Xe=je,ze++):(je++,ze++);else if(We!==-1)ze=We+1,Xe++,je=Xe;else return!1;for(;ze<K.length&&K[ze]==="*";)ze++;return ze===K.length}function o(){let G=[...t.names,...t.skips.map((G=>"-"+G))].join(",");return t.enable(""),G}function f(G){for(let K of t.skips)if(s(G,K))return!1;for(let K of t.names)if(s(G,K))return!0;return!1}function u(G){return G instanceof Error?G.stack||G.message:G}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}K.exports=jt}));var jr=v(((G,K)=>{G.formatArgs=Kt;G.save=Vt;G.load=Xt;G.useColors=Ht;G.storage=$t();G.destroy=(()=>{let G=!1;return()=>{G||(G=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();G.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Ht(){if(typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let G;return typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&(G=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(G[1],10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Kt(G){if(G[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+G[0]+(this.useColors?"%c ":" ")+"+"+K.exports.humanize(this.diff),!this.useColors)return;let je="color: "+this.color;G.splice(1,0,je,"color: inherit");let ze=0,We=0;G[0].replace(/%[a-zA-Z%]/g,(G=>{G!=="%%"&&(ze++,G==="%c"&&(We=ze))})),G.splice(We,0,je)}G.log=console.debug||console.log||(()=>{});function Vt(K){try{K?G.storage.setItem("debug",K):G.storage.removeItem("debug")}catch{}}function Xt(){let K;try{K=G.storage.getItem("debug")}catch{}return!K&&typeof process!="undefined"&&"env"in process&&(K=process.env.DEBUG),K}function $t(){try{return localStorage}catch{}}K.exports=Rr()(G);var{formatters:je}=K.exports;je.j=function(G){try{return JSON.stringify(G)}catch(G){return"[UnexpectedJSONParseError]: "+G.message}}}));var zr=v(((G,K)=>{"use strict";K.exports=(G,K=process.argv)=>{let je=G.startsWith("-")?"":G.length===1?"-":"--",ze=K.indexOf(je+G),We=K.indexOf("--");return ze!==-1&&(We===-1||ze<We)}}));var fi=v(((G,K)=>{"use strict";var ze=je(70857),We=je(52018),Xe=zr(),{env:rt}=process,at;Xe("no-color")||Xe("no-colors")||Xe("color=false")||Xe("color=never")?at=0:(Xe("color")||Xe("colors")||Xe("color=true")||Xe("color=always"))&&(at=1);function kt(){if("FORCE_COLOR"in rt)return rt.FORCE_COLOR==="true"?1:rt.FORCE_COLOR==="false"?0:rt.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(rt.FORCE_COLOR,10),3)}function en(G){return G===0?!1:{level:G,hasBasic:!0,has256:G>=2,has16m:G>=3}}function rn(G,{streamIsTTY:K,sniffFlags:je=!0}={}){let We=kt();We!==void 0&&(at=We);let ft=je?at:We;if(ft===0)return 0;if(je){if(Xe("color=16m")||Xe("color=full")||Xe("color=truecolor"))return 3;if(Xe("color=256"))return 2}if(G&&!K&&ft===void 0)return 0;let mt=ft||0;if(rt.TERM==="dumb")return mt;if(process.platform==="win32"){let G=ze.release().split(".");return Number(G[0])>=10&&Number(G[2])>=10586?Number(G[2])>=14931?3:2:1}if("CI"in rt)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some((G=>G in rt))||rt.CI_NAME==="codeship"?1:mt;if("TEAMCITY_VERSION"in rt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(rt.TEAMCITY_VERSION)?1:0;if(rt.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in rt){let G=Number.parseInt((rt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(rt.TERM_PROGRAM){case"iTerm.app":return G>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(rt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(rt.TERM)||"COLORTERM"in rt?1:mt}function Je(G,K={}){let je=rn(G,{streamIsTTY:G&&G.isTTY,...K});return en(je)}K.exports={supportsColor:Je,stdout:Je({isTTY:We.isatty(1)}),stderr:Je({isTTY:We.isatty(2)})}}));var mi=v(((G,K)=>{var ze=je(52018),We=je(39023);G.init=cn;G.log=fn;G.formatArgs=on;G.save=an;G.load=un;G.useColors=nn;G.destroy=We.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");G.colors=[6,2,3,4,5,1];try{let K=fi();K&&(K.stderr||K).level>=2&&(G.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}G.inspectOpts=Object.keys(process.env).filter((G=>/^debug_/i.test(G))).reduce(((G,K)=>{let je=K.substring(6).toLowerCase().replace(/_([a-z])/g,((G,K)=>K.toUpperCase())),ze=process.env[K];return/^(yes|on|true|enabled)$/i.test(ze)?ze=!0:/^(no|off|false|disabled)$/i.test(ze)?ze=!1:ze==="null"?ze=null:ze=Number(ze),G[je]=ze,G}),{});function nn(){return"colors"in G.inspectOpts?!!G.inspectOpts.colors:ze.isatty(process.stderr.fd)}function on(G){let{namespace:je,useColors:ze}=this;if(ze){let ze=this.color,We="[3"+(ze<8?ze:"8;5;"+ze),Xe=` ${We};1m${je} `;G[0]=Xe+G[0].split(`\n`).join(`\n`+Xe),G.push(We+"m+"+K.exports.humanize(this.diff)+"")}else G[0]=sn()+je+" "+G[0]}function sn(){return G.inspectOpts.hideDate?"":(new Date).toISOString()+" "}function fn(...K){return process.stderr.write(We.formatWithOptions(G.inspectOpts,...K)+`\n`)}function an(G){G?process.env.DEBUG=G:delete process.env.DEBUG}function un(){return process.env.DEBUG}function cn(K){K.inspectOpts={};let je=Object.keys(G.inspectOpts);for(let ze=0;ze<je.length;ze++)K.inspectOpts[je[ze]]=G.inspectOpts[je[ze]]}K.exports=Rr()(G);var{formatters:Xe}=K.exports;Xe.o=function(G){return this.inspectOpts.colors=this.useColors,We.inspect(G,this.inspectOpts).split(`\n`).map((G=>G.trim())).join(" ")};Xe.O=function(G){return this.inspectOpts.colors=this.useColors,We.inspect(G,this.inspectOpts)}}));var bi=v(((G,K)=>{typeof process=="undefined"||process.type==="renderer"||process.browser===!0||process.__nwjs?K.exports=jr():K.exports=mi()}));var Si=v(((G,K)=>{K.exports=Qr;function Qr(G,K){if(G&&K)return Qr(G)(K);if(typeof G!="function")throw new TypeError("need wrapper function");return Object.keys(G).forEach((function(K){t[K]=G[K]})),t;function t(){for(var K=new Array(arguments.length),je=0;je<K.length;je++)K[je]=arguments[je];var ze=G.apply(this,K),We=K[K.length-1];return typeof ze=="function"&&ze!==We&&Object.keys(We).forEach((function(G){ze[G]=We[G]})),ze}}}));var Ei=v(((G,K)=>{var je=Si();K.exports=je(Oe);K.exports.strict=je(tt);Oe.proto=Oe((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return Oe(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return tt(this)},configurable:!0})}));function Oe(G){var r=function(){return r.called?r.value:(r.called=!0,r.value=G.apply(this,arguments))};return r.called=!1,r}function tt(G){var r=function(){if(r.called)throw new Error(r.onceError);return r.called=!0,r.value=G.apply(this,arguments)},K=G.name||"Function wrapped with `once`";return r.onceError=K+" shouldn't be called more than once",r.called=!1,r}}));var ki=v(((G,K)=>{var je=Ei(),ln=function(){},hn=function(G){return G.setHeader&&typeof G.abort=="function"},mn=function(G){return G.stdio&&Array.isArray(G.stdio)&&G.stdio.length===3},nt=function(G,K,ze){if(typeof K=="function")return nt(G,null,K);K||(K={}),ze=je(ze||ln);var We=G._writableState,Xe=G._readableState,rt=K.readable||K.readable!==!1&&G.readable,at=K.writable||K.writable!==!1&&G.writable,ft=!1,u=function(){G.writable||l()},l=function(){at=!1,rt||ze.call(G)},a=function(){rt=!1,at||ze.call(G)},c=function(K){ze.call(G,K?new Error("exited with error code: "+K):null)},d=function(K){ze.call(G,K)},h=function(){process.nextTick(E)},E=function(){if(!ft){if(rt&&!(Xe&&Xe.ended&&!Xe.destroyed))return ze.call(G,new Error("premature close"));if(at&&!(We&&We.ended&&!We.destroyed))return ze.call(G,new Error("premature close"))}},p=function(){G.req.on("finish",l)};return hn(G)?(G.on("complete",l),G.on("abort",h),G.req?p():G.on("request",p)):at&&!We&&(G.on("end",u),G.on("close",u)),mn(G)&&G.on("exit",c),G.on("end",a),G.on("finish",l),K.error!==!1&&G.on("error",d),G.on("close",h),function(){ft=!0,G.removeListener("complete",l),G.removeListener("abort",h),G.removeListener("request",p),G.req&&G.req.removeListener("finish",l),G.removeListener("end",u),G.removeListener("close",u),G.removeListener("finish",l),G.removeListener("exit",c),G.removeListener("end",a),G.removeListener("error",d),G.removeListener("close",h)}};K.exports=nt}));var Ci=v(((G,K)=>{var ze=Ei(),We=ki(),Xe;try{Xe=je(79896)}catch{}var te=function(){},rt=/^v?\.0/.test(process.version),_e=function(G){return typeof G=="function"},vn=function(G){return!rt||!Xe?!1:(G instanceof(Xe.ReadStream||te)||G instanceof(Xe.WriteStream||te))&&_e(G.close)},wn=function(G){return G.setHeader&&_e(G.abort)},yn=function(G,K,je,Xe){Xe=ze(Xe);var rt=!1;G.on("close",(function(){rt=!0})),We(G,{readable:K,writable:je},(function(G){if(G)return Xe(G);rt=!0,Xe()}));var at=!1;return function(K){if(!rt&&!at){if(at=!0,vn(G))return G.close(te);if(wn(G))return G.abort();if(_e(G.destroy))return G.destroy();Xe(K||new Error("stream was destroyed"))}}},st=function(G){G()},gn=function(G,K){return G.pipe(K)},Cn=function(){var G=Array.prototype.slice.call(arguments),K=_e(G[G.length-1]||te)&&G.pop()||te;if(Array.isArray(G[0])&&(G=G[0]),G.length<2)throw new Error("pump requires two streams per minimum");var je,ze=G.map((function(We,Xe){var rt=Xe<G.length-1,at=Xe>0;return yn(We,rt,at,(function(G){je||(je=G),G&&ze.forEach(st),!rt&&(ze.forEach(st),K(je))}))}));return G.reduce(gn)};K.exports=Cn}));var Ti=v(((G,K)=>{"use strict";var{PassThrough:ze}=je(2203);K.exports=G=>{G={...G};let{array:K}=G,{encoding:je}=G,We=je==="buffer",Xe=!1;K?Xe=!(je||We):je=je||"utf8",We&&(je=null);let rt=new ze({objectMode:Xe});je&&rt.setEncoding(je);let at=0,ft=[];return rt.on("data",(G=>{ft.push(G),Xe?at=ft.length:at+=G.length})),rt.getBufferedValue=()=>K?ft:We?Buffer.concat(ft,at):ft.join(""),rt.getBufferedLength=()=>at,rt}}));var Pi=v(((G,K)=>{"use strict";var{constants:ze}=je(20181),We=Ci(),Xe=Ti(),rt=class extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};async function De(G,K){if(!G)return Promise.reject(new Error("Expected a stream"));K={maxBuffer:1/0,...K};let{maxBuffer:je}=K,at;return await new Promise(((ft,mt)=>{let o=G=>{G&&at.getBufferedLength()<=ze.MAX_LENGTH&&(G.bufferedData=at.getBufferedValue()),mt(G)};at=We(G,Xe(K),(G=>{if(G){o(G);return}ft()})),at.on("data",(()=>{at.getBufferedLength()>je&&o(new rt)}))})),at.getBufferedValue()}K.exports=De;K.exports.default=De;K.exports.buffer=(G,K)=>De(G,{...K,encoding:"buffer"});K.exports.array=(G,K)=>De(G,{...K,array:!0});K.exports.MaxBufferError=rt}));var Ii=v(((G,K)=>{"use strict";var ze=bi()("extract-zip"),{createWriteStream:We,promises:Xe}=je(79896),rt=Pi(),at=je(16928),{promisify:ft}=je(39023),mt=je(2203),vt=lr(),yt=ft(vt.open),wt=ft(mt.pipeline),Er=class{constructor(G,K){this.zipPath=G,this.opts=K}async extract(){return ze("opening",this.zipPath,"with opts",this.opts),this.zipfile=await yt(this.zipPath,{lazyEntries:!0}),this.canceled=!1,new Promise(((G,K)=>{this.zipfile.on("error",(G=>{this.canceled=!0,K(G)})),this.zipfile.readEntry(),this.zipfile.on("close",(()=>{this.canceled||(ze("zip extraction complete"),G())})),this.zipfile.on("entry",(async G=>{if(this.canceled){ze("skipping entry",G.fileName,{cancelled:this.canceled});return}if(ze("zipfile entry",G.fileName),G.fileName.startsWith("__MACOSX/")){this.zipfile.readEntry();return}let je=at.dirname(at.join(this.opts.dir,G.fileName));try{await Xe.mkdir(je,{recursive:!0});let K=await Xe.realpath(je);if(at.relative(this.opts.dir,K).split(at.sep).includes(".."))throw new Error(`Out of bound path "${K}" found while processing file ${G.fileName}`);await this.extractEntry(G),ze("finished processing",G.fileName),this.zipfile.readEntry()}catch(G){this.canceled=!0,this.zipfile.close(),K(G)}}))}))}async extractEntry(G){if(this.canceled){ze("skipping entry extraction",G.fileName,{cancelled:this.canceled});return}this.opts.onEntry&&this.opts.onEntry(G,this.zipfile);let K=at.join(this.opts.dir,G.fileName),je=G.externalFileAttributes>>16&65535,mt=61440,vt=16384,yt=(je&mt)===40960,lr=(je&mt)===vt;!lr&&G.fileName.endsWith("/")&&(lr=!0);let Er=G.versionMadeBy>>8;lr||(lr=Er===0&&G.externalFileAttributes===16),ze("extracting entry",{filename:G.fileName,isDir:lr,isSymlink:yt});let Rr=this.getExtractedMode(je,lr)&511,jr=lr?K:at.dirname(K),zr={recursive:!0};if(lr&&(zr.mode=Rr),ze("mkdir",{dir:jr,...zr}),await Xe.mkdir(jr,zr),lr)return;ze("opening read stream",K);let fi=await ft(this.zipfile.openReadStream.bind(this.zipfile))(G);if(yt){let G=await rt(fi);ze("creating symlink",G,K),await Xe.symlink(G,K)}else await wt(fi,We(K,{mode:Rr}))}getExtractedMode(G,K){let je=G;return je===0&&(K?(this.opts.defaultDirMode&&(je=parseInt(this.opts.defaultDirMode,10)),je||(je=493)):(this.opts.defaultFileMode&&(je=parseInt(this.opts.defaultFileMode,10)),je||(je=420))),je}};K.exports=async function(G,K){if(ze("creating target directory",K.dir),!at.isAbsolute(K.dir))throw new Error("Target directory is expected to be absolute");return await Xe.mkdir(K.dir,{recursive:!0}),K.dir=await Xe.realpath(K.dir),new Er(G,K).extract()}}));var Ri={};Ct(Ri,{extract:()=>ps,yauzl:()=>qi,yazl:()=>Mi});G.exports=bt(Ri);var Mi=sr(vt()),qi=sr(lr()),Xi=Ii(),ps=Xi;0&&0},47885:(G,K,je)=>{G.exports=je(92383)},34881:(G,K,je)=>{"use strict";const ze=je(51940);G.exports=(G="")=>{const K=G.match(ze);if(!K){return null}const[je,We]=K[0].replace(/#! ?/,"").split(" ");const Xe=je.split("/").pop();if(Xe==="env"){return We}return We?`${Xe} ${We}`:Xe}},51940:G=>{"use strict";G.exports=/^#!(.*)/},31192:(G,K,je)=>{const ze=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys";const We=je(16928);const Xe=ze?";":":";const rt=je(97105);const getNotFoundError=G=>Object.assign(new Error(`not found: ${G}`),{code:"ENOENT"});const getPathInfo=(G,K)=>{const je=K.colon||Xe;const We=G.match(/\//)||ze&&G.match(/\\/)?[""]:[...ze?[process.cwd()]:[],...(K.path||process.env.PATH||"").split(je)];const rt=ze?K.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"";const at=ze?rt.split(je):[""];if(ze){if(G.indexOf(".")!==-1&&at[0]!=="")at.unshift("")}return{pathEnv:We,pathExt:at,pathExtExe:rt}};const which=(G,K,je)=>{if(typeof K==="function"){je=K;K={}}if(!K)K={};const{pathEnv:ze,pathExt:Xe,pathExtExe:at}=getPathInfo(G,K);const ft=[];const step=je=>new Promise(((Xe,rt)=>{if(je===ze.length)return K.all&&ft.length?Xe(ft):rt(getNotFoundError(G));const at=ze[je];const mt=/^".*"$/.test(at)?at.slice(1,-1):at;const vt=We.join(mt,G);const yt=!mt&&/^\.[\\\/]/.test(G)?G.slice(0,2)+vt:vt;Xe(subStep(yt,je,0))}));const subStep=(G,je,ze)=>new Promise(((We,mt)=>{if(ze===Xe.length)return We(step(je+1));const vt=Xe[ze];rt(G+vt,{pathExt:at},((Xe,rt)=>{if(!Xe&&rt){if(K.all)ft.push(G+vt);else return We(G+vt)}return We(subStep(G,je,ze+1))}))}));return je?step(0).then((G=>je(null,G)),je):step(0)};const whichSync=(G,K)=>{K=K||{};const{pathEnv:je,pathExt:ze,pathExtExe:Xe}=getPathInfo(G,K);const at=[];for(let ft=0;ft<je.length;ft++){const mt=je[ft];const vt=/^".*"$/.test(mt)?mt.slice(1,-1):mt;const yt=We.join(vt,G);const wt=!vt&&/^\.[\\\/]/.test(G)?G.slice(0,2)+yt:yt;for(let G=0;G<ze.length;G++){const je=wt+ze[G];try{const G=rt.sync(je,{pathExt:Xe});if(G){if(K.all)at.push(je);else return je}}catch(G){}}}if(K.all&&at.length)return at;if(K.nothrow)return null;throw getNotFoundError(G)};G.exports=which;which.sync=whichSync},35440:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.ArchitectAgent=void 0;const ze=je(4843);const We=je(18984);const Xe=je(45037);const rt=je(21393);class ArchitectAgent{deps;constructor(G={}){this.deps=G}async run(G){let K;if(G.rawDocs?.length&&this.deps.llmIrGenerator){K=await this.deps.llmIrGenerator.generate(G.rawDocs.join("\n\n"))}else{K=(0,Xe.buildIRFromDiscovery)(G)}const je=(0,rt.planShards)(K.tools.map((G=>({name:G.name,domain:"default"}))),40);const at=(0,We.generateRuntimeConfig)(je);const ft=(0,ze.checkTokenBudget)(JSON.stringify(K.tools),8e3);return{ir:K,shards:je,config:at,budget:ft}}}K.ArchitectAgent=ArchitectAgent},18984:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.generateRuntimeConfig=generateRuntimeConfig;function generateRuntimeConfig(G){const K=['version: "3.9"',"services:"];for(const je of G){K.push(` ${je.id}:`);K.push(" image: mcp-claw/mcp-server:latest");K.push(` ports: ["${je.port}:${je.port}"]`)}const je=["server {"," listen 443 ssl;"];for(const K of G){je.push(` location /mcp/${K.id} {`);je.push(` proxy_pass http://127.0.0.1:${K.port};`);je.push(" }")}je.push("}");return{compose:`${K.join("\n")}\n`,nginx:`${je.join("\n")}\n`}}},45037:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.buildIRFromDiscovery=buildIRFromDiscovery;function toToolName(G){const K=G.replace(/^\/+/,"").replace(/[^a-zA-Z0-9]+/g,"_");return K||"root"}function toTool(G){const K=new URL(G.url);return{name:toToolName(K.pathname),description:`GET ${K.pathname}`,method:"GET",path:K.pathname||"/",needsConfirmation:false,isAsync:false,params:[]}}function buildIRFromDiscovery(G){const K=G.endpoints[0]?.url??"https://example.com";const je=new URL(K).origin;return{system:{code:"target-system",baseUrl:je,authType:"none"},tools:G.endpoints.map(toTool)}}},27275:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.LlmIrGenerator=void 0;const je={system:{code:"unknown",baseUrl:"https://api.example.com",authType:"none"},tools:[]};const ze=new Set(["GET","POST","PUT","DELETE"]);const We=new Set(["none","bearer","api-key"]);function stripMarkdownFences(G){const K=G.trim();const je=K.match(/^```[a-zA-Z0-9_-]*\s*([\s\S]*?)\s*```$/);return je?.[1]?.trim()??K}function normalizeMethod(G){const K=typeof G==="string"?G.toUpperCase():"";if(ze.has(K)){return K}return"GET"}function normalizeAuthType(G){const K=typeof G==="string"?G.toLowerCase():"";if(We.has(K)){return K}return"none"}function toSnakeCase(G){const K=G.trim().replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toLowerCase();return K||"generated_tool"}function normalizeParams(G){if(!Array.isArray(G)){return[]}return G.filter((G=>Boolean(G)&&typeof G==="object")).map((G=>({name:typeof G.name==="string"?G.name:"",type:typeof G.type==="string"?G.type:"string",required:G.required===true,description:typeof G.description==="string"?G.description:undefined}))).filter((G=>G.name.length>0))}function normalizeTools(G){if(!Array.isArray(G)){return[]}const K=[];for(const je of G){if(!je||typeof je!=="object"){continue}const G=je;const ze=normalizeMethod(G.method);const We=typeof G.path==="string"&&G.path.startsWith("/")?G.path:"/";const Xe=toSnakeCase(typeof G.name==="string"?G.name:We);const rt=normalizeParams(G.params);K.push({name:Xe,description:typeof G.description==="string"&&G.description.trim().length>0?G.description.trim():`${ze} ${We}`,method:ze,path:We,params:rt,needsConfirmation:false,isAsync:false})}return K}function normalizeIr(G){if(!G||typeof G!=="object"){return null}const K=G;const ze=typeof K.system?.code==="string"?K.system.code.trim():"";const We=typeof K.system?.baseUrl==="string"&&K.system.baseUrl.trim().length>0?K.system.baseUrl.trim():je.system.baseUrl;return{system:{code:ze||je.system.code,baseUrl:We,authType:normalizeAuthType(K.system?.authType)},tools:normalizeTools(K.tools)}}class LlmIrGenerator{llm;constructor(G){this.llm=G}async generate(G){const K=G.slice(0,8e4);const ze=["You are an API analyst that converts API documentation into MCP IR JSON.","Return ONLY valid JSON without markdown fences.","Use this exact schema:","{",' "system": {',' "code": "string",',' "baseUrl": "string",',' "authType": "none|bearer|api-key"'," },",' "tools": ['," {",' "name": "snake_case",',' "description": "string",',' "method": "GET|POST|PUT|DELETE",',' "path": "/path",',' "params": ['," {",' "name": "query",',' "type": "string",',' "required": true,',' "description": "Search query text"'," }"," ],",' "needsConfirmation": false,',' "isAsync": false'," }"," ]","}","","Source documentation:",K].join("\n");const We=await this.llm.complete(ze);const Xe=stripMarkdownFences(We);try{const G=JSON.parse(Xe);return normalizeIr(G)??je}catch{throw new Error(`LLM returned invalid JSON. First 200 chars: ${Xe.slice(0,200)}`)}}}K.LlmIrGenerator=LlmIrGenerator},21393:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.planShards=planShards;function planShards(G,K=40,je=8081){const ze=[];for(const We of G){let G=ze.find((G=>G.tools.length<K));if(!G){G={id:`shard-${ze.length+1}`,port:je+ze.length,tools:[]};ze.push(G)}G.tools.push(We.name)}return ze}},78536:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.BuilderAgent=void 0;const ze=je(4843);const We=je(44562);function isIr(G){if(!G||typeof G!=="object"){return false}const K=G;return typeof K.system?.code==="string"&&typeof K.system?.baseUrl==="string"&&typeof K.system?.authType==="string"&&Array.isArray(K.tools)}function parseIrPlanDoc(G){const K=G.trim();if(!K){return null}try{const G=JSON.parse(K);return isIr(G)?G:null}catch{return null}}function buildTemplateArtifact(G){const K=G.system.code||"package";return{archivePath:`/tmp/${K}.tgz`,manifestPath:`/tmp/${K}-manifest.json`,sbomPath:`/tmp/${K}-sbom.json`,signaturePath:`/tmp/${K}-signature.sig`}}class BuilderAgent{deps;constructor(G){this.deps=G}async run(G){const K=parseIrPlanDoc(G.planDoc);const je=K?{...buildTemplateArtifact(K),files:(0,ze.renderFromIR)(K)}:await this.deps.adapter.run(G.planDoc);const Xe=this.deps.writer??{write:We.writeGeneratedFiles};const rt=await Xe.write(G.root,je.files);await this.deps.installer.install(G.root);const{files:at,...ft}=je;return{artifact:ft,writtenFiles:rt}}}K.BuilderAgent=BuilderAgent},20052:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.CoreCodegenAdapter=void 0;class CoreCodegenAdapter{core;constructor(G){this.core=G}async run(G){const K=await this.core.generate({kind:"markdown",content:G});const je=K.files;return{...K,files:je??[]}}}K.CoreCodegenAdapter=CoreCodegenAdapter},65402:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.DependencyInstaller=void 0;const ze=je(31421);const We=je(57975);const Xe=(0,We.promisify)(ze.exec);async function defaultExec(G,K,je){return Xe(`${G} ${K.join(" ")}`,{cwd:je?.cwd,timeout:je?.timeout,windowsHide:true})}const rt=["pnpm","yarn","npm"];async function detectPm(G){for(const K of rt){try{await G(K,["--version"],{timeout:5e3});return K}catch{}}return"npm"}class DependencyInstaller{exec;constructor(G=defaultExec){this.exec=G}async install(G){const K=await detectPm(this.exec);await this.exec(K,["install"],{cwd:G,timeout:12e4})}}K.DependencyInstaller=DependencyInstaller},44562:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.writeGeneratedFiles=writeGeneratedFiles;const We=je(73024);const Xe=ze(je(76760));async function writeGeneratedFiles(G,K){const je=[];for(const ze of K){const K=Xe.default.resolve(G,ze.path);await We.promises.mkdir(Xe.default.dirname(K),{recursive:true});await We.promises.writeFile(K,ze.content,"utf8");je.push(K)}return je}},51792:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.ExplorerAgent=void 0;const ze=je(73024);const We=je(76760);const Xe=je(75364);const rt=je(65737);const at=je(20336);const ft=["*.md","*.txt","*.pdf","*.json","*.yaml","*.yml","*.ts","*.js","*.mjs","*.cjs","*.xml","*.toml","*.env","openapi*.json","openapi*.yaml","openapi*.yml","docker-compose*.yml"];function readTextFile(G){try{return(0,ze.readFileSync)(G,"utf8")}catch{return null}}class ExplorerAgent{deps;constructor(G={fsTool:new rt.FsTool,dockerTool:new Xe.DockerInspectTool,httpTool:new at.HttpFetchTool}){this.deps=G}async run(G){const[K,je]=await Promise.all([this.deps.fsTool.glob(G.root,ft),this.deps.dockerTool.listContainers()]);const ze=[];const Xe=[];const rt=[];for(const K of G.urls){if(this.deps.browserTool){const G=await this.deps.browserTool.fetch(K);Xe.push(G);ze.push({url:G.url,status:200,body:G.html});if(G.text.trim().length>0){rt.push(G.text)}continue}const G=await this.deps.httpTool.fetch(K);ze.push(G);if(G.body.trim().length>0){rt.push(G.body)}}for(const G of K){const K=(0,We.extname)(G).toLowerCase();if(K===".pdf"){if(this.deps.pdfTool){try{const K=await this.deps.pdfTool.extractFromFile(G);if(K.text.trim().length>0){rt.push(K.text)}}catch{}}continue}const je=readTextFile(G);if(je&&je.trim().length>0){rt.push(je)}}return{files:[...K].sort(),containers:[...je].sort(((G,K)=>G.id.localeCompare(K.id))),endpoints:[...ze].sort(((G,K)=>G.url.localeCompare(K.url))),rawDocs:rt,browserPages:[...Xe].sort(((G,K)=>G.url.localeCompare(K.url)))}}}K.ExplorerAgent=ExplorerAgent},78519:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.extractCoverage=extractCoverage;function readPercent(G,K){const je=G.match(new RegExp(`${K}\\s*:\\s*(\\d+(?:\\.\\d+)?)%`,"i"));return Number(je?.[1]??0)}function extractCoverage(G){return{lines:readPercent(G,"Lines"),statements:readPercent(G,"Statements"),functions:readPercent(G,"Functions"),branches:readPercent(G,"Branches")}}},19562:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.IntegrationTester=void 0;K.frameMcpMessage=frameMcpMessage;K.parseMcpMessages=parseMcpMessages;const ze=je(31421);const We=je(57975);const Xe=(0,We.promisify)(ze.exec);const rt=1500;const at=1e4;const ft=1e4;const mt=15e3;const vt=1e4;const yt=25;function sleep(G){return new Promise((K=>{setTimeout(K,G)}))}function errorMessage(G){return G instanceof Error?G.message:String(G)}function summarizePayload(G,K=300){let je;if(typeof G==="string"){je=G}else{try{je=JSON.stringify(G)}catch{je=String(G)}}if(je.length<=K){return je}return`${je.slice(0,K)}...`}function isAuthRelated(G){const K=G.toLowerCase();return/\b401\b/.test(K)||/\b403\b/.test(K)||K.includes("unauthorized")||K.includes("forbidden")||K.includes("api.key")||K.includes("api_key")||K.includes("api key")}function asRecord(G){if(G&&typeof G==="object"&&!Array.isArray(G)){return G}return{}}function sampleValue(G,K){const je=Array.isArray(K.enum)?K.enum:[];if(je.length>0){return je[0]}const ze=G.toLowerCase();const We=typeof K.type==="string"?K.type.toLowerCase():"string";if(ze.includes("url")){return"https://example.com"}if(ze==="q"||ze.includes("query")||ze.includes("keyword")||ze.includes("search")){return"test"}if(ze.includes("email")){return"test@example.com"}if(ze.includes("id")){return"1"}switch(We){case"integer":case"number":return 1;case"boolean":return true;case"array":return[];case"object":return{};default:return"test"}}function buildToolArgs(G){const K=asRecord(G.inputSchema);const je=asRecord(K.properties);const ze=Array.isArray(K.required)?K.required.filter((G=>typeof G==="string")):[];const We={};const Xe=new Set(ze);for(const[G,K]of Object.entries(je)){if(!Xe.has(G)){continue}We[G]=sampleValue(G,asRecord(K))}if(Object.keys(We).length===0){return{}}return We}function extractToolCallDetail(G){const K=G.error;if(K){return summarizePayload(K)}const je=G.result;if(typeof je==="string"){return summarizePayload(je)}if(je&&typeof je==="object"){const G=je;const K=G.content;if(Array.isArray(K)){for(const G of K){if(G&&typeof G==="object"){const K=G.text;if(typeof K==="string"&&K.trim().length>0){return summarizePayload(K)}}}}return summarizePayload(G)}return summarizePayload(je)}function isToolCallSuccessful(G){if(G.error){return false}const K=G.result;if(K&&typeof K==="object"&&!Array.isArray(K)){const G=K;if(G.isError===true){return false}}return true}function frameMcpMessage(G){const K=Buffer.from(JSON.stringify(G),"utf8");const je=Buffer.from(`Content-Length: ${String(K.length)}\r\n\r\n`,"utf8");return Buffer.concat([je,K])}function parseMcpMessages(G){const K=[];let je=Buffer.from(G);const pushJson=G=>{const je=G.trim();if(!je){return}try{const G=JSON.parse(je);if(G&&typeof G==="object"&&!Array.isArray(G)){K.push(G)}}catch{}};while(je.length>0){const G=je.subarray(0,Math.min(je.length,32)).toString("utf8").toLowerCase();const K=G.startsWith("content-length:");if(K){const G=je.indexOf("\r\n\r\n");if(G===-1){break}const K=je.subarray(0,G).toString("utf8");const ze=/content-length:\s*(\d+)/i.exec(K);if(!ze){const G=je.indexOf("\n");if(G===-1){break}je=je.subarray(G+1);continue}const We=Number(ze[1]);if(!Number.isFinite(We)||We<0){const G=je.indexOf("\n");if(G===-1){break}je=je.subarray(G+1);continue}const Xe=G+4+We;if(je.length<Xe){break}const rt=je.subarray(G+4,Xe).toString("utf8");pushJson(rt);je=je.subarray(Xe);continue}const ze=je.indexOf("\n");if(ze===-1){break}const We=je.subarray(0,ze).toString("utf8").replace(/\r$/,"");pushJson(We);je=je.subarray(ze+1)}return{messages:K,rest:je}}class IntegrationTester{exec;spawn;startupWaitMs;initializeTimeoutMs;toolsListTimeoutMs;connectionTimeoutMs;authProbeTimeoutMs;pollIntervalMs;constructor(G={}){this.exec=G.exec??((G,K)=>Xe(G,{windowsHide:true,...K}));this.spawn=G.spawn??ze.spawn;this.startupWaitMs=G.startupWaitMs??rt;this.initializeTimeoutMs=G.initializeTimeoutMs??at;this.toolsListTimeoutMs=G.toolsListTimeoutMs??ft;this.connectionTimeoutMs=G.connectionTimeoutMs??mt;this.authProbeTimeoutMs=G.authProbeTimeoutMs??vt;this.pollIntervalMs=G.pollIntervalMs??yt}async run(G){try{await this.exec("pnpm install",{cwd:G.dir,timeout:12e4});await this.exec("pnpm run build",{cwd:G.dir,timeout:12e4})}catch(G){return{passed:false,toolsFound:0,toolsCalled:[],error:`Build failed: ${errorMessage(G)}`}}const K=[];const je=[];let ze;let We=false;let Xe=null;let rt=null;let at=null;try{const ft={...process.env,...G.authEnv,MCP_BASE_URL:G.baseUrl};const pushLog=(G,K)=>{const je=K.trim();if(!je){return}G.push(je);if(G.length>40){G.splice(0,G.length-40)}};const diagnostics=()=>{const G=K.slice(-20).join("\n").trim();const ze=je.slice(-20).join("\n").trim();const We=[];if(G){We.push(`stderr:\n${G}`)}if(ze){We.push(`stdout(non-mcp):\n${ze}`)}return We.length>0?`\n${We.join("\n\n")}`:""};const buildExitError=G=>{const K=Xe===null?"null":String(Xe);const je=rt?`, signal ${rt}`:"";return`Server exited (code ${K}${je}) before responding to id=${G}${diagnostics()}`};ze=this.spawn("node",["dist/index.js"],{cwd:G.dir,env:ft,windowsHide:true});ze.on("error",(G=>{at=errorMessage(G)}));ze.on("exit",((G,K)=>{We=true;Xe=G;rt=K}));ze.stderr?.on("data",(G=>{pushLog(K,typeof G==="string"?G:G.toString("utf8"))}));const mt=[];let vt=Buffer.alloc(0);ze.stdout?.on("data",(G=>{const K=typeof G==="string"?Buffer.from(G):G;vt=Buffer.concat([vt,K]);const je=parseMcpMessages(vt);vt=je.rest;mt.push(...je.messages)}));if(this.startupWaitMs>0){await sleep(this.startupWaitMs)}const writeMessage=G=>{if(!ze?.stdin){throw new Error("Server stdin is not available")}if(at){throw new Error(`Server process error: ${at}${diagnostics()}`)}if(We){throw new Error(buildExitError(Number(G.id??-1)))}ze.stdin.write(frameMcpMessage(G))};const waitForResponseById=async(G,K)=>{const je=Date.now();while(Date.now()-je<K){const K=mt.findIndex((K=>K.id===G));if(K>=0){const[G]=mt.splice(K,1);return G}if(at){throw new Error(`Server process error: ${at}${diagnostics()}`)}if(We){throw new Error(buildExitError(G))}await sleep(this.pollIntervalMs)}throw new Error(`Timeout waiting for MCP response id=${G}${diagnostics()}`)};const yt={jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"integration-test",version:"1.0.0"}}};const wt=Math.min(3e3,this.initializeTimeoutMs);const lr=Math.max(this.initializeTimeoutMs-wt,0);writeMessage(yt);try{await waitForResponseById(1,wt)}catch(G){const K=G instanceof Error&&G.message.includes("Timeout waiting for MCP response id=1");if(!K||We||at||lr===0){throw G}writeMessage(yt);await waitForResponseById(1,lr)}writeMessage({jsonrpc:"2.0",method:"notifications/initialized"});writeMessage({jsonrpc:"2.0",id:2,method:"tools/list"});const Er=await waitForResponseById(2,this.toolsListTimeoutMs);const Rr=Er.result;const jr=Rr?.tools?.filter((G=>typeof G?.name==="string")).map((G=>({name:G.name,...typeof G.description==="string"?{description:G.description}:{},...G.inputSchema&&typeof G.inputSchema==="object"?{inputSchema:G.inputSchema}:{}})))??[];if(!Er.result&&Er.error){throw new Error(`tools/list failed: ${JSON.stringify(Er.error)}`)}const zr=[];const fi=[];let mi;let bi;let Si=3;const Ei=jr.some((G=>G.name==="test_connection"));if(Ei){const G=Si++;writeMessage({jsonrpc:"2.0",id:G,method:"tools/call",params:{name:"test_connection",arguments:{}}});zr.push("test_connection");const K=await waitForResponseById(G,this.connectionTimeoutMs);const je=isToolCallSuccessful(K);const ze=extractToolCallDetail(K);mi={ok:je,detail:ze};fi.push({name:"test_connection",ok:je,detail:ze,args:{}})}const ki=jr.find((G=>G.name!=="test_connection"));if(ki){try{const G=Si++;writeMessage({jsonrpc:"2.0",id:G,method:"tools/call",params:{name:ki.name,arguments:{}}});zr.push(ki.name);const K=await waitForResponseById(G,this.authProbeTimeoutMs);const je=K.error;const ze=K.result;const We=summarizePayload(je??ze);bi={authRequired:isAuthRelated(We),...We?{authHint:We}:{},toolName:ki.name}}catch(G){bi={authRequired:false,authHint:summarizePayload(`probe failed: ${errorMessage(G)}`),toolName:ki.name}}}for(const G of jr){if(G.name==="test_connection"){continue}const K=buildToolArgs(G);const je=Si++;writeMessage({jsonrpc:"2.0",id:je,method:"tools/call",params:{name:G.name,arguments:K}});zr.push(G.name);try{const ze=await waitForResponseById(je,this.connectionTimeoutMs);fi.push({name:G.name,ok:isToolCallSuccessful(ze),detail:extractToolCallDetail(ze),args:K})}catch(je){fi.push({name:G.name,ok:false,detail:`call failed: ${errorMessage(je)}`,args:K})}}const Ci=fi.filter((G=>G.name!=="test_connection"));const Ti=jr.length>0&&Ci.length>0&&Ci.every((G=>G.ok));const Pi=Ti&&(mi?mi.ok:true);return{passed:Pi,toolsFound:jr.length,toolsCalled:zr,tools:jr,toolResults:fi,allToolsPassed:Ti,...mi?{connectionTest:mi}:{},...bi?{authProbe:bi}:{},serverLog:[...K,...je].slice(-20).join("\n")}}catch(G){return{passed:false,toolsFound:0,toolsCalled:[],error:errorMessage(G),serverLog:[...K,...je].slice(-20).join("\n")}}finally{ze?.kill()}}}K.IntegrationTester=IntegrationTester},74664:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.TesterSandboxAdapter=void 0;class TesterSandboxAdapter{sandbox;constructor(G){this.sandbox=G}execute(G){return this.sandbox.runTests({files:G,timeoutMs:30*60*1e3})}}K.TesterSandboxAdapter=TesterSandboxAdapter},59159:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.parseTestResult=parseTestResult;function readNumber(G,K){const je=G.match(new RegExp(`(\\d+)\\s+${K}`,"i"));return Number(je?.[1]??0)}function parseTestResult(G){return{passed:readNumber(G,"passed"),failed:readNumber(G,"failed"),total:readNumber(G,"total")}}},60403:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.TestRunner=void 0;const ze=je(31421);const We=je(73024);const Xe=je(76760);const rt=je(57975);const at=(0,rt.promisify)(ze.exec);async function defaultExec(G,K,je){const ze=await at(`${G} ${K.join(" ")}`,{cwd:je?.cwd,timeout:je?.timeout,windowsHide:true});return{stdout:ze.stdout,stderr:ze.stderr}}const ft=["pnpm","yarn","npx"];async function detectPm(G){for(const K of ft){try{await G(K,["--version"],{timeout:5e3});return K}catch{}}return"npx"}function hasTestSetup(G){const K=(0,Xe.join)(G,"package.json");if(!(0,We.existsSync)(K)){return false}try{const G=JSON.parse((0,We.readFileSync)(K,"utf8"));if(G.scripts?.test&&!G.scripts.test.includes("no test specified")){return true}const je={...G.dependencies,...G.devDependencies};return Boolean(je?.jest||je?.vitest)}catch{return false}}class TestRunner{exec;constructor(G=defaultExec){this.exec=G}async run(G,K="jest"){if(hasTestSetup(G)){const je=await detectPm(this.exec);return this.exec(je,[K],{cwd:G,timeout:18e4})}return this.compileCheck(G)}async compileCheck(G){const K=(0,We.existsSync)((0,Xe.join)(G,"tsconfig.json"));try{if(K){const K=await this.exec("npx",["tsc","--noEmit"],{cwd:G,timeout:6e4});return{stdout:`Compile check PASS (tsc --noEmit)\n${K.stdout}`,stderr:K.stderr}}const je=(0,Xe.join)(G,"package.json");if((0,We.existsSync)(je)){const K=JSON.parse((0,We.readFileSync)(je,"utf8"));const ze=K.main??"index.js";if((0,We.existsSync)((0,Xe.join)(G,ze))){const K=await this.exec("node",["--check",ze],{cwd:G,timeout:3e4});return{stdout:`Compile check PASS (node --check ${ze})\n${K.stdout}`,stderr:K.stderr}}}return{stdout:"No testable files found. Skipping validation.",stderr:""}}catch(G){const K=G instanceof Error?G.message:String(G);return{stdout:`Compile check FAIL\n${K}`,stderr:K}}}}K.TestRunner=TestRunner},68100:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.TesterAgent=void 0;const ze=je(78519);const We=je(59159);class TesterAgent{deps;constructor(G){this.deps=G}async run(G){const K=await this.deps.sandboxAdapter.execute(G.files);const je=await this.deps.runner.run(G.root,"jest");return{passed:K.passed,summary:(0,We.parseTestResult)(je.stdout),coverage:(0,ze.extractCoverage)(je.stdout),logs:K.logs,failedTests:K.failedTests}}}K.TesterAgent=TesterAgent},66015:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.loadChatConfig=loadChatConfig;const ze=je(73024);const We=je(76760);const Xe=je(18296);const rt="google/gemini-3-flash-preview";const at="https://openrouter.ai/api/v1";function asString(G){if(typeof G!=="string"){return undefined}const K=G.trim();return K.length>0?K:undefined}function loadEnvFile(G,K=5){let je=(0,We.resolve)(G);for(let G=0;G<=K;G+=1){const G=(0,We.resolve)(je,".env");if((0,ze.existsSync)(G)){const K=new Map;for(const je of(0,ze.readFileSync)(G,"utf8").split(/\r?\n/)){const G=je.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);if(G)K.set(G[1],G[2])}return K}const K=(0,We.dirname)(je);if(K===je)break;je=K}return new Map}function loadChatConfig(G=process.cwd()){const K=loadEnvFile(G);const je=new Xe.SgaConfig;const ze=asString(je.get("model.coder"))??asString(je.get("model.default"))??K.get("LLM_CODER_MODEL")??process.env.LLM_CODER_MODEL??rt;const We=asString(je.get("openrouter.apiKey"))??K.get("OPENROUTER_API_KEY")??process.env.OPENROUTER_API_KEY??"";const ft=asString(je.get("openrouter.baseUrl"))??K.get("OPENROUTER_BASE_URL")??process.env.OPENROUTER_BASE_URL??at;return{model:ze,apiKey:We,baseUrl:ft,workDir:G}}},48347:function(G,K,je){"use strict";var ze=this&&this.__createBinding||(Object.create?function(G,K,je,ze){if(ze===undefined)ze=je;var We=Object.getOwnPropertyDescriptor(K,je);if(!We||("get"in We?!K.__esModule:We.writable||We.configurable)){We={enumerable:true,get:function(){return K[je]}}}Object.defineProperty(G,ze,We)}:function(G,K,je,ze){if(ze===undefined)ze=je;G[ze]=K[je]});var We=this&&this.__setModuleDefault||(Object.create?function(G,K){Object.defineProperty(G,"default",{enumerable:true,value:K})}:function(G,K){G["default"]=K});var Xe=this&&this.__importStar||function(){var ownKeys=function(G){ownKeys=Object.getOwnPropertyNames||function(G){var K=[];for(var je in G)if(Object.prototype.hasOwnProperty.call(G,je))K[K.length]=je;return K};return ownKeys(G)};return function(G){if(G&&G.__esModule)return G;var K={};if(G!=null)for(var je=ownKeys(G),Xe=0;Xe<je.length;Xe++)if(je[Xe]!=="default")ze(K,G,je[Xe]);We(K,G);return K}}();var rt=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.startChatLoop=startChatLoop;const at=Xe(je(26848));const ft=rt(je(39559));const mt=je(18296);const vt=je(40381);const yt=[{alias:"gemini-flash",id:"google/gemini-3-flash-preview",label:"Gemini 3 Flash"},{alias:"minimax",id:"minimax/minimax-m2.5",label:"MiniMax M2.5"}];function createRl(){process.stdin.resume();if(typeof process.stdin.ref==="function"){process.stdin.ref()}return at.createInterface({input:process.stdin,output:process.stdout})}function pickModel(G,K){return new Promise((je=>{G.pause();const ze=process.stdin;const We=process.stdout;const Xe=ze.isRaw;if(typeof ze.setRawMode==="function"){ze.setRawMode(true)}ze.resume();let rt=Math.max(0,yt.findIndex((G=>G.id===K)));const at=yt.length;const draw=()=>{We.write(`\n ${ft.default.white.bold("Select model")} ${ft.default.gray("(↑/↓ choose, Enter confirm, Esc cancel)")}\n`);for(let G=0;G<at;G+=1){const K=yt[G];const je=G===rt;const ze=je?ft.default.cyan(">"):" ";const Xe=je?ft.default.cyan.bold(K.alias):ft.default.white(K.alias);const at=je?ft.default.white(K.label):ft.default.gray(K.label);const mt=ft.default.gray.dim(K.id);We.write(` ${ze} ${Xe.padEnd(16)} ${at.padEnd(18)} ${mt}\n`)}We.write(` ${ft.default.gray("-".repeat(72))}\n`)};const redraw=()=>{We.write(`[${at+3}A`);draw()};const cleanup=()=>{ze.removeListener("data",onKey);if(typeof ze.setRawMode==="function"){ze.setRawMode(Xe??false)}ze.resume();G.resume()};const onKey=G=>{const K=G.toString();if(K===""||K===""){cleanup();je(null);return}if(K==="\r"||K==="\n"){cleanup();je(yt[rt].id);return}if(K===""||K==="k"){rt=(rt-1+at)%at;redraw();return}if(K===""||K==="j"){rt=(rt+1)%at;redraw();return}const ze=Number.parseInt(K,10);if(Number.isInteger(ze)&&ze>=1&&ze<=at){rt=ze-1;redraw()}};draw();ze.on("data",onKey)}))}function printBanner(G){const K=[" ███╗ ███╗ ██████╗██████╗ ██████╗██╗ █████╗ ██╗ ██╗"," ████╗ ████║██╔════╝██╔══██╗ ██╔════╝██║ ██╔══██╗██║ ██║"," ██╔████╔██║██║ ██████╔╝ ██║ ██║ ███████║██║ █╗ ██║"," ██║╚██╔╝██║██║ ██╔═══╝ ██║ ██║ ██╔══██║██║███╗██║"," ██║ ╚═╝ ██║╚██████╗██║ ╚██████╗███████╗██║ ██║╚███╔███╔╝"," ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═════╝╚══════╝╚═╝ ╚═╝ ╚══╝╚══╝ "];console.log("");for(const G of K){console.log(ft.default.cyan(G))}console.log("");console.log(ft.default.white(" AI-powered MCP Server Generator")+" · "+ft.default.yellow("by SGA 中文社区"));console.log(ft.default.gray(" "+"─".repeat(55)));console.log(" "+ft.default.gray("Model")+" "+ft.default.green(G.model));const je=G.apiKey?ft.default.green("sk-or-..."+G.apiKey.slice(-4)):ft.default.red("未配置 (mcp-claw config set-env --key YOUR_KEY)");console.log(" "+ft.default.gray("Key")+" "+je);console.log(ft.default.gray(" /help · /model · /history · /clear · Ctrl+C 退出"));console.log("")}function printRestoredHistory(G){const K=G.restoredCount;if(K===0){return}const je=Math.floor(K/2);console.log(` ${ft.default.dim("->")} ${ft.default.gray(`restored previous chat (${je} turns)`)}`);const ze=G.getRecentRounds(3);if(ze.length>0){console.log(ft.default.gray(" "+"-".repeat(50)));for(const G of ze){const K=G.userText.replace(/\s+/g," ").slice(0,60);const je=G.assistantText.replace(/\s+/g," ").slice(0,70);const ze=G.toolCount>0?ft.default.dim(` [${G.toolCount} tools]`):"";console.log(` ${ft.default.cyan("you")} ${ft.default.white(K)}${G.userText.length>60?ft.default.dim("..."):""}`);if(je){console.log(` ${ft.default.green("bot")} ${ft.default.dim(je)}${G.assistantText.length>70?ft.default.dim("..."):""}${ze}`)}else if(G.toolCount>0){console.log(` ${ft.default.green("bot")}${ze}`)}}console.log(ft.default.gray(" "+"-".repeat(50)))}console.log("")}let wt="";async function startChatLoop(G){let K=G;const je={rl:createRl()};const rejectionHandler=G=>{const K=G instanceof Error?G.message:String(G);console.error(`\n ${ft.default.red("unhandled rejection")} ${ft.default.red(K)}\n`)};process.on("unhandledRejection",rejectionHandler);const exceptionHandler=G=>{console.error(`\n ${ft.default.red("uncaught exception")} ${ft.default.red(G.message)}\n`)};process.on("uncaughtException",exceptionHandler);const exitHandler=G=>{if(G!==0){console.error(ft.default.dim(` [exit code ${G}]`))}};process.on("exit",exitHandler);if(!K.apiKey){console.log(ft.default.yellow("\n No API key configured."));console.log(ft.default.gray(" Get one free at: https://openrouter.ai/settings/keys"));console.log("");let G="";try{G=(await je.rl.question(" Enter OpenRouter API Key (sk-or-...): ")).trim()}catch{je.rl.close();cleanup();return}if(!G){console.log(ft.default.red(" API key is required. Exiting."));je.rl.close();cleanup();return}const ze=new mt.SgaConfig;ze.set("openrouter.apiKey",G);K={...K,apiKey:G};console.log(ft.default.green(" Saved to ~/.sga/config.yaml\n"))}const ze=new vt.ChatSession(K);wt=K.model;printBanner(K);printRestoredHistory(ze);let We=0;let Xe=false;const handleSigint=()=>{if(Xe){We=0;return}We++;if(We>=2){console.log(ft.default.gray("\n bye.\n"));je.rl.close();process.exit(0)}console.log(ft.default.gray("\n (Ctrl+C again to exit)\n"));process.stdout.write(ft.default.cyan.bold("> "))};process.on("SIGINT",handleSigint);const rt=ft.default.cyan.bold("> ");const at=ft.default.gray(" "+"-".repeat(50));function cleanup(){process.off("SIGINT",handleSigint);process.off("unhandledRejection",rejectionHandler);process.off("uncaughtException",exceptionHandler);process.off("exit",exitHandler)}try{for(;;){We=0;if(process.stdin.destroyed||!process.stdin.readable){console.error(ft.default.red("\n stdin destroyed, cannot continue.\n"));break}process.stdin.resume();if(typeof process.stdin.ref==="function"){process.stdin.ref()}let G;try{G=await je.rl.question(rt)}catch{try{je.rl.close()}catch{}if(process.stdin.destroyed||!process.stdin.readable){console.error(ft.default.red("\n stdin closed, exiting.\n"));break}console.error(ft.default.yellow("\n readline reset, retrying...\n"));je.rl=createRl();try{G=await je.rl.question(rt)}catch{console.error(ft.default.red("\n readline unrecoverable, exiting.\n"));break}}const K=G.trim();if(!K){continue}if(K==="/help"){console.log(ft.default.gray(" /help | /model | /model <alias|id> | /history | /clear"));console.log("");continue}if(K==="/clear"){ze.clearHistory();console.log(` ${ft.default.green("ok")} ${ft.default.gray("history cleared")}\n`);continue}if(K==="/history"){printRestoredHistory(ze);continue}if(K==="/model"||K==="/models"){const G=await pickModel(je.rl,wt);if(G){wt=G;ze.setModel(G);console.log(` ${ft.default.green("ok")} model switched to ${ft.default.green(G)}\n`)}else{console.log(` ${ft.default.gray("cancelled")}\n`)}continue}if(K.startsWith("/model ")){const G=K.slice("/model ".length).trim();if(!G){console.log(` ${ft.default.yellow("usage: /model <alias|id>")}\n`);continue}const je=yt.find((K=>K.alias===G));const We=je?je.id:G;wt=We;ze.setModel(We);console.log(` ${ft.default.green("ok")} model switched to ${ft.default.green(We)}\n`);continue}console.log(at);Xe=true;try{await ze.send(K)}catch(G){const K=G instanceof Error?G.message:String(G);console.error(`\n ${ft.default.red("error")} ${ft.default.red(K)}`);if(G instanceof Error&&G.cause){console.error(` ${ft.default.gray(G.cause.message??String(G.cause))}`)}console.error("")}finally{Xe=false}}}finally{cleanup();je.rl.close()}}},40381:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.ChatSession=void 0;const We=je(31421);const Xe=je(73024);const rt=je(51455);const at=je(76760);const ft=je(57975);const mt=ze(je(39559));const vt=je(19562);const yt=je(60403);const wt=je(72966);const lr=je(26120);const Er=je(18296);const Rr=je(49904);const jr=je(29441);const zr=je(61108);const fi=je(65737);const mi=je(20336);const bi=je(15158);const Si=je(59265);const Ei=je(2330);const ki=je(66191);const Ci=(0,ft.promisify)(We.exec);const Ti=["*"];const Pi=new Set([".md",".txt",".json",".yaml",".yml",".ts",".js",".mjs",".cjs",".xml",".toml",".env"]);const Ii=30;const Ri=2e5;const Mi=6e3;const qi=1e5;const Xi=2e4;const ps=50;const Ls=15e4;const qs=10;const Ws=30;const Js=5;const eo=50;const to=100;const ro=new Set(["get","post","put","delete","patch","options","head","trace"]);function truncate(G,K){if(G.length<=K){return G}return`${G.slice(0,K)}...`}function asRecord(G){if(G&&typeof G==="object"&&!Array.isArray(G)){return G}return{}}function parseToolArguments(G){try{return asRecord(JSON.parse(G))}catch{return{}}}function formatError(G){return G instanceof Error?G.message:String(G)}function toStringValue(G){return typeof G==="string"?G:""}function toNumber(G,K){if(typeof G!=="number"||!Number.isFinite(G)){return K}return G}function toStringArray(G){if(!Array.isArray(G)){return[]}return G.filter((G=>typeof G==="string"))}function deriveSgaSearchEndpoint(G){const K=new URL(G);return`${K.protocol}//${K.host}/v1/agent/search`}function parseSearchPayload(G,K){const je=asRecord(G);const ze=Array.isArray(je.results)?je.results:[];const We=[];for(const G of ze){const K=asRecord(G);const je=toStringValue(K.title);const ze=toStringValue(K.url);if(!ze){continue}const Xe=toStringValue(K.content);const rt=Xe.length>0?Xe.slice(0,300):toStringValue(K.snippet).slice(0,300);const at=toStringValue(K.published_date);const ft=toStringValue(K.domain);We.push({title:je,url:ze,snippet:rt,...at?{published_date:at}:{},...ft?{domain:ft}:{}})}return{total:toNumber(je.total_results,We.length),results:We.slice(0,K),suggestions:toStringArray(je.suggestions)}}function parseYamlScalar(G){const K=G.trim();if(K.startsWith('"')&&K.endsWith('"')||K.startsWith("'")&&K.endsWith("'")){return K.slice(1,-1)}return K}function parseMinimalOpenApiYaml(G){const K=G.split(/\r?\n/);const je={info:{},servers:[],paths:{},components:{securitySchemes:{},schemas:{}}};let ze="";let We=false;let Xe=false;let rt="";let at="";let ft=-1;for(const G of K){const K=G.replace(/\s+#.*$/,"");if(!K.trim()){continue}const mt=K.match(/^ */)?.[0].length??0;const vt=K.trim();if(mt===0){if(vt.startsWith("openapi:")){je.openapi=parseYamlScalar(vt.slice("openapi:".length))}else if(vt.startsWith("swagger:")){je.swagger=parseYamlScalar(vt.slice("swagger:".length))}else if(vt==="info:"){ze="info"}else if(vt==="servers:"){ze="servers"}else if(vt==="paths:"){ze="paths"}else if(vt==="components:"){ze="components"}else{ze=""}We=false;Xe=false;rt="";at="";ft=-1;continue}if(ze==="info"&&mt===2){const G=vt.match(/^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/);if(G){const K=asRecord(je.info);K[G[1]]=parseYamlScalar(G[2]);je.info=K}continue}if(ze==="servers"){if(mt===2&&vt.startsWith("-")){const G=vt.slice(1).trim();const K={};const ze=G.match(/^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/);if(ze){K[ze[1]]=parseYamlScalar(ze[2])}const We=Array.isArray(je.servers)?je.servers:[];We.push(K);je.servers=We;ft=We.length-1}else if(mt===4&&ft>=0){const G=vt.match(/^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/);if(G){const K=Array.isArray(je.servers)?je.servers:[];const ze=asRecord(K[ft]);ze[G[1]]=parseYamlScalar(G[2]);K[ft]=ze;je.servers=K}}continue}if(ze==="components"){if(mt===2&&vt==="securitySchemes:"){We=true;Xe=false;continue}if(mt===2&&vt==="schemas:"){Xe=true;We=false;continue}if(mt===4&&We&&vt.endsWith(":")){const G=vt.slice(0,-1).trim();const K=asRecord(je.components);const ze=asRecord(K.securitySchemes);ze[G]={};K.securitySchemes=ze;je.components=K;continue}if(mt===6&&We){const G=vt.match(/^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/);if(G){const K=asRecord(je.components);const ze=asRecord(K.securitySchemes);const We=Object.entries(ze);if(We.length>0){const[Xe]=We[We.length-1];const rt=asRecord(ze[Xe]);rt[G[1]]=parseYamlScalar(G[2]);ze[Xe]=rt;K.securitySchemes=ze;je.components=K}}continue}if(mt===4&&Xe&&vt.endsWith(":")){const G=vt.slice(0,-1).trim();const K=asRecord(je.components);const ze=asRecord(K.schemas);ze[G]={};K.schemas=ze;je.components=K;continue}continue}if(ze==="paths"){if(mt===2&&vt.endsWith(":")){rt=vt.slice(0,-1).trim();const G=asRecord(je.paths);G[rt]={};je.paths=G;at="";continue}if(mt===4&&vt.endsWith(":")&&rt){const G=vt.slice(0,-1).trim().toLowerCase();if(ro.has(G)){at=G;const K=asRecord(je.paths);const ze=asRecord(K[rt]);ze[at]={};K[rt]=ze;je.paths=K}continue}if(mt===6&&rt&&at){const G=vt.match(/^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/);if(G){const K=asRecord(je.paths);const ze=asRecord(K[rt]);const We=asRecord(ze[at]);We[G[1]]=parseYamlScalar(G[2]);ze[at]=We;K[rt]=ze;je.paths=K}}}}return je}function summarizeSchema(G){const K=asRecord(G);const je=toStringValue(K.type);const ze=toStringValue(K.$ref);if(ze){return ze}if(je){return je}return"object"}function extractAuthSchemes(G){const K=asRecord(G.components);const je=asRecord(K.securitySchemes);const ze=new Set;for(const G of Object.values(je)){const K=asRecord(G);const je=toStringValue(K.type).toLowerCase();if(je==="apikey"){ze.add("apiKey")}else if(je==="oauth2"){ze.add("oauth2")}else if(je==="http"){const G=toStringValue(K.scheme).toLowerCase();if(G==="bearer"){ze.add("bearer")}else if(G==="basic"){ze.add("basic")}}}return[...ze]}function extractOpenApiEndpoints(G,K){const je=asRecord(G.paths);const ze=[];let We=0;for(const[G,Xe]of Object.entries(je)){const je=asRecord(Xe);const rt=Array.isArray(je.parameters)?je.parameters:[];for(const[Xe,at]of Object.entries(je)){const je=Xe.toLowerCase();if(!ro.has(je)){continue}We+=1;if(ze.length>=K){continue}const ft=asRecord(at);const mt=Array.isArray(ft.parameters)?ft.parameters:[];const vt=[...rt,...mt];const yt=vt.map((G=>asRecord(G))).map((G=>{const K=asRecord(G.schema);return{name:toStringValue(G.name),in:toStringValue(G.in),required:Boolean(G.required),type:toStringValue(K.type)||summarizeSchema(K)}})).filter((G=>G.name.length>0));let wt;const lr=asRecord(ft.requestBody);const Er=asRecord(lr.content);const Rr=Object.keys(Er);if(Rr.length>0){const G=Rr[0];const K=asRecord(Er[G]);wt={contentType:G,schema:summarizeSchema(K.schema)}}const jr=asRecord(ft.responses);const zr={};for(const[G,K]of Object.entries(jr)){const je=asRecord(K);zr[G]=toStringValue(je.description)}ze.push({method:je.toUpperCase(),path:G,operationId:toStringValue(ft.operationId),summary:toStringValue(ft.summary),description:toStringValue(ft.description),parameters:yt,...wt?{requestBody:wt}:{},responses:zr})}}return{endpointCount:We,endpoints:ze}}function findNearestFile(G,K,je=6){let ze=(0,at.resolve)(G);for(let G=0;G<=je;G+=1){const G=(0,at.join)(ze,K);if((0,Xe.existsSync)(G)){return G}const je=(0,at.resolve)(ze,"..");if(je===ze){break}ze=je}return undefined}async function runGit(G,K){try{const{stdout:je}=await Ci(`git ${K.join(" ")}`,{cwd:G,windowsHide:true});const ze=je.trim();return ze.length>0?ze:undefined}catch{return undefined}}async function readProjectName(G){const K=findNearestFile(G,"package.json");if(!K){return undefined}try{const G=await(0,rt.readFile)(K,"utf8");const je=JSON.parse(G);return typeof je.name==="string"?je.name:undefined}catch{return undefined}}async function readGitContext(G){const K=await runGit(G,["rev-parse","--is-inside-work-tree"]);if(K!=="true"){return{isRepo:false}}const[je,ze]=await Promise.all([runGit(G,["branch","--show-current"]),runGit(G,["log","-1","--pretty=format:%h %s"])]);return{isRepo:true,branch:je,latestCommit:ze}}async function buildSystemPrompt(G,K=0,je=18){const[ze,We]=await Promise.all([readProjectName(G),readGitContext(G)]);const Xe=(new Date).toISOString();const rt=We.isRepo?We.branch??"detached":"n/a";const at=We.isRepo?We.latestCommit??"n/a":"n/a";return["# Environment",`cwd: ${G}`,`platform: ${process.platform}`,`time: ${Xe}`,`project: ${ze??"unknown"}`,`git: ${rt} | ${at}`,...K>0?[`chat_history: ${K} messages restored from previous session 鈥?you HAVE full context`,""]:[],"","# Role","You are mcp-claw, a specialist AI for generating MCP (Model Context Protocol) servers.","You are NOT a generic coding assistant. Your domain is MCP server creation.","","# MCP Protocol Specification","","## Core Primitives","MCP servers expose capabilities to AI hosts (Claude Desktop, Cursor, Windsurf, etc.) via:","","### Tools (functions the AI can invoke)","- name: snake_case, verb_noun pattern (get_user, create_order, list_products)","- description: one-sentence purpose, mention side effects if any","- inputSchema: JSON Schema with required/optional params, each with description","- One tool = one atomic API operation. Do NOT merge multiple endpoints into one tool.","- Return structured JSON. Include relevant fields, not raw API response.","","### Resources (read-only data the AI can access)","- Exposed via URI: resource://users/{id}, resource://config","- Use for reference data, configs, documentation. Use tools for mutations.","","## Server Structure (TypeScript, best practice)","```","src/"," index.ts # McpServer + StdioServerTransport entry"," tools/ # One file per tool group"," users.ts # registerUserTools(server, client)"," orders.ts"," lib/"," api-client.ts # Shared HTTP client: base URL, auth, error handling"," types.ts # Shared TypeScript interfaces",'package.json # type: "module", bin: { "mcp-server-xxx": "./dist/index.js" }',"tsconfig.json # target: ES2022, module: NodeNext","README.md # Install, configure, use with Claude/Cursor","```","","## Authentication Patterns","- API Key: read from env var (e.g., XXX_API_KEY), inject into headers","- Bearer Token: env var, Authorization: Bearer ${token}","- OAuth2: implement token refresh, store in memory or file","- NEVER hardcode secrets. Always use env vars: {SERVICE}_API_KEY","- Server must fail fast with clear error if required env var is missing","- Document all required env vars in README with examples","","## Error Handling","- Wrap every tool handler in try/catch",'- Return { error: "Human-readable message" } on failure, not stack traces',"- Handle HTTP 401/403 specifically: suggest checking API key","- Handle network errors: suggest checking connectivity","- Handle rate limits (429): include retry-after info if available","","## Publishing Checklist",'- package.json: name starts with "mcp-server-", keywords include "mcp-server"',"- bin field points to compiled entry","- README includes claude_desktop_config.json example:",' { "mcpServers": { "name": { "command": "npx", "args": ["-y", "mcp-server-xxx"], "env": { "API_KEY": "..." } } } }',"- Server starts cleanly with: npx mcp-server-xxx","- All env vars documented with descriptions and defaults","","## Quality Standards","- Generated code must compile with strict TypeScript (no any, no implicit)","- Each tool must handle missing/invalid params gracefully","- Include at least one integration test per tool","- Use zod or JSON Schema validation on tool inputs","","# Behavior Rules","- Act first, explain briefly. Call tools instead of asking questions.","- Keep responses to 1-4 sentences. Expand only when user asks.",'- When user says "project dir" / "current folder" / "here" -> use cwd, no questions.','- When user mentions a specific file (e.g., "agent_api.md") -> call read_file with that filename.','- When user says "I put a file" without name -> call read_folder on cwd to discover it, then read_file to read fully.',"- If read_folder preview is truncated, ALWAYS follow up with read_file to get the complete content.","- Relative paths resolve from cwd.","- IMPORTANT: Only call fetch_url when user gives an explicit http/https URL."," Local files/folders -> always read_folder. Never mix fetch_url with local file operations.","- Call ONE tool at a time. Do not call multiple tools in parallel unless clearly needed.","- After reading docs, summarize what tools you would generate BEFORE generating.","","# CRITICAL: read_folder vs read_file","- read_folder returns ONLY a file listing (names and sizes). It does NOT return file content.","- You MUST call read_file for EACH documentation file you need to analyze.","- Workflow: read_folder (discover files) → read_file (read each relevant file FULLY) → analyze → generate.","- NEVER skip read_file. NEVER assume you have file content from read_folder alone.","- If there are multiple doc files (.md, .txt, .json, .yaml), read ALL of them before generating.","","# Available Tools Summary",`You have ${String(je)} tools. Use them in combination:`,"","Discovery flow:",' "make MCP for Stripe" -> sga_search("Stripe API documentation") -> discover best docs URL -> fetch_url or crawl_docs -> generate_mcp',"","OpenAPI fast path:"," User provides URL -> http_request(url + /openapi.json) to probe -> if found, parse_openapi -> generate_mcp","","Editing flow:",' After generate_mcp -> search_files("error") -> write_file to fix -> run_command("npx tsc --noEmit")',"","PDF docs:"," User drops a PDF -> read_pdf -> generate_mcp","","The sga_search tool searches the web with Chinese/WeChat support. prefer it over fetch_url for discovery.","Configure with: mcp-claw config set search.url http://<host>/v1/agent/search","","# Shell Access (run_command)","You have full shell access via run_command. Critical rules for Windows compatibility:","",'## NEVER do this (causes "Command failed" with no useful error):',' WRONG: run_command("cd generated && npx tsc --noEmit")',' WRONG: run_command("cd generated && npx jest 2>&1")',' WRONG: run_command("node_modules/.bin/tsc --noEmit")',' WRONG: run_command("node_modules\\.bin\\tsc")',"","## ALWAYS do this instead (use the cwd parameter):",' RIGHT: run_command("npx tsc --noEmit", cwd: "generated")',' RIGHT: run_command("npx jest --no-coverage", cwd: "generated")',' RIGHT: run_command("pnpm install", cwd: "generated")',' RIGHT: run_command("dir src", cwd: "generated") // Windows: use dir not ls',"","## Key rules:","- NEVER use `cd path && command` 鈥?use cwd parameter instead","- NEVER use `2>&1` 鈥?stderr is captured automatically on errors","- NEVER use `node_modules/.bin/` or `node_modules\\.bin\\` 鈥?use `npx <tool>` instead","- On Windows use `dir` not `ls`, use `type` not `cat`","- The cwd defaults to the last generated project dir automatically",'- To compile: run_command("npx tsc --noEmit") 鈥?no cd needed if cwd is already right','- To install deps: run_command("pnpm install") in project cwd',"","## When run_command returns status: error 鈥?MANDATORY debug protocol:","1. STOP. Do NOT immediately retry the same command.",'2. READ the full "output" field 鈥?it contains the actual error messages.',' TypeScript errors: "src/file.ts(10,5): error TS2345: Argument of type..."'," Missing module: \"Cannot find module 'zod' or its type declarations\"","3. Identify WHICH file and line number has the error.","4. read_file the problematic file to understand the code.","5. write_file to fix the error.",'6. run_command("npx tsc --noEmit") again to verify the fix.',"","## Special case: Empty output from run_command (V8 crash)","If run_command returns status: error with empty or missing output for a TypeScript command:"," CAUSE: JavaScript heap out of memory - TypeScript type checker crashed.",' ALWAYS check server.ts for: zodToJsonSchema(schema) as Tool["inputSchema"]',' FIX: Replace with toInputSchema helper (see below) or use (zodToJsonSchema as (s: unknown) => Tool["inputSchema"])(schema)'," DO NOT retry the same tsc command - it will always crash until the code is fixed.","","## NEVER do these when you see an error:",'- NEVER add 2>&1 to capture stderr (stderr is already in "output")',"- NEVER add || true to suppress exit codes (hides real errors)","- NEVER retry the exact same command without first fixing root cause","When something fails, DO NOT give up. Analyze 鈫?Fix 鈫?Verify.","","# Workflow","1) Discover files: call read_folder to get file listing (names + sizes only).","2) Read each file: call read_file for EVERY documentation file found. Do NOT skip any."," IMPORTANT: read_folder does NOT return file content. You MUST call read_file individually."," For web sources: use fetch_url or crawl_docs.","3) Analyze: identify ALL endpoints, params, auth method, data models.","4) Propose: tell user what MCP tools you will generate and why. Wait for user confirmation.","5) Generate: call generate_mcp to produce the server code.","6) Validate: use run_command to compile and verify the generated project:",' - run_command("npx tsc --noEmit") to check TypeScript compilation'," - If errors, fix them with run_command (install deps, etc.)",' - run_command("npx jest") if tests exist',"7) **STOP here.** Report generation result ACCURATELY:"," - Use search_files or read_file on the generated src/ to count the EXACT number of tools."," - Report the exact tool count, tool names, file list, and output directory."," - Do NOT guess or estimate the tool count. Count them from the source code."," Then ask the user:",' - "瑕佽繘琛岄泦鎴愭祴璇曞悧锛熻鎻愪緵锛?) API base URL 2) 闇€瑕佺殑 credentials (濡?API key)"'," - Do NOT call test_integration until the user provides the URL and credentials."," - If user says skip, go directly to step 10.","8) Integration test: call test_integration with the user-provided base_url and auth_env."," - test_integration MUST execute every discovered tool at least once."," - Publishing is allowed only when all tools pass (allToolsPassed=true)."," - If test_integration fails, report the exact failed tools and errors to the user."," - Do NOT retry blindly."," - Do NOT modify generated server source code just to silence test failures.",'9) **STOP again.** Show test results. Ask: "要发布到 MCP Market 吗?"'," - Do NOT call publish_mcp until user confirms."," - publish_mcp requires market_url (e.g. http://localhost:3000) and token (access token)."," - Token is saved after first use; market_url is saved after first use."," - On success, show the returned packageUrl to the user as a clickable link.","","10) Publish: call publish_mcp.","","# CRITICAL: Never auto-proceed past step 7. Always pause for user input before integration testing and publishing.","","# Self-Evolution Protocol","When you complete an error鈫抐ix鈫抳erify cycle (run_command failed 鈫?you fixed it 鈫?run_command passed):"," ALWAYS call record_learning immediately after the fix is confirmed."," This saves the pattern to .mcp-claw/patterns.md and helps future sessions avoid the same mistake."," Good triggers: missing dependency, TypeScript type error, wrong import path, config issue.","","# Chat History vs Run History 鈥?IMPORTANT DISTINCTION","Your conversation messages are ALWAYS loaded at startup from .mcp-claw/chat-history.json.",'If you can see prior "user" and "assistant" messages in your context, that IS the real history.','NEVER say "I have no context" or "I cannot find previous conversation" when history is present.',"NEVER use show_history to look for chat content 鈥?it only returns MCP generation run logs, NOT chat.",'show_history is for: "what MCPs have I generated before?" NOT for: "what did we discuss?"',"","Default language: Chinese. Keep technical terms in English (MCP, tool, schema, API, etc.).",...loadLearnedPatterns(G)].join("\n")}function loadLearnedPatterns(G){const K=(0,at.join)(G,".mcp-claw","patterns.md");if(!(0,Xe.existsSync)(K))return[];try{const G=(0,Xe.readFileSync)(K,"utf8").trim();if(G.length<10)return[];return["","# Learned Patterns (from this project 鈥?apply these automatically)",G]}catch{return[]}}function historyPath(G){return(0,at.join)(G,".mcp-claw","chat-history.json")}function loadPersistedState(G){const K=historyPath(G);if(!(0,Xe.existsSync)(K)){return null}try{const G=(0,Xe.readFileSync)(K,"utf8");return JSON.parse(G)}catch{return null}}function savePersistedState(G,K){const je=historyPath(G);const ze=(0,at.join)(G,".mcp-claw");if(!(0,Xe.existsSync)(ze)){(0,Xe.mkdirSync)(ze,{recursive:true})}const We={...K,history:K.history.slice(-40)};(0,Xe.writeFileSync)(je,JSON.stringify(We,null,2),"utf8")}class ChatSession{config;history=[];tools;llm;fsTool;browserTool;httpTool;pdfTool;sessionReader;generate;testRunner;output;toolHandlers;sgaConfig;lastSource;lastGeneratedDir;lastIntegrationDir;lastIntegrationSummary;cachedSystemPrompt;constructor(G,K={}){this.config=G;this.tools=(0,ki.buildToolDefinitions)(this.config);this.llm=K.llm??new Rr.OpenRouterProvider("openrouter-chat",this.config.model,this.config.apiKey,this.config.baseUrl);this.fsTool=K.fsTool??new fi.FsTool;this.browserTool=K.browserTool??new zr.BrowserTool;this.httpTool=K.httpTool??new mi.HttpFetchTool;this.pdfTool=K.pdfTool??new bi.PdfTool;this.sessionReader=K.sessionReader??new jr.SessionReader;this.generate=K.generate??wt.generateCommand;this.testRunner=K.testRunner??new yt.TestRunner;this.output=K.output??process.stdout;this.toolHandlers=K.toolHandlers??{};this.sgaConfig=new Er.SgaConfig;const je=loadPersistedState(this.config.workDir);if(je){this.history.push(...je.history);this.lastSource=je.lastSource;this.lastGeneratedDir=je.lastGeneratedDir;this.lastIntegrationDir=je.lastIntegrationDir;this.lastIntegrationSummary=je.lastIntegrationSummary}}get restoredCount(){return this.history.length}async send(G){this.cachedSystemPrompt=await buildSystemPrompt(this.config.workDir,this.history.length,this.tools.length);const K=this.history.length;this.history.push({role:"user",content:G});try{for(;;){const G=await this.callLlm();if(G.finish_reason==="stop"){const K=G.content.trim();if(K.length>0){this.writeAssistant(K)}this.history.push({role:"assistant",content:G.content});this.persistState();return}const K=G.content.trim();if(K.length>0){this.writeAssistant(K)}const je=G.tool_calls??[];this.history.push({role:"assistant",content:G.content,...je.length>0?{tool_calls:je}:{}});for(const G of je){const K=parseToolArguments(G.function.arguments);this.writeToolStart(G.function.name,K);const je=await this.executeTool(G);this.writeToolDone(G.function.name,je);this.history.push({role:"tool",content:je,tool_call_id:G.id})}}}catch(G){this.history.length=K;throw G}}async callLlm(){const G=this.cachedSystemPrompt??await buildSystemPrompt(this.config.workDir,this.history.length,this.tools.length);const K=[{role:"system",content:G},...this.history];return this.llm.chat(K,this.tools)}async executeTool(G){const K=G.function.name;const je=parseToolArguments(G.function.arguments);const ze=this.toolHandlers[K];if(ze){return ze(je)}try{switch(K){case"read_folder":return this.readFolder(je);case"read_file":return this.readSingleFile(je);case"fetch_url":return this.fetchUrl(je);case"write_file":return this.writeFile(je);case"search_files":return this.searchFiles(je);case"read_pdf":return this.readPdf(je);case"http_request":return this.httpRequest(je);case"crawl_docs":return this.crawlDocs(je);case"discover_docs":return this.discoverDocs(je);case"sga_search":return this.sgaSearch(je);case"parse_openapi":return this.parseOpenApi(je);case"run_command":return this.runShellCommand(je);case"generate_mcp":return this.generateMcp(je);case"run_tests":return this.runTests(je);case"test_integration":return this.testIntegration(je);case"publish_mcp":return this.publishMcp(je);case"show_history":return this.showHistory();case"record_learning":return this.recordLearning(je);default:return JSON.stringify({error:`Unknown tool: ${G.function.name}`})}}catch(G){return JSON.stringify({error:formatError(G)})}}resolvePath(G){return(0,at.isAbsolute)(G)?G:(0,at.resolve)(this.config.workDir,G)}async readFolder(G){const K=typeof G.path==="string"&&G.path.trim()?G.path.trim():this.config.workDir;const je=this.resolvePath(K);if(!(0,Xe.existsSync)(je)){return JSON.stringify({error:`Path not found: ${je}`})}const ze=await this.fsTool.glob(je,Ti);const We=await Promise.all(ze.slice(0,Ii).map((async G=>{const K=(0,at.relative)(this.config.workDir,G)||G;let je=0;try{const K=await this.fsTool.readFile(G);je=K.length}catch{}const ze=(0,at.extname)(G).toLowerCase();const We=Pi.has(ze);return{path:K,size:je,isText:We}})));this.lastSource=K;return JSON.stringify({path:je,fileCount:ze.length,listing:We,hint:"This is a file listing only. Call read_file on each relevant file to get its full content."},null,2)}async readSingleFile(G){const K=typeof G.path==="string"?G.path.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: path"})}const je=this.resolvePath(K);if(!(0,Xe.existsSync)(je)){return JSON.stringify({error:`File not found: ${je}`})}const ze=await this.fsTool.readFile(je);this.lastSource=K;return JSON.stringify({path:je,length:ze.length,content:truncate(ze,Ri)},null,2)}async fetchUrl(G){const K=typeof G.url==="string"?G.url:"";if(!K){return JSON.stringify({error:"Missing required argument: url"})}const je=await this.browserTool.fetch(K);this.lastSource=K;return JSON.stringify({url:je.url,title:je.title,links:je.links.slice(0,100),openApiUrls:je.openApiUrls,text:truncate(je.text,8e3)},null,2)}async writeFile(G){const K=typeof G.path==="string"?G.path.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: path"})}if(typeof G.content!=="string"){return JSON.stringify({error:"Missing required argument: content"})}const je=this.resolvePath(K);(0,Xe.mkdirSync)((0,at.dirname)(je),{recursive:true});await this.fsTool.writeFile(je,G.content);return JSON.stringify({status:"ok",path:je,bytes:G.content.length},null,2)}async searchFiles(G){const K=typeof G.pattern==="string"?G.pattern.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: pattern"})}const je=typeof G.path==="string"&&G.path.trim()?G.path.trim():this.lastGeneratedDir??this.config.workDir;const ze=this.resolvePath(je);const We=typeof G.glob==="string"&&G.glob.trim()?G.glob.trim():"*";let Xe;try{Xe=new RegExp(K,"i")}catch(G){return JSON.stringify({error:`Invalid pattern: ${formatError(G)}`})}const rt=await this.fsTool.glob(ze,[We]);const ft=[];let mt=0;for(const G of rt){let K;try{K=await this.fsTool.readFile(G)}catch{continue}const je=K.split(/\r?\n/);for(let K=0;K<je.length;K+=1){const ze=je[K];if(!Xe.test(ze)){continue}mt+=1;if(ft.length<ps){ft.push({file:(0,at.relative)(this.config.workDir,G)||G,line:K+1,text:ze})}}}return JSON.stringify({matches:ft,totalMatches:mt},null,2)}async readPdf(G){const K=typeof G.path==="string"?G.path.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: path"})}const je=this.resolvePath(K);if(!(0,Xe.existsSync)(je)){return JSON.stringify({error:`File not found: ${je}`})}const ze=await this.pdfTool.extract(je);return JSON.stringify({path:je,length:ze.length,content:truncate(ze,qi)},null,2)}async httpRequest(G){const K=typeof G.url==="string"?G.url.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: url"})}const je=typeof G.method==="string"&&G.method.trim()?G.method.trim().toUpperCase():"GET";const ze=typeof G.timeout_ms==="number"&&Number.isFinite(G.timeout_ms)?Math.max(1,Math.floor(G.timeout_ms)):1e4;const We={};if(G.headers&&typeof G.headers==="object"&&!Array.isArray(G.headers)){for(const[K,je]of Object.entries(G.headers)){if(typeof je==="string"){We[K]=je}}}const Xe=typeof G.body==="string"?G.body:undefined;try{const G=await this.httpTool.request({url:K,method:je,headers:We,body:Xe,timeoutMs:ze});return JSON.stringify({status:G.status,statusText:G.statusText,headers:G.headers,body:truncate(G.body,Xi),url:G.url},null,2)}catch(G){return JSON.stringify({error:formatError(G),url:K},null,2)}}async crawlDocs(G){const K=typeof G.start_url==="string"?G.start_url.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: start_url"})}let je;try{je=new URL(K)}catch{return JSON.stringify({error:`Invalid URL: ${K}`})}const ze=typeof G.max_pages==="number"&&Number.isFinite(G.max_pages)?Math.floor(G.max_pages):qs;const We=Math.min(Ws,Math.max(1,ze));let Xe;if(typeof G.link_pattern==="string"&&G.link_pattern.trim()){try{Xe=new RegExp(G.link_pattern,"i")}catch(G){return JSON.stringify({error:`Invalid link_pattern: ${formatError(G)}`})}}const rt=[je.href];const at=new Set;const ft=new Set([je.href]);const mt=[];const vt=[];while(rt.length>0&&at.size<We){const G=rt.shift();if(!G||at.has(G)){continue}at.add(G);let K;try{K=await this.browserTool.fetch(G)}catch{continue}mt.push({url:K.url,title:K.title,textLength:K.text.length});vt.push(K.text);for(const G of K.links){let K;try{K=new URL(G)}catch{continue}const ze=K.href;ft.add(ze);if(K.hostname!==je.hostname){continue}if(Xe&&!Xe.test(ze)){continue}if(at.has(ze)||rt.includes(ze)){continue}rt.push(ze)}}const yt=truncate(vt.join("\n\n"),Ls);return JSON.stringify({pagesVisited:mt.length,pages:mt,combinedText:yt,discoveredUrls:[...ft]},null,2)}async discoverDocs(G){const K=typeof G.query==="string"?G.query.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: query"})}const je=typeof G.max_results==="number"&&Number.isFinite(G.max_results)?Math.max(1,Math.floor(G.max_results)):5;const ze=this.sgaConfig.get("search.url");const We=typeof ze==="string"&&ze.trim().length>0?ze.trim():process.env.SEARCH_ENGINE_URL?.trim();if(!We){return JSON.stringify({error:"No search engine configured. Set search.url in config: mcp-claw config set search.url https://your-search-engine/search"},null,2)}let Xe;try{Xe=deriveSgaSearchEndpoint(We)}catch{return JSON.stringify({error:`Invalid search.url: ${We}`},null,2)}const rt=new URL(Xe);rt.searchParams.set("q",K);rt.searchParams.set("limit",String(je));rt.searchParams.set("preset","general");rt.searchParams.set("sort","relevance");rt.searchParams.set("depth","basic");const at=await this.httpTool.request({url:rt.toString(),method:"GET",timeoutMs:1e4});if(at.status>=400){return JSON.stringify({query:K,error:`Search request failed with HTTP ${at.status}`},null,2)}let ft;try{ft=JSON.parse(at.body)}catch{return JSON.stringify({query:K,error:"Search engine returned non-JSON response"},null,2)}const mt=parseSearchPayload(ft,je);return JSON.stringify({query:K,results:mt.results,suggestions:mt.suggestions},null,2)}async sgaSearch(G){const K=typeof G.q==="string"?G.q.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: q"})}const je=typeof G.preset==="string"&&["chinese","wechat","general"].includes(G.preset)?G.preset:"chinese";const ze=Math.min(eo,Math.max(1,Math.floor(toNumber(G.limit,Js))));const We=typeof G.sort==="string"&&["time","relevance"].includes(G.sort)?G.sort:"time";const Xe=typeof G.depth==="string"&&["basic","enriched"].includes(G.depth)?G.depth:"basic";const rt=this.sgaConfig.get("search.url");const at=typeof rt==="string"&&rt.trim().length>0?rt.trim():process.env.SEARCH_ENGINE_URL?.trim();if(!at){return JSON.stringify({error:"No search engine configured. Set search.url in config: mcp-claw config set search.url https://your-search-engine/search"},null,2)}let ft;try{ft=deriveSgaSearchEndpoint(at)}catch{return JSON.stringify({error:`Invalid search.url: ${at}`},null,2)}const mt=new URL(ft);mt.searchParams.set("q",K);mt.searchParams.set("preset",je);mt.searchParams.set("limit",String(ze));mt.searchParams.set("sort",We);mt.searchParams.set("depth",Xe);const vt=await this.httpTool.request({url:mt.toString(),method:"GET",timeoutMs:1e4});if(vt.status>=400){return JSON.stringify({query:K,error:`Search request failed with HTTP ${vt.status}`},null,2)}let yt;try{yt=JSON.parse(vt.body)}catch{return JSON.stringify({query:K,error:"Search engine returned non-JSON response"},null,2)}const wt=parseSearchPayload(yt,ze);return JSON.stringify({query:K,total:wt.total,results:wt.results,suggestions:wt.suggestions},null,2)}async parseOpenApi(G){const K=typeof G.source==="string"?G.source.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: source"})}const je=Math.max(1,Math.floor(typeof G.max_endpoints==="number"&&Number.isFinite(G.max_endpoints)?G.max_endpoints:to));let ze="";try{if(/^https?:\/\//i.test(K)){const G=await this.httpTool.request({url:K,method:"GET",timeoutMs:1e4});ze=G.body}else{const G=this.resolvePath(K);ze=await this.fsTool.readFile(G)}}catch(G){return JSON.stringify({error:formatError(G),rawPreview:""},null,2)}let We=null;try{const G=JSON.parse(ze);if(G&&typeof G==="object"&&!Array.isArray(G)){We=G}}catch{}if(!We){const G=ze.trimStart();if(/^(openapi|swagger)\s*:/i.test(G)){We=parseMinimalOpenApiYaml(ze)}else{return JSON.stringify({error:"Failed to parse as JSON or recognizable OpenAPI YAML",rawPreview:ze.slice(0,1e3)},null,2)}}const Xe=asRecord(We.info);const rt=Array.isArray(We.servers)?We.servers.map((G=>{const K=asRecord(G);return{url:toStringValue(K.url),description:toStringValue(K.description)}})):[];const at=rt.filter((G=>G.url.length>0));const ft=extractAuthSchemes(We);const mt=extractOpenApiEndpoints(We,je);const vt=asRecord(We.components);const yt=Object.keys(asRecord(vt.schemas));return JSON.stringify({title:toStringValue(Xe.title),version:toStringValue(Xe.version),description:toStringValue(Xe.description),baseUrl:at[0]?.url??"",auth:ft,endpointCount:mt.endpointCount,endpoints:mt.endpoints,models:yt},null,2)}async runShellCommand(G){const K=typeof G.command==="string"?G.command.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: command"})}const je=typeof G.cwd==="string"&&G.cwd.trim()?G.cwd.trim():this.lastGeneratedDir??this.config.workDir;const ze=this.resolvePath(je);try{const{stdout:G,stderr:je}=await Ci(K,{cwd:ze,timeout:12e4,windowsHide:true,maxBuffer:10*1024*1024});const We=[G,je].filter(Boolean).join("\n");return JSON.stringify({status:"ok",cwd:ze,command:K,output:truncate(We,Mi)},null,2)}catch(G){const je=G;const We=(je.stdout??"").trim();const Xe=(je.stderr??"").trim();const rt=(je.message??"").split("\n");const at=rt.slice(1).join("\n").trim();let ft=[We,Xe,at].filter(Boolean).join("\n").trim();if(!ft||ft===je.message){const ze=je.code===null||je.code===undefined||String(je.code)==="null"||je.killed===false&&!We&&!Xe;if(ze&&(K.includes("tsc")||K.includes("npx"))){ft=["Command crashed with no output - likely JavaScript heap out of memory (V8 OOM).","","DIAGNOSIS: TypeScript type-checking consumed too much memory.","COMMON CAUSE: zodToJsonSchema() called with complex Zod schemas causes recursive type inference.","FIX: In server.ts, replace:",' zodToJsonSchema(mySchema) as Tool["inputSchema"]',"with:",' (zodToJsonSchema as (s: unknown) => Tool["inputSchema"])(mySchema)',"","Or add this helper before the tools array:",' function toInputSchema(schema: unknown): Tool["inputSchema"] {',' return zodToJsonSchema(schema as Parameters<typeof zodToJsonSchema>[0]) as Tool["inputSchema"];'," }","Then use: toInputSchema(mySchema)"].join("\n")}else{ft=je.message??String(G)}}return JSON.stringify({status:"error",cwd:ze,command:K,output:truncate(ft,Mi)},null,2)}}async generateMcp(G){const K=typeof G.source==="string"&&G.source.trim()?G.source:this.lastSource;const je=typeof G.output_dir==="string"&&G.output_dir.trim()?G.output_dir:undefined;if(!K){return JSON.stringify({error:"Missing required argument: source"})}const ze=[];const We=je??(0,at.resolve)(this.config.workDir,"generated",(0,wt.deriveProjectName)(K));const Xe=await this.generate({source:K,output:We,logger:{log:G=>ze.push(G)}});this.lastSource=K;this.lastGeneratedDir=Xe.root;return JSON.stringify({status:"ok",source:K,outputDir:this.lastGeneratedDir,logs:ze},null,2)}async runTests(G){const K=typeof G.dir==="string"&&G.dir.trim()?G.dir:this.lastGeneratedDir;if(!K){return JSON.stringify({error:"Missing required argument: dir"})}const je=this.resolvePath(K);const ze=await this.testRunner.run(je);const We=[ze.stdout,ze.stderr].filter(Boolean).join("\n");return JSON.stringify({dir:je,output:truncate(We,Mi)},null,2)}async testIntegration(G){const K=typeof G.dir==="string"&&G.dir.trim()?G.dir.trim():this.lastGeneratedDir??this.config.workDir;const je=typeof G.base_url==="string"?G.base_url.trim():"";if(!je){return JSON.stringify({error:"base_url is required"})}const ze={};if(G.auth_env&&typeof G.auth_env==="object"&&!Array.isArray(G.auth_env)){for(const[K,je]of Object.entries(G.auth_env)){if(typeof je==="string"){ze[K]=je}}}const We=new vt.IntegrationTester;const rt=this.resolvePath(K);const ft=await We.run({dir:rt,baseUrl:je,authEnv:ze});this.lastIntegrationDir=rt;this.lastIntegrationSummary={passed:ft.passed===true,allToolsPassed:ft.allToolsPassed===true,toolsFound:typeof ft.toolsFound==="number"?ft.toolsFound:undefined,failedTools:Array.isArray(ft.toolResults)?ft.toolResults.filter((G=>Boolean(G)&&typeof G.name==="string"&&G.ok===false)).map((G=>({name:G.name,...typeof G.detail==="string"?{detail:G.detail}:{}}))):[]};if(ft.tools&&ft.tools.length>0){const G=(0,at.join)(rt,"manifest.json");try{const K=(0,Xe.existsSync)(G)?JSON.parse((0,Xe.readFileSync)(G,"utf8")):{};K.tools=ft.tools;K.toolsCount=ft.tools.length;(0,Xe.writeFileSync)(G,JSON.stringify(K,null,2)+"\n","utf8")}catch{}}this.persistState();return JSON.stringify(ft,null,2)}async publishMcp(G){const K=typeof G.dir==="string"&&G.dir.trim()?G.dir.trim():this.lastGeneratedDir??this.config.workDir;const je=typeof G.market_url==="string"?G.market_url.trim():"";const ze=typeof G.token==="string"?G.token.trim():"";const We=(0,Si.getToken)();if(ze){(0,Si.saveToken)(ze,je||(0,Si.getMarketUrl)())}else if(je&&We){(0,Si.saveToken)(We,je)}const Xe=this.resolvePath(K);const rt=this.lastIntegrationSummary?.passed===true&&this.lastIntegrationSummary?.allToolsPassed===true&&this.lastIntegrationDir===Xe;if(!rt){return JSON.stringify({error:"Publish blocked: run test_integration on this directory and ensure all discovered tools pass before publish.",expectedDir:Xe,lastIntegrationDir:this.lastIntegrationDir??null,lastIntegration:this.lastIntegrationSummary??null},null,2)}try{const G=await(0,lr.publishCommand)({},Xe);const K=`${G.marketUrl}/repository`;return JSON.stringify({status:"ok",name:G.name,version:G.version,packageUrl:K,marketUrl:G.marketUrl,dir:Xe})}catch(G){return JSON.stringify({error:formatError(G)})}}async showHistory(){const G=this.sessionReader.listSessions(10).map((G=>({file:G.file,time:G.mtime.toISOString(),title:G.preview.replace(/^#\s*/,"").trim()})));const K=this.sessionReader.lastRun(this.config.workDir);return JSON.stringify({recentSessions:G,lastRun:K?{source:K.source,status:K.status,finishedAt:K.finishedAt,toolCount:K.ir?.toolCount??0}:null},null,2)}async recordLearning(G){const K=typeof G.title==="string"?G.title.trim():"";const je=typeof G.problem==="string"?G.problem.trim():"";const ze=typeof G.fix==="string"?G.fix.trim():"";if(!K||!je||!ze){return JSON.stringify({error:"title, problem, and fix are all required"})}const We=(0,at.join)(this.config.workDir,".mcp-claw");const rt=(0,at.join)(We,"patterns.md");if(!(0,Xe.existsSync)(We)){(0,Xe.mkdirSync)(We,{recursive:true})}const ft=Array.isArray(G.tags)?G.tags.filter((G=>typeof G==="string")):[];const mt=(new Date).toISOString().split("T")[0];const vt=[`\n## ${K} (${mt})`,`**Problem**: ${je}`,`**Fix**: ${ze}`,...ft.length>0?[`**Tags**: ${ft.join(", ")}`]:[],""].join("\n");const yt=(0,Xe.existsSync)(rt)?(0,Xe.readFileSync)(rt,"utf8"):"# Learned Patterns\n";(0,Xe.writeFileSync)(rt,yt+vt,"utf8");return JSON.stringify({status:"ok",message:`Pattern "${K}" saved`,file:rt},null,2)}getRecentRounds(G){const K=[];let je=0;while(je<this.history.length){const G=this.history[je];if(G.role==="user"){const ze=typeof G.content==="string"?G.content:"";let We="";let Xe=0;let rt=je+1;while(rt<this.history.length&&this.history[rt].role!=="user"){const G=this.history[rt];if(G.role==="assistant"){if(typeof G.content==="string"&&G.content.trim()){We=G.content}Xe+=Array.isArray(G.tool_calls)?G.tool_calls.length:0}rt++}K.push({userText:ze,assistantText:We,toolCount:Xe});je=rt}else{je++}}return K.slice(-G)}setModel(G){this.llm=new Rr.OpenRouterProvider("openrouter-chat",G,this.config.apiKey,this.config.baseUrl);this.cachedSystemPrompt=undefined;return G}clearHistory(){this.history.length=0;this.lastSource=undefined;this.lastGeneratedDir=undefined;this.lastIntegrationDir=undefined;this.lastIntegrationSummary=undefined;this.persistState()}persistState(){try{savePersistedState(this.config.workDir,{history:this.history,lastSource:this.lastSource,lastGeneratedDir:this.lastGeneratedDir,lastIntegrationDir:this.lastIntegrationDir,lastIntegrationSummary:this.lastIntegrationSummary})}catch{}}writeAssistant(G){this.output.write("\n");this.output.write((0,Ei.renderMarkdown)(G));this.output.write("\n\n")}writeToolStart(G,K){const je=this.toolArgsSummary(G,K);this.output.write(` ${mt.default.dim("...")} ${mt.default.cyan(G)}${je?mt.default.gray(` ${je}`):""}\n`)}writeToolDone(G,K){try{const je=JSON.parse(K);const ze=je.error||je.status==="error"||je.passed===false;if(ze){const K=je.error?String(je.error):this.toolResultSummary(G,je);this.output.write(` ${mt.default.red("x")} ${mt.default.red(K)}\n`)}else{const K=this.toolResultSummary(G,je);this.output.write(` ${mt.default.green("ok")} ${mt.default.dim(K)}\n`)}}catch{const G=K.length>80?`${K.slice(0,80)}...`:K;this.output.write(` ${mt.default.green("ok")} ${mt.default.dim(G)}\n`)}}toolArgsSummary(G,K){switch(G){case"read_folder":case"read_file":case"write_file":case"read_pdf":return typeof K.path==="string"?K.path:"";case"search_files":{const G=typeof K.pattern==="string"?K.pattern:"";const je=typeof K.path==="string"?K.path:"project";return`${G} in ${je}`.trim()}case"fetch_url":return typeof K.url==="string"?K.url:"";case"http_request":{const G=typeof K.method==="string"?K.method.toUpperCase():"GET";const je=typeof K.url==="string"?K.url:"";return`${G} ${je}`.trim()}case"crawl_docs":{const G=typeof K.start_url==="string"?K.start_url:"";const je=typeof K.max_pages==="number"?K.max_pages:qs;return`${G} (max ${je} pages)`}case"discover_docs":return typeof K.query==="string"?K.query:"";case"sga_search":{const G=typeof K.q==="string"?K.q:"";const je=typeof K.preset==="string"?K.preset:"chinese";return`${G} (${je})`.trim()}case"parse_openapi":return typeof K.source==="string"?K.source:"";case"run_command":return typeof K.command==="string"?K.command:"";case"generate_mcp":return typeof K.source==="string"?K.source:"";case"run_tests":case"test_integration":return typeof K.dir==="string"?K.dir:"";case"record_learning":return typeof K.title==="string"?K.title:"";default:return""}}toolResultSummary(G,K){switch(G){case"read_folder":{const G=typeof K.fileCount==="number"?K.fileCount:"?";return`${G} files`}case"read_file":{const G=typeof K.length==="number"?K.length:"?";return`${G} chars`}case"write_file":{const G=typeof K.bytes==="number"?K.bytes:"?";return`${G} bytes written`}case"search_files":{const G=typeof K.totalMatches==="number"?K.totalMatches:0;return`${G} matches`}case"read_pdf":{const G=typeof K.length==="number"?K.length:0;return`${G} chars extracted`}case"fetch_url":return typeof K.title==="string"?K.title:"fetched";case"http_request":{const G=typeof K.status==="number"?K.status:"?";return`HTTP ${G}`}case"crawl_docs":{const G=typeof K.pagesVisited==="number"?K.pagesVisited:0;const je=typeof K.combinedText==="string"?K.combinedText.length:0;return`${G} pages, ${je} chars`}case"discover_docs":{const G=Array.isArray(K.results)?K.results:[];const je=G.length;const ze=G.map((G=>G&&typeof G==="object"?G.url:undefined)).filter((G=>typeof G==="string")).slice(0,3);return`${je} results found${ze.length>0?`: ${ze.join(", ")}`:""}`}case"sga_search":{const G=typeof K.total==="number"?K.total:0;return`${G} results`}case"parse_openapi":{const G=typeof K.endpointCount==="number"?K.endpointCount:0;const je=Array.isArray(K.auth)?K.auth.filter((G=>typeof G==="string")):[];return`${G} endpoints, ${je.length>0?je.join("+"):"no auth"}`}case"run_command":{if(K.status==="ok"){const G=typeof K.output==="string"?(K.output.split("\n").find((G=>G.trim()))??"").slice(0,60):"";return`exit 0${G?` | ${G}`:""}`}const G=typeof K.output==="string"?K.output:"";const je=G.split("\n").map((G=>G.trim())).filter((G=>G&&!G.startsWith("Command failed")&&!G.startsWith("npm warn")&&!G.startsWith("npm notice")));const ze=je.slice(0,3).join(" | ");return`error · ${(ze||G).slice(0,300)}`}case"generate_mcp":{const G=Array.isArray(K.logs)?K.logs:[];return G.length>0?String(G[G.length-1]):"done"}case"run_tests":return typeof K.output==="string"?K.output.split("\n")[0]??"done":"done";case"test_integration":{const G=K.passed===true?"PASS":"FAIL";const je=typeof K.toolsFound==="number"?K.toolsFound:0;const ze=K.allToolsPassed===true;const We=Array.isArray(K.toolResults)?K.toolResults.filter((G=>Boolean(G)&&typeof G==="object"&&G.ok===false)).length:0;const Xe=K.authProbe;const rt=Xe?Xe.authRequired?" | AUTH REQUIRED":" | no auth needed":"";const at=ze?" | all tools passed":` | failed tools: ${We}`;return`${G} · ${je} tools${at}${rt}`}case"publish_mcp":return K.status==="ok"?`published → ${String(K.packageUrl??K.marketUrl??"market")}`:"done";case"show_history":return"loaded";case"record_learning":return K.status==="ok"?`recorded: ${String(K.message??"done")}`:"done";default:return"done"}}}K.ChatSession=ChatSession},2330:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.renderMarkdown=renderMarkdown;const We=ze(je(39559));const Xe=" ";function stripAnsi(G){return G.replace(/\x1b\[[0-9;]*m/g,"")}function visibleLength(G){return stripAnsi(G).length}function padEnd(G,K){const je=K-visibleLength(G);return je>0?G+" ".repeat(je):G}function formatInline(G){let K=G;K=K.replace(/`([^`]+)`/g,((G,K)=>We.default.cyan(K)));K=K.replace(/\*\*([^*]+)\*\*/g,((G,K)=>We.default.bold(K)));K=K.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,((G,K)=>We.default.italic(K)));return K}function isTableSeparator(G){return/^\|[\s:*-]+\|$/.test(G.trim().replace(/[\s:-]+/g,(G=>G)))}function isSeparatorRow(G){const K=G.trim();if(!K.startsWith("|")||!K.endsWith("|"))return false;const je=K.slice(1,-1).split("|");return je.every((G=>/^\s*:?-+:?\s*$/.test(G)))}function parseTableRow(G){const K=G.trim();const je=K.startsWith("|")?K.slice(1):K;const ze=je.endsWith("|")?je.slice(0,-1):je;return ze.split("|").map((G=>G.trim()))}function renderTable(G,K){const je=G.headers.length;const ze=[G.headers,...G.rows];const rt=new Array(je).fill(0);for(const G of ze){for(let K=0;K<je;K++){const je=(G[K]??"").length;if(je>rt[K]){rt[K]=je}}}const at=Xe.length+je*3+1;const ft=Math.max(K-at,je*8);const mt=rt.reduce(((G,K)=>G+K),0);const vt=mt<=ft?rt:rt.map((G=>Math.max(6,Math.floor(G/mt*ft))));const yt=[];const wt=Xe+"┌"+vt.map((G=>"─".repeat(G+2))).join("┬")+"┐";yt.push(We.default.gray(wt));const lr=G.headers.map(((G,K)=>{const je=We.default.bold(truncateCell(G,vt[K]));return" "+padEnd(je,vt[K])+" "}));yt.push(Xe+We.default.gray("│")+lr.join(We.default.gray("│"))+We.default.gray("│"));const Er=Xe+"├"+vt.map((G=>"─".repeat(G+2))).join("┼")+"┤";yt.push(We.default.gray(Er));for(const K of G.rows){const G=K.map(((G,K)=>{const je=formatInline(truncateCell(G,vt[K]));return" "+padEnd(je,vt[K])+" "}));yt.push(Xe+We.default.gray("│")+G.join(We.default.gray("│"))+We.default.gray("│"))}const Rr=Xe+"└"+vt.map((G=>"─".repeat(G+2))).join("┴")+"┘";yt.push(We.default.gray(Rr));return yt}function truncateCell(G,K){if(G.length<=K)return G;return G.slice(0,K-1)+"…"}function renderMarkdown(G){const K=process.stdout.columns||100;const je=G.split("\n");const ze=[];let rt=0;while(rt<je.length){const G=je[rt];const at=G.trim();if(at.startsWith("```")){const G=at.slice(3).trim();if(G){ze.push(Xe+We.default.gray(` ── ${G} ──`))}rt++;const ft=[];while(rt<je.length&&!je[rt].trim().startsWith("```")){ft.push(je[rt]);rt++}for(const G of ft){ze.push(Xe+We.default.green(" "+G))}if(G){ze.push(Xe+We.default.gray(" "+"─".repeat(Math.min(50,K-6))))}rt++;continue}if(at.startsWith("|")&&at.endsWith("|")){const G=[];while(rt<je.length&&je[rt].trim().startsWith("|")&&je[rt].trim().endsWith("|")){G.push(je[rt]);rt++}if(G.length>=2){const je=parseTableRow(G[0]);const We=isSeparatorRow(G[1])?2:1;const Xe=G.slice(We).filter((G=>!isSeparatorRow(G))).map(parseTableRow);const rt=je.length;const at=Xe.map((G=>{while(G.length<rt)G.push("");return G.slice(0,rt)}));ze.push(...renderTable({headers:je,rows:at},K))}else{ze.push(Xe+formatInline(at))}continue}const ft=at.match(/^(#{1,4})\s+(.+)$/);if(ft){const G=ft[1].length;const K=ft[2];ze.push("");if(G===1){ze.push(Xe+We.default.cyan.bold.underline(K))}else if(G===2){ze.push(Xe+We.default.cyan.bold(K))}else if(G===3){ze.push(Xe+We.default.white.bold(K))}else{ze.push(Xe+We.default.white(K))}rt++;continue}if(/^[-*_]{3,}$/.test(at)){ze.push(Xe+We.default.gray("─".repeat(Math.min(50,K-4))));rt++;continue}const mt=G.match(/^(\s*)[-*+]\s+(.+)$/);if(mt){const G=Math.floor(mt[1].length/2);const K=G===0?"•":G===1?"◦":"‣";ze.push(Xe+" ".repeat(G)+We.default.gray(K)+" "+formatInline(mt[2]));rt++;continue}const vt=G.match(/^(\s*)(\d+)\.\s+(.+)$/);if(vt){const G=Math.floor(vt[1].length/2);ze.push(Xe+" ".repeat(G)+We.default.gray(vt[2]+".")+" "+formatInline(vt[3]));rt++;continue}if(at.startsWith(">")){const G=at.replace(/^>\s*/,"");ze.push(Xe+We.default.gray("│ ")+We.default.italic(formatInline(G)));rt++;continue}if(!at){ze.push("");rt++;continue}ze.push(Xe+formatInline(at));rt++}return ze.join("\n")}},66191:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.buildToolDefinitions=buildToolDefinitions;function buildToolDefinitions(G){return[{type:"function",function:{name:"read_folder",description:["List files in a local directory. Returns ONLY file names, sizes, and types — NO file content.","Use this first to discover what files exist, then call read_file on each relevant file.",`If path is omitted, default to current working directory: ${G.workDir}.`].join(" "),parameters:{type:"object",properties:{path:{type:"string",description:`Optional folder path. Relative paths are resolved from ${G.workDir}.`}},required:[],additionalProperties:false}}},{type:"function",function:{name:"read_file",description:["Read the FULL content of a single file. ALWAYS call this after read_folder to get actual file content.","read_folder only lists file names — this tool reads the content.","Call this for EVERY relevant file discovered by read_folder."].join(" "),parameters:{type:"object",properties:{path:{type:"string",description:`File path. Relative paths are resolved from ${G.workDir}.`}},required:["path"],additionalProperties:false}}},{type:"function",function:{name:"fetch_url",description:["Fetch content from a remote http/https URL.","ONLY use when the user explicitly provides a URL starting with http:// or https://.","Do NOT call this for local files, folders, or paths. Use read_folder instead for anything local."].join(" "),parameters:{type:"object",properties:{url:{type:"string",description:"Target documentation URL"}},required:["url"],additionalProperties:false}}},{type:"function",function:{name:"write_file",description:["Create or overwrite a file with the given content.","Use this to create config files, fix generated code, or add missing files."].join(" "),parameters:{type:"object",properties:{path:{type:"string",description:`Target file path. Relative paths are resolved from ${G.workDir}.`},content:{type:"string",description:"Full file content to write."}},required:["path","content"],additionalProperties:false}}},{type:"function",function:{name:"search_files",description:["Search for a pattern in files within a directory and return matching lines.","Use this like grep to quickly locate endpoints, auth keys, or code symbols."].join(" "),parameters:{type:"object",properties:{pattern:{type:"string",description:"Pattern to search (case-insensitive regex)."},path:{type:"string",description:"Optional root directory. Defaults to last generated directory or current project."},glob:{type:"string",description:"Optional file glob, for example *.ts, *.md. Defaults to *."}},required:["pattern"],additionalProperties:false}}},{type:"function",function:{name:"read_pdf",description:"Extract text content from a PDF file, useful for PDF API documentation.",parameters:{type:"object",properties:{path:{type:"string",description:`PDF file path. Relative paths are resolved from ${G.workDir}.`}},required:["path"],additionalProperties:false}}},{type:"function",function:{name:"http_request",description:["Make an HTTP request to probe or test an API endpoint.","Use this to test endpoint behavior or check if a URL returns an OpenAPI spec."].join(" "),parameters:{type:"object",properties:{url:{type:"string",description:"Target URL."},method:{type:"string",description:"HTTP method. Defaults to GET."},headers:{type:"object",description:"Optional request headers.",additionalProperties:{type:"string"}},body:{type:"string",description:"Optional request body as string."},timeout_ms:{type:"number",description:"Request timeout in milliseconds. Defaults to 10000."}},required:["url"],additionalProperties:false}}},{type:"function",function:{name:"crawl_docs",description:["Crawl multiple pages of API documentation starting from a URL.","Follows same-domain links, optionally filtered by a link regex pattern."].join(" "),parameters:{type:"object",properties:{start_url:{type:"string",description:"Starting documentation URL."},max_pages:{type:"number",description:"Maximum pages to crawl. Default 10, max 30."},link_pattern:{type:"string",description:"Optional regex to filter links to follow, for example /docs/ or /api/."}},required:["start_url"],additionalProperties:false}}},{type:"function",function:{name:"discover_docs",description:["Search the web for official API documentation by product/service name.","Use when the user does not provide a docs URL."].join(" "),parameters:{type:"object",properties:{query:{type:"string",description:"Search query, for example Stripe API documentation."},max_results:{type:"number",description:"Maximum number of results to return. Defaults to 5."}},required:["query"],additionalProperties:false}}},{type:"function",function:{name:"sga_search",description:"Search the web using the SGA search engine. Supports Chinese search, WeChat articles, and enriched full-text extraction. Use this when you need to find information, research APIs, or look up documentation.",parameters:{type:"object",properties:{q:{type:"string",description:"Search query"},preset:{type:"string",enum:["chinese","wechat","general"],description:"Search preset. Defaults to chinese."},limit:{type:"number",description:"Result limit. Defaults to 5, max 50."},sort:{type:"string",enum:["time","relevance"],description:"Sort mode. Defaults to time."},depth:{type:"string",enum:["basic","enriched"],description:"Result depth. Defaults to basic."}},required:["q"],additionalProperties:false}}},{type:"function",function:{name:"parse_openapi",description:"Parse an OpenAPI/Swagger specification from a URL or file path. Extracts endpoints, parameters, auth schemes, and data models in a structured format.",parameters:{type:"object",properties:{source:{type:"string",description:"URL (http/https) or local file path to OpenAPI JSON/YAML"},max_endpoints:{type:"number",description:"Maximum endpoints returned. Defaults to 100."}},required:["source"],additionalProperties:false}}},{type:"function",function:{name:"run_command",description:["Execute a shell command in the project directory.","Use this to install dependencies (npm install), compile code (npx tsc),","run tests (npx jest), check project structure (ls, cat), fix issues, etc.","You can run ANY command needed to set up, build, test, or debug the generated server.","Always check the output and fix problems iteratively, just like a human developer would."].join(" "),parameters:{type:"object",properties:{command:{type:"string",description:'Shell command to execute, e.g. "npm install jest --save-dev" or "npx tsc --noEmit"'},cwd:{type:"string",description:`Working directory. Defaults to last generated project or ${G.workDir}.`}},required:["command"],additionalProperties:false}}},{type:"function",function:{name:"generate_mcp",description:["Generate MCP server code from analyzed source content.","Use after enough documentation context is collected and the user confirms generation."].join(" "),parameters:{type:"object",properties:{source:{type:"string",description:"Source folder path or URL"},output_dir:{type:"string",description:"Optional output directory for generated files"}},required:["source"],additionalProperties:false}}},{type:"function",function:{name:"run_tests",description:["Run tests against a generated MCP server project.","Use this after generation or when the user asks to verify quality."].join(" "),parameters:{type:"object",properties:{dir:{type:"string",description:"Directory containing generated server code"}},required:["dir"],additionalProperties:false}}},{type:"function",function:{name:"test_integration",description:["Build the generated MCP server, start it as a subprocess, then perform real MCP tools/list and tools/call connectivity checks.","Use this after generate_mcp and run_tests.","Requires base_url; auth_env is optional key/value credentials.","This test validates every discovered tool. Publish only after all tools pass."].join(" "),parameters:{type:"object",properties:{dir:{type:"string",description:"Path to generated MCP server. Defaults to last generated directory."},base_url:{type:"string",description:"Real upstream API base URL, for example https://api.myservice.com"},auth_env:{type:"object",description:'Optional credentials as env vars, for example {"MY_API_KEY":"sk-xxx"}',additionalProperties:{type:"string"}}},required:["base_url"],additionalProperties:false}}},{type:"function",function:{name:"publish_mcp",description:["Publish generated MCP package to SGA Market using manifest.json in the target directory.","Use after successful integration testing.","Can accept market_url/token overrides; otherwise defaults to local login config."].join(" "),parameters:{type:"object",properties:{dir:{type:"string",description:"Path containing generated manifest.json. Defaults to last generated directory."},market_url:{type:"string",description:"Optional market URL override."},token:{type:"string",description:"Optional auth token override."}},required:[],additionalProperties:false}}},{type:"function",function:{name:"show_history",description:"Show previous MCP SERVER GENERATION RUNS (not chat history). Use this to see: which MCPs were generated, their status (pass/fail), tool counts. Do NOT use this to find chat context — your conversation history is already in your message context.",parameters:{type:"object",properties:{},additionalProperties:false}}},{type:"function",function:{name:"record_learning",description:["Record a lesson learned from fixing a bug or error.","ALWAYS call this after completing an error→fix→verify cycle:"," - run_command failed → you diagnosed the cause → write_file fixed it → run_command passed","The pattern gets saved to .mcp-claw/patterns.md and loaded in future sessions.","This is how the agent evolves and avoids repeating the same mistakes."].join(" "),parameters:{type:"object",properties:{title:{type:"string",description:'Short title of the problem, < 60 chars. e.g. "Missing zod dependency in generated project"'},problem:{type:"string",description:"What the error was. Include error message or code if helpful."},fix:{type:"string",description:"What fixed it. Be specific: which file was changed, what command was run."},tags:{type:"array",items:{type:"string"},description:'Optional tags e.g. ["typescript", "windows", "pnpm", "missing-dep"]'}},required:["title","problem","fix"],additionalProperties:false}}}]}},28123:function(__unused_webpack_module,exports,__nccwpck_require__){"use strict";var __importDefault=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(exports,"__esModule",{value:true});exports.createCli=createCli;exports.main=main;const commander_1=__nccwpck_require__(61414);const chalk_1=__importDefault(__nccwpck_require__(39559));const chat_config_1=__nccwpck_require__(66015);const chat_loop_1=__nccwpck_require__(48347);const config_command_1=__nccwpck_require__(77855);const generate_command_1=__nccwpck_require__(72966);const hub_command_1=__nccwpck_require__(15372);const install_command_1=__nccwpck_require__(98160);const login_command_1=__nccwpck_require__(81198);const logout_command_1=__nccwpck_require__(44731);const memory_command_1=__nccwpck_require__(55418);const publish_command_1=__nccwpck_require__(26120);const run_command_1=__nccwpck_require__(60390);const test_command_1=__nccwpck_require__(28713);function createCli(){const G=new commander_1.Command;G.name("mcp-claw").description("AI-powered MCP server generator").version("0.2.0");G.command("run").description("Run MCP Claw agent loop").requiredOption("--root <path>","Workspace root path").option("--report-to <url>","Backend URL for progress reporting").action((async G=>{await(0,run_command_1.runCommand)({root:G.root,logger:console,reportTo:G.reportTo})}));G.command("generate <source>").description("Generate an MCP server from a folder or URL").option("-o, --output <dir>").option("--publish").action((async(G,K)=>{await(0,generate_command_1.generateCommand)({source:G,output:K.output,publish:K.publish,logger:console})}));(0,config_command_1.registerConfigCommand)(G);(0,login_command_1.registerLoginCommand)(G);(0,logout_command_1.registerLogoutCommand)(G);(0,memory_command_1.registerMemoryCommand)(G);(0,publish_command_1.registerPublishCommand)(G);(0,install_command_1.registerInstallCommand)(G);(0,hub_command_1.registerHubCommand)(G);(0,test_command_1.registerTestCommand)(G);G.action((async()=>{const G=(0,chat_config_1.loadChatConfig)();await(0,chat_loop_1.startChatLoop)(G)}));return G}async function main(G=process.argv){const K=createCli();await K.parseAsync(G)}if(require.main===require.cache[eval("__filename")]){main().catch((G=>{const K=G instanceof Error?G.message:String(G);console.error(chalk_1.default.red(K));process.exitCode=1}))}},77855:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.showConfig=showConfig;K.setConfig=setConfig;K.setSgaConfig=setSgaConfig;K.testConfig=testConfig;K.registerConfigCommand=registerConfigCommand;const We=je(73024);const Xe=je(76760);const rt=ze(je(39559));const at=je(18296);const ft=je(49904);const mt=["google/gemini-3-flash-preview","minimax/minimax-m2.5"];const vt=new Set(mt);const yt="https://openrouter.ai/api/v1";function findEnvPath(G,K=4){let je=(0,Xe.resolve)(G);for(let G=0;G<=K;G+=1){const G=(0,Xe.resolve)(je,".env");if((0,We.existsSync)(G)){return G}const K=(0,Xe.dirname)(je);if(K===je){break}je=K}throw new Error("Unable to locate .env file from current directory (searched up to 4 levels).")}function parseEnvState(G){const K=(0,We.readFileSync)(G,"utf8");const je=K.split(/\r?\n/);const ze=new Map;for(const G of je){const K=G.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);if(!K){continue}ze.set(K[1],K[2])}return{path:G,lines:je,values:ze}}function writeEnvState(G){(0,We.writeFileSync)(G.path,`${G.lines.join("\n")}\n`,"utf8")}function upsertEnvKey(G,K,je){const ze=new RegExp(`^${K}=.*$`);const We=`${K}=${je}`;const Xe=G.lines.findIndex((G=>ze.test(G)));if(Xe>=0){G.lines[Xe]=We}else{G.lines.push(We)}G.values.set(K,je)}function currentConfig(G){return{parserModel:G.values.get("LLM_PARSER_MODEL")??"",coderModel:G.values.get("LLM_CODER_MODEL")??"",agentModel:G.values.get("LLM_AGENT_MODEL")??"",apiKey:G.values.get("OPENROUTER_API_KEY")??"",baseUrl:G.values.get("OPENROUTER_BASE_URL")??yt}}function validateModel(G,K){if(!vt.has(G)){throw new Error(`Invalid ${K} model: ${G}\nAllowed models:\n- ${mt.join("\n- ")}`)}}function parseConfigValue(G){const K=G.trim();const je=K.toLowerCase();if(je==="true"){return true}if(je==="false"){return false}if(/^-?\d+(\.\d+)?$/.test(K)){return Number(K)}return G}function showConfig(G=console,K=process.cwd()){const je=findEnvPath(K);const ze=parseEnvState(je);const We=currentConfig(ze);const Xe=[["OPENROUTER_BASE_URL",We.baseUrl],["LLM_PARSER_MODEL",We.parserModel],["LLM_CODER_MODEL",We.coderModel],["LLM_AGENT_MODEL",We.agentModel],["OPENROUTER_API_KEY",We.apiKey]];const ft=Math.max(...Xe.map((([G])=>G.length)));G.log(rt.default.gray(`.env: ${je}`));for(const[K,je]of Xe){const ze=je.length>0?je:"(empty)";G.log(`${rt.default.cyan(K.padEnd(ft))} = ${rt.default.green(ze)}`)}const mt=new at.SgaConfig;const vt=mt.getAll();G.log("");G.log(rt.default.gray(`~/.sga/config.yaml: ${at.DEFAULT_CONFIG_PATH}`));if(Object.keys(vt).length===0){G.log(rt.default.yellow("(empty)"))}else{G.log(rt.default.green(JSON.stringify(vt,null,2)))}}function setConfig(G,K=console,je=process.cwd()){const ze=findEnvPath(je);const We=parseEnvState(ze);const Xe=[];if(typeof G.parser==="string"){validateModel(G.parser,"--parser");Xe.push(["LLM_PARSER_MODEL",G.parser])}if(typeof G.coder==="string"){validateModel(G.coder,"--coder");Xe.push(["LLM_CODER_MODEL",G.coder])}if(typeof G.agent==="string"){validateModel(G.agent,"--agent");Xe.push(["LLM_AGENT_MODEL",G.agent])}if(typeof G.key==="string"){Xe.push(["OPENROUTER_API_KEY",G.key])}if(Xe.length===0){throw new Error("No config field specified. Use --parser, --coder, --agent, or --key.")}for(const[G,K]of Xe){upsertEnvKey(We,G,K)}writeEnvState(We);K.log(rt.default.green(`Updated ${Xe.length} setting(s) in ${ze}`));const ft=new at.SgaConfig;if(typeof G.key==="string"){ft.set("openrouter.apiKey",G.key)}if(typeof G.parser==="string"){ft.set("model.parser",G.parser)}if(typeof G.coder==="string"){ft.set("model.coder",G.coder)}if(typeof G.agent==="string"){ft.set("model.agent",G.agent)}K.log(rt.default.green(`Synced to ${at.DEFAULT_CONFIG_PATH}`))}function setSgaConfig(G,K,je=console){const ze=new at.SgaConfig;ze.set(G,K);je.log(rt.default.green(`Updated ${G} in ${at.DEFAULT_CONFIG_PATH}`))}async function testConfig(G=console,K=process.cwd()){const je=findEnvPath(K);const ze=parseEnvState(je);const We=currentConfig(ze);const Xe=We.parserModel||"anthropic/claude-haiku-4.5";const at=We.apiKey;const mt=We.baseUrl||yt;if(!at){G.error(rt.default.red("Connection failed: OPENROUTER_API_KEY is empty"));process.exitCode=1;return}const vt=new ft.OpenRouterProvider("openrouter-test",Xe,at,mt);try{await vt.complete("Reply with exactly: pong");G.log(rt.default.green(`OpenRouter reachable, model: ${Xe}`))}catch(K){const je=K instanceof Error?K.message:String(K);G.error(rt.default.red(`Connection failed: ${je}`));process.exitCode=1}}function registerConfigCommand(G){const K=G.command("config").description("Show and update LLM/OpenRouter configuration");K.command("show").description("Show settings from .env and ~/.sga/config.yaml").action((()=>{showConfig(console)}));K.command("set <key> <value>").description("Set a key in ~/.sga/config.yaml (supports dot notation)").action(((G,K)=>{setSgaConfig(G,parseConfigValue(K),console)}));K.command("set-env").description("Update one or more model settings in .env").option("--parser <model>","Set LLM_PARSER_MODEL").option("--coder <model>","Set LLM_CODER_MODEL").option("--agent <model>","Set LLM_AGENT_MODEL").option("--key <apiKey>","Set OPENROUTER_API_KEY").action((G=>{setConfig(G,console)}));K.command("test").description("Test OpenRouter connectivity").action((async()=>{await testConfig(console)}))}},72966:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.isUrl=isUrl;K.deriveProjectName=deriveProjectName;K.generateCommand=generateCommand;const ze=je(73024);const We=je(76760);const Xe=je(60390);function isUrl(G){return/^https?:\/\//i.test(G)}function deriveProjectName(G){let K;if(isUrl(G)){try{const je=new URL(G);const ze=je.hostname.replace(/^www\./,"");const We=je.pathname.split("/").filter(Boolean)[0]??"";K=We?`${ze}-${We}`:ze}catch{K="api"}}else{K=(0,We.basename)(G,(0,We.extname)(G))}const je=K.replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-+|-+$/g,"").toLowerCase();return`mcp-server-${je||"generated"}`}async function generateCommand(G){const K=G.logger??console;const je=G.source;let rt;let at;let ft;if(isUrl(je)){const K=deriveProjectName(je);rt=G.output??(0,We.resolve)(process.cwd(),K);at=[je]}else{const K=(0,We.resolve)(je);if(!(0,ze.existsSync)(K)){throw new Error(`Source path not found: ${K}`)}if((0,ze.statSync)(K).isFile()){const je=deriveProjectName(K);rt=G.output??(0,We.resolve)((0,We.dirname)(K),je);ft=[(0,ze.readFileSync)(K,"utf8")];at=[]}else{rt=G.output??K;at=[]}}await(0,Xe.runCommand)({root:rt,urls:at,rawDocs:ft,logger:K,dryRun:G.dryRun});if(G.publish){K.log("Publish requested. Use `sga publish` after generation completes.")}return{root:rt}}},15372:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.hubConnectCommand=hubConnectCommand;K.hubStatusCommand=hubStatusCommand;K.registerHubCommand=registerHubCommand;const We=je(31421);const Xe=je(73024);const rt=ze(je(76760));const at=ze(je(39559));const ft=je(18296);const mt="http://localhost:3000/api/mcp";function isRecord(G){return Boolean(G)&&typeof G==="object"&&!Array.isArray(G)}function readConfiguredHubUrl(){const G=new ft.SgaConfig;const K=G.get("hub.url");if(typeof K!=="string"){return null}const je=K.trim();return je.length>0?je:null}function normalizeHubUrl(G){const K=new URL(G);const je=K.pathname.replace(/\/+$/,"");if(je===""||je==="/"){K.pathname="/api/mcp"}else if(je.endsWith("/api/mcp/connect")){K.pathname=je.slice(0,-"/connect".length)}else if(je.endsWith("/api/mcp")){K.pathname=je}else{K.pathname=`${je}/api/mcp`}K.search="";K.hash="";return K.toString().replace(/\/$/,"")}function getConnectEndpoint(G){const K=new URL(G);K.pathname=`${K.pathname.replace(/\/+$/,"")}/connect`;K.search="";K.hash="";return K.toString()}async function fetchConnectConfig(G){const K=await fetch(getConnectEndpoint(G),{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!K.ok){throw new Error(`Hub responded with HTTP ${K.status}`)}const je=await K.json();const ze=isRecord(je)&&"data"in je?je.data:je;if(!isRecord(ze)||typeof ze.hubName!=="string"||typeof ze.hubSseUrl!=="string"||typeof ze.toolCount!=="number"||!isRecord(ze.clients)){throw new Error("Invalid Hub connect response")}return ze}function saveHubUrl(G){const K=new ft.SgaConfig;K.set("hub.url",G)}function mergeCursorConfig(G,K){const je=isRecord(G)?G:{};const ze={...je,...K};const We=isRecord(je.mcpServers)?je.mcpServers:{};const Xe=isRecord(K.mcpServers)?K.mcpServers:{};ze.mcpServers={...We,...Xe};return ze}function autoConfigureCursor(G){const K=rt.default.resolve(process.cwd(),".cursor","mcp.json");(0,Xe.mkdirSync)(rt.default.dirname(K),{recursive:true});let je={};if((0,Xe.existsSync)(K)){try{je=JSON.parse((0,Xe.readFileSync)(K,"utf8"))}catch{je={}}}const ze=mergeCursorConfig(je,G.clients.cursor.config);(0,Xe.writeFileSync)(K,`${JSON.stringify(ze,null,2)}\n`,"utf8");return K}function printConnectSummary(G){console.log(at.default.bold("\nHub Connect Configuration"));console.log(`${at.default.cyan("Hub")}: ${G.hubName}`);console.log(`${at.default.cyan("SSE URL")}: ${G.hubSseUrl}`);console.log(`${at.default.cyan("Tool Count")}: ${G.toolCount}`);console.log(at.default.bold("\nClient Commands"));console.log(`${at.default.green("Claude Code")}: ${G.clients.claudeCode.command}`);console.log(`${at.default.green("mcp-claw")}: ${G.clients.mcpClaw.command}`);console.log(`${at.default.green("Generic SSE")}: ${G.clients.genericSse.url}`);console.log(at.default.bold("\nClient Config Paths"));console.log(`${at.default.green("Claude Desktop")}: ${G.clients.claudeDesktop.filePath}`);console.log(`${at.default.green("Cursor")}: ${G.clients.cursor.filePath}`);console.log(`${at.default.green("Windsurf")}: ${G.clients.windsurf.filePath}`);console.log(`${at.default.green("VS Code (Copilot)")}: ${G.clients.vscode.filePath}`);console.log(at.default.bold("\nOther Integrations"));console.log(`${at.default.green("Augment")}: ${G.clients.augment.instruction}`);console.log(`${at.default.green("Dify")}: ${G.clients.dify.instruction}`);console.log(`${at.default.green("HiAgent")}: ${G.clients.hiagent.instruction}`);console.log("")}function resolveTargetHubUrl(G){const K=readConfiguredHubUrl();const je=G?.trim()||K||mt;return normalizeHubUrl(je)}async function hubConnectCommand(G,K={}){const je=resolveTargetHubUrl(G);const ze=await fetchConnectConfig(je);const Xe=normalizeHubUrl(ze.hubSseUrl||je);saveHubUrl(Xe);console.log(at.default.green(`Connected to Hub: ${Xe}`));printConnectSummary(ze);if(K.claude){try{console.log(at.default.dim(`Running: ${ze.clients.claudeCode.command}`));(0,We.execSync)(ze.clients.claudeCode.command,{stdio:"inherit"});console.log(at.default.green("Claude Code configured successfully."))}catch(G){const K=G instanceof Error?G.message:String(G);console.warn(at.default.yellow(`Failed to configure Claude Code automatically: ${K}`))}}if(K.cursor){try{const G=autoConfigureCursor(ze);console.log(at.default.green(`Cursor config written to ${G}`))}catch(G){const K=G instanceof Error?G.message:String(G);console.warn(at.default.yellow(`Failed to write Cursor config: ${K}`))}}}async function hubStatusCommand(){const G=readConfiguredHubUrl();if(!G){console.log(at.default.yellow("Hub is not configured. Run: mcp-claw hub connect"));process.exitCode=1;return}const K=normalizeHubUrl(G);try{const G=await fetchConnectConfig(K);console.log(at.default.green("Hub status: connected"));console.log(`${at.default.cyan("URL")}: ${normalizeHubUrl(G.hubSseUrl||K)}`);console.log(`${at.default.cyan("Hub")}: ${G.hubName}`);console.log(`${at.default.cyan("Tool Count")}: ${G.toolCount}`)}catch(G){const K=G instanceof Error?G.message:String(G);console.log(at.default.red("Hub status: disconnected"));console.log(at.default.red(K));process.exitCode=1}}function registerHubCommand(G){const K=G.command("hub").description("Connect and manage MCP Hub settings");K.command("connect [url]").description("Connect to an MCP Hub and save hub.url in config").option("--claude","Automatically run Claude Code setup command").option("--cursor","Automatically write .cursor/mcp.json").action((async(G,K)=>{await hubConnectCommand(G,K)}));K.command("status").description("Check Hub connectivity using configured hub.url").action((async()=>{await hubStatusCommand()}))}},98160:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.installCommand=installCommand;K.registerInstallCommand=registerInstallCommand;const ze=je(26848);const We=je(18296);const Xe=je(72966);const rt=je(26120);function looksLikeFilePath(G){return/[\\/]/.test(G)||/\.[A-Za-z0-9]+$/.test(G)}function toSearchEndpoint(G){const K=new URL(G);return`${K.protocol}//${K.host}/v1/agent/search`}async function ask(G){const K=(0,ze.createInterface)({input:process.stdin,output:process.stdout});try{return(await K.question(G)).trim()}finally{K.close()}}async function discoverSourceByName(G){const K=new We.SgaConfig;const je=K.get("search.url");const ze=typeof je==="string"&&je.trim().length>0?je.trim():process.env.SEARCH_ENGINE_URL?.trim();if(!ze){return null}let Xe;try{Xe=toSearchEndpoint(ze)}catch{return null}const rt=new URL(Xe);rt.searchParams.set("q",`${G} API documentation`);rt.searchParams.set("preset","general");rt.searchParams.set("limit","3");const at=await fetch(rt.toString(),{method:"GET"});if(!at.ok){return null}const ft=await at.json();const mt=ft.results?.find((G=>typeof G.url==="string"&&G.url.length>0))?.url;return typeof mt==="string"?mt:null}async function installCommand(G){const K=G.trim();let je;if((0,Xe.isUrl)(K)){je=K}else if(looksLikeFilePath(K)){je=K}else{const G=await discoverSourceByName(K).catch((()=>null));if(G){je=G;console.log(`Auto-discovered docs URL: ${je}`)}else{const G=await ask("Could not auto-discover docs. Please provide the API docs URL: ");if(!G){throw new Error("Install aborted: no docs URL provided.")}je=G}}const ze=await(0,Xe.generateCommand)({source:je,logger:console});console.log(`Generation completed. Output directory: ${ze.root}`);const We=await ask("Publish to MCP Market? (y/N) ");if(/^y(es)?$/i.test(We)){await(0,rt.publishCommand)({},ze.root)}}function registerInstallCommand(G){G.command("install <name>").description("Generate an MCP server from an API name, URL, or local file").action((async G=>{await installCommand(G)}))}},81198:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.runLogin=runLogin;K.registerLoginCommand=registerLoginCommand;const We=ze(je(80481));const Xe=ze(je(39559));const rt=je(59265);function normalizeMarketUrl(G){return G.replace(/\/+$/,"")}async function verifyToken(G,K){const je=`${normalizeMarketUrl(G)}/auth/verify`;const ze=await fetch(je,{method:"GET",headers:{Authorization:`Bearer ${K}`}});if(!ze.ok){const G=await ze.text();throw new Error(`Token verification failed (${ze.status}): ${G}`)}}function promptHiddenToken(G="Token: "){return new Promise((K=>{const je=We.default.createInterface({input:process.stdin,output:process.stdout,terminal:true});const ze=je;ze.stdoutMuted=false;ze._writeToOutput=G=>{if(ze.stdoutMuted){process.stdout.write("*");return}process.stdout.write(G)};ze.stdoutMuted=false;je.question(G,(G=>{je.close();process.stdout.write("\n");K(G.trim())}));ze.stdoutMuted=true}))}async function runLogin(G){const K=(0,rt.getMarketUrl)();const je=G.token?.trim()||await promptHiddenToken();if(!je){console.error(Xe.default.red("Token is required."));process.exitCode=1;return}try{await verifyToken(K,je);(0,rt.saveToken)(je,K);console.log(Xe.default.green("登录成功"))}catch(G){const K=G instanceof Error?G.message:String(G);console.error(Xe.default.red(K));process.exitCode=1}}function registerLoginCommand(G){G.command("login").description("Login to MCP Market").option("--token <token>","Access token").action((async G=>{await runLogin(G)}))}},44731:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.runLogout=runLogout;K.registerLogoutCommand=registerLogoutCommand;const We=ze(je(39559));const Xe=je(59265);function runLogout(){(0,Xe.clearToken)();console.log(We.default.green("已退出登录"))}function registerLogoutCommand(G){G.command("logout").description("Logout from MCP Market").action((()=>{runLogout()}))}},55418:function(G,K,je){"use strict";var ze=this&&this.__createBinding||(Object.create?function(G,K,je,ze){if(ze===undefined)ze=je;var We=Object.getOwnPropertyDescriptor(K,je);if(!We||("get"in We?!K.__esModule:We.writable||We.configurable)){We={enumerable:true,get:function(){return K[je]}}}Object.defineProperty(G,ze,We)}:function(G,K,je,ze){if(ze===undefined)ze=je;G[ze]=K[je]});var We=this&&this.__setModuleDefault||(Object.create?function(G,K){Object.defineProperty(G,"default",{enumerable:true,value:K})}:function(G,K){G["default"]=K});var Xe=this&&this.__importStar||function(){var ownKeys=function(G){ownKeys=Object.getOwnPropertyNames||function(G){var K=[];for(var je in G)if(Object.prototype.hasOwnProperty.call(G,je))K[K.length]=je;return K};return ownKeys(G)};return function(G){if(G&&G.__esModule)return G;var K={};if(G!=null)for(var je=ownKeys(G),Xe=0;Xe<je.length;Xe++)if(je[Xe]!=="default")ze(K,G,je[Xe]);We(K,G);return K}}();var rt=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.clearSessions=clearSessions;K.registerMemoryCommand=registerMemoryCommand;const at=Xe(je(73024));const ft=je(76760);const mt=rt(je(39559));const vt=je(29441);const yt=je(64109);function shortDate(G,K){const je=Number.isNaN(Date.parse(G))?K:new Date(G);const ze=je.getFullYear();const We=String(je.getMonth()+1).padStart(2,"0");const Xe=String(je.getDate()).padStart(2,"0");const rt=String(je.getHours()).padStart(2,"0");const at=String(je.getMinutes()).padStart(2,"0");return`${ze}-${We}-${Xe} ${rt}:${at}`}function parseSessionFile(G,K,je){const ze=at.readFileSync(G,"utf8");const We=K.replace(/^#\s*/,"").trim()||"(unknown)";const Xe=ze.match(/- 状态:\s*(✅ success|❌ failed)/);const rt=ze.match(/- 工具数:\s*(\d+)/);const ft=ze.match(/- 时间:\s*(.+)/);return{source:We,status:Xe?.[1]==="❌ failed"?"failed":"success",toolCount:Number(rt?.[1]??"0"),time:shortDate(ft?.[1]??"",je)}}function statusLabel(G){return G==="success"?mt.default.green("✅ success"):mt.default.red("❌ failed")}function showLastRun(G,K){const je=G.ir?.toolNames.join(", ")||"(none)";const ze=G.filesWritten.join(", ")||"(none)";K.log("Last run in this project (.sga/last-run.json):");K.log(` Source: ${G.source}`);K.log(` Status: ${statusLabel(G.status)}`);K.log(` Tools: ${je}`);K.log(` Files: ${ze}`);K.log(` Time: ${G.finishedAt} (${G.durationMs}ms)`)}function clearSessions(){const G=(0,yt.resolveGlobalSessionsDir)();at.mkdirSync(G,{recursive:true});const K=at.readdirSync(G).filter((G=>G.endsWith(".md")));for(const je of K){at.unlinkSync((0,ft.join)(G,je))}return K.length}function registerMemoryCommand(G){const K=G.command("memory").description("Inspect and manage SGA memory");K.command("show").description("Show recent sessions").action((()=>{const G=new vt.SessionReader;const K=G.listSessions(10);console.log(mt.default.cyan("Recent sessions (10):"));if(K.length===0){console.log(mt.default.gray(" (none)"));return}K.forEach(((G,K)=>{const je=parseSessionFile(G.file,G.preview,G.mtime);const ze=je.source.length>30?`${je.source.slice(0,27)}...`:je.source;console.log(` ${K+1}. ${ze.padEnd(30)} [${statusLabel(je.status)}] ${je.toolCount} tools ${je.time}`)}))}));K.command("last").description("Show last run for this project").action((()=>{const G=(new vt.SessionReader).lastRun();if(!G){console.log(mt.default.yellow("No run history found in this project."));return}showLastRun(G,console)}));K.command("clear").description("Delete all global session files").action((()=>{const G=clearSessions();console.log(mt.default.green(`Cleared ${G} session file(s).`))}))}},26120:function(G,K,je){"use strict";var ze=this&&this.__createBinding||(Object.create?function(G,K,je,ze){if(ze===undefined)ze=je;var We=Object.getOwnPropertyDescriptor(K,je);if(!We||("get"in We?!K.__esModule:We.writable||We.configurable)){We={enumerable:true,get:function(){return K[je]}}}Object.defineProperty(G,ze,We)}:function(G,K,je,ze){if(ze===undefined)ze=je;G[ze]=K[je]});var We=this&&this.__setModuleDefault||(Object.create?function(G,K){Object.defineProperty(G,"default",{enumerable:true,value:K})}:function(G,K){G["default"]=K});var Xe=this&&this.__importStar||function(){var ownKeys=function(G){ownKeys=Object.getOwnPropertyNames||function(G){var K=[];for(var je in G)if(Object.prototype.hasOwnProperty.call(G,je))K[K.length]=je;return K};return ownKeys(G)};return function(G){if(G&&G.__esModule)return G;var K={};if(G!=null)for(var je=ownKeys(G),Xe=0;Xe<je.length;Xe++)if(je[Xe]!=="default")ze(K,G,je[Xe]);We(K,G);return K}}();var rt=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.publishCommand=publishCommand;K.registerPublishCommand=registerPublishCommand;const at=je(77598);const ft=je(73024);const mt=rt(je(76760));const vt=je(57075);const yt=rt(je(39559));const wt=je(66015);const lr=je(49904);const Er=je(59265);function normalizeBaseUrl(G){return G.replace(/\/+$/,"")}function slugify(G){const K=G.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return K||"generated-package"}async function createTarball(G){const K=await Promise.resolve().then((()=>Xe(je(29200))));return new Promise(((je,ze)=>{const We=[];const Xe=new vt.Writable({write(G,K,je){We.push(Buffer.isBuffer(G)?G:Buffer.from(G));je()}});const rt=K.default("tar",{gzip:true});rt.on("error",ze);Xe.on("finish",(()=>je(Buffer.concat(We))));rt.pipe(Xe);rt.directory(G,false);rt.finalize().catch(ze)}))}function readManifest(G=process.cwd()){const K=mt.default.join(G,"manifest.json");if(!(0,ft.existsSync)(K)){throw new Error(`manifest.json not found at ${K}`)}const je=(0,ft.readFileSync)(K,"utf8");const ze=JSON.parse(je);if(!ze||typeof ze!=="object"){throw new Error("manifest.json must contain a JSON object")}const We=ze;const Xe=Array.isArray(We.tools)?We.tools.map((G=>{if(!G||typeof G!=="object"){return null}const K=G;if(typeof K.name!=="string"||K.name.trim().length===0){return null}return{name:K.name,...typeof K.description==="string"?{description:K.description}:{},...K.inputSchema&&typeof K.inputSchema==="object"?{inputSchema:K.inputSchema}:{}}})).filter((G=>G!==null)):undefined;return{name:typeof We.name==="string"?We.name:undefined,version:typeof We.version==="string"?We.version:undefined,category:typeof We.category==="string"?We.category:undefined,description:typeof We.description==="string"?We.description:undefined,toolsCount:typeof We.toolsCount==="number"?We.toolsCount:undefined,tools:Xe,credentials:Array.isArray(We.credentials)?We.credentials:undefined}}function resolvePublishPayload(G,K){const je=K.name??G.name;const ze=K.version??G.version;const We=K.category??G.category??"other";const Xe=K.description??G.description??"";if(!je||!ze){throw new Error("name and version are required (from options or manifest.json)")}return{name:je,version:ze,category:We,description:Xe,toolsCount:G.toolsCount,tools:G.tools,credentials:G.credentials}}function estimateToolsCount(G){if(!(0,ft.existsSync)(G)){return 0}const K=new Set([".ts",".js",".py"]);const je=[/server\.tool\(/gi,/tools\.add\(/gi,/addTool\(/gi,/@tool/gi,/def\s+tool_/gi];const ze=[G];let We=0;while(ze.length>0){const G=ze.pop();if(!G){continue}let Xe;try{Xe=(0,ft.readdirSync)(G,{withFileTypes:true,encoding:"utf8"})}catch{continue}for(const rt of Xe){const Xe=mt.default.join(G,rt.name);if(rt.isDirectory()){ze.push(Xe);continue}if(!rt.isFile()){continue}const at=mt.default.extname(rt.name).toLowerCase();if(!K.has(at)){continue}try{const G=(0,ft.readFileSync)(Xe,"utf8");for(const K of je){const je=G.match(K);if(je){We+=je.length}}}catch{continue}}}return We}function extractJsonObject(G){const K=G.indexOf("{");const je=G.lastIndexOf("}");if(K===-1||je===-1||je<=K){return null}try{const ze=JSON.parse(G.slice(K,je+1));if(!ze||typeof ze!=="object"||Array.isArray(ze)){return null}return ze}catch{return null}}async function autoEnhanceManifest(G,K){const je=(0,wt.loadChatConfig)(G);if(!je.apiKey){return{}}const ze=mt.default.join(G,"README.md");const We=(0,ft.existsSync)(ze)?(0,ft.readFileSync)(ze,"utf8").slice(0,3e3):"";const Xe=mt.default.join(G,"src");const rt=estimateToolsCount(Xe);const at=new lr.OpenRouterProvider("publish-enhance",je.model,je.apiKey,je.baseUrl);const vt=["You are enhancing MCP package metadata for publishing.","Return JSON only with shape:",'{ "description": string, "category": string, "toolsCount": number }',"category must be one of ['productivity', 'developer-tools', 'data', 'communication', 'ai', 'security', 'other'].","",`Package name: ${K.name}`,`Version: ${K.version}`,`Current category: ${K.category}`,`Current description: ${K.description||"(empty)"}`,`Estimated tools count from source scan: ${rt}`,`Credentials fields count: ${Array.isArray(K.credentials)?K.credentials.length:0}`,"","README excerpt (may be empty):",We||"(empty)","","Rules:","- description should be concise, practical, and at least 20 characters.","- toolsCount should be a non-negative integer.",'- If uncertain, choose category "other".'].join("\n");const yt=await at.complete(vt);const Er=extractJsonObject(yt);if(!Er){return{}}const Rr=typeof Er.description==="string"&&Er.description.trim().length>0?Er.description.trim():undefined;const jr=typeof Er.category==="string"&&Er.category.trim().length>0?Er.category.trim():undefined;const zr=typeof Er.toolsCount==="number"?Er.toolsCount:typeof Er.toolsCount==="string"?Number(Er.toolsCount):Number.NaN;const fi=Number.isFinite(zr)&&zr>=0?Math.floor(zr):rt>0?rt:undefined;return{...Rr?{description:Rr}:{},...jr?{category:jr}:{},...typeof fi==="number"?{toolsCount:fi}:{}}}async function publishCommand(G,K=process.cwd()){const je=(0,Er.getToken)();if(!je){throw new Error("Not logged in. Run `mcp-claw login` first.")}const ze=normalizeBaseUrl((0,Er.getMarketUrl)());const We=readManifest(K);const Xe=resolvePublishPayload(We,G);const rt=G.enhance!==false;if(rt&&Xe.description.trim().length<20){try{const je=await autoEnhanceManifest(K,Xe);let ze=false;if(!G.description&&je.description){Xe.description=je.description;ze=true}if(!G.category&&je.category){Xe.category=je.category;ze=true}if(typeof Xe.toolsCount!=="number"&&typeof je.toolsCount==="number"){Xe.toolsCount=je.toolsCount;ze=true}if(ze){console.log(yt.default.dim("AI enhanced: description + toolsCount"))}}catch(G){const K=G instanceof Error?G.message:String(G);console.warn(yt.default.yellow(`AI enhance skipped: ${K}`))}}const ft=await createTarball(K);const mt=(0,at.createHash)("sha256").update(ft).digest("hex");const vt=slugify(`${Xe.name}-${Xe.version}`);const wt={id:vt,name:Xe.name,version:Xe.version,description:Xe.description||"",category:Xe.category,toolCount:Xe.toolsCount??0,...Xe.tools?{tools:Xe.tools}:{},serverCount:1,sha256:mt,signed:false,downloads:0,publishedAt:(new Date).toISOString(),...Xe.credentials?{credentials:Xe.credentials}:{}};const lr=new FormData;lr.append("file",new Blob([new Uint8Array(ft)],{type:"application/gzip"}),`${vt}.tgz`);lr.append("metadata",JSON.stringify({packageId:vt,manifest:wt,autoDeploy:false}));const Rr=await fetch(`${ze}/packages/sync/push`,{method:"POST",headers:{Authorization:`Bearer ${je}`},body:lr});if(!Rr.ok){const G=await Rr.text();throw new Error(`Publish failed: HTTP ${Rr.status} ${G}`)}const jr=`${ze}/repository`;console.log(yt.default.green(`Published package ${Xe.name}@${Xe.version}`));console.log(yt.default.cyan(`View at: ${jr}`));return{name:Xe.name,version:Xe.version,marketUrl:ze,packageUrl:jr}}function registerPublishCommand(G){G.command("publish").description("Publish local manifest.json to SGA Market").option("--name <name>","Override package name").option("--version <version>","Override package version").option("--category <category>","Override package category").option("--description <description>","Override package description").option("--no-enhance","Skip LLM metadata enhancement before upload").action((async G=>{await publishCommand(G)}))}},60390:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.runCommand=runCommand;const ze=je(73024);const We=je(76760);const Xe=je(18296);const rt=je(4843);const at=je(35440);const ft=je(27275);const mt=je(78536);const vt=je(20052);const yt=je(65402);const wt=je(51792);const lr=je(64109);const Er=je(60403);const Rr=je(74664);const jr=je(68100);const zr=je(49904);const fi=je(61108);const mi=je(75364);const bi=je(65737);const Si=je(20336);const Ei=je(15158);const ki=je(30244);const Ci=je(61301);const Ti="anthropic/claude-sonnet-4.5";const Pi="https://openrouter.ai/api/v1";function normalizeBaseUrl(G){return G.replace(/\/+$/,"")}function loadEnvConfig(G,K=5){let je=(0,We.resolve)(G);for(let G=0;G<=K;G+=1){const G=(0,We.resolve)(je,".env");if((0,ze.existsSync)(G)){const K=(0,ze.readFileSync)(G,"utf8");const je=new Map;for(const G of K.split(/\r?\n/)){const K=G.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);if(K){je.set(K[1],K[2])}}return je}const K=(0,We.dirname)(je);if(K===je){break}je=K}return new Map}function defaultIr(){return{system:{code:"generated-system",baseUrl:"https://example.local",authType:"none"},tools:[{name:"default_tool",description:"Fallback generated tool",method:"GET",path:"/health",needsConfirmation:false,isAsync:false,params:[]}]}}function isIR(G){if(!G||typeof G!=="object"){return false}const K=G;return typeof K.system?.code==="string"&&typeof K.system?.baseUrl==="string"&&typeof K.system?.authType==="string"&&Array.isArray(K.tools)}function parsePlanDoc(G){const K=G.trim();if(!K){return defaultIr()}try{const G=JSON.parse(K);if(isIR(G)){return G}}catch{}return defaultIr()}function createCore(G){const K=new rt.InMemoryPackager;return new rt.McpClawCore({parse:async G=>parsePlanDoc(G.content),codegen:async K=>{if(G.dryRun||!G.llmProvider){return[]}const je=(0,rt.buildCodegenPrompt)(K);const ze=await G.llmProvider.complete(je);return(0,rt.parseGeneratedFiles)(ze)},sandbox:{runTests:async()=>({passed:true,logs:[],failedTests:[]})},packager:{build:async G=>{const je=await K.build(G);return{...je,files:G.files}}}})}function createExplorer(G){if(!G){return new wt.ExplorerAgent({fsTool:new bi.FsTool,dockerTool:new mi.DockerInspectTool,httpTool:new Si.HttpFetchTool,browserTool:new fi.BrowserTool,pdfTool:new Ei.PdfTool})}return new wt.ExplorerAgent({fsTool:{glob:async()=>[]},dockerTool:{listContainers:async()=>[]},httpTool:{fetch:async G=>({url:G,status:200,body:""})}})}async function postJson(G,K){const je=await fetch(G,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(K)});if(!je.ok){const G=await je.text();throw new Error(`HTTP ${je.status}: ${G}`)}return await je.json()}function nowIso(){return(new Date).toISOString()}async function createReporter(G,K){if(!G){return{reportEvent:async()=>Promise.resolve()}}const je=normalizeBaseUrl(G);try{const G=await postJson(`${je}/monitor/cli-runs`,{root:K});const ze=G.data.runId;return{runId:ze,reportEvent:async G=>{try{await postJson(`${je}/monitor/cli-runs/${ze}/events`,G)}catch{}}}}catch{return{reportEvent:async()=>Promise.resolve()}}}async function runCommand(G){const K=Date.now();const je=G.urls?.[0]??G.root;const We=new lr.SessionWriter;const rt=await createReporter(G.reportTo,G.root);await rt.reportEvent({type:"log",level:"info",message:`CLI run started for ${G.root}`,timestamp:nowIso()});const wt=new Ci.PipelineProgress({silent:Boolean(G.dryRun)});let fi;let mi;let bi=[];try{const lr=loadEnvConfig(G.root);const Si=new Xe.SgaConfig;const Ei=lr.get("OPENROUTER_API_KEY")??process.env.OPENROUTER_API_KEY??Si.get("openrouter.apiKey")??"";const Ci=lr.get("LLM_CODER_MODEL")??process.env.LLM_CODER_MODEL??Si.get("model.coder")??Ti;const Ii=lr.get("OPENROUTER_BASE_URL")??process.env.OPENROUTER_BASE_URL??Si.get("openrouter.baseUrl")??Pi;const Ri=G.urls??[];const Mi=!G.dryRun&&Ei?new zr.OpenRouterProvider("openrouter-coder",Ci,Ei,Ii):undefined;if(!G.dryRun&&!Mi){G.logger.log("Warning: No API key configured. LLM analysis disabled — results will be limited.");G.logger.log(" Run: mcp-claw config set-env --key YOUR_OPENROUTER_KEY")}if(!(0,ze.existsSync)(G.root)){(0,ze.mkdirSync)(G.root,{recursive:true})}fi="Explorer";wt.start("Explorer","scanning sources...");const qi=createExplorer(Boolean(G.dryRun));const Xi=await qi.run({root:G.root,urls:Ri});if(G.rawDocs?.length){Xi.rawDocs=[...G.rawDocs,...Xi.rawDocs??[]]}const ps=Xi.rawDocs?.length??0;const Ls=`found ${Xi.files.length} files`;const qs=ps>0?`, ${ps} docs loaded`:"";const Ws=`${Ls}${qs}`;wt.done("Explorer",Ws);G.logger.log(`Explorer - ${Ws}`);fi="Architect";wt.start("Architect","designing MCP tools...");const Js=new at.ArchitectAgent(Mi?{llmIrGenerator:new ft.LlmIrGenerator(Mi)}:undefined);const eo=await Js.run(Xi);const to=`planned ${eo.ir.tools.length} tools`;wt.done("Architect",to);G.logger.log(`Architect - ${to}`);mi={system:eo.ir.system,toolCount:eo.ir.tools.length,toolNames:eo.ir.tools.map((G=>G.name))};fi="Builder";wt.start("Builder","generating code...");const ro=createCore({dryRun:Boolean(G.dryRun),llmProvider:Mi});const no=new vt.CoreCodegenAdapter(ro);const io=G.dryRun?{install:async()=>Promise.resolve()}:new yt.DependencyInstaller;const so=new mt.BuilderAgent({adapter:no,installer:io});const oo=await so.run({root:G.root,planDoc:G.dryRun?"":JSON.stringify(eo.ir,null,2)});if(!G.dryRun){const K=await(0,ki.writeManifest)(G.root,eo.ir);G.logger.log(`Builder - wrote manifest: ${K}`)}const ao=`wrote ${oo.writtenFiles.length} files`;wt.done("Builder",ao);G.logger.log(`Builder - ${ao}`);bi=oo.writtenFiles;fi="Tester";wt.start("Tester","validating generated server...");let co=false;try{const K=G.dryRun?{run:async()=>({stdout:"Tests: 0 passed, 0 failed, 0 total\nLines : 0%"})}:new Er.TestRunner;const je=new jr.TesterAgent({sandboxAdapter:new Rr.TesterSandboxAdapter({runTests:async()=>({passed:true,logs:[],failedTests:[]})}),runner:K});const ze=await je.run({root:G.root,files:oo.writtenFiles.map((G=>({path:G,content:""})))});co=ze.passed;if(co){wt.done("Tester","PASS");G.logger.log("Tester - PASS")}else{wt.done("Tester","FAIL (non-blocking)");G.logger.log("Tester - FAIL (non-blocking)")}}catch(K){const je=K instanceof Error?K.message:String(K);wt.done("Tester","SKIPPED");G.logger.log(`Tester - skipped: ${je}`)}if(!G.dryRun){const ze={id:`${Date.now()}`,source:je,startedAt:new Date(K).toISOString(),finishedAt:(new Date).toISOString(),status:co?"success":"failed",ir:mi,filesWritten:bi,durationMs:Date.now()-K};We.write(ze,G.root)}fi=undefined;await rt.reportEvent({type:"done",projectId:rt.runId??"cli-run",artifactCount:oo.writtenFiles.length})}catch(ze){const Xe=ze instanceof Error?ze.message:String(ze);if(fi){wt.fail(fi,Xe);G.logger.log(`${fi} - ${Xe}`)}if(!G.dryRun){const ze={id:`${Date.now()}`,source:je,startedAt:new Date(K).toISOString(),finishedAt:(new Date).toISOString(),status:"failed",ir:mi,filesWritten:bi,errorMessage:Xe,durationMs:Date.now()-K};try{We.write(ze,G.root)}catch{}}const at={type:"error",message:Xe};await rt.reportEvent(at);throw ze}}},28713:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.testCommand=testCommand;K.registerTestCommand=registerTestCommand;const We=je(31421);const Xe=je(73024);const rt=je(76760);const at=je(26848);const ft=je(57975);const mt=ze(je(39559));const vt=je(19562);const yt=(0,ft.promisify)(We.exec);function asRecord(G){if(G&&typeof G==="object"&&!Array.isArray(G)){return G}return{}}function sampleValue(G,K){const je=Array.isArray(K.enum)?K.enum:[];if(je.length>0){return je[0]}const ze=G.toLowerCase();const We=typeof K.type==="string"?K.type.toLowerCase():"string";if(ze.includes("url"))return"https://example.com";if(ze==="q"||ze.includes("query")||ze.includes("keyword")||ze.includes("search")){return"test"}if(ze.includes("id"))return"1";switch(We){case"integer":case"number":return 1;case"boolean":return true;case"array":return[];case"object":return{};default:return"test"}}function buildToolArgs(G){const K=asRecord(G);const je=asRecord(K.properties);const ze=Array.isArray(K.required)?K.required.filter((G=>typeof G==="string")):[];const We={};for(const G of ze){We[G]=sampleValue(G,asRecord(je[G]))}return We}function sleep(G){return new Promise((K=>setTimeout(K,G)))}async function ask(G){const K=(0,at.createInterface)({input:process.stdin,output:process.stdout});try{return(await K.question(G)).trim()}finally{K.close()}}async function askHidden(G){if(!process.stdin.isTTY||typeof process.stdin.setRawMode!=="function"){return ask(G)}return new Promise(((K,je)=>{const ze=process.stdin;const We=process.stdout;const Xe=ze.isRaw;let rt="";const cleanup=()=>{ze.off("data",onData);ze.setRawMode(Xe??false);ze.pause();We.write("\n")};const onData=G=>{const ze=G.toString("utf8");if(ze==="\r"||ze==="\n"){cleanup();K(rt.trim());return}if(ze===""){cleanup();je(new Error("Input interrupted"));return}if(ze==="\b"||ze===""){rt=rt.slice(0,-1);return}rt+=ze};We.write(G);ze.setRawMode(true);ze.resume();ze.on("data",onData)}))}function readManifest(G){const K=(0,rt.resolve)(G,"manifest.json");if(!(0,Xe.existsSync)(K)){throw new Error(`manifest.json not found: ${K}`)}const je=(0,Xe.readFileSync)(K,"utf8");const ze=JSON.parse(je);if(!ze||typeof ze!=="object"){throw new Error("manifest.json must be a JSON object")}return ze}async function collectCredentialEnv(G){const K={};for(const je of G){if(!je||typeof je.key!=="string"||je.key.trim().length===0){continue}const G=je.key.trim();const ze=typeof je.label==="string"&&je.label.trim().length>0?je.label.trim():G;const We=je.required===true;const Xe=typeof je.defaultValue==="string"&&je.defaultValue.trim().length>0?je.defaultValue:"";for(;;){const rt=We?" (required)":"";const at=Xe?` [default: ${Xe}]`:"";const ft=` ${ze} (${G})${rt}${at}: `;const vt=je.type==="password"?await askHidden(ft):await ask(ft);const yt=vt||Xe;if(We&&!yt){console.log(mt.default.red(` ${G} is required.`));continue}if(yt){K[G]=yt}break}}return K}function createWaitForResponse(G){return async(K,je=5e3)=>{const ze=Date.now();while(Date.now()-ze<je){const je=G.findIndex((G=>G.id===K));if(je>=0){const[K]=G.splice(je,1);return K}await sleep(25)}throw new Error(`Timeout waiting for MCP response id=${K}`)}}function responseError(G){return Object.prototype.hasOwnProperty.call(G,"error")?G.error:undefined}function responseResult(G){return Object.prototype.hasOwnProperty.call(G,"result")?G.result:undefined}function summarizeConnectionResult(G){if(!G){return"empty result"}if(typeof G==="string"){return G}if(typeof G==="object"&&G!==null){const K=G.content;if(Array.isArray(K)){const G=K.find((G=>G&&typeof G==="object"&&typeof G.text==="string"));if(G?.text){return G.text}}}return JSON.stringify(G)}function ensureEntrypoint(G,K){const je=typeof K.entrypoint==="string"&&K.entrypoint.trim().length>0?K.entrypoint.trim():"dist/index.js";return(0,rt.resolve)(G,je)}async function buildIfNeeded(G,K){if((0,Xe.existsSync)(K)){return}await yt("pnpm install",{cwd:G,timeout:12e4,windowsHide:true});await yt("pnpm run build",{cwd:G,timeout:12e4,windowsHide:true})}async function testCommand(G){const K=(0,rt.resolve)(G);console.log(mt.default.cyan(" Reading manifest.json..."));const je=readManifest(K);const ze=Array.isArray(je.credentials)?je.credentials:[];console.log(mt.default.gray(` Found ${ze.length} credentials`));const at=await collectCredentialEnv(ze);let ft=ensureEntrypoint(K,je);if(!(0,Xe.existsSync)(ft)){console.log(mt.default.cyan(" Entrypoint missing, running pnpm install && pnpm run build..."));await buildIfNeeded(K,ft);ft=ensureEntrypoint(K,je)}if(!(0,Xe.existsSync)(ft)){throw new Error(`Entrypoint not found after build: ${ft}`)}console.log(mt.default.cyan(" Starting MCP server..."));const yt=[];const wt=[];const lr=createWaitForResponse(wt);let Er;let Rr=Buffer.alloc(0);try{Er=(0,We.spawn)("node",[ft],{cwd:K,env:{...process.env,...at},windowsHide:true,stdio:["pipe","pipe","pipe"]});Er.stderr.on("data",(G=>{yt.push(typeof G==="string"?G:G.toString("utf8"))}));Er.stdout.on("data",(G=>{const K=typeof G==="string"?Buffer.from(G):G;Rr=Buffer.concat([Rr,K]);const je=(0,vt.parseMcpMessages)(Rr);Rr=je.rest;wt.push(...je.messages)}));await sleep(2e3);const writeMessage=G=>{if(!Er?.stdin){throw new Error("Server stdin is not available")}Er.stdin.write((0,vt.frameMcpMessage)(G))};writeMessage({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"mcp-claw-test",version:"1.0.0"}}});const G=await lr(1,1e4);if(responseError(G)){throw new Error(`initialize failed: ${JSON.stringify(responseError(G))}`)}console.log(mt.default.green(" OK initialize"));writeMessage({jsonrpc:"2.0",method:"notifications/initialized"});writeMessage({jsonrpc:"2.0",id:2,method:"tools/list"});const je=await lr(2,1e4);if(responseError(je)){throw new Error(`tools/list failed: ${JSON.stringify(responseError(je))}`)}const ze=responseResult(je);const Xe=ze?.tools?.filter((G=>typeof G?.name==="string"))??[];console.log(mt.default.green(` OK tools/list: ${Xe.length} tools`));if(Xe.length>0){console.log(mt.default.gray(` ${Xe.map((G=>G.name)).join(", ")}`))}let rt=3;const jr=Xe.some((G=>G.name==="test_connection"));if(jr){const G=rt++;writeMessage({jsonrpc:"2.0",id:G,method:"tools/call",params:{name:"test_connection",arguments:{}}});const K=await lr(G,1e4);if(responseError(K)){console.log(mt.default.red(` FAIL test_connection: ${JSON.stringify(responseError(K))}`));throw new Error("test_connection failed")}const je=summarizeConnectionResult(responseResult(K));console.log(mt.default.green(` OK test_connection: ${je}`))}const zr=Xe.filter((G=>G.name!=="test_connection"));let fi=0;for(const G of zr){const K=buildToolArgs(G.inputSchema);const je=rt++;writeMessage({jsonrpc:"2.0",id:je,method:"tools/call",params:{name:G.name,arguments:K}});const ze=await lr(je,1e4);const We=responseError(ze);const Xe=responseResult(ze);const at=Boolean(Xe&&Xe.isError===true);if(We||at){fi+=1;console.log(mt.default.red(` FAIL ${G.name}: ${We?JSON.stringify(We):summarizeConnectionResult(Xe)}`))}else{console.log(mt.default.green(` OK ${G.name}`))}}if(fi>0){throw new Error(`${fi}/${zr.length} tools failed`)}console.log("");console.log(mt.default.green(" All checks passed."))}finally{Er?.kill();if(yt.length>0&&process.env.DEBUG){console.log(mt.default.gray("\n Server logs:"));console.log(mt.default.gray(yt.slice(-20).join("")))}}}function registerTestCommand(G){G.command("test [dir]").description("Test MCP server connectivity and credentials").action((async G=>{try{await testCommand(G??process.cwd())}catch(G){const K=G instanceof Error?G.message:String(G);console.error(mt.default.red(` ${K}`));process.exitCode=1}}))}},18296:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.SgaConfig=K.DEFAULT_CONFIG_PATH=void 0;const We=je(73024);const Xe=je(48161);const rt=je(76760);const at=ze(je(15309));K.DEFAULT_CONFIG_PATH=(0,rt.join)((0,Xe.homedir)(),".sga","config.yaml");function isRecord(G){return Boolean(G)&&typeof G==="object"&&!Array.isArray(G)}class SgaConfig{path;constructor(G=K.DEFAULT_CONFIG_PATH){this.path=G}get(G){const K=this.load();const je=G.split(".").filter(Boolean);let ze=K;for(const G of je){if(!isRecord(ze)||!(G in ze)){return undefined}ze=ze[G]}return ze}set(G,K){const je=this.load();const ze=G.split(".").filter(Boolean);if(ze.length===0){throw new Error("Config key must not be empty")}let We=je;for(let G=0;G<ze.length-1;G+=1){const K=ze[G];const je=We[K];if(!isRecord(je)){We[K]={}}We=We[K]}We[ze[ze.length-1]]=K;this.save(je)}getAll(){return this.load()}load(){if(!(0,We.existsSync)(this.path)){return{}}const G=(0,We.readFileSync)(this.path,"utf8");const K=at.default.load(G);if(!isRecord(K)){return{}}return K}save(G){(0,We.mkdirSync)((0,rt.dirname)(this.path),{recursive:true});const K=at.default.dump(G,{lineWidth:-1});(0,We.writeFileSync)(this.path,K,"utf8")}}K.SgaConfig=SgaConfig},49904:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.LlmClientRouter=K.OpenRouterProvider=void 0;function sleep(G){return new Promise((K=>setTimeout(K,G)))}function extractTextContent(G){if(typeof G==="string"){return G}if(Array.isArray(G)){return G.map((G=>typeof G?.text==="string"?G.text:"")).join("\n").trim()}return""}function extractToolCalls(G){if(!Array.isArray(G)){return[]}return G.filter((G=>typeof G?.id==="string"&&(G?.type==="function"||typeof G?.type==="undefined")&&typeof G?.function?.name==="string")).map((G=>({id:G.id,type:"function",function:{name:G.function?.name,arguments:typeof G.function?.arguments==="string"?G.function.arguments:"{}"}})))}class OpenRouterProvider{model;apiKey;baseUrl;name;constructor(G,K,je,ze="https://openrouter.ai/api/v1"){this.model=K;this.apiKey=je;this.baseUrl=ze;this.name=G}async chat(G,K){const je=`${this.baseUrl.replace(/\/+$/,"")}/chat/completions`;const ze=this.model.toLowerCase().includes("minimax");const We=JSON.stringify({model:this.model,messages:G.map((G=>({role:G.role,content:G.content,...G.tool_call_id?{tool_call_id:G.tool_call_id}:{},...G.tool_calls?{tool_calls:G.tool_calls}:{}}))),...!ze&&K&&K.length>0?{tools:K,tool_choice:"auto"}:{},max_tokens:8192});const Xe=3;let rt;for(let G=0;G<Xe;G++){try{const K=new AbortController;const ze=setTimeout((()=>K.abort()),12e4);const Xe=await fetch(je,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","HTTP-Referer":"https://github.com/mcp-claw","X-Title":"MCP-Claw"},body:We,signal:K.signal});clearTimeout(ze);if(Xe.status>=500||Xe.status===429){rt=new Error(`OpenRouter error: ${Xe.status} ${await Xe.text()}`);await sleep(1e3*Math.pow(2,G));continue}if(!Xe.ok){throw new Error(`OpenRouter error: ${Xe.status} ${await Xe.text()}`)}const at=await Xe.json();const ft=at.choices?.[0];const mt=extractTextContent(ft?.message?.content);const vt=extractToolCalls(ft?.message?.tool_calls);const yt=vt.length>0||ft?.finish_reason==="tool_calls"?"tool_calls":"stop";return{content:mt,finish_reason:yt,...vt.length>0?{tool_calls:vt}:{}}}catch(K){rt=K instanceof Error?K:new Error(String(K));const je=rt.message;if(je.includes("fetch failed")||je.includes("Timeout")||je.includes("abort")||je.includes("ECONNRESET")||je.includes("ECONNREFUSED")){await sleep(1e3*Math.pow(2,G));continue}throw rt}}throw rt??new Error("OpenRouter request failed after retries")}async complete(G){const K=await this.chat([{role:"user",content:G}]);return K.content}}K.OpenRouterProvider=OpenRouterProvider;class LlmClientRouter{providers=new Map;constructor(G){for(const K of G){this.providers.set(K.name,K)}}async complete(G){const K=this.providers.get(G.provider);if(!K){throw new Error("provider not found")}return K.complete(G.prompt)}}K.LlmClientRouter=LlmClientRouter},29441:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.SessionReader=void 0;const ze=je(73024);const We=je(76760);const Xe=je(64109);class SessionReader{lastRun(G=process.cwd()){const K=(0,Xe.resolveProjectLastRunPath)(G);if(!(0,ze.existsSync)(K)){return null}try{return JSON.parse((0,ze.readFileSync)(K,"utf8"))}catch{return null}}listSessions(G=20){const K=(0,Xe.resolveGlobalSessionsDir)();if(!(0,ze.existsSync)(K)){return[]}const je=(0,ze.readdirSync)(K).filter((G=>G.endsWith(".md"))).map((G=>(0,We.join)(K,G))).map((G=>({file:G,mtime:(0,ze.statSync)(G).mtime}))).sort(((G,K)=>K.mtime.getTime()-G.mtime.getTime())).slice(0,G);return je.map((G=>{const K=(0,ze.readFileSync)(G.file,"utf8");const je=K.split(/\r?\n/,1)[0]??"";return{file:G.file,mtime:G.mtime,preview:je}}))}}K.SessionReader=SessionReader},64109:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.SessionWriter=void 0;K.resolveProjectStateDir=resolveProjectStateDir;K.resolveProjectLastRunPath=resolveProjectLastRunPath;K.resolveGlobalSessionsDir=resolveGlobalSessionsDir;const ze=je(73024);const We=je(48161);const Xe=je(76760);function pad(G){return String(G).padStart(2,"0")}function toSlug(G){const K=G.trim().replace(/^https?:\/\//i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").toLowerCase();if(!K){return"run"}return K.slice(0,40)}function formatSessionFileName(G){const K=new Date(G.startedAt);const je=[K.getFullYear(),pad(K.getMonth()+1),pad(K.getDate())].join("-");const ze=[pad(K.getHours()),pad(K.getMinutes())].join("-");return`${je}-${ze}-${toSlug(G.source)}.md`}function formatSessionMarkdown(G){const K=G.status==="success"?"✅ success":"❌ failed";const je=G.ir?.toolCount??0;const ze=G.ir?.toolNames.join(", ")||"(none)";const We=G.filesWritten.length>0?G.filesWritten.join(", "):"(none)";const Xe=[`# ${G.source}`,`- 时间:${G.startedAt}`,`- 状态:${K}`,`- 工具数:${je}`,`- 工具列表:${ze}`,`- 生成文件:${We}`,`- 耗时:${G.durationMs}ms`];if(G.errorMessage){Xe.push(`- 错误:${G.errorMessage}`)}return`${Xe.join("\n")}\n`}function resolveProjectStateDir(G=process.cwd()){return(0,Xe.join)(G,".sga")}function resolveProjectLastRunPath(G=process.cwd()){return(0,Xe.join)(resolveProjectStateDir(G),"last-run.json")}function resolveHomeDir(){return process.env.SGA_HOME||(0,We.homedir)()}function resolveGlobalSessionsDir(G=resolveHomeDir()){return(0,Xe.join)(G,".sga","sessions")}class SessionWriter{write(G,K=process.cwd()){const je=resolveProjectStateDir(K);(0,ze.mkdirSync)(je,{recursive:true});(0,ze.writeFileSync)(resolveProjectLastRunPath(K),JSON.stringify(G,null,2),"utf8");const We=resolveGlobalSessionsDir();(0,ze.mkdirSync)(We,{recursive:true});(0,ze.writeFileSync)((0,Xe.join)(We,formatSessionFileName(G)),formatSessionMarkdown(G),"utf8")}}K.SessionWriter=SessionWriter},61108:function(G,K,je){"use strict";var ze=this&&this.__createBinding||(Object.create?function(G,K,je,ze){if(ze===undefined)ze=je;var We=Object.getOwnPropertyDescriptor(K,je);if(!We||("get"in We?!K.__esModule:We.writable||We.configurable)){We={enumerable:true,get:function(){return K[je]}}}Object.defineProperty(G,ze,We)}:function(G,K,je,ze){if(ze===undefined)ze=je;G[ze]=K[je]});var We=this&&this.__setModuleDefault||(Object.create?function(G,K){Object.defineProperty(G,"default",{enumerable:true,value:K})}:function(G,K){G["default"]=K});var Xe=this&&this.__importStar||function(){var ownKeys=function(G){ownKeys=Object.getOwnPropertyNames||function(G){var K=[];for(var je in G)if(Object.prototype.hasOwnProperty.call(G,je))K[K.length]=je;return K};return ownKeys(G)};return function(G){if(G&&G.__esModule)return G;var K={};if(G!=null)for(var je=ownKeys(G),Xe=0;Xe<je.length;Xe++)if(je[Xe]!=="default")ze(K,G,je[Xe]);We(K,G);return K}}();Object.defineProperty(K,"__esModule",{value:true});K.BrowserTool=void 0;function normalizeText(G){return G.replace(/\s+/g," ").trim()}function isOpenApiLink(G){return/(openapi|swagger|api-docs|api\.json|api\.ya?ml)/i.test(G)}function unique(G){return[...new Set(G)]}function extractLinksFromHtml(G,K){const je=/href=["']([^"']+)["']/gi;const ze=[];let We;while((We=je.exec(G))!==null){try{ze.push(new URL(We[1],K).href)}catch{}}return unique(ze)}function extractTextFromHtml(G){return G.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<nav[\s\S]*?<\/nav>/gi,"").replace(/<header[\s\S]*?<\/header>/gi,"").replace(/<footer[\s\S]*?<\/footer>/gi,"").replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/\s+/g," ").trim()}function extractTitleFromHtml(G){const K=G.match(/<title[^>]*>([\s\S]*?)<\/title>/i);return K?normalizeText(K[1]):""}async function fetchWithNative(G,K){const je=new AbortController;const ze=setTimeout((()=>je.abort()),K);try{const K=await fetch(G,{signal:je.signal,headers:{"User-Agent":"mcp-claw/1.0"}});const ze=await K.text();const We=K.url||G;const Xe=extractLinksFromHtml(ze,We);return{url:We,html:ze,text:extractTextFromHtml(ze),title:extractTitleFromHtml(ze),links:Xe,openApiUrls:Xe.filter(isOpenApiLink)}}finally{clearTimeout(ze)}}class BrowserTool{async launchBrowser(){const{chromium:G}=await Promise.resolve().then((()=>Xe(je(47885))));return G.launch({headless:true})}async fetch(G,K=3e4){try{return await this.fetchWithBrowser(G,K)}catch(je){const ze=je instanceof Error?je.message:"";if(ze.includes("Executable")||ze.includes("browserType.launch")||ze.includes("Cannot find module")){return fetchWithNative(G,K)}throw je}}async fetchWithBrowser(G,K){const je=await this.launchBrowser();const ze=await je.newContext();const We=await ze.newPage();try{await We.goto(G,{waitUntil:"domcontentloaded",timeout:K});const je=await We.content();const ze=await We.evaluate((()=>{const G=document.title||"";const K=Array.from(document.querySelectorAll("a[href]")).map((G=>G.href)).filter(Boolean);const je=document.body.cloneNode(true);if(je){je.querySelectorAll("script,style,nav,header,footer").forEach((G=>G.remove()))}return{title:G,text:je?.innerText??"",links:K}}));const Xe=unique(ze.links);return{url:We.url(),html:je,text:normalizeText(ze.text),title:normalizeText(ze.title),links:Xe,openApiUrls:Xe.filter(isOpenApiLink)}}finally{await ze.close();await je.close()}}}K.BrowserTool=BrowserTool},75364:function(G,K,je){"use strict";var ze=this&&this.__createBinding||(Object.create?function(G,K,je,ze){if(ze===undefined)ze=je;var We=Object.getOwnPropertyDescriptor(K,je);if(!We||("get"in We?!K.__esModule:We.writable||We.configurable)){We={enumerable:true,get:function(){return K[je]}}}Object.defineProperty(G,ze,We)}:function(G,K,je,ze){if(ze===undefined)ze=je;G[ze]=K[je]});var We=this&&this.__setModuleDefault||(Object.create?function(G,K){Object.defineProperty(G,"default",{enumerable:true,value:K})}:function(G,K){G["default"]=K});var Xe=this&&this.__importStar||function(){var ownKeys=function(G){ownKeys=Object.getOwnPropertyNames||function(G){var K=[];for(var je in G)if(Object.prototype.hasOwnProperty.call(G,je))K[K.length]=je;return K};return ownKeys(G)};return function(G){if(G&&G.__esModule)return G;var K={};if(G!=null)for(var je=ownKeys(G),Xe=0;Xe<je.length;Xe++)if(je[Xe]!=="default")ze(K,G,je[Xe]);We(K,G);return K}}();Object.defineProperty(K,"__esModule",{value:true});K.DockerInspectTool=void 0;async function defaultDockerExec(G){const{execa:K}=await Promise.resolve().then((()=>Xe(je(10978))));const{stdout:ze}=await K("docker",G,{timeout:1e4});return{stdout:ze}}class DockerInspectTool{dockerExec;constructor(G=G=>defaultDockerExec(G)){this.dockerExec=G}async listContainers(){try{const{stdout:G}=await this.dockerExec(["ps","--format","{{json .}}"]);return G.split(/\r?\n/).filter(Boolean).map((G=>JSON.parse(G))).map((G=>({id:G.ID,image:G.Image,status:G.Status})))}catch{return[]}}}K.DockerInspectTool=DockerInspectTool},65737:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.FsTool=void 0;const We=je(73024);const Xe=ze(je(76760));const rt=new Set(["node_modules",".git","dist","build",".next",".nuxt","out","coverage",".cache","__pycache__",".venv","venv",".idea",".vscode","vendor","target"]);const at=8;function globToRegex(G){const K=G.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${K}$`,"i")}async function walk(G,K=0){if(K>at)return[];let je;try{je=await We.promises.readdir(G,{withFileTypes:true})}catch{return[]}const ze=[];for(const We of je){const je=We.name;const at=Xe.default.join(G,je);if(We.isDirectory()){if(rt.has(je)||je.startsWith("."))continue;ze.push(...await walk(at,K+1))}else{ze.push(at)}}return ze}class FsTool{async readFile(G){return We.promises.readFile(G,"utf8")}async writeFile(G,K){await We.promises.writeFile(G,K,"utf8")}async glob(G,K){const je=await walk(G);const ze=K.map(globToRegex);return je.filter((G=>{const K=Xe.default.basename(G);return ze.some((G=>G.test(K)))}))}}K.FsTool=FsTool},20336:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.HttpFetchTool=void 0;class HttpFetchTool{fetchImpl;constructor(G=fetch){this.fetchImpl=G}async fetch(G,K=5e3){const je=await this.request({url:G,method:"GET",headers:{accept:"application/json,application/yaml,text/plain,*/*"},timeoutMs:K});return{url:je.url,status:je.status,body:je.body}}async request(G){const K=new AbortController;const je=setTimeout((()=>K.abort()),G.timeoutMs??5e3);try{const je=await this.fetchImpl(G.url,{method:G.method??"GET",signal:K.signal,headers:G.headers,body:G.body});const ze={};je.headers?.forEach(((G,K)=>{ze[K]=G}));return{url:je.url||G.url,status:je.status,statusText:je.statusText||"",headers:ze,body:await je.text()}}finally{clearTimeout(je)}}}K.HttpFetchTool=HttpFetchTool},15158:function(G,K,je){"use strict";var ze=this&&this.__createBinding||(Object.create?function(G,K,je,ze){if(ze===undefined)ze=je;var We=Object.getOwnPropertyDescriptor(K,je);if(!We||("get"in We?!K.__esModule:We.writable||We.configurable)){We={enumerable:true,get:function(){return K[je]}}}Object.defineProperty(G,ze,We)}:function(G,K,je,ze){if(ze===undefined)ze=je;G[ze]=K[je]});var We=this&&this.__setModuleDefault||(Object.create?function(G,K){Object.defineProperty(G,"default",{enumerable:true,value:K})}:function(G,K){G["default"]=K});var Xe=this&&this.__importStar||function(){var ownKeys=function(G){ownKeys=Object.getOwnPropertyNames||function(G){var K=[];for(var je in G)if(Object.prototype.hasOwnProperty.call(G,je))K[K.length]=je;return K};return ownKeys(G)};return function(G){if(G&&G.__esModule)return G;var K={};if(G!=null)for(var je=ownKeys(G),Xe=0;Xe<je.length;Xe++)if(je[Xe]!=="default")ze(K,G,je[Xe]);We(K,G);return K}}();Object.defineProperty(K,"__esModule",{value:true});K.PdfTool=void 0;const rt=je(51455);class PdfTool{async extract(G){const K=await this.extractFromFile(G);return K.text}async extractFromFile(G){const K=await(0,rt.readFile)(G);return this.extractFromBuffer(K)}async extractFromBuffer(G){const{PDFParse:K}=await Promise.resolve().then((()=>Xe(je(95074))));const ze=new K({data:new Uint8Array(G)});try{const[G,K]=await Promise.all([ze.getText(),ze.getInfo()]);return{text:G.text,pages:G.total,info:K.info??{}}}finally{await ze.destroy()}}}K.PdfTool=PdfTool},59265:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.getToken=getToken;K.saveToken=saveToken;K.clearToken=clearToken;K.getMarketUrl=getMarketUrl;const We=je(73024);const Xe=ze(je(48161));const rt=ze(je(76760));const at="https://market.sga.dev";const ft=rt.default.join(Xe.default.homedir(),".sga","config.json");function readConfig(){if(!(0,We.existsSync)(ft)){return{}}try{const G=(0,We.readFileSync)(ft,"utf8");const K=JSON.parse(G);if(!K||typeof K!=="object"){return{}}const je=K;return{token:typeof je.token==="string"?je.token:undefined,marketUrl:typeof je.marketUrl==="string"?je.marketUrl:undefined}}catch{return{}}}function writeConfig(G){(0,We.mkdirSync)(rt.default.dirname(ft),{recursive:true});(0,We.writeFileSync)(ft,`${JSON.stringify(G,null,2)}\n`,"utf8")}function getToken(){const G=readConfig().token?.trim();return G&&G.length>0?G:null}function saveToken(G,K){const je={token:G.trim(),marketUrl:K.trim()||at};writeConfig(je)}function clearToken(){const G=readConfig();const K={marketUrl:G.marketUrl?.trim()||at};writeConfig(K)}function getMarketUrl(){const G=readConfig().marketUrl?.trim();return G&&G.length>0?G:at}},30244:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.writeManifest=writeManifest;const ze=je(73024);const We=je(76760);function toKebab(G){const K=G.replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-|-$/g,"").toLowerCase();return K||"generated"}function toUpperSnake(G){const K=G.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"");return K||"SERVICE"}function buildCredentials(G){const K=toUpperSnake(G.system.code);const je=[];je.push({key:`${K}_BASE_URL`,label:"服务地址",type:"string",required:true,description:`${G.system.code} 的 API 基础地址`});if(G.system.authType!=="none"){je.push({key:`${K}_API_KEY`,label:"API Key",type:"secret",required:true,description:`API key for ${G.system.code}`})}return je}function buildManifest(G){return{name:`mcp-server-${toKebab(G.system.code)}`,version:"1.0.0",description:`MCP server for ${G.system.code} API`,category:"api",toolsCount:G.tools.length,credentials:buildCredentials(G)}}async function writeManifest(G,K,je=ze.promises){const Xe=buildManifest(K);const rt=(0,We.join)(G,"manifest.json");await je.writeFile(rt,JSON.stringify(Xe,null,2),"utf8");return rt}},61301:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.PipelineProgress=void 0;const We=ze(je(39559));const Xe=ze(je(84492));class PipelineProgress{spinner;silent;constructor(G={}){this.silent=Boolean(G.silent)}start(G,K){const je=this.formatMessage(G,K);if(this.silent){console.log(je);return}if(this.spinner?.isSpinning){this.spinner.stop()}this.spinner=(0,Xe.default)(je).start()}done(G,K){const je=this.formatMessage(G,K);if(this.silent){console.log(`${We.default.green("✔")} ${je}`);return}if(this.spinner?.isSpinning){this.spinner.stopAndPersist({symbol:We.default.green("✔"),text:je});return}console.log(`${We.default.green("✔")} ${je}`)}fail(G,K){const je=this.formatMessage(G,K);if(this.silent){console.log(`${We.default.red("✘")} ${je}`);return}if(this.spinner?.isSpinning){this.spinner.stopAndPersist({symbol:We.default.red("✘"),text:je});return}console.log(`${We.default.red("✘")} ${je}`)}formatMessage(G,K){return`${We.default.cyan(G)} ${K}`}}K.PipelineProgress=PipelineProgress},11029:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});var ze=je(55825);class AbortSignal extends ze.EventTarget{constructor(){super();throw new TypeError("AbortSignal cannot be constructed directly")}get aborted(){const G=We.get(this);if(typeof G!=="boolean"){throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this===null?"null":typeof this}`)}return G}}ze.defineEventAttribute(AbortSignal.prototype,"abort");function createAbortSignal(){const G=Object.create(AbortSignal.prototype);ze.EventTarget.call(G);We.set(G,false);return G}function abortSignal(G){if(We.get(G)!==false){return}We.set(G,true);G.dispatchEvent({type:"abort"})}const We=new WeakMap;Object.defineProperties(AbortSignal.prototype,{aborted:{enumerable:true}});if(typeof Symbol==="function"&&typeof Symbol.toStringTag==="symbol"){Object.defineProperty(AbortSignal.prototype,Symbol.toStringTag,{configurable:true,value:"AbortSignal"})}class AbortController{constructor(){Xe.set(this,createAbortSignal())}get signal(){return getSignal(this)}abort(){abortSignal(getSignal(this))}}const Xe=new WeakMap;function getSignal(G){const K=Xe.get(G);if(K==null){throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${G===null?"null":typeof G}`)}return K}Object.defineProperties(AbortController.prototype,{signal:{enumerable:true},abort:{enumerable:true}});if(typeof Symbol==="function"&&typeof Symbol.toStringTag==="symbol"){Object.defineProperty(AbortController.prototype,Symbol.toStringTag,{configurable:true,value:"AbortController"})}K.AbortController=AbortController;K.AbortSignal=AbortSignal;K["default"]=AbortController;G.exports=AbortController;G.exports.AbortController=G.exports["default"]=AbortController;G.exports.AbortSignal=AbortSignal},78352:(G,K,je)=>{var ze=je(25744);var We=je(16928);var Xe=je(55207);var rt=je(27294);var at=je(52838);var ft=je(93294);var mt=je(98875);var vt=G.exports={};var yt=/[\/\\]/g;var processPatterns=function(G,K){var je=[];Xe(G).forEach((function(G){var ze=G.indexOf("!")===0;if(ze){G=G.slice(1)}var We=K(G);if(ze){je=rt(je,We)}else{je=at(je,We)}}));return je};vt.exists=function(){var G=We.join.apply(We,arguments);return ze.existsSync(G)};vt.expand=function(...G){var K=ft(G[0])?G.shift():{};var je=Array.isArray(G[0])?G[0]:G;if(je.length===0){return[]}var Xe=processPatterns(je,(function(G){return mt.sync(G,K)}));if(K.filter){Xe=Xe.filter((function(G){G=We.join(K.cwd||"",G);try{if(typeof K.filter==="function"){return K.filter(G)}else{return ze.statSync(G)[K.filter]()}}catch(G){return false}}))}return Xe};vt.expandMapping=function(G,K,je){je=Object.assign({rename:function(G,K){return We.join(G||"",K)}},je);var ze=[];var Xe={};vt.expand(je,G).forEach((function(G){var rt=G;if(je.flatten){rt=We.basename(rt)}if(je.ext){rt=rt.replace(/(\.[^\/]*)?$/,je.ext)}var at=je.rename(K,rt,je);if(je.cwd){G=We.join(je.cwd,G)}at=at.replace(yt,"/");G=G.replace(yt,"/");if(Xe[at]){Xe[at].src.push(G)}else{ze.push({src:[G],dest:at});Xe[at]=ze[ze.length-1]}}));return ze};vt.normalizeFilesArray=function(G){var K=[];G.forEach((function(G){var je;if("src"in G||"dest"in G){K.push(G)}}));if(K.length===0){return[]}K=_(K).chain().forEach((function(G){if(!("src"in G)||!G.src){return}if(Array.isArray(G.src)){G.src=Xe(G.src)}else{G.src=[G.src]}})).map((function(G){var K=Object.assign({},G);delete K.src;delete K.dest;if(G.expand){return vt.expandMapping(G.src,G.dest,K).map((function(K){var je=Object.assign({},G);je.orig=Object.assign({},G);je.src=K.src;je.dest=K.dest;["expand","cwd","flatten","rename","ext"].forEach((function(G){delete je[G]}));return je}))}var je=Object.assign({},G);je.orig=Object.assign({},G);if("src"in je){Object.defineProperty(je,"src",{enumerable:true,get:function fn(){var je;if(!("result"in fn)){je=G.src;je=Array.isArray(je)?Xe(je):[je];fn.result=vt.expand(K,je)}return fn.result}})}if("dest"in je){je.dest=G.dest}return je})).flatten().value();return K}},57504:(G,K,je)=>{var ze=je(25744);var We=je(16928);var Xe=je(35855);var rt=je(20718);var at=je(90229);var ft=je(12743);var mt=je(2203).Stream;var vt=je(35355).PassThrough;var yt=G.exports={};yt.file=je(78352);yt.collectStream=function(G,K){var je=[];var ze=0;G.on("error",K);G.on("data",(function(G){je.push(G);ze+=G.length}));G.on("end",(function(){var G=Buffer.alloc(ze);var We=0;je.forEach((function(K){K.copy(G,We);We+=K.length}));K(null,G)}))};yt.dateify=function(G){G=G||new Date;if(G instanceof Date){G=G}else if(typeof G==="string"){G=new Date(G)}else{G=new Date}return G};yt.defaults=function(G,K,je){var ze=arguments;ze[0]=ze[0]||{};return ft(...ze)};yt.isStream=function(G){return Xe(G)};yt.lazyReadStream=function(G){return new rt.Readable((function(){return ze.createReadStream(G)}))};yt.normalizeInputSource=function(G){if(G===null){return Buffer.alloc(0)}else if(typeof G==="string"){return Buffer.from(G)}else if(yt.isStream(G)){return G.pipe(new vt)}return G};yt.sanitizePath=function(G){return at(G,false).replace(/^\w+:/,"").replace(/^(\.\.\/|\/)+/,"")};yt.trailingSlashIt=function(G){return G.slice(-1)!=="/"?G+"/":G};yt.unixifyPath=function(G){return at(G,false).replace(/^\w+:/,"")};yt.walkdir=function(G,K,je){var Xe=[];if(typeof K==="function"){je=K;K=G}ze.readdir(G,(function(rt,at){var ft=0;var mt;var vt;if(rt){return je(rt)}(function next(){mt=at[ft++];if(!mt){return je(null,Xe)}vt=We.join(G,mt);ze.stat(vt,(function(G,ze){Xe.push({path:vt,relative:We.relative(K,vt).replace(/\\/g,"/"),stats:ze});if(ze&&ze.isDirectory()){yt.walkdir(vt,K,(function(G,K){if(G){return je(G)}K.forEach((function(G){Xe.push(G)}));next()}))}else{next()}}))})()}))}},29200:(G,K,je)=>{
57
+ */},43730:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{KeyParser:()=>KeyParser,ParserError:()=>ParserError,ariaNodesEqual:()=>ariaNodesEqual,findNewNode:()=>findNewNode,hasPointerCursor:()=>hasPointerCursor,parseAriaSnapshot:()=>parseAriaSnapshot,parseAriaSnapshotUnsafe:()=>parseAriaSnapshotUnsafe,textValue:()=>textValue});G.exports=__toCommonJS(Xe);function ariaNodesEqual(G,K){if(G.role!==K.role||G.name!==K.name)return false;if(!ariaPropsEqual(G,K)||hasPointerCursor(G)!==hasPointerCursor(K))return false;const je=Object.keys(G.props);const ze=Object.keys(K.props);return je.length===ze.length&&je.every((je=>G.props[je]===K.props[je]))}function hasPointerCursor(G){return G.box.cursor==="pointer"}function ariaPropsEqual(G,K){return G.active===K.active&&G.checked===K.checked&&G.disabled===K.disabled&&G.expanded===K.expanded&&G.selected===K.selected&&G.level===K.level&&G.pressed===K.pressed}function parseAriaSnapshotUnsafe(G,K,je={}){const ze=parseAriaSnapshot(G,K,je);if(ze.errors.length)throw new Error(ze.errors[0].message);return ze.fragment}function parseAriaSnapshot(G,K,je={}){const ze=new G.LineCounter;const We={keepSourceTokens:true,lineCounter:ze,...je};const Xe=G.parseDocument(K,We);const at=[];const convertRange=G=>[ze.linePos(G[0]),ze.linePos(G[1])];const addError=G=>{at.push({message:G.message,range:[ze.linePos(G.pos[0]),ze.linePos(G.pos[1])]})};const convertSeq=(K,je)=>{for(const ze of je.items){const Xe=ze instanceof G.Scalar&&typeof ze.value==="string";if(Xe){const G=KeyParser.parse(ze,We,at);if(G){K.children=K.children||[];K.children.push(G)}continue}const rt=ze instanceof G.YAMLMap;if(rt){convertMap(K,ze);continue}at.push({message:"Sequence items should be strings or maps",range:convertRange(ze.range||je.range)})}};const convertMap=(K,je)=>{for(const ze of je.items){K.children=K.children||[];const Xe=ze.key instanceof G.Scalar&&typeof ze.key.value==="string";if(!Xe){at.push({message:"Only string keys are supported",range:convertRange(ze.key.range||je.range)});continue}const rt=ze.key;const ft=ze.value;if(rt.value==="text"){const We=ft instanceof G.Scalar&&typeof ft.value==="string";if(!We){at.push({message:"Text value should be a string",range:convertRange(ze.value.range||je.range)});continue}K.children.push({kind:"text",text:textValue(ft.value)});continue}if(rt.value==="/children"){const We=ft instanceof G.Scalar&&typeof ft.value==="string";if(!We||ft.value!=="contain"&&ft.value!=="equal"&&ft.value!=="deep-equal"){at.push({message:'Strict value should be "contain", "equal" or "deep-equal"',range:convertRange(ze.value.range||je.range)});continue}K.containerMode=ft.value;continue}if(rt.value.startsWith("/")){const We=ft instanceof G.Scalar&&typeof ft.value==="string";if(!We){at.push({message:"Property value should be a string",range:convertRange(ze.value.range||je.range)});continue}K.props=K.props??{};K.props[rt.value.slice(1)]=textValue(ft.value);continue}const mt=KeyParser.parse(rt,We,at);if(!mt)continue;const vt=ft instanceof G.Scalar;if(vt){const G=typeof ft.value;if(G!=="string"&&G!=="number"&&G!=="boolean"){at.push({message:"Node value should be a string or a sequence",range:convertRange(ze.value.range||je.range)});continue}K.children.push({...mt,children:[{kind:"text",text:textValue(String(ft.value))}]});continue}const yt=ft instanceof G.YAMLSeq;if(yt){K.children.push(mt);convertSeq(mt,ft);continue}at.push({message:"Map values should be strings or sequences",range:convertRange(ze.value.range||je.range)})}};const ft={kind:"role",role:"fragment"};Xe.errors.forEach(addError);if(at.length)return{errors:at,fragment:ft};if(!(Xe.contents instanceof G.YAMLSeq)){at.push({message:'Aria snapshot must be a YAML sequence, elements starting with " -"',range:Xe.contents?convertRange(Xe.contents.range):[{line:0,col:0},{line:0,col:0}]})}if(at.length)return{errors:at,fragment:ft};convertSeq(ft,Xe.contents);if(at.length)return{errors:at,fragment:rt};if(ft.children?.length===1&&(!ft.containerMode||ft.containerMode==="contain"))return{fragment:ft.children[0],errors:[]};return{fragment:ft,errors:[]}}const rt={kind:"role",role:"fragment"};function normalizeWhitespace(G){return G.replace(/[\u200b\u00ad]/g,"").replace(/[\r\n\s\t]+/g," ").trim()}function textValue(G){return{raw:G,normalized:normalizeWhitespace(G)}}class KeyParser{static parse(G,K,je){try{return new KeyParser(G.value)._parse()}catch(ze){if(ze instanceof ParserError){const We=K.prettyErrors===false?ze.message:ze.message+":\n\n"+G.value+"\n"+" ".repeat(ze.pos)+"^\n";je.push({message:We,range:[K.lineCounter.linePos(G.range[0]),K.lineCounter.linePos(G.range[0]+ze.pos)]});return null}throw ze}}constructor(G){this._input=G;this._pos=0;this._length=G.length}_peek(){return this._input[this._pos]||""}_next(){if(this._pos<this._length)return this._input[this._pos++];return null}_eof(){return this._pos>=this._length}_isWhitespace(){return!this._eof()&&/\s/.test(this._peek())}_skipWhitespace(){while(this._isWhitespace())this._pos++}_readIdentifier(G){if(this._eof())this._throwError(`Unexpected end of input when expecting ${G}`);const K=this._pos;while(!this._eof()&&/[a-zA-Z]/.test(this._peek()))this._pos++;return this._input.slice(K,this._pos)}_readString(){let G="";let K=false;while(!this._eof()){const je=this._next();if(K){G+=je;K=false}else if(je==="\\"){K=true}else if(je==='"'){return G}else{G+=je}}this._throwError("Unterminated string")}_throwError(G,K=0){throw new ParserError(G,K||this._pos)}_readRegex(){let G="";let K=false;let je=false;while(!this._eof()){const ze=this._next();if(K){G+=ze;K=false}else if(ze==="\\"){K=true;G+=ze}else if(ze==="/"&&!je){return{pattern:G}}else if(ze==="["){je=true;G+=ze}else if(ze==="]"&&je){G+=ze;je=false}else{G+=ze}}this._throwError("Unterminated regex")}_readStringOrRegex(){const G=this._peek();if(G==='"'){this._next();return normalizeWhitespace(this._readString())}if(G==="/"){this._next();return this._readRegex()}return null}_readAttributes(G){let K=this._pos;while(true){this._skipWhitespace();if(this._peek()==="["){this._next();this._skipWhitespace();K=this._pos;const je=this._readIdentifier("attribute");this._skipWhitespace();let ze="";if(this._peek()==="="){this._next();this._skipWhitespace();K=this._pos;while(this._peek()!=="]"&&!this._isWhitespace()&&!this._eof())ze+=this._next()}this._skipWhitespace();if(this._peek()!=="]")this._throwError("Expected ]");this._next();this._applyAttribute(G,je,ze||"true",K)}else{break}}}_parse(){this._skipWhitespace();const G=this._readIdentifier("role");this._skipWhitespace();const K=this._readStringOrRegex()||"";const je={kind:"role",role:G,name:K};this._readAttributes(je);this._skipWhitespace();if(!this._eof())this._throwError("Unexpected input");return je}_applyAttribute(G,K,je,ze){if(K==="checked"){this._assert(je==="true"||je==="false"||je==="mixed",'Value of "checked" attribute must be a boolean or "mixed"',ze);G.checked=je==="true"?true:je==="false"?false:"mixed";return}if(K==="disabled"){this._assert(je==="true"||je==="false",'Value of "disabled" attribute must be a boolean',ze);G.disabled=je==="true";return}if(K==="expanded"){this._assert(je==="true"||je==="false",'Value of "expanded" attribute must be a boolean',ze);G.expanded=je==="true";return}if(K==="active"){this._assert(je==="true"||je==="false",'Value of "active" attribute must be a boolean',ze);G.active=je==="true";return}if(K==="level"){this._assert(!isNaN(Number(je)),'Value of "level" attribute must be a number',ze);G.level=Number(je);return}if(K==="pressed"){this._assert(je==="true"||je==="false"||je==="mixed",'Value of "pressed" attribute must be a boolean or "mixed"',ze);G.pressed=je==="true"?true:je==="false"?false:"mixed";return}if(K==="selected"){this._assert(je==="true"||je==="false",'Value of "selected" attribute must be a boolean',ze);G.selected=je==="true";return}this._assert(false,`Unsupported attribute [${K}]`,ze)}_assert(G,K,je){if(!G)this._throwError(K||"Assertion error",je)}}class ParserError extends Error{constructor(G,K){super(G);this.pos=K}}function findNewNode(G,K){function fillMap(G,K,je){let ze=1;let We=je+ze;for(const je of G.children||[]){if(typeof je==="string"){ze++;We++}else{ze+=fillMap(je,K,We);We+=ze}}if(!["none","presentation","fragment","iframe","generic"].includes(G.role)&&G.name){let We=K.get(G.role);if(!We){We=new Map;K.set(G.role,We)}const Xe=We.get(G.name);const rt=ze*100-je;if(!Xe||Xe.sizeAndPosition<rt)We.set(G.name,{node:G,sizeAndPosition:rt})}return ze}const je=new Map;if(G)fillMap(G,je,0);const ze=new Map;fillMap(K,ze,0);const We=[];for(const[G,K]of ze){for(const[ze,Xe]of K){const K=je.get(G)?.get(ze);if(!K)We.push(Xe)}}We.sort(((G,K)=>K.sizeAndPosition-G.sizeAndPosition));return We[0]?.node}0&&0},16353:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{assert:()=>assert});G.exports=__toCommonJS(Xe);function assert(G,K){if(!G)throw new Error(K||"Assertion error")}0&&0},38607:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{noColors:()=>at,webColors:()=>rt});G.exports=__toCommonJS(Xe);const rt={enabled:true,reset:G=>applyStyle(0,0,G),bold:G=>applyStyle(1,22,G),dim:G=>applyStyle(2,22,G),italic:G=>applyStyle(3,23,G),underline:G=>applyStyle(4,24,G),inverse:G=>applyStyle(7,27,G),hidden:G=>applyStyle(8,28,G),strikethrough:G=>applyStyle(9,29,G),black:G=>applyStyle(30,39,G),red:G=>applyStyle(31,39,G),green:G=>applyStyle(32,39,G),yellow:G=>applyStyle(33,39,G),blue:G=>applyStyle(34,39,G),magenta:G=>applyStyle(35,39,G),cyan:G=>applyStyle(36,39,G),white:G=>applyStyle(37,39,G),gray:G=>applyStyle(90,39,G),grey:G=>applyStyle(90,39,G)};const at={enabled:false,reset:G=>G,bold:G=>G,dim:G=>G,italic:G=>G,underline:G=>G,inverse:G=>G,hidden:G=>G,strikethrough:G=>G,black:G=>G,red:G=>G,green:G=>G,yellow:G=>G,blue:G=>G,magenta:G=>G,cyan:G=>G,white:G=>G,gray:G=>G,grey:G=>G};const applyStyle=(G,K,je)=>`[${G}m${je}[${K}m`;0&&0},59891:(G,K,je)=>{"use strict";var ze=Object.create;var We=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var at=Object.getPrototypeOf;var ft=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)We(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,ze)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let at of rt(K))if(!ft.call(G,at)&&at!==je)We(G,at,{get:()=>K[at],enumerable:!(ze=Xe(K,at))||ze.enumerable})}return G};var __toESM=(G,K,je)=>(je=G!=null?ze(at(G)):{},__copyProps(K||!G||!G.__esModule?We(je,"default",{value:G,enumerable:true}):je,G));var __toCommonJS=G=>__copyProps(We({},"__esModule",{value:true}),G);var mt={};__export(mt,{InvalidSelectorError:()=>InvalidSelectorError,isInvalidSelectorError:()=>isInvalidSelectorError,parseCSS:()=>parseCSS,serializeSelector:()=>serializeSelector});G.exports=__toCommonJS(mt);var vt=__toESM(je(6071));class InvalidSelectorError extends Error{}function isInvalidSelectorError(G){return G instanceof InvalidSelectorError}function parseCSS(G,K){let je;try{je=vt.tokenize(G);if(!(je[je.length-1]instanceof vt.EOFToken))je.push(new vt.EOFToken)}catch(K){const je=K.message+` while parsing css selector "${G}". Did you mean to CSS.escape it?`;const ze=(K.stack||"").indexOf(K.message);if(ze!==-1)K.stack=K.stack.substring(0,ze)+je+K.stack.substring(ze+K.message.length);K.message=je;throw K}const ze=je.find((G=>G instanceof vt.AtKeywordToken||G instanceof vt.BadStringToken||G instanceof vt.BadURLToken||G instanceof vt.ColumnToken||G instanceof vt.CDOToken||G instanceof vt.CDCToken||G instanceof vt.SemicolonToken||G instanceof vt.OpenCurlyToken||G instanceof vt.CloseCurlyToken||G instanceof vt.URLToken||G instanceof vt.PercentageToken));if(ze)throw new InvalidSelectorError(`Unsupported token "${ze.toSource()}" while parsing css selector "${G}". Did you mean to CSS.escape it?`);let We=0;const Xe=new Set;function unexpected(){return new InvalidSelectorError(`Unexpected token "${je[We].toSource()}" while parsing css selector "${G}". Did you mean to CSS.escape it?`)}function skipWhitespace(){while(je[We]instanceof vt.WhitespaceToken)We++}function isIdent(G=We){return je[G]instanceof vt.IdentToken}function isString(G=We){return je[G]instanceof vt.StringToken}function isNumber(G=We){return je[G]instanceof vt.NumberToken}function isComma(G=We){return je[G]instanceof vt.CommaToken}function isOpenParen(G=We){return je[G]instanceof vt.OpenParenToken}function isCloseParen(G=We){return je[G]instanceof vt.CloseParenToken}function isFunction(G=We){return je[G]instanceof vt.FunctionToken}function isStar(G=We){return je[G]instanceof vt.DelimToken&&je[G].value==="*"}function isEOF(G=We){return je[G]instanceof vt.EOFToken}function isClauseCombinator(G=We){return je[G]instanceof vt.DelimToken&&[">","+","~"].includes(je[G].value)}function isSelectorClauseEnd(G=We){return isComma(G)||isCloseParen(G)||isEOF(G)||isClauseCombinator(G)||je[G]instanceof vt.WhitespaceToken}function consumeFunctionArguments(){const G=[consumeArgument()];while(true){skipWhitespace();if(!isComma())break;We++;G.push(consumeArgument())}return G}function consumeArgument(){skipWhitespace();if(isNumber())return je[We++].value;if(isString())return je[We++].value;return consumeComplexSelector()}function consumeComplexSelector(){const G={simples:[]};skipWhitespace();if(isClauseCombinator()){G.simples.push({selector:{functions:[{name:"scope",args:[]}]},combinator:""})}else{G.simples.push({selector:consumeSimpleSelector(),combinator:""})}while(true){skipWhitespace();if(isClauseCombinator()){G.simples[G.simples.length-1].combinator=je[We++].value;skipWhitespace()}else if(isSelectorClauseEnd()){break}G.simples.push({combinator:"",selector:consumeSimpleSelector()})}return G}function consumeSimpleSelector(){let G="";const ze=[];while(!isSelectorClauseEnd()){if(isIdent()||isStar()){G+=je[We++].toSource()}else if(je[We]instanceof vt.HashToken){G+=je[We++].toSource()}else if(je[We]instanceof vt.DelimToken&&je[We].value==="."){We++;if(isIdent())G+="."+je[We++].toSource();else throw unexpected()}else if(je[We]instanceof vt.ColonToken){We++;if(isIdent()){if(!K.has(je[We].value.toLowerCase())){G+=":"+je[We++].toSource()}else{const G=je[We++].value.toLowerCase();ze.push({name:G,args:[]});Xe.add(G)}}else if(isFunction()){const rt=je[We++].value.toLowerCase();if(!K.has(rt)){G+=`:${rt}(${consumeBuiltinFunctionArguments()})`}else{ze.push({name:rt,args:consumeFunctionArguments()});Xe.add(rt)}skipWhitespace();if(!isCloseParen())throw unexpected();We++}else{throw unexpected()}}else if(je[We]instanceof vt.OpenSquareToken){G+="[";We++;while(!(je[We]instanceof vt.CloseSquareToken)&&!isEOF())G+=je[We++].toSource();if(!(je[We]instanceof vt.CloseSquareToken))throw unexpected();G+="]";We++}else{throw unexpected()}}if(!G&&!ze.length)throw unexpected();return{css:G||void 0,functions:ze}}function consumeBuiltinFunctionArguments(){let G="";let K=1;while(!isEOF()){if(isOpenParen()||isFunction())K++;if(isCloseParen())K--;if(!K)break;G+=je[We++].toSource()}return G}const rt=consumeFunctionArguments();if(!isEOF())throw unexpected();if(rt.some((G=>typeof G!=="object"||!("simples"in G))))throw new InvalidSelectorError(`Error while parsing css selector "${G}". Did you mean to CSS.escape it?`);return{selector:rt,names:Array.from(Xe)}}function serializeSelector(G){return G.map((G=>{if(typeof G==="string")return`"${G}"`;if(typeof G==="number")return String(G);return G.simples.map((({selector:G,combinator:K})=>{let je=G.css||"";je=je+G.functions.map((G=>`:${G.name}(${serializeSelector(G.args)})`)).join("");if(K)je+=" "+K;return je})).join(" ")})).join(", ")}0&&0},6071:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{AtKeywordToken:()=>AtKeywordToken,BadStringToken:()=>BadStringToken,BadURLToken:()=>BadURLToken,CDCToken:()=>CDCToken,CDOToken:()=>CDOToken,CSSParserToken:()=>CSSParserToken,CloseCurlyToken:()=>CloseCurlyToken,CloseParenToken:()=>CloseParenToken,CloseSquareToken:()=>CloseSquareToken,ColonToken:()=>ColonToken,ColumnToken:()=>ColumnToken,CommaToken:()=>CommaToken,DashMatchToken:()=>DashMatchToken,DelimToken:()=>DelimToken,DimensionToken:()=>DimensionToken,EOFToken:()=>EOFToken,FunctionToken:()=>FunctionToken,GroupingToken:()=>GroupingToken,HashToken:()=>HashToken,IdentToken:()=>IdentToken,IncludeMatchToken:()=>IncludeMatchToken,InvalidCharacterError:()=>InvalidCharacterError,NumberToken:()=>NumberToken,OpenCurlyToken:()=>OpenCurlyToken,OpenParenToken:()=>OpenParenToken,OpenSquareToken:()=>OpenSquareToken,PercentageToken:()=>PercentageToken,PrefixMatchToken:()=>PrefixMatchToken,SemicolonToken:()=>SemicolonToken,StringToken:()=>StringToken,StringValuedToken:()=>StringValuedToken,SubstringMatchToken:()=>SubstringMatchToken,SuffixMatchToken:()=>SuffixMatchToken,URLToken:()=>URLToken,WhitespaceToken:()=>WhitespaceToken,tokenize:()=>tokenize});G.exports=__toCommonJS(Xe);const between=function(G,K,je){return G>=K&&G<=je};function digit(G){return between(G,48,57)}function hexdigit(G){return digit(G)||between(G,65,70)||between(G,97,102)}function uppercaseletter(G){return between(G,65,90)}function lowercaseletter(G){return between(G,97,122)}function letter(G){return uppercaseletter(G)||lowercaseletter(G)}function nonascii(G){return G>=128}function namestartchar(G){return letter(G)||nonascii(G)||G===95}function namechar(G){return namestartchar(G)||digit(G)||G===45}function nonprintable(G){return between(G,0,8)||G===11||between(G,14,31)||G===127}function newline(G){return G===10}function whitespace(G){return newline(G)||G===9||G===32}const rt=1114111;class InvalidCharacterError extends Error{constructor(G){super(G);this.name="InvalidCharacterError"}}function preprocess(G){const K=[];for(let je=0;je<G.length;je++){let ze=G.charCodeAt(je);if(ze===13&&G.charCodeAt(je+1)===10){ze=10;je++}if(ze===13||ze===12)ze=10;if(ze===0)ze=65533;if(between(ze,55296,56319)&&between(G.charCodeAt(je+1),56320,57343)){const K=ze-55296;const We=G.charCodeAt(je+1)-56320;ze=Math.pow(2,16)+K*Math.pow(2,10)+We;je++}K.push(ze)}return K}function stringFromCode(G){if(G<=65535)return String.fromCharCode(G);G-=Math.pow(2,16);const K=Math.floor(G/Math.pow(2,10))+55296;const je=G%Math.pow(2,10)+56320;return String.fromCharCode(K)+String.fromCharCode(je)}function tokenize(G){const K=preprocess(G);let je=-1;const ze=[];let We;let Xe=0;let at=0;let ft=0;const incrLineno=function(){Xe+=1;ft=at;at=0};const mt={line:Xe,column:at};const codepoint=function(G){if(G>=K.length)return-1;return K[G]};const next=function(G){if(G===void 0)G=1;if(G>3)throw"Spec Error: no more than three codepoints of lookahead.";return codepoint(je+G)};const consume=function(G){if(G===void 0)G=1;je+=G;We=codepoint(je);if(newline(We))incrLineno();else at+=G;return true};const reconsume=function(){je-=1;if(newline(We)){Xe-=1;at=ft}else{at-=1}mt.line=Xe;mt.column=at;return true};const eof=function(G){if(G===void 0)G=We;return G===-1};const donothing=function(){};const parseerror=function(){};const consumeAToken=function(){consumeComments();consume();if(whitespace(We)){while(whitespace(next()))consume();return new WhitespaceToken}else if(We===34){return consumeAStringToken()}else if(We===35){if(namechar(next())||areAValidEscape(next(1),next(2))){const G=new HashToken("");if(wouldStartAnIdentifier(next(1),next(2),next(3)))G.type="id";G.value=consumeAName();return G}else{return new DelimToken(We)}}else if(We===36){if(next()===61){consume();return new SuffixMatchToken}else{return new DelimToken(We)}}else if(We===39){return consumeAStringToken()}else if(We===40){return new OpenParenToken}else if(We===41){return new CloseParenToken}else if(We===42){if(next()===61){consume();return new SubstringMatchToken}else{return new DelimToken(We)}}else if(We===43){if(startsWithANumber()){reconsume();return consumeANumericToken()}else{return new DelimToken(We)}}else if(We===44){return new CommaToken}else if(We===45){if(startsWithANumber()){reconsume();return consumeANumericToken()}else if(next(1)===45&&next(2)===62){consume(2);return new CDCToken}else if(startsWithAnIdentifier()){reconsume();return consumeAnIdentlikeToken()}else{return new DelimToken(We)}}else if(We===46){if(startsWithANumber()){reconsume();return consumeANumericToken()}else{return new DelimToken(We)}}else if(We===58){return new ColonToken}else if(We===59){return new SemicolonToken}else if(We===60){if(next(1)===33&&next(2)===45&&next(3)===45){consume(3);return new CDOToken}else{return new DelimToken(We)}}else if(We===64){if(wouldStartAnIdentifier(next(1),next(2),next(3)))return new AtKeywordToken(consumeAName());else return new DelimToken(We)}else if(We===91){return new OpenSquareToken}else if(We===92){if(startsWithAValidEscape()){reconsume();return consumeAnIdentlikeToken()}else{parseerror();return new DelimToken(We)}}else if(We===93){return new CloseSquareToken}else if(We===94){if(next()===61){consume();return new PrefixMatchToken}else{return new DelimToken(We)}}else if(We===123){return new OpenCurlyToken}else if(We===124){if(next()===61){consume();return new DashMatchToken}else if(next()===124){consume();return new ColumnToken}else{return new DelimToken(We)}}else if(We===125){return new CloseCurlyToken}else if(We===126){if(next()===61){consume();return new IncludeMatchToken}else{return new DelimToken(We)}}else if(digit(We)){reconsume();return consumeANumericToken()}else if(namestartchar(We)){reconsume();return consumeAnIdentlikeToken()}else if(eof()){return new EOFToken}else{return new DelimToken(We)}};const consumeComments=function(){while(next(1)===47&&next(2)===42){consume(2);while(true){consume();if(We===42&&next()===47){consume();break}else if(eof()){parseerror();return}}}};const consumeANumericToken=function(){const G=consumeANumber();if(wouldStartAnIdentifier(next(1),next(2),next(3))){const K=new DimensionToken;K.value=G.value;K.repr=G.repr;K.type=G.type;K.unit=consumeAName();return K}else if(next()===37){consume();const K=new PercentageToken;K.value=G.value;K.repr=G.repr;return K}else{const K=new NumberToken;K.value=G.value;K.repr=G.repr;K.type=G.type;return K}};const consumeAnIdentlikeToken=function(){const G=consumeAName();if(G.toLowerCase()==="url"&&next()===40){consume();while(whitespace(next(1))&&whitespace(next(2)))consume();if(next()===34||next()===39)return new FunctionToken(G);else if(whitespace(next())&&(next(2)===34||next(2)===39))return new FunctionToken(G);else return consumeAURLToken()}else if(next()===40){consume();return new FunctionToken(G)}else{return new IdentToken(G)}};const consumeAStringToken=function(G){if(G===void 0)G=We;let K="";while(consume()){if(We===G||eof()){return new StringToken(K)}else if(newline(We)){parseerror();reconsume();return new BadStringToken}else if(We===92){if(eof(next()))donothing();else if(newline(next()))consume();else K+=stringFromCode(consumeEscape())}else{K+=stringFromCode(We)}}throw new Error("Internal error")};const consumeAURLToken=function(){const G=new URLToken("");while(whitespace(next()))consume();if(eof(next()))return G;while(consume()){if(We===41||eof()){return G}else if(whitespace(We)){while(whitespace(next()))consume();if(next()===41||eof(next())){consume();return G}else{consumeTheRemnantsOfABadURL();return new BadURLToken}}else if(We===34||We===39||We===40||nonprintable(We)){parseerror();consumeTheRemnantsOfABadURL();return new BadURLToken}else if(We===92){if(startsWithAValidEscape()){G.value+=stringFromCode(consumeEscape())}else{parseerror();consumeTheRemnantsOfABadURL();return new BadURLToken}}else{G.value+=stringFromCode(We)}}throw new Error("Internal error")};const consumeEscape=function(){consume();if(hexdigit(We)){const G=[We];for(let K=0;K<5;K++){if(hexdigit(next())){consume();G.push(We)}else{break}}if(whitespace(next()))consume();let K=parseInt(G.map((function(G){return String.fromCharCode(G)})).join(""),16);if(K>rt)K=65533;return K}else if(eof()){return 65533}else{return We}};const areAValidEscape=function(G,K){if(G!==92)return false;if(newline(K))return false;return true};const startsWithAValidEscape=function(){return areAValidEscape(We,next())};const wouldStartAnIdentifier=function(G,K,je){if(G===45)return namestartchar(K)||K===45||areAValidEscape(K,je);else if(namestartchar(G))return true;else if(G===92)return areAValidEscape(G,K);else return false};const startsWithAnIdentifier=function(){return wouldStartAnIdentifier(We,next(1),next(2))};const wouldStartANumber=function(G,K,je){if(G===43||G===45){if(digit(K))return true;if(K===46&&digit(je))return true;return false}else if(G===46){if(digit(K))return true;return false}else if(digit(G)){return true}else{return false}};const startsWithANumber=function(){return wouldStartANumber(We,next(1),next(2))};const consumeAName=function(){let G="";while(consume()){if(namechar(We)){G+=stringFromCode(We)}else if(startsWithAValidEscape()){G+=stringFromCode(consumeEscape())}else{reconsume();return G}}throw new Error("Internal parse error")};const consumeANumber=function(){let G="";let K="integer";if(next()===43||next()===45){consume();G+=stringFromCode(We)}while(digit(next())){consume();G+=stringFromCode(We)}if(next(1)===46&&digit(next(2))){consume();G+=stringFromCode(We);consume();G+=stringFromCode(We);K="number";while(digit(next())){consume();G+=stringFromCode(We)}}const je=next(1),ze=next(2),Xe=next(3);if((je===69||je===101)&&digit(ze)){consume();G+=stringFromCode(We);consume();G+=stringFromCode(We);K="number";while(digit(next())){consume();G+=stringFromCode(We)}}else if((je===69||je===101)&&(ze===43||ze===45)&&digit(Xe)){consume();G+=stringFromCode(We);consume();G+=stringFromCode(We);consume();G+=stringFromCode(We);K="number";while(digit(next())){consume();G+=stringFromCode(We)}}const rt=convertAStringToANumber(G);return{type:K,value:rt,repr:G}};const convertAStringToANumber=function(G){return+G};const consumeTheRemnantsOfABadURL=function(){while(consume()){if(We===41||eof()){return}else if(startsWithAValidEscape()){consumeEscape();donothing()}else{donothing()}}};let vt=0;while(!eof(next())){ze.push(consumeAToken());vt++;if(vt>K.length*2)throw new Error("I'm infinite-looping!")}return ze}class CSSParserToken{constructor(){this.tokenType=""}toJSON(){return{token:this.tokenType}}toString(){return this.tokenType}toSource(){return""+this}}class BadStringToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="BADSTRING"}}class BadURLToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="BADURL"}}class WhitespaceToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="WHITESPACE"}toString(){return"WS"}toSource(){return" "}}class CDOToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="CDO"}toSource(){return"\x3c!--"}}class CDCToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="CDC"}toSource(){return"--\x3e"}}class ColonToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType=":"}}class SemicolonToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType=";"}}class CommaToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType=","}}class GroupingToken extends CSSParserToken{constructor(){super(...arguments);this.value="";this.mirror=""}}class OpenCurlyToken extends GroupingToken{constructor(){super();this.tokenType="{";this.value="{";this.mirror="}"}}class CloseCurlyToken extends GroupingToken{constructor(){super();this.tokenType="}";this.value="}";this.mirror="{"}}class OpenSquareToken extends GroupingToken{constructor(){super();this.tokenType="[";this.value="[";this.mirror="]"}}class CloseSquareToken extends GroupingToken{constructor(){super();this.tokenType="]";this.value="]";this.mirror="["}}class OpenParenToken extends GroupingToken{constructor(){super();this.tokenType="(";this.value="(";this.mirror=")"}}class CloseParenToken extends GroupingToken{constructor(){super();this.tokenType=")";this.value=")";this.mirror="("}}class IncludeMatchToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="~="}}class DashMatchToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="|="}}class PrefixMatchToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="^="}}class SuffixMatchToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="$="}}class SubstringMatchToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="*="}}class ColumnToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="||"}}class EOFToken extends CSSParserToken{constructor(){super(...arguments);this.tokenType="EOF"}toSource(){return""}}class DelimToken extends CSSParserToken{constructor(G){super();this.tokenType="DELIM";this.value="";this.value=stringFromCode(G)}toString(){return"DELIM("+this.value+")"}toJSON(){const G=this.constructor.prototype.constructor.prototype.toJSON.call(this);G.value=this.value;return G}toSource(){if(this.value==="\\")return"\\\n";else return this.value}}class StringValuedToken extends CSSParserToken{constructor(){super(...arguments);this.value=""}ASCIIMatch(G){return this.value.toLowerCase()===G.toLowerCase()}toJSON(){const G=this.constructor.prototype.constructor.prototype.toJSON.call(this);G.value=this.value;return G}}class IdentToken extends StringValuedToken{constructor(G){super();this.tokenType="IDENT";this.value=G}toString(){return"IDENT("+this.value+")"}toSource(){return escapeIdent(this.value)}}class FunctionToken extends StringValuedToken{constructor(G){super();this.tokenType="FUNCTION";this.value=G;this.mirror=")"}toString(){return"FUNCTION("+this.value+")"}toSource(){return escapeIdent(this.value)+"("}}class AtKeywordToken extends StringValuedToken{constructor(G){super();this.tokenType="AT-KEYWORD";this.value=G}toString(){return"AT("+this.value+")"}toSource(){return"@"+escapeIdent(this.value)}}class HashToken extends StringValuedToken{constructor(G){super();this.tokenType="HASH";this.value=G;this.type="unrestricted"}toString(){return"HASH("+this.value+")"}toJSON(){const G=this.constructor.prototype.constructor.prototype.toJSON.call(this);G.value=this.value;G.type=this.type;return G}toSource(){if(this.type==="id")return"#"+escapeIdent(this.value);else return"#"+escapeHash(this.value)}}class StringToken extends StringValuedToken{constructor(G){super();this.tokenType="STRING";this.value=G}toString(){return'"'+escapeString(this.value)+'"'}}class URLToken extends StringValuedToken{constructor(G){super();this.tokenType="URL";this.value=G}toString(){return"URL("+this.value+")"}toSource(){return'url("'+escapeString(this.value)+'")'}}class NumberToken extends CSSParserToken{constructor(){super();this.tokenType="NUMBER";this.type="integer";this.repr=""}toString(){if(this.type==="integer")return"INT("+this.value+")";return"NUMBER("+this.value+")"}toJSON(){const G=super.toJSON();G.value=this.value;G.type=this.type;G.repr=this.repr;return G}toSource(){return this.repr}}class PercentageToken extends CSSParserToken{constructor(){super();this.tokenType="PERCENTAGE";this.repr=""}toString(){return"PERCENTAGE("+this.value+")"}toJSON(){const G=this.constructor.prototype.constructor.prototype.toJSON.call(this);G.value=this.value;G.repr=this.repr;return G}toSource(){return this.repr+"%"}}class DimensionToken extends CSSParserToken{constructor(){super();this.tokenType="DIMENSION";this.type="integer";this.repr="";this.unit=""}toString(){return"DIM("+this.value+","+this.unit+")"}toJSON(){const G=this.constructor.prototype.constructor.prototype.toJSON.call(this);G.value=this.value;G.type=this.type;G.repr=this.repr;G.unit=this.unit;return G}toSource(){const G=this.repr;let K=escapeIdent(this.unit);if(K[0].toLowerCase()==="e"&&(K[1]==="-"||between(K.charCodeAt(1),48,57))){K="\\65 "+K.slice(1,K.length)}return G+K}}function escapeIdent(G){G=""+G;let K="";const je=G.charCodeAt(0);for(let ze=0;ze<G.length;ze++){const We=G.charCodeAt(ze);if(We===0)throw new InvalidCharacterError("Invalid character: the input contains U+0000.");if(between(We,1,31)||We===127||ze===0&&between(We,48,57)||ze===1&&between(We,48,57)&&je===45)K+="\\"+We.toString(16)+" ";else if(We>=128||We===45||We===95||between(We,48,57)||between(We,65,90)||between(We,97,122))K+=G[ze];else K+="\\"+G[ze]}return K}function escapeHash(G){G=""+G;let K="";for(let je=0;je<G.length;je++){const ze=G.charCodeAt(je);if(ze===0)throw new InvalidCharacterError("Invalid character: the input contains U+0000.");if(ze>=128||ze===45||ze===95||between(ze,48,57)||between(ze,65,90)||between(ze,97,122))K+=G[je];else K+="\\"+ze.toString(16)+" "}return K}function escapeString(G){G=""+G;let K="";for(let je=0;je<G.length;je++){const ze=G.charCodeAt(je);if(ze===0)throw new InvalidCharacterError("Invalid character: the input contains U+0000.");if(between(ze,1,31)||ze===127)K+="\\"+ze.toString(16)+" ";else if(ze===34||ze===92)K+="\\"+G[je];else K+=G[je]}return K}0&&0},71761:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{headersArrayToObject:()=>headersArrayToObject,headersObjectToArray:()=>headersObjectToArray});G.exports=__toCommonJS(Xe);function headersObjectToArray(G,K,je){if(!je)je=K;const ze=[];for(const We in G){const Xe=G[We];if(Xe===void 0)continue;if(K){const G=We.toLowerCase()==="set-cookie"?je:K;for(const K of Xe.split(G))ze.push({name:We,value:K.trim()})}else{ze.push({name:We,value:Xe})}}return ze}function headersArrayToObject(G,K){const je={};for(const{name:ze,value:We}of G)je[K?ze.toLowerCase():ze]=We;return je}0&&0},78359:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{CSharpLocatorFactory:()=>CSharpLocatorFactory,JavaLocatorFactory:()=>JavaLocatorFactory,JavaScriptLocatorFactory:()=>JavaScriptLocatorFactory,JsonlLocatorFactory:()=>JsonlLocatorFactory,PythonLocatorFactory:()=>PythonLocatorFactory,asLocator:()=>asLocator,asLocatorDescription:()=>asLocatorDescription,asLocators:()=>asLocators,locatorCustomDescription:()=>locatorCustomDescription});G.exports=__toCommonJS(at);var ft=je(37673);var mt=je(70017);function asLocatorDescription(G,K){try{const je=(0,ft.parseSelector)(K);const ze=parseCustomDescription(je);if(ze)return ze;return innerAsLocators(new vt[G],je,false,1)[0]}catch(G){return K}}function locatorCustomDescription(G){try{const K=(0,ft.parseSelector)(G);return parseCustomDescription(K)}catch(G){return void 0}}function parseCustomDescription(G){const K=G.parts[G.parts.length-1];if(K?.name==="internal:describe"){const G=JSON.parse(K.body);if(typeof G==="string")return G}return void 0}function asLocator(G,K,je=false){return asLocators(G,K,je,1)[0]}function asLocators(G,K,je=false,ze=20,We){try{return innerAsLocators(new vt[G](We),(0,ft.parseSelector)(K),je,ze)}catch(G){return[K]}}function innerAsLocators(G,K,je=false,ze=20){const We=[...K.parts];const Xe=[];let rt=je?"frame-locator":"page";for(let K=0;K<We.length;K++){const je=We[K];const at=rt;rt="locator";if(je.name==="internal:describe")continue;if(je.name==="nth"){if(je.body==="0")Xe.push([G.generateLocator(at,"first",""),G.generateLocator(at,"nth","0")]);else if(je.body==="-1")Xe.push([G.generateLocator(at,"last",""),G.generateLocator(at,"nth","-1")]);else Xe.push([G.generateLocator(at,"nth",je.body)]);continue}if(je.name==="visible"){Xe.push([G.generateLocator(at,"visible",je.body),G.generateLocator(at,"default",`visible=${je.body}`)]);continue}if(je.name==="internal:text"){const{exact:K,text:ze}=detectExact(je.body);Xe.push([G.generateLocator(at,"text",ze,{exact:K})]);continue}if(je.name==="internal:has-text"){const{exact:K,text:ze}=detectExact(je.body);if(!K){Xe.push([G.generateLocator(at,"has-text",ze,{exact:K})]);continue}}if(je.name==="internal:has-not-text"){const{exact:K,text:ze}=detectExact(je.body);if(!K){Xe.push([G.generateLocator(at,"has-not-text",ze,{exact:K})]);continue}}if(je.name==="internal:has"){const K=innerAsLocators(G,je.body.parsed,false,ze);Xe.push(K.map((K=>G.generateLocator(at,"has",K))));continue}if(je.name==="internal:has-not"){const K=innerAsLocators(G,je.body.parsed,false,ze);Xe.push(K.map((K=>G.generateLocator(at,"hasNot",K))));continue}if(je.name==="internal:and"){const K=innerAsLocators(G,je.body.parsed,false,ze);Xe.push(K.map((K=>G.generateLocator(at,"and",K))));continue}if(je.name==="internal:or"){const K=innerAsLocators(G,je.body.parsed,false,ze);Xe.push(K.map((K=>G.generateLocator(at,"or",K))));continue}if(je.name==="internal:chain"){const K=innerAsLocators(G,je.body.parsed,false,ze);Xe.push(K.map((K=>G.generateLocator(at,"chain",K))));continue}if(je.name==="internal:label"){const{exact:K,text:ze}=detectExact(je.body);Xe.push([G.generateLocator(at,"label",ze,{exact:K})]);continue}if(je.name==="internal:role"){const K=(0,ft.parseAttributeSelector)(je.body,true);const ze={attrs:[]};for(const G of K.attributes){if(G.name==="name"){ze.exact=G.caseSensitive;ze.name=G.value}else{if(G.name==="level"&&typeof G.value==="string")G.value=+G.value;ze.attrs.push({name:G.name==="include-hidden"?"includeHidden":G.name,value:G.value})}}Xe.push([G.generateLocator(at,"role",K.name,ze)]);continue}if(je.name==="internal:testid"){const K=(0,ft.parseAttributeSelector)(je.body,true);const{value:ze}=K.attributes[0];Xe.push([G.generateLocator(at,"test-id",ze)]);continue}if(je.name==="internal:attr"){const K=(0,ft.parseAttributeSelector)(je.body,true);const{name:ze,value:We,caseSensitive:rt}=K.attributes[0];const mt=We;const vt=!!rt;if(ze==="placeholder"){Xe.push([G.generateLocator(at,"placeholder",mt,{exact:vt})]);continue}if(ze==="alt"){Xe.push([G.generateLocator(at,"alt",mt,{exact:vt})]);continue}if(ze==="title"){Xe.push([G.generateLocator(at,"title",mt,{exact:vt})]);continue}}if(je.name==="internal:control"&&je.body==="enter-frame"){const je=Xe[Xe.length-1];const ze=We[K-1];const mt=je.map((K=>G.chainLocators([K,G.generateLocator(at,"frame","")])));if(["xpath","css"].includes(ze.name)){mt.push(G.generateLocator(at,"frame-locator",(0,ft.stringifySelector)({parts:[ze]})),G.generateLocator(at,"frame-locator",(0,ft.stringifySelector)({parts:[ze]},true)))}je.splice(0,je.length,...mt);rt="frame-locator";continue}const mt=We[K+1];const vt=(0,ft.stringifySelector)({parts:[je]});const yt=G.generateLocator(at,"default",vt);if(mt&&["internal:has-text","internal:has-not-text"].includes(mt.name)){const{exact:je,text:ze}=detectExact(mt.body);if(!je){const We=G.generateLocator("locator",mt.name==="internal:has-text"?"has-text":"has-not-text",ze,{exact:je});const rt={};if(mt.name==="internal:has-text")rt.hasText=ze;else rt.hasNotText=ze;const ft=G.generateLocator(at,"default",vt,rt);Xe.push([G.chainLocators([yt,We]),ft]);K++;continue}}let wt;if(["xpath","css"].includes(je.name)){const K=(0,ft.stringifySelector)({parts:[je]},true);wt=G.generateLocator(at,"default",K)}Xe.push([yt,wt].filter(Boolean))}return combineTokens(G,Xe,ze)}function combineTokens(G,K,je){const ze=K.map((()=>""));const We=[];const visit=Xe=>{if(Xe===K.length){We.push(G.chainLocators(ze));return We.length<je}for(const G of K[Xe]){ze[Xe]=G;if(!visit(Xe+1))return false}return true};visit(0);return We}function detectExact(G){let K=false;const je=G.match(/^\/(.*)\/([igm]*)$/);if(je)return{text:new RegExp(je[1],je[2])};if(G.endsWith('"')){G=JSON.parse(G);K=true}else if(G.endsWith('"s')){G=JSON.parse(G.substring(0,G.length-1));K=true}else if(G.endsWith('"i')){G=JSON.parse(G.substring(0,G.length-1));K=false}return{exact:K,text:G}}class JavaScriptLocatorFactory{constructor(G){this.preferredQuote=G}generateLocator(G,K,je,ze={}){switch(K){case"default":if(ze.hasText!==void 0)return`locator(${this.quote(je)}, { hasText: ${this.toHasText(ze.hasText)} })`;if(ze.hasNotText!==void 0)return`locator(${this.quote(je)}, { hasNotText: ${this.toHasText(ze.hasNotText)} })`;return`locator(${this.quote(je)})`;case"frame-locator":return`frameLocator(${this.quote(je)})`;case"frame":return`contentFrame()`;case"nth":return`nth(${je})`;case"first":return`first()`;case"last":return`last()`;case"visible":return`filter({ visible: ${je==="true"?"true":"false"} })`;case"role":const G=[];if(isRegExp(ze.name)){G.push(`name: ${this.regexToSourceString(ze.name)}`)}else if(typeof ze.name==="string"){G.push(`name: ${this.quote(ze.name)}`);if(ze.exact)G.push(`exact: true`)}for(const{name:K,value:je}of ze.attrs)G.push(`${K}: ${typeof je==="string"?this.quote(je):je}`);const We=G.length?`, { ${G.join(", ")} }`:"";return`getByRole(${this.quote(je)}${We})`;case"has-text":return`filter({ hasText: ${this.toHasText(je)} })`;case"has-not-text":return`filter({ hasNotText: ${this.toHasText(je)} })`;case"has":return`filter({ has: ${je} })`;case"hasNot":return`filter({ hasNot: ${je} })`;case"and":return`and(${je})`;case"or":return`or(${je})`;case"chain":return`locator(${je})`;case"test-id":return`getByTestId(${this.toTestIdValue(je)})`;case"text":return this.toCallWithExact("getByText",je,!!ze.exact);case"alt":return this.toCallWithExact("getByAltText",je,!!ze.exact);case"placeholder":return this.toCallWithExact("getByPlaceholder",je,!!ze.exact);case"label":return this.toCallWithExact("getByLabel",je,!!ze.exact);case"title":return this.toCallWithExact("getByTitle",je,!!ze.exact);default:throw new Error("Unknown selector kind "+K)}}chainLocators(G){return G.join(".")}regexToSourceString(G){return(0,mt.normalizeEscapedRegexQuotes)(String(G))}toCallWithExact(G,K,je){if(isRegExp(K))return`${G}(${this.regexToSourceString(K)})`;return je?`${G}(${this.quote(K)}, { exact: true })`:`${G}(${this.quote(K)})`}toHasText(G){if(isRegExp(G))return this.regexToSourceString(G);return this.quote(G)}toTestIdValue(G){if(isRegExp(G))return this.regexToSourceString(G);return this.quote(G)}quote(G){return(0,mt.escapeWithQuotes)(G,this.preferredQuote??"'")}}class PythonLocatorFactory{generateLocator(G,K,je,ze={}){switch(K){case"default":if(ze.hasText!==void 0)return`locator(${this.quote(je)}, has_text=${this.toHasText(ze.hasText)})`;if(ze.hasNotText!==void 0)return`locator(${this.quote(je)}, has_not_text=${this.toHasText(ze.hasNotText)})`;return`locator(${this.quote(je)})`;case"frame-locator":return`frame_locator(${this.quote(je)})`;case"frame":return`content_frame`;case"nth":return`nth(${je})`;case"first":return`first`;case"last":return`last`;case"visible":return`filter(visible=${je==="true"?"True":"False"})`;case"role":const G=[];if(isRegExp(ze.name)){G.push(`name=${this.regexToString(ze.name)}`)}else if(typeof ze.name==="string"){G.push(`name=${this.quote(ze.name)}`);if(ze.exact)G.push(`exact=True`)}for(const{name:K,value:je}of ze.attrs){let ze=typeof je==="string"?this.quote(je):je;if(typeof je==="boolean")ze=je?"True":"False";G.push(`${(0,mt.toSnakeCase)(K)}=${ze}`)}const We=G.length?`, ${G.join(", ")}`:"";return`get_by_role(${this.quote(je)}${We})`;case"has-text":return`filter(has_text=${this.toHasText(je)})`;case"has-not-text":return`filter(has_not_text=${this.toHasText(je)})`;case"has":return`filter(has=${je})`;case"hasNot":return`filter(has_not=${je})`;case"and":return`and_(${je})`;case"or":return`or_(${je})`;case"chain":return`locator(${je})`;case"test-id":return`get_by_test_id(${this.toTestIdValue(je)})`;case"text":return this.toCallWithExact("get_by_text",je,!!ze.exact);case"alt":return this.toCallWithExact("get_by_alt_text",je,!!ze.exact);case"placeholder":return this.toCallWithExact("get_by_placeholder",je,!!ze.exact);case"label":return this.toCallWithExact("get_by_label",je,!!ze.exact);case"title":return this.toCallWithExact("get_by_title",je,!!ze.exact);default:throw new Error("Unknown selector kind "+K)}}chainLocators(G){return G.join(".")}regexToString(G){const K=G.flags.includes("i")?", re.IGNORECASE":"";return`re.compile(r"${(0,mt.normalizeEscapedRegexQuotes)(G.source).replace(/\\\//,"/").replace(/"/g,'\\"')}"${K})`}toCallWithExact(G,K,je){if(isRegExp(K))return`${G}(${this.regexToString(K)})`;if(je)return`${G}(${this.quote(K)}, exact=True)`;return`${G}(${this.quote(K)})`}toHasText(G){if(isRegExp(G))return this.regexToString(G);return`${this.quote(G)}`}toTestIdValue(G){if(isRegExp(G))return this.regexToString(G);return this.quote(G)}quote(G){return(0,mt.escapeWithQuotes)(G,'"')}}class JavaLocatorFactory{generateLocator(G,K,je,ze={}){let We;switch(G){case"page":We="Page";break;case"frame-locator":We="FrameLocator";break;case"locator":We="Locator";break}switch(K){case"default":if(ze.hasText!==void 0)return`locator(${this.quote(je)}, new ${We}.LocatorOptions().setHasText(${this.toHasText(ze.hasText)}))`;if(ze.hasNotText!==void 0)return`locator(${this.quote(je)}, new ${We}.LocatorOptions().setHasNotText(${this.toHasText(ze.hasNotText)}))`;return`locator(${this.quote(je)})`;case"frame-locator":return`frameLocator(${this.quote(je)})`;case"frame":return`contentFrame()`;case"nth":return`nth(${je})`;case"first":return`first()`;case"last":return`last()`;case"visible":return`filter(new ${We}.FilterOptions().setVisible(${je==="true"?"true":"false"}))`;case"role":const G=[];if(isRegExp(ze.name)){G.push(`.setName(${this.regexToString(ze.name)})`)}else if(typeof ze.name==="string"){G.push(`.setName(${this.quote(ze.name)})`);if(ze.exact)G.push(`.setExact(true)`)}for(const{name:K,value:je}of ze.attrs)G.push(`.set${(0,mt.toTitleCase)(K)}(${typeof je==="string"?this.quote(je):je})`);const Xe=G.length?`, new ${We}.GetByRoleOptions()${G.join("")}`:"";return`getByRole(AriaRole.${(0,mt.toSnakeCase)(je).toUpperCase()}${Xe})`;case"has-text":return`filter(new ${We}.FilterOptions().setHasText(${this.toHasText(je)}))`;case"has-not-text":return`filter(new ${We}.FilterOptions().setHasNotText(${this.toHasText(je)}))`;case"has":return`filter(new ${We}.FilterOptions().setHas(${je}))`;case"hasNot":return`filter(new ${We}.FilterOptions().setHasNot(${je}))`;case"and":return`and(${je})`;case"or":return`or(${je})`;case"chain":return`locator(${je})`;case"test-id":return`getByTestId(${this.toTestIdValue(je)})`;case"text":return this.toCallWithExact(We,"getByText",je,!!ze.exact);case"alt":return this.toCallWithExact(We,"getByAltText",je,!!ze.exact);case"placeholder":return this.toCallWithExact(We,"getByPlaceholder",je,!!ze.exact);case"label":return this.toCallWithExact(We,"getByLabel",je,!!ze.exact);case"title":return this.toCallWithExact(We,"getByTitle",je,!!ze.exact);default:throw new Error("Unknown selector kind "+K)}}chainLocators(G){return G.join(".")}regexToString(G){const K=G.flags.includes("i")?", Pattern.CASE_INSENSITIVE":"";return`Pattern.compile(${this.quote((0,mt.normalizeEscapedRegexQuotes)(G.source))}${K})`}toCallWithExact(G,K,je,ze){if(isRegExp(je))return`${K}(${this.regexToString(je)})`;if(ze)return`${K}(${this.quote(je)}, new ${G}.${(0,mt.toTitleCase)(K)}Options().setExact(true))`;return`${K}(${this.quote(je)})`}toHasText(G){if(isRegExp(G))return this.regexToString(G);return this.quote(G)}toTestIdValue(G){if(isRegExp(G))return this.regexToString(G);return this.quote(G)}quote(G){return(0,mt.escapeWithQuotes)(G,'"')}}class CSharpLocatorFactory{generateLocator(G,K,je,ze={}){switch(K){case"default":if(ze.hasText!==void 0)return`Locator(${this.quote(je)}, new() { ${this.toHasText(ze.hasText)} })`;if(ze.hasNotText!==void 0)return`Locator(${this.quote(je)}, new() { ${this.toHasNotText(ze.hasNotText)} })`;return`Locator(${this.quote(je)})`;case"frame-locator":return`FrameLocator(${this.quote(je)})`;case"frame":return`ContentFrame`;case"nth":return`Nth(${je})`;case"first":return`First`;case"last":return`Last`;case"visible":return`Filter(new() { Visible = ${je==="true"?"true":"false"} })`;case"role":const G=[];if(isRegExp(ze.name)){G.push(`NameRegex = ${this.regexToString(ze.name)}`)}else if(typeof ze.name==="string"){G.push(`Name = ${this.quote(ze.name)}`);if(ze.exact)G.push(`Exact = true`)}for(const{name:K,value:je}of ze.attrs)G.push(`${(0,mt.toTitleCase)(K)} = ${typeof je==="string"?this.quote(je):je}`);const We=G.length?`, new() { ${G.join(", ")} }`:"";return`GetByRole(AriaRole.${(0,mt.toTitleCase)(je)}${We})`;case"has-text":return`Filter(new() { ${this.toHasText(je)} })`;case"has-not-text":return`Filter(new() { ${this.toHasNotText(je)} })`;case"has":return`Filter(new() { Has = ${je} })`;case"hasNot":return`Filter(new() { HasNot = ${je} })`;case"and":return`And(${je})`;case"or":return`Or(${je})`;case"chain":return`Locator(${je})`;case"test-id":return`GetByTestId(${this.toTestIdValue(je)})`;case"text":return this.toCallWithExact("GetByText",je,!!ze.exact);case"alt":return this.toCallWithExact("GetByAltText",je,!!ze.exact);case"placeholder":return this.toCallWithExact("GetByPlaceholder",je,!!ze.exact);case"label":return this.toCallWithExact("GetByLabel",je,!!ze.exact);case"title":return this.toCallWithExact("GetByTitle",je,!!ze.exact);default:throw new Error("Unknown selector kind "+K)}}chainLocators(G){return G.join(".")}regexToString(G){const K=G.flags.includes("i")?", RegexOptions.IgnoreCase":"";return`new Regex(${this.quote((0,mt.normalizeEscapedRegexQuotes)(G.source))}${K})`}toCallWithExact(G,K,je){if(isRegExp(K))return`${G}(${this.regexToString(K)})`;if(je)return`${G}(${this.quote(K)}, new() { Exact = true })`;return`${G}(${this.quote(K)})`}toHasText(G){if(isRegExp(G))return`HasTextRegex = ${this.regexToString(G)}`;return`HasText = ${this.quote(G)}`}toTestIdValue(G){if(isRegExp(G))return this.regexToString(G);return this.quote(G)}toHasNotText(G){if(isRegExp(G))return`HasNotTextRegex = ${this.regexToString(G)}`;return`HasNotText = ${this.quote(G)}`}quote(G){return(0,mt.escapeWithQuotes)(G,'"')}}class JsonlLocatorFactory{generateLocator(G,K,je,ze={}){return JSON.stringify({kind:K,body:je,options:ze})}chainLocators(G){const K=G.map((G=>JSON.parse(G)));for(let G=0;G<K.length-1;++G)K[G].next=K[G+1];return JSON.stringify(K[0])}}const vt={javascript:JavaScriptLocatorFactory,python:PythonLocatorFactory,java:JavaLocatorFactory,csharp:CSharpLocatorFactory,jsonl:JsonlLocatorFactory};function isRegExp(G){return G instanceof RegExp}0&&0},32930:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{locatorOrSelectorAsSelector:()=>locatorOrSelectorAsSelector,unsafeLocatorOrSelectorAsSelector:()=>unsafeLocatorOrSelectorAsSelector});G.exports=__toCommonJS(at);var ft=je(78359);var mt=je(37673);var vt=je(70017);function parseLocator(G,K){G=G.replace(/AriaRole\s*\.\s*([\w]+)/g,((G,K)=>K.toLowerCase())).replace(/(get_by_role|getByRole)\s*\(\s*(?:["'`])([^'"`]+)['"`]/g,((G,K,je)=>`${K}(${je.toLowerCase()}`));const je=[];let ze="";for(let K=0;K<G.length;++K){const We=G[K];if(We!=='"'&&We!=="'"&&We!=="`"&&We!=="/"){ze+=We;continue}const Xe=G[K-1]==="r"||G[K]==="/";++K;let rt="";while(K<G.length){if(G[K]==="\\"){if(Xe){if(G[K+1]!==We)rt+=G[K];++K;rt+=G[K]}else{++K;if(G[K]==="n")rt+="\n";else if(G[K]==="r")rt+="\r";else if(G[K]==="t")rt+="\t";else rt+=G[K]}++K;continue}if(G[K]!==We){rt+=G[K++];continue}break}je.push({quote:We,text:rt});ze+=(We==="/"?"r":"")+"$"+je.length}ze=ze.toLowerCase().replace(/get_by_alt_text/g,"getbyalttext").replace(/get_by_test_id/g,"getbytestid").replace(/get_by_([\w]+)/g,"getby$1").replace(/has_not_text/g,"hasnottext").replace(/has_text/g,"hastext").replace(/has_not/g,"hasnot").replace(/frame_locator/g,"framelocator").replace(/content_frame/g,"contentframe").replace(/[{}\s]/g,"").replace(/new\(\)/g,"").replace(/new[\w]+\.[\w]+options\(\)/g,"").replace(/\.set/g,",set").replace(/\.or_\(/g,"or(").replace(/\.and_\(/g,"and(").replace(/:/g,"=").replace(/,re\.ignorecase/g,"i").replace(/,pattern.case_insensitive/g,"i").replace(/,regexoptions.ignorecase/g,"i").replace(/re.compile\(([^)]+)\)/g,"$1").replace(/pattern.compile\(([^)]+)\)/g,"r$1").replace(/newregex\(([^)]+)\)/g,"r$1").replace(/string=/g,"=").replace(/regex=/g,"=").replace(/,,/g,",").replace(/,\)/g,")");const We=je.map((G=>G.quote)).filter((G=>"'\"`".includes(G)))[0];return{selector:transform(ze,je,K),preferredQuote:We}}function countParams(G){return[...G.matchAll(/\$\d+/g)].length}function shiftParams(G,K){return G.replace(/\$(\d+)/g,((G,je)=>`$${je-K}`))}function transform(G,K,je){while(true){const ze=G.match(/filter\(,?(has=|hasnot=|sethas\(|sethasnot\()/);if(!ze)break;const We=ze.index+ze[0].length;let Xe=0;let rt=We;for(;rt<G.length;rt++){if(G[rt]==="(")Xe++;else if(G[rt]===")")Xe--;if(Xe<0)break}let at=G.substring(0,We);let ft=0;if(["sethas(","sethasnot("].includes(ze[1])){ft=1;at=at.replace(/sethas\($/,"has=").replace(/sethasnot\($/,"hasnot=")}const mt=countParams(G.substring(0,We));const vt=shiftParams(G.substring(We,rt),mt);const yt=countParams(vt);const wt=K.slice(mt,mt+yt);const lr=JSON.stringify(transform(vt,wt,je));G=at.replace(/=$/,"2=")+`$${mt+1}`+shiftParams(G.substring(rt+ft),yt-1);const Er=K.slice(0,mt);const Rr=K.slice(mt+yt);K=Er.concat([{quote:'"',text:lr}]).concat(Rr)}G=G.replace(/\,set([\w]+)\(([^)]+)\)/g,((G,K,je)=>","+K.toLowerCase()+"="+je.toLowerCase())).replace(/framelocator\(([^)]+)\)/g,"$1.internal:control=enter-frame").replace(/contentframe(\(\))?/g,"internal:control=enter-frame").replace(/locator\(([^)]+),hastext=([^),]+)\)/g,"locator($1).internal:has-text=$2").replace(/locator\(([^)]+),hasnottext=([^),]+)\)/g,"locator($1).internal:has-not-text=$2").replace(/locator\(([^)]+),hastext=([^),]+)\)/g,"locator($1).internal:has-text=$2").replace(/locator\(([^)]+)\)/g,"$1").replace(/getbyrole\(([^)]+)\)/g,"internal:role=$1").replace(/getbytext\(([^)]+)\)/g,"internal:text=$1").replace(/getbylabel\(([^)]+)\)/g,"internal:label=$1").replace(/getbytestid\(([^)]+)\)/g,`internal:testid=[${je}=$1]`).replace(/getby(placeholder|alt|title)(?:text)?\(([^)]+)\)/g,"internal:attr=[$1=$2]").replace(/first(\(\))?/g,"nth=0").replace(/last(\(\))?/g,"nth=-1").replace(/nth\(([^)]+)\)/g,"nth=$1").replace(/filter\(,?visible=true\)/g,"visible=true").replace(/filter\(,?visible=false\)/g,"visible=false").replace(/filter\(,?hastext=([^)]+)\)/g,"internal:has-text=$1").replace(/filter\(,?hasnottext=([^)]+)\)/g,"internal:has-not-text=$1").replace(/filter\(,?has2=([^)]+)\)/g,"internal:has=$1").replace(/filter\(,?hasnot2=([^)]+)\)/g,"internal:has-not=$1").replace(/,exact=false/g,"").replace(/,exact=true/g,"s").replace(/,includehidden=/g,",include-hidden=").replace(/\,/g,"][");const ze=G.split(".");for(let G=0;G<ze.length-1;G++){if(ze[G]==="internal:control=enter-frame"&&ze[G+1].startsWith("nth=")){const[K]=ze.splice(G,1);ze.splice(G+1,0,K)}}return ze.map((G=>{if(!G.startsWith("internal:")||G==="internal:control")return G.replace(/\$(\d+)/g,((G,je)=>{const ze=K[+je-1];return ze.text}));G=G.includes("[")?G.replace(/\]/,"")+"]":G;G=G.replace(/(?:r)\$(\d+)(i)?/g,((je,ze,We)=>{const Xe=K[+ze-1];if(G.startsWith("internal:attr")||G.startsWith("internal:testid")||G.startsWith("internal:role"))return(0,vt.escapeForAttributeSelector)(new RegExp(Xe.text),false)+(We||"");return(0,vt.escapeForTextSelector)(new RegExp(Xe.text,We),false)})).replace(/\$(\d+)(i|s)?/g,((je,ze,We)=>{const Xe=K[+ze-1];if(G.startsWith("internal:has=")||G.startsWith("internal:has-not="))return Xe.text;if(G.startsWith("internal:testid"))return(0,vt.escapeForAttributeSelector)(Xe.text,true);if(G.startsWith("internal:attr")||G.startsWith("internal:role"))return(0,vt.escapeForAttributeSelector)(Xe.text,We==="s");return(0,vt.escapeForTextSelector)(Xe.text,We==="s")}));return G})).join(" >> ")}function locatorOrSelectorAsSelector(G,K,je){try{return unsafeLocatorOrSelectorAsSelector(G,K,je)}catch(G){return""}}function unsafeLocatorOrSelectorAsSelector(G,K,je){try{(0,mt.parseSelector)(K);return K}catch(G){}const{selector:ze,preferredQuote:We}=parseLocator(K,je);const Xe=(0,ft.asLocators)(G,ze,void 0,void 0,We);const rt=digestForComparison(G,K);if(Xe.some((K=>digestForComparison(G,K)===rt)))return ze;return""}function digestForComparison(G,K){K=K.replace(/\s/g,"");if(G==="javascript")K=K.replace(/\\?["`]/g,"'").replace(/,{}/g,"");return K}0&&0},25880:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{getByAltTextSelector:()=>getByAltTextSelector,getByLabelSelector:()=>getByLabelSelector,getByPlaceholderSelector:()=>getByPlaceholderSelector,getByRoleSelector:()=>getByRoleSelector,getByTestIdSelector:()=>getByTestIdSelector,getByTextSelector:()=>getByTextSelector,getByTitleSelector:()=>getByTitleSelector});G.exports=__toCommonJS(at);var ft=je(70017);function getByAttributeTextSelector(G,K,je){return`internal:attr=[${G}=${(0,ft.escapeForAttributeSelector)(K,je?.exact||false)}]`}function getByTestIdSelector(G,K){return`internal:testid=[${G}=${(0,ft.escapeForAttributeSelector)(K,true)}]`}function getByLabelSelector(G,K){return"internal:label="+(0,ft.escapeForTextSelector)(G,!!K?.exact)}function getByAltTextSelector(G,K){return getByAttributeTextSelector("alt",G,K)}function getByTitleSelector(G,K){return getByAttributeTextSelector("title",G,K)}function getByPlaceholderSelector(G,K){return getByAttributeTextSelector("placeholder",G,K)}function getByTextSelector(G,K){return"internal:text="+(0,ft.escapeForTextSelector)(G,!!K?.exact)}function getByRoleSelector(G,K={}){const je=[];if(K.checked!==void 0)je.push(["checked",String(K.checked)]);if(K.disabled!==void 0)je.push(["disabled",String(K.disabled)]);if(K.selected!==void 0)je.push(["selected",String(K.selected)]);if(K.expanded!==void 0)je.push(["expanded",String(K.expanded)]);if(K.includeHidden!==void 0)je.push(["include-hidden",String(K.includeHidden)]);if(K.level!==void 0)je.push(["level",String(K.level)]);if(K.name!==void 0)je.push(["name",(0,ft.escapeForAttributeSelector)(K.name,!!K.exact)]);if(K.pressed!==void 0)je.push(["pressed",String(K.pressed)]);return`internal:role=${G}${je.map((([G,K])=>`[${G}=${K}]`)).join("")}`}0&&0},28040:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{LongStandingScope:()=>LongStandingScope,ManualPromise:()=>ManualPromise});G.exports=__toCommonJS(at);var ft=je(46662);class ManualPromise extends Promise{constructor(){let G;let K;super(((je,ze)=>{G=je;K=ze}));this._isDone=false;this._resolve=G;this._reject=K}isDone(){return this._isDone}resolve(G){this._isDone=true;this._resolve(G)}reject(G){this._isDone=true;this._reject(G)}static get[Symbol.species](){return Promise}get[Symbol.toStringTag](){return"ManualPromise"}}class LongStandingScope{constructor(){this._terminatePromises=new Map;this._isClosed=false}reject(G){this._isClosed=true;this._terminateError=G;for(const K of this._terminatePromises.keys())K.resolve(G)}close(G){this._isClosed=true;this._closeError=G;for(const[K,je]of this._terminatePromises)K.resolve(cloneError(G,je))}isClosed(){return this._isClosed}static async raceMultiple(G,K){return Promise.race(G.map((G=>G.race(K))))}async race(G){return this._race(Array.isArray(G)?G:[G],false)}async safeRace(G,K){return this._race([G],true,K)}async _race(G,K,je){const ze=new ManualPromise;const We=(0,ft.captureRawStack)();if(this._terminateError)ze.resolve(this._terminateError);if(this._closeError)ze.resolve(cloneError(this._closeError,We));this._terminatePromises.set(ze,We);try{return await Promise.race([ze.then((G=>K?je:Promise.reject(G))),...G])}finally{this._terminatePromises.delete(ze)}}}function cloneError(G,K){const je=new Error;je.name=G.name;je.message=G.message;je.stack=[G.name+":"+G.message,...K].join("\n");return je}0&&0},22467:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{getMimeTypeForPath:()=>getMimeTypeForPath,isJsonMimeType:()=>isJsonMimeType,isTextualMimeType:()=>isTextualMimeType});G.exports=__toCommonJS(Xe);function isJsonMimeType(G){return!!G.match(/^(application\/json|application\/.*?\+json|text\/(x-)?json)(;\s*charset=.*)?$/)}function isTextualMimeType(G){return!!G.match(/^(text\/.*?|application\/(json|(x-)?javascript|xml.*?|ecmascript|graphql|x-www-form-urlencoded)|image\/svg(\+xml)?|application\/.*?(\+json|\+xml))(;\s*charset=.*)?$/)}function getMimeTypeForPath(G){const K=G.lastIndexOf(".");if(K===-1)return null;const je=G.substring(K+1);return rt.get(je)||null}const rt=new Map([["ez","application/andrew-inset"],["aw","application/applixware"],["atom","application/atom+xml"],["atomcat","application/atomcat+xml"],["atomdeleted","application/atomdeleted+xml"],["atomsvc","application/atomsvc+xml"],["dwd","application/atsc-dwd+xml"],["held","application/atsc-held+xml"],["rsat","application/atsc-rsat+xml"],["bdoc","application/bdoc"],["xcs","application/calendar+xml"],["ccxml","application/ccxml+xml"],["cdfx","application/cdfx+xml"],["cdmia","application/cdmi-capability"],["cdmic","application/cdmi-container"],["cdmid","application/cdmi-domain"],["cdmio","application/cdmi-object"],["cdmiq","application/cdmi-queue"],["cu","application/cu-seeme"],["mpd","application/dash+xml"],["davmount","application/davmount+xml"],["dbk","application/docbook+xml"],["dssc","application/dssc+der"],["xdssc","application/dssc+xml"],["ecma","application/ecmascript"],["es","application/ecmascript"],["emma","application/emma+xml"],["emotionml","application/emotionml+xml"],["epub","application/epub+zip"],["exi","application/exi"],["exp","application/express"],["fdt","application/fdt+xml"],["pfr","application/font-tdpfr"],["geojson","application/geo+json"],["gml","application/gml+xml"],["gpx","application/gpx+xml"],["gxf","application/gxf"],["gz","application/gzip"],["hjson","application/hjson"],["stk","application/hyperstudio"],["ink","application/inkml+xml"],["inkml","application/inkml+xml"],["ipfix","application/ipfix"],["its","application/its+xml"],["ear","application/java-archive"],["jar","application/java-archive"],["war","application/java-archive"],["ser","application/java-serialized-object"],["class","application/java-vm"],["js","application/javascript"],["mjs","application/javascript"],["json","application/json"],["map","application/json"],["json5","application/json5"],["jsonml","application/jsonml+json"],["jsonld","application/ld+json"],["lgr","application/lgr+xml"],["lostxml","application/lost+xml"],["hqx","application/mac-binhex40"],["cpt","application/mac-compactpro"],["mads","application/mads+xml"],["webmanifest","application/manifest+json"],["mrc","application/marc"],["mrcx","application/marcxml+xml"],["ma","application/mathematica"],["mb","application/mathematica"],["nb","application/mathematica"],["mathml","application/mathml+xml"],["mbox","application/mbox"],["mscml","application/mediaservercontrol+xml"],["metalink","application/metalink+xml"],["meta4","application/metalink4+xml"],["mets","application/mets+xml"],["maei","application/mmt-aei+xml"],["musd","application/mmt-usd+xml"],["mods","application/mods+xml"],["m21","application/mp21"],["mp21","application/mp21"],["m4p","application/mp4"],["mp4s","application/mp4"],["doc","application/msword"],["dot","application/msword"],["mxf","application/mxf"],["nq","application/n-quads"],["nt","application/n-triples"],["cjs","application/node"],["bin","application/octet-stream"],["bpk","application/octet-stream"],["buffer","application/octet-stream"],["deb","application/octet-stream"],["deploy","application/octet-stream"],["dist","application/octet-stream"],["distz","application/octet-stream"],["dll","application/octet-stream"],["dmg","application/octet-stream"],["dms","application/octet-stream"],["dump","application/octet-stream"],["elc","application/octet-stream"],["exe","application/octet-stream"],["img","application/octet-stream"],["iso","application/octet-stream"],["lrf","application/octet-stream"],["mar","application/octet-stream"],["msi","application/octet-stream"],["msm","application/octet-stream"],["msp","application/octet-stream"],["pkg","application/octet-stream"],["so","application/octet-stream"],["oda","application/oda"],["opf","application/oebps-package+xml"],["ogx","application/ogg"],["omdoc","application/omdoc+xml"],["onepkg","application/onenote"],["onetmp","application/onenote"],["onetoc","application/onenote"],["onetoc2","application/onenote"],["oxps","application/oxps"],["relo","application/p2p-overlay+xml"],["xer","application/patch-ops-error+xml"],["pdf","application/pdf"],["pgp","application/pgp-encrypted"],["asc","application/pgp-signature"],["sig","application/pgp-signature"],["prf","application/pics-rules"],["p10","application/pkcs10"],["p7c","application/pkcs7-mime"],["p7m","application/pkcs7-mime"],["p7s","application/pkcs7-signature"],["p8","application/pkcs8"],["ac","application/pkix-attr-cert"],["cer","application/pkix-cert"],["crl","application/pkix-crl"],["pkipath","application/pkix-pkipath"],["pki","application/pkixcmp"],["pls","application/pls+xml"],["ai","application/postscript"],["eps","application/postscript"],["ps","application/postscript"],["provx","application/provenance+xml"],["pskcxml","application/pskc+xml"],["raml","application/raml+yaml"],["owl","application/rdf+xml"],["rdf","application/rdf+xml"],["rif","application/reginfo+xml"],["rnc","application/relax-ng-compact-syntax"],["rl","application/resource-lists+xml"],["rld","application/resource-lists-diff+xml"],["rs","application/rls-services+xml"],["rapd","application/route-apd+xml"],["sls","application/route-s-tsid+xml"],["rusd","application/route-usd+xml"],["gbr","application/rpki-ghostbusters"],["mft","application/rpki-manifest"],["roa","application/rpki-roa"],["rsd","application/rsd+xml"],["rss","application/rss+xml"],["rtf","application/rtf"],["sbml","application/sbml+xml"],["scq","application/scvp-cv-request"],["scs","application/scvp-cv-response"],["spq","application/scvp-vp-request"],["spp","application/scvp-vp-response"],["sdp","application/sdp"],["senmlx","application/senml+xml"],["sensmlx","application/sensml+xml"],["setpay","application/set-payment-initiation"],["setreg","application/set-registration-initiation"],["shf","application/shf+xml"],["sieve","application/sieve"],["siv","application/sieve"],["smi","application/smil+xml"],["smil","application/smil+xml"],["rq","application/sparql-query"],["srx","application/sparql-results+xml"],["gram","application/srgs"],["grxml","application/srgs+xml"],["sru","application/sru+xml"],["ssdl","application/ssdl+xml"],["ssml","application/ssml+xml"],["swidtag","application/swid+xml"],["tei","application/tei+xml"],["teicorpus","application/tei+xml"],["tfi","application/thraud+xml"],["tsd","application/timestamped-data"],["toml","application/toml"],["trig","application/trig"],["ttml","application/ttml+xml"],["ubj","application/ubjson"],["rsheet","application/urc-ressheet+xml"],["td","application/urc-targetdesc+xml"],["vxml","application/voicexml+xml"],["wasm","application/wasm"],["wgt","application/widget"],["hlp","application/winhlp"],["wsdl","application/wsdl+xml"],["wspolicy","application/wspolicy+xml"],["xaml","application/xaml+xml"],["xav","application/xcap-att+xml"],["xca","application/xcap-caps+xml"],["xdf","application/xcap-diff+xml"],["xel","application/xcap-el+xml"],["xns","application/xcap-ns+xml"],["xenc","application/xenc+xml"],["xht","application/xhtml+xml"],["xhtml","application/xhtml+xml"],["xlf","application/xliff+xml"],["rng","application/xml"],["xml","application/xml"],["xsd","application/xml"],["xsl","application/xml"],["dtd","application/xml-dtd"],["xop","application/xop+xml"],["xpl","application/xproc+xml"],["*xsl","application/xslt+xml"],["xslt","application/xslt+xml"],["xspf","application/xspf+xml"],["mxml","application/xv+xml"],["xhvml","application/xv+xml"],["xvm","application/xv+xml"],["xvml","application/xv+xml"],["yang","application/yang"],["yin","application/yin+xml"],["zip","application/zip"],["*3gpp","audio/3gpp"],["adp","audio/adpcm"],["amr","audio/amr"],["au","audio/basic"],["snd","audio/basic"],["kar","audio/midi"],["mid","audio/midi"],["midi","audio/midi"],["rmi","audio/midi"],["mxmf","audio/mobile-xmf"],["*mp3","audio/mp3"],["m4a","audio/mp4"],["mp4a","audio/mp4"],["m2a","audio/mpeg"],["m3a","audio/mpeg"],["mp2","audio/mpeg"],["mp2a","audio/mpeg"],["mp3","audio/mpeg"],["mpga","audio/mpeg"],["oga","audio/ogg"],["ogg","audio/ogg"],["opus","audio/ogg"],["spx","audio/ogg"],["s3m","audio/s3m"],["sil","audio/silk"],["wav","audio/wav"],["*wav","audio/wave"],["weba","audio/webm"],["xm","audio/xm"],["ttc","font/collection"],["otf","font/otf"],["ttf","font/ttf"],["woff","font/woff"],["woff2","font/woff2"],["exr","image/aces"],["apng","image/apng"],["avif","image/avif"],["bmp","image/bmp"],["cgm","image/cgm"],["drle","image/dicom-rle"],["emf","image/emf"],["fits","image/fits"],["g3","image/g3fax"],["gif","image/gif"],["heic","image/heic"],["heics","image/heic-sequence"],["heif","image/heif"],["heifs","image/heif-sequence"],["hej2","image/hej2k"],["hsj2","image/hsj2"],["ief","image/ief"],["jls","image/jls"],["jp2","image/jp2"],["jpg2","image/jp2"],["jpe","image/jpeg"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["jph","image/jph"],["jhc","image/jphc"],["jpm","image/jpm"],["jpf","image/jpx"],["jpx","image/jpx"],["jxr","image/jxr"],["jxra","image/jxra"],["jxrs","image/jxrs"],["jxs","image/jxs"],["jxsc","image/jxsc"],["jxsi","image/jxsi"],["jxss","image/jxss"],["ktx","image/ktx"],["ktx2","image/ktx2"],["png","image/png"],["sgi","image/sgi"],["svg","image/svg+xml"],["svgz","image/svg+xml"],["t38","image/t38"],["tif","image/tiff"],["tiff","image/tiff"],["tfx","image/tiff-fx"],["webp","image/webp"],["wmf","image/wmf"],["disposition-notification","message/disposition-notification"],["u8msg","message/global"],["u8dsn","message/global-delivery-status"],["u8mdn","message/global-disposition-notification"],["u8hdr","message/global-headers"],["eml","message/rfc822"],["mime","message/rfc822"],["3mf","model/3mf"],["gltf","model/gltf+json"],["glb","model/gltf-binary"],["iges","model/iges"],["igs","model/iges"],["mesh","model/mesh"],["msh","model/mesh"],["silo","model/mesh"],["mtl","model/mtl"],["obj","model/obj"],["stpx","model/step+xml"],["stpz","model/step+zip"],["stpxz","model/step-xml+zip"],["stl","model/stl"],["vrml","model/vrml"],["wrl","model/vrml"],["*x3db","model/x3d+binary"],["x3dbz","model/x3d+binary"],["x3db","model/x3d+fastinfoset"],["*x3dv","model/x3d+vrml"],["x3dvz","model/x3d+vrml"],["x3d","model/x3d+xml"],["x3dz","model/x3d+xml"],["x3dv","model/x3d-vrml"],["appcache","text/cache-manifest"],["manifest","text/cache-manifest"],["ics","text/calendar"],["ifb","text/calendar"],["coffee","text/coffeescript"],["litcoffee","text/coffeescript"],["css","text/css"],["csv","text/csv"],["htm","text/html"],["html","text/html"],["shtml","text/html"],["jade","text/jade"],["jsx","text/jsx"],["less","text/less"],["markdown","text/markdown"],["md","text/markdown"],["mml","text/mathml"],["mdx","text/mdx"],["n3","text/n3"],["conf","text/plain"],["def","text/plain"],["in","text/plain"],["ini","text/plain"],["list","text/plain"],["log","text/plain"],["text","text/plain"],["txt","text/plain"],["rtx","text/richtext"],["*rtf","text/rtf"],["sgm","text/sgml"],["sgml","text/sgml"],["shex","text/shex"],["slim","text/slim"],["slm","text/slim"],["spdx","text/spdx"],["styl","text/stylus"],["stylus","text/stylus"],["tsv","text/tab-separated-values"],["man","text/troff"],["me","text/troff"],["ms","text/troff"],["roff","text/troff"],["t","text/troff"],["tr","text/troff"],["ttl","text/turtle"],["uri","text/uri-list"],["uris","text/uri-list"],["urls","text/uri-list"],["vcard","text/vcard"],["vtt","text/vtt"],["*xml","text/xml"],["yaml","text/yaml"],["yml","text/yaml"],["3gp","video/3gpp"],["3gpp","video/3gpp"],["3g2","video/3gpp2"],["h261","video/h261"],["h263","video/h263"],["h264","video/h264"],["m4s","video/iso.segment"],["jpgv","video/jpeg"],["jpm","video/jpm"],["jpgm","video/jpm"],["mj2","video/mj2"],["mjp2","video/mj2"],["ts","application/typescript"],["mp4","video/mp4"],["mp4v","video/mp4"],["mpg4","video/mp4"],["m1v","video/mpeg"],["m2v","video/mpeg"],["mpe","video/mpeg"],["mpeg","video/mpeg"],["mpg","video/mpeg"],["ogv","video/ogg"],["mov","video/quicktime"],["qt","video/quicktime"],["webm","video/webm"]]);0&&0},27094:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{MultiMap:()=>MultiMap});G.exports=__toCommonJS(Xe);class MultiMap{constructor(){this._map=new Map}set(G,K){let je=this._map.get(G);if(!je){je=[];this._map.set(G,je)}je.push(K)}get(G){return this._map.get(G)||[]}has(G){return this._map.has(G)}delete(G,K){const je=this._map.get(G);if(!je)return;if(je.includes(K))this._map.set(G,je.filter((G=>K!==G)))}deleteAll(G){this._map.delete(G)}hasValue(G,K){const je=this._map.get(G);if(!je)return false;return je.includes(K)}get size(){return this._map.size}[Symbol.iterator](){return this._map[Symbol.iterator]()}keys(){return this._map.keys()}values(){const G=[];for(const K of this.keys())G.push(...this.get(K));return G}clear(){this._map.clear()}}0&&0},13601:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{formatProtocolParam:()=>formatProtocolParam,getActionGroup:()=>getActionGroup,renderTitleForCall:()=>renderTitleForCall});G.exports=__toCommonJS(at);var ft=je(81438);function formatProtocolParam(G,K){return _formatProtocolParam(G,K)?.replaceAll("\n","\\n")}function _formatProtocolParam(G,K){if(!G)return void 0;for(const je of K.split("|")){if(je==="url"){try{const K=new URL(G[je]);if(K.protocol==="data:")return K.protocol;if(K.protocol==="about:")return G[je];return K.pathname+K.search}catch(K){if(G[je]!==void 0)return G[je]}}if(je==="timeNumber"&&G[je]!==void 0){return new Date(G[je]).toString()}const K=deepParam(G,je);if(K!==void 0)return K}}function deepParam(G,K){const je=K.split(".");let ze=G;for(const G of je){if(typeof ze!=="object"||ze===null)return void 0;ze=ze[G]}if(ze===void 0)return void 0;return String(ze)}function renderTitleForCall(G){const K=G.title??ft.methodMetainfo.get(G.type+"."+G.method)?.title??G.method;return K.replace(/\{([^}]+)\}/g,((K,je)=>formatProtocolParam(G.params,je)??K))}function getActionGroup(G){return ft.methodMetainfo.get(G.type+"."+G.method)?.group}0&&0},81438:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{methodMetainfo:()=>rt});G.exports=__toCommonJS(Xe);const rt=new Map([["APIRequestContext.fetch",{title:'{method} "{url}"'}],["APIRequestContext.fetchResponseBody",{title:"Get response body",group:"getter"}],["APIRequestContext.fetchLog",{internal:true}],["APIRequestContext.storageState",{title:"Get storage state"}],["APIRequestContext.disposeAPIResponse",{internal:true}],["APIRequestContext.dispose",{internal:true}],["LocalUtils.zip",{internal:true}],["LocalUtils.harOpen",{internal:true}],["LocalUtils.harLookup",{internal:true}],["LocalUtils.harClose",{internal:true}],["LocalUtils.harUnzip",{internal:true}],["LocalUtils.connect",{internal:true}],["LocalUtils.tracingStarted",{internal:true}],["LocalUtils.addStackToTracingNoReply",{internal:true}],["LocalUtils.traceDiscarded",{internal:true}],["LocalUtils.globToRegex",{internal:true}],["Root.initialize",{internal:true}],["Playwright.newRequest",{title:"Create request context"}],["DebugController.initialize",{internal:true}],["DebugController.setReportStateChanged",{internal:true}],["DebugController.setRecorderMode",{internal:true}],["DebugController.highlight",{internal:true}],["DebugController.hideHighlight",{internal:true}],["DebugController.resume",{internal:true}],["DebugController.kill",{internal:true}],["SocksSupport.socksConnected",{internal:true}],["SocksSupport.socksFailed",{internal:true}],["SocksSupport.socksData",{internal:true}],["SocksSupport.socksError",{internal:true}],["SocksSupport.socksEnd",{internal:true}],["BrowserType.launch",{title:"Launch browser"}],["BrowserType.launchPersistentContext",{title:"Launch persistent context"}],["BrowserType.connectOverCDP",{title:"Connect over CDP"}],["Browser.close",{title:"Close browser",pausesBeforeAction:true}],["Browser.killForTests",{internal:true}],["Browser.defaultUserAgentForTest",{internal:true}],["Browser.newContext",{title:"Create context"}],["Browser.newContextForReuse",{internal:true}],["Browser.disconnectFromReusedContext",{internal:true}],["Browser.newBrowserCDPSession",{title:"Create CDP session",group:"configuration"}],["Browser.startTracing",{title:"Start browser tracing",group:"configuration"}],["Browser.stopTracing",{title:"Stop browser tracing",group:"configuration"}],["EventTarget.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["BrowserContext.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["Page.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["Worker.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["WebSocket.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["ElectronApplication.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["AndroidDevice.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["PageAgent.waitForEventInfo",{title:'Wait for event "{info.event}"',snapshot:true}],["BrowserContext.addCookies",{title:"Add cookies",group:"configuration"}],["BrowserContext.addInitScript",{title:"Add init script",group:"configuration"}],["BrowserContext.clearCookies",{title:"Clear cookies",group:"configuration"}],["BrowserContext.clearPermissions",{title:"Clear permissions",group:"configuration"}],["BrowserContext.close",{title:"Close context",pausesBeforeAction:true}],["BrowserContext.cookies",{title:"Get cookies",group:"getter"}],["BrowserContext.exposeBinding",{title:"Expose binding",group:"configuration"}],["BrowserContext.grantPermissions",{title:"Grant permissions",group:"configuration"}],["BrowserContext.newPage",{title:"Create page"}],["BrowserContext.registerSelectorEngine",{internal:true}],["BrowserContext.setTestIdAttributeName",{internal:true}],["BrowserContext.setExtraHTTPHeaders",{title:"Set extra HTTP headers",group:"configuration"}],["BrowserContext.setGeolocation",{title:"Set geolocation",group:"configuration"}],["BrowserContext.setHTTPCredentials",{title:"Set HTTP credentials",group:"configuration"}],["BrowserContext.setNetworkInterceptionPatterns",{title:"Route requests",group:"route"}],["BrowserContext.setWebSocketInterceptionPatterns",{title:"Route WebSockets",group:"route"}],["BrowserContext.setOffline",{title:"Set offline mode"}],["BrowserContext.storageState",{title:"Get storage state"}],["BrowserContext.pause",{title:"Pause"}],["BrowserContext.enableRecorder",{internal:true}],["BrowserContext.disableRecorder",{internal:true}],["BrowserContext.exposeConsoleApi",{internal:true}],["BrowserContext.newCDPSession",{title:"Create CDP session",group:"configuration"}],["BrowserContext.harStart",{internal:true}],["BrowserContext.harExport",{internal:true}],["BrowserContext.createTempFiles",{internal:true}],["BrowserContext.updateSubscription",{internal:true}],["BrowserContext.clockFastForward",{title:'Fast forward clock "{ticksNumber|ticksString}"'}],["BrowserContext.clockInstall",{title:'Install clock "{timeNumber|timeString}"'}],["BrowserContext.clockPauseAt",{title:'Pause clock "{timeNumber|timeString}"'}],["BrowserContext.clockResume",{title:"Resume clock"}],["BrowserContext.clockRunFor",{title:'Run clock "{ticksNumber|ticksString}"'}],["BrowserContext.clockSetFixedTime",{title:'Set fixed time "{timeNumber|timeString}"'}],["BrowserContext.clockSetSystemTime",{title:'Set system time "{timeNumber|timeString}"'}],["Page.addInitScript",{title:"Add init script",group:"configuration"}],["Page.close",{title:"Close page",pausesBeforeAction:true}],["Page.consoleMessages",{title:"Get console messages",group:"getter"}],["Page.emulateMedia",{title:"Emulate media",snapshot:true,pausesBeforeAction:true}],["Page.exposeBinding",{title:"Expose binding",group:"configuration"}],["Page.goBack",{title:"Go back",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.goForward",{title:"Go forward",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.requestGC",{title:"Request garbage collection",group:"configuration"}],["Page.registerLocatorHandler",{title:"Register locator handler"}],["Page.resolveLocatorHandlerNoReply",{internal:true}],["Page.unregisterLocatorHandler",{title:"Unregister locator handler"}],["Page.reload",{title:"Reload",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.expectScreenshot",{title:"Expect screenshot",snapshot:true,pausesBeforeAction:true}],["Page.screenshot",{title:"Screenshot",snapshot:true,pausesBeforeAction:true}],["Page.setExtraHTTPHeaders",{title:"Set extra HTTP headers",group:"configuration"}],["Page.setNetworkInterceptionPatterns",{title:"Route requests",group:"route"}],["Page.setWebSocketInterceptionPatterns",{title:"Route WebSockets",group:"route"}],["Page.setViewportSize",{title:"Set viewport size",snapshot:true,pausesBeforeAction:true}],["Page.keyboardDown",{title:'Key down "{key}"',slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.keyboardUp",{title:'Key up "{key}"',slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.keyboardInsertText",{title:'Insert "{text}"',slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.keyboardType",{title:'Type "{text}"',slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.keyboardPress",{title:'Press "{key}"',slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.mouseMove",{title:"Mouse move",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.mouseDown",{title:"Mouse down",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.mouseUp",{title:"Mouse up",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.mouseClick",{title:"Click",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.mouseWheel",{title:"Mouse wheel",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.touchscreenTap",{title:"Tap",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Page.pageErrors",{title:"Get page errors",group:"getter"}],["Page.pdf",{title:"PDF"}],["Page.requests",{title:"Get network requests",group:"getter"}],["Page.snapshotForAI",{internal:true}],["Page.startJSCoverage",{title:"Start JS coverage",group:"configuration"}],["Page.stopJSCoverage",{title:"Stop JS coverage",group:"configuration"}],["Page.startCSSCoverage",{title:"Start CSS coverage",group:"configuration"}],["Page.stopCSSCoverage",{title:"Stop CSS coverage",group:"configuration"}],["Page.bringToFront",{title:"Bring to front"}],["Page.updateSubscription",{internal:true}],["Page.agent",{internal:true}],["Frame.evalOnSelector",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["Frame.evalOnSelectorAll",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["Frame.addScriptTag",{title:"Add script tag",snapshot:true,pausesBeforeAction:true}],["Frame.addStyleTag",{title:"Add style tag",snapshot:true,pausesBeforeAction:true}],["Frame.ariaSnapshot",{title:"Aria snapshot",snapshot:true,pausesBeforeAction:true}],["Frame.blur",{title:"Blur",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Frame.check",{title:"Check",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.click",{title:"Click",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.content",{title:"Get content",snapshot:true,pausesBeforeAction:true}],["Frame.dragAndDrop",{title:"Drag and drop",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.dblclick",{title:"Double click",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.dispatchEvent",{title:'Dispatch "{type}"',slowMo:true,snapshot:true,pausesBeforeAction:true}],["Frame.evaluateExpression",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["Frame.evaluateExpressionHandle",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["Frame.fill",{title:'Fill "{value}"',slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.focus",{title:"Focus",slowMo:true,snapshot:true,pausesBeforeAction:true}],["Frame.frameElement",{title:"Get frame element",group:"getter"}],["Frame.resolveSelector",{internal:true}],["Frame.highlight",{title:"Highlight element",group:"configuration"}],["Frame.getAttribute",{title:'Get attribute "{name}"',snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.goto",{title:'Navigate to "{url}"',slowMo:true,snapshot:true,pausesBeforeAction:true}],["Frame.hover",{title:"Hover",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.innerHTML",{title:"Get HTML",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.innerText",{title:"Get inner text",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.inputValue",{title:"Get input value",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.isChecked",{title:"Is checked",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.isDisabled",{title:"Is disabled",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.isEnabled",{title:"Is enabled",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.isHidden",{title:"Is hidden",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.isVisible",{title:"Is visible",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.isEditable",{title:"Is editable",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.press",{title:'Press "{key}"',slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.querySelector",{title:"Query selector",snapshot:true}],["Frame.querySelectorAll",{title:"Query selector all",snapshot:true}],["Frame.queryCount",{title:"Query count",snapshot:true,pausesBeforeAction:true}],["Frame.selectOption",{title:"Select option",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.setContent",{title:"Set content",snapshot:true,pausesBeforeAction:true}],["Frame.setInputFiles",{title:"Set input files",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.tap",{title:"Tap",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.textContent",{title:"Get text content",snapshot:true,pausesBeforeAction:true,group:"getter"}],["Frame.title",{title:"Get page title",group:"getter"}],["Frame.type",{title:'Type "{text}"',slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.uncheck",{title:"Uncheck",slowMo:true,snapshot:true,pausesBeforeInput:true}],["Frame.waitForTimeout",{title:"Wait for timeout",snapshot:true}],["Frame.waitForFunction",{title:"Wait for function",snapshot:true,pausesBeforeAction:true}],["Frame.waitForSelector",{title:"Wait for selector",snapshot:true}],["Frame.expect",{title:'Expect "{expression}"',snapshot:true,pausesBeforeAction:true}],["Worker.evaluateExpression",{title:"Evaluate"}],["Worker.evaluateExpressionHandle",{title:"Evaluate"}],["Worker.updateSubscription",{internal:true}],["JSHandle.dispose",{internal:true}],["ElementHandle.dispose",{internal:true}],["JSHandle.evaluateExpression",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["ElementHandle.evaluateExpression",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["JSHandle.evaluateExpressionHandle",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["ElementHandle.evaluateExpressionHandle",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["JSHandle.getPropertyList",{title:"Get property list",group:"getter"}],["ElementHandle.getPropertyList",{title:"Get property list",group:"getter"}],["JSHandle.getProperty",{title:"Get JS property",group:"getter"}],["ElementHandle.getProperty",{title:"Get JS property",group:"getter"}],["JSHandle.jsonValue",{title:"Get JSON value",group:"getter"}],["ElementHandle.jsonValue",{title:"Get JSON value",group:"getter"}],["ElementHandle.evalOnSelector",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["ElementHandle.evalOnSelectorAll",{title:"Evaluate",snapshot:true,pausesBeforeAction:true}],["ElementHandle.boundingBox",{title:"Get bounding box",snapshot:true,pausesBeforeAction:true}],["ElementHandle.check",{title:"Check",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.click",{title:"Click",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.contentFrame",{title:"Get content frame",group:"getter"}],["ElementHandle.dblclick",{title:"Double click",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.dispatchEvent",{title:"Dispatch event",slowMo:true,snapshot:true,pausesBeforeAction:true}],["ElementHandle.fill",{title:'Fill "{value}"',slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.focus",{title:"Focus",slowMo:true,snapshot:true,pausesBeforeAction:true}],["ElementHandle.getAttribute",{title:"Get attribute",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.hover",{title:"Hover",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.innerHTML",{title:"Get HTML",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.innerText",{title:"Get inner text",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.inputValue",{title:"Get input value",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.isChecked",{title:"Is checked",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.isDisabled",{title:"Is disabled",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.isEditable",{title:"Is editable",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.isEnabled",{title:"Is enabled",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.isHidden",{title:"Is hidden",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.isVisible",{title:"Is visible",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.ownerFrame",{title:"Get owner frame",group:"getter"}],["ElementHandle.press",{title:'Press "{key}"',slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.querySelector",{title:"Query selector",snapshot:true}],["ElementHandle.querySelectorAll",{title:"Query selector all",snapshot:true}],["ElementHandle.screenshot",{title:"Screenshot",snapshot:true,pausesBeforeAction:true}],["ElementHandle.scrollIntoViewIfNeeded",{title:"Scroll into view",slowMo:true,snapshot:true,pausesBeforeAction:true}],["ElementHandle.selectOption",{title:"Select option",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.selectText",{title:"Select text",slowMo:true,snapshot:true,pausesBeforeAction:true}],["ElementHandle.setInputFiles",{title:"Set input files",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.tap",{title:"Tap",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.textContent",{title:"Get text content",snapshot:true,pausesBeforeAction:true,group:"getter"}],["ElementHandle.type",{title:"Type",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.uncheck",{title:"Uncheck",slowMo:true,snapshot:true,pausesBeforeInput:true}],["ElementHandle.waitForElementState",{title:"Wait for state",snapshot:true,pausesBeforeAction:true}],["ElementHandle.waitForSelector",{title:"Wait for selector",snapshot:true}],["Request.response",{internal:true}],["Request.rawRequestHeaders",{internal:true}],["Route.redirectNavigationRequest",{internal:true}],["Route.abort",{title:"Abort request",group:"route"}],["Route.continue",{title:"Continue request",group:"route"}],["Route.fulfill",{title:"Fulfill request",group:"route"}],["WebSocketRoute.connect",{title:"Connect WebSocket to server",group:"route"}],["WebSocketRoute.ensureOpened",{internal:true}],["WebSocketRoute.sendToPage",{title:"Send WebSocket message",group:"route"}],["WebSocketRoute.sendToServer",{title:"Send WebSocket message",group:"route"}],["WebSocketRoute.closePage",{internal:true}],["WebSocketRoute.closeServer",{internal:true}],["Response.body",{title:"Get response body",group:"getter"}],["Response.securityDetails",{internal:true}],["Response.serverAddr",{internal:true}],["Response.rawResponseHeaders",{internal:true}],["Response.sizes",{internal:true}],["BindingCall.reject",{internal:true}],["BindingCall.resolve",{internal:true}],["Dialog.accept",{title:"Accept dialog"}],["Dialog.dismiss",{title:"Dismiss dialog"}],["Tracing.tracingStart",{title:"Start tracing",group:"configuration"}],["Tracing.tracingStartChunk",{title:"Start tracing",group:"configuration"}],["Tracing.tracingGroup",{title:'Trace "{name}"'}],["Tracing.tracingGroupEnd",{title:"Group end"}],["Tracing.tracingStopChunk",{title:"Stop tracing",group:"configuration"}],["Tracing.tracingStop",{title:"Stop tracing",group:"configuration"}],["Artifact.pathAfterFinished",{internal:true}],["Artifact.saveAs",{internal:true}],["Artifact.saveAsStream",{internal:true}],["Artifact.failure",{internal:true}],["Artifact.stream",{internal:true}],["Artifact.cancel",{internal:true}],["Artifact.delete",{internal:true}],["Stream.read",{internal:true}],["Stream.close",{internal:true}],["WritableStream.write",{internal:true}],["WritableStream.close",{internal:true}],["CDPSession.send",{title:"Send CDP command",group:"configuration"}],["CDPSession.detach",{title:"Detach CDP session",group:"configuration"}],["Electron.launch",{title:"Launch electron"}],["ElectronApplication.browserWindow",{internal:true}],["ElectronApplication.evaluateExpression",{title:"Evaluate"}],["ElectronApplication.evaluateExpressionHandle",{title:"Evaluate"}],["ElectronApplication.updateSubscription",{internal:true}],["Android.devices",{internal:true}],["AndroidSocket.write",{internal:true}],["AndroidSocket.close",{internal:true}],["AndroidDevice.wait",{title:"Wait"}],["AndroidDevice.fill",{title:'Fill "{text}"'}],["AndroidDevice.tap",{title:"Tap"}],["AndroidDevice.drag",{title:"Drag"}],["AndroidDevice.fling",{title:"Fling"}],["AndroidDevice.longTap",{title:"Long tap"}],["AndroidDevice.pinchClose",{title:"Pinch close"}],["AndroidDevice.pinchOpen",{title:"Pinch open"}],["AndroidDevice.scroll",{title:"Scroll"}],["AndroidDevice.swipe",{title:"Swipe"}],["AndroidDevice.info",{internal:true}],["AndroidDevice.screenshot",{title:"Screenshot"}],["AndroidDevice.inputType",{title:"Type"}],["AndroidDevice.inputPress",{title:"Press"}],["AndroidDevice.inputTap",{title:"Tap"}],["AndroidDevice.inputSwipe",{title:"Swipe"}],["AndroidDevice.inputDrag",{title:"Drag"}],["AndroidDevice.launchBrowser",{title:"Launch browser"}],["AndroidDevice.open",{title:"Open app"}],["AndroidDevice.shell",{title:"Execute shell command",group:"configuration"}],["AndroidDevice.installApk",{title:"Install apk"}],["AndroidDevice.push",{title:"Push"}],["AndroidDevice.connectToWebView",{title:"Connect to Web View"}],["AndroidDevice.close",{internal:true}],["JsonPipe.send",{internal:true}],["JsonPipe.close",{internal:true}],["PageAgent.perform",{title:'Perform "{task}"'}],["PageAgent.expect",{title:'Expect "{expectation}"'}],["PageAgent.extract",{title:'Extract "{query}"'}],["PageAgent.dispose",{internal:true}],["PageAgent.usage",{title:"Get agent usage",group:"configuration"}]]);0&&0},96298:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{isError:()=>isError,isObject:()=>isObject,isRegExp:()=>isRegExp,isString:()=>ft.isString});G.exports=__toCommonJS(at);var ft=je(70017);function isRegExp(G){return G instanceof RegExp||Object.prototype.toString.call(G)==="[object RegExp]"}function isObject(G){return typeof G==="object"&&G!==null}function isError(G){return G instanceof Error||G&&Object.getPrototypeOf(G)?.name==="Error"}0&&0},37673:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{InvalidSelectorError:()=>mt.InvalidSelectorError,customCSSNames:()=>wt,isInvalidSelectorError:()=>mt.isInvalidSelectorError,parseAttributeSelector:()=>parseAttributeSelector,parseSelector:()=>parseSelector,splitSelectorByFrame:()=>splitSelectorByFrame,stringifySelector:()=>stringifySelector,visitAllSelectorParts:()=>visitAllSelectorParts});G.exports=__toCommonJS(at);var ft=je(59891);var mt=je(59891);const vt=new Set(["internal:has","internal:has-not","internal:and","internal:or","internal:chain","left-of","right-of","above","below","near"]);const yt=new Set(["left-of","right-of","above","below","near"]);const wt=new Set(["not","is","where","has","scope","light","visible","text","text-matches","text-is","has-text","above","below","right-of","left-of","near","nth-match"]);function parseSelector(G){const K=parseSelectorString(G);const je=[];for(const G of K.parts){if(G.name==="css"||G.name==="css:light"){if(G.name==="css:light")G.body=":light("+G.body+")";const K=(0,ft.parseCSS)(G.body,wt);je.push({name:"css",body:K.selector,source:G.body});continue}if(vt.has(G.name)){let K;let ze;try{const je=JSON.parse("["+G.body+"]");if(!Array.isArray(je)||je.length<1||je.length>2||typeof je[0]!=="string")throw new ft.InvalidSelectorError(`Malformed selector: ${G.name}=`+G.body);K=je[0];if(je.length===2){if(typeof je[1]!=="number"||!yt.has(G.name))throw new ft.InvalidSelectorError(`Malformed selector: ${G.name}=`+G.body);ze=je[1]}}catch(K){throw new ft.InvalidSelectorError(`Malformed selector: ${G.name}=`+G.body)}const We={name:G.name,source:G.body,body:{parsed:parseSelector(K),distance:ze}};const Xe=[...We.body.parsed.parts].reverse().find((G=>G.name==="internal:control"&&G.body==="enter-frame"));const rt=Xe?We.body.parsed.parts.indexOf(Xe):-1;if(rt!==-1&&selectorPartsEqual(We.body.parsed.parts.slice(0,rt+1),je.slice(0,rt+1)))We.body.parsed.parts.splice(0,rt+1);je.push(We);continue}je.push({...G,source:G.body})}if(vt.has(je[0].name))throw new ft.InvalidSelectorError(`"${je[0].name}" selector cannot be first`);return{capture:K.capture,parts:je}}function splitSelectorByFrame(G){const K=parseSelector(G);const je=[];let ze={parts:[]};let We=0;for(let G=0;G<K.parts.length;++G){const Xe=K.parts[G];if(Xe.name==="internal:control"&&Xe.body==="enter-frame"){if(!ze.parts.length)throw new ft.InvalidSelectorError("Selector cannot start with entering frame, select the iframe first");je.push(ze);ze={parts:[]};We=G+1;continue}if(K.capture===G)ze.capture=G-We;ze.parts.push(Xe)}if(!ze.parts.length)throw new ft.InvalidSelectorError(`Selector cannot end with entering frame, while parsing selector ${G}`);je.push(ze);if(typeof K.capture==="number"&&typeof je[je.length-1].capture!=="number")throw new ft.InvalidSelectorError(`Can not capture the selector before diving into the frame. Only use * after the last frame has been selected`);return je}function selectorPartsEqual(G,K){return stringifySelector({parts:G})===stringifySelector({parts:K})}function stringifySelector(G,K){if(typeof G==="string")return G;return G.parts.map(((je,ze)=>{let We=true;if(!K&&ze!==G.capture){if(je.name==="css")We=false;else if(je.name==="xpath"&&je.source.startsWith("//")||je.source.startsWith(".."))We=false}const Xe=We?je.name+"=":"";return`${ze===G.capture?"*":""}${Xe}${je.source}`})).join(" >> ")}function visitAllSelectorParts(G,K){const visit=(G,je)=>{for(const ze of G.parts){K(ze,je);if(vt.has(ze.name))visit(ze.body.parsed,true)}};visit(G,false)}function parseSelectorString(G){let K=0;let je;let ze=0;const We={parts:[]};const append=()=>{const je=G.substring(ze,K).trim();const Xe=je.indexOf("=");let rt;let at;if(Xe!==-1&&je.substring(0,Xe).trim().match(/^[a-zA-Z_0-9-+:*]+$/)){rt=je.substring(0,Xe).trim();at=je.substring(Xe+1)}else if(je.length>1&&je[0]==='"'&&je[je.length-1]==='"'){rt="text";at=je}else if(je.length>1&&je[0]==="'"&&je[je.length-1]==="'"){rt="text";at=je}else if(/^\(*\/\//.test(je)||je.startsWith("..")){rt="xpath";at=je}else{rt="css";at=je}let mt=false;if(rt[0]==="*"){mt=true;rt=rt.substring(1)}We.parts.push({name:rt,body:at});if(mt){if(We.capture!==void 0)throw new ft.InvalidSelectorError(`Only one of the selectors can capture using * modifier`);We.capture=We.parts.length-1}};if(!G.includes(">>")){K=G.length;append();return We}const shouldIgnoreTextSelectorQuote=()=>{const je=G.substring(ze,K);const We=je.match(/^\s*text\s*=(.*)$/);return!!We&&!!We[1]};while(K<G.length){const We=G[K];if(We==="\\"&&K+1<G.length){K+=2}else if(We===je){je=void 0;K++}else if(!je&&(We==='"'||We==="'"||We==="`")&&!shouldIgnoreTextSelectorQuote()){je=We;K++}else if(!je&&We===">"&&G[K+1]===">"){append();K+=2;ze=K}else{K++}}append();return We}function parseAttributeSelector(G,K){let je=0;let ze=G.length===0;const next=()=>G[je]||"";const eat1=()=>{const K=next();++je;ze=je>=G.length;return K};const syntaxError=K=>{if(ze)throw new ft.InvalidSelectorError(`Unexpected end of selector while parsing selector \`${G}\``);throw new ft.InvalidSelectorError(`Error while parsing selector \`${G}\` - unexpected symbol "${next()}" at position ${je}`+(K?" during "+K:""))};function skipSpaces(){while(!ze&&/\s/.test(next()))eat1()}function isCSSNameChar(G){return G>="€"||G>="0"&&G<="9"||G>="A"&&G<="Z"||G>="a"&&G<="z"||G>="0"&&G<="9"||G==="_"||G==="-"}function readIdentifier(){let G="";skipSpaces();while(!ze&&isCSSNameChar(next()))G+=eat1();return G}function readQuotedString(G){let K=eat1();if(K!==G)syntaxError("parsing quoted string");while(!ze&&next()!==G){if(next()==="\\")eat1();K+=eat1()}if(next()!==G)syntaxError("parsing quoted string");K+=eat1();return K}function readRegularExpression(){if(eat1()!=="/")syntaxError("parsing regular expression");let K="";let je=false;while(!ze){if(next()==="\\"){K+=eat1();if(ze)syntaxError("parsing regular expression")}else if(je&&next()==="]"){je=false}else if(!je&&next()==="["){je=true}else if(!je&&next()==="/"){break}K+=eat1()}if(eat1()!=="/")syntaxError("parsing regular expression");let We="";while(!ze&&next().match(/[dgimsuy]/))We+=eat1();try{return new RegExp(K,We)}catch(K){throw new ft.InvalidSelectorError(`Error while parsing selector \`${G}\`: ${K.message}`)}}function readAttributeToken(){let G="";skipSpaces();if(next()===`'`||next()===`"`)G=readQuotedString(next()).slice(1,-1);else G=readIdentifier();if(!G)syntaxError("parsing property path");return G}function readOperator(){skipSpaces();let G="";if(!ze)G+=eat1();if(!ze&&G!=="=")G+=eat1();if(!["=","*=","^=","$=","|=","~="].includes(G))syntaxError("parsing operator");return G}function readAttribute(){eat1();const je=[];je.push(readAttributeToken());skipSpaces();while(next()==="."){eat1();je.push(readAttributeToken());skipSpaces()}if(next()==="]"){eat1();return{name:je.join("."),jsonPath:je,op:"<truthy>",value:null,caseSensitive:false}}const We=readOperator();let Xe=void 0;let rt=true;skipSpaces();if(next()==="/"){if(We!=="=")throw new ft.InvalidSelectorError(`Error while parsing selector \`${G}\` - cannot use ${We} in attribute with regular expression`);Xe=readRegularExpression()}else if(next()===`'`||next()===`"`){Xe=readQuotedString(next()).slice(1,-1);skipSpaces();if(next()==="i"||next()==="I"){rt=false;eat1()}else if(next()==="s"||next()==="S"){rt=true;eat1()}}else{Xe="";while(!ze&&(isCSSNameChar(next())||next()==="+"||next()==="."))Xe+=eat1();if(Xe==="true"){Xe=true}else if(Xe==="false"){Xe=false}else{if(!K){Xe=+Xe;if(Number.isNaN(Xe))syntaxError("parsing attribute value")}}}skipSpaces();if(next()!=="]")syntaxError("parsing attribute value");eat1();if(We!=="="&&typeof Xe!=="string")throw new ft.InvalidSelectorError(`Error while parsing selector \`${G}\` - cannot use ${We} in attribute with non-string matching value - ${Xe}`);return{name:je.join("."),jsonPath:je,op:We,value:Xe,caseSensitive:rt}}const We={name:"",attributes:[]};We.name=readIdentifier();skipSpaces();while(next()==="["){We.attributes.push(readAttribute());skipSpaces()}if(!ze)syntaxError(void 0);if(!We.name&&!We.attributes.length)throw new ft.InvalidSelectorError(`Error while parsing selector \`${G}\` - selector cannot be empty`);return We}0&&0},26265:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{Semaphore:()=>Semaphore});G.exports=__toCommonJS(at);var ft=je(28040);class Semaphore{constructor(G){this._acquired=0;this._queue=[];this._max=G}setMax(G){this._max=G}acquire(){const G=new ft.ManualPromise;this._queue.push(G);this._flush();return G}release(){--this._acquired;this._flush()}_flush(){while(this._acquired<this._max&&this._queue.length){++this._acquired;this._queue.shift().resolve()}}}0&&0},46662:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{captureRawStack:()=>captureRawStack,parseErrorStack:()=>parseErrorStack,parseStackFrame:()=>parseStackFrame,rewriteErrorMessage:()=>rewriteErrorMessage,splitErrorMessage:()=>splitErrorMessage,stringifyStackFrames:()=>stringifyStackFrames});G.exports=__toCommonJS(Xe);function captureRawStack(){const G=Error.stackTraceLimit;Error.stackTraceLimit=50;const K=new Error;const je=K.stack||"";Error.stackTraceLimit=G;return je.split("\n")}function parseStackFrame(G,K,je){const ze=G&&G.match(rt);if(!ze)return null;let We=ze[2];let Xe=ze[7];if(!Xe)return null;if(!je&&(Xe.startsWith("internal")||Xe.startsWith("node:")))return null;const ft=ze[8];const mt=ze[9];const vt=ze[11]===")";const yt={file:"",line:0,column:0};if(ft)yt.line=Number(ft);if(mt)yt.column=Number(mt);if(vt&&Xe){let G=0;for(let K=Xe.length-1;K>0;K--){if(Xe.charAt(K)===")"){G++}else if(Xe.charAt(K)==="("&&Xe.charAt(K-1)===" "){G--;if(G===-1&&Xe.charAt(K-1)===" "){const G=Xe.slice(0,K-1);const je=Xe.slice(K+1);Xe=je;We+=` (${G}`;break}}}}if(We){const G=We.match(at);if(G)We=G[1]}if(Xe){if(Xe.startsWith("file://"))Xe=fileURLToPath(Xe,K);yt.file=Xe}if(We)yt.function=We;return yt}function rewriteErrorMessage(G,K){const je=(G.stack?.split("\n")||[]).filter((G=>G.startsWith(" at ")));G.message=K;const ze=`${G.name}: ${G.message}`;if(je.length)G.stack=`${ze}\n${je.join("\n")}`;return G}function stringifyStackFrames(G){const K=[];for(const je of G){if(je.function)K.push(` at ${je.function} (${je.file}:${je.line}:${je.column})`);else K.push(` at ${je.file}:${je.line}:${je.column}`)}return K}function splitErrorMessage(G){const K=G.indexOf(":");return{name:K!==-1?G.slice(0,K):"",message:K!==-1&&K+2<=G.length?G.substring(K+2):G}}function parseErrorStack(G,K,je=false){const ze=G.split("\n");let We=ze.findIndex((G=>G.startsWith(" at ")));if(We===-1)We=ze.length;const Xe=ze.slice(0,We).join("\n");const rt=ze.slice(We);let at;for(const G of rt){const ze=parseStackFrame(G,K,je);if(!ze||!ze.file)continue;if(belongsToNodeModules(ze.file,K))continue;at={file:ze.file,column:ze.column||0,line:ze.line||0};break}return{message:Xe,stackLines:rt,location:at}}function belongsToNodeModules(G,K){return G.includes(`${K}node_modules${K}`)}const rt=new RegExp("^(?:\\s*at )?(?:(new) )?(?:(.*?) \\()?(?:eval at ([^ ]+) \\((.+?):(\\d+):(\\d+)\\), )?(?:(.+?):(\\d+):(\\d+)|(native))(\\)?)$");const at=/^(.*?) \[as (.*?)\]$/;function fileURLToPath(G,K){if(!G.startsWith("file://"))return G;let je=decodeURIComponent(G.slice(7));if(je.startsWith("/")&&/^[a-zA-Z]:/.test(je.slice(1)))je=je.slice(1);return je.replace(/\//g,K)}0&&0},70017:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{ansiRegex:()=>ft,cacheNormalizedWhitespaces:()=>cacheNormalizedWhitespaces,escapeForAttributeSelector:()=>escapeForAttributeSelector,escapeForTextSelector:()=>escapeForTextSelector,escapeHTML:()=>escapeHTML,escapeHTMLAttribute:()=>escapeHTMLAttribute,escapeRegExp:()=>escapeRegExp,escapeTemplateString:()=>escapeTemplateString,escapeWithQuotes:()=>escapeWithQuotes,formatObject:()=>formatObject,formatObjectOrVoid:()=>formatObjectOrVoid,isString:()=>isString,longestCommonSubstring:()=>longestCommonSubstring,normalizeEscapedRegexQuotes:()=>normalizeEscapedRegexQuotes,normalizeWhiteSpace:()=>normalizeWhiteSpace,parseRegex:()=>parseRegex,quoteCSSAttributeValue:()=>quoteCSSAttributeValue,stripAnsiEscapes:()=>stripAnsiEscapes,toSnakeCase:()=>toSnakeCase,toTitleCase:()=>toTitleCase,trimString:()=>trimString,trimStringWithEllipsis:()=>trimStringWithEllipsis});G.exports=__toCommonJS(Xe);function escapeWithQuotes(G,K="'"){const je=JSON.stringify(G);const ze=je.substring(1,je.length-1).replace(/\\"/g,'"');if(K==="'")return K+ze.replace(/[']/g,"\\'")+K;if(K==='"')return K+ze.replace(/["]/g,'\\"')+K;if(K==="`")return K+ze.replace(/[`]/g,"\\`")+K;throw new Error("Invalid escape char")}function escapeTemplateString(G){return G.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function isString(G){return typeof G==="string"||G instanceof String}function toTitleCase(G){return G.charAt(0).toUpperCase()+G.substring(1)}function toSnakeCase(G){return G.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function formatObject(G,K=" ",je="multiline"){if(typeof G==="string")return escapeWithQuotes(G,"'");if(Array.isArray(G))return`[${G.map((G=>formatObject(G))).join(", ")}]`;if(typeof G==="object"){const ze=Object.keys(G).filter((K=>G[K]!==void 0)).sort();if(!ze.length)return"{}";const We=[];for(const K of ze)We.push(`${K}: ${formatObject(G[K])}`);if(je==="multiline")return`{\n${We.join(`,\n${K}`)}\n}`;return`{ ${We.join(", ")} }`}return String(G)}function formatObjectOrVoid(G,K=" "){const je=formatObject(G,K);return je==="{}"?"":je}function quoteCSSAttributeValue(G){return`"${G.replace(/["\\]/g,(G=>"\\"+G))}"`}let rt;function cacheNormalizedWhitespaces(){rt=new Map}function normalizeWhiteSpace(G){let K=rt?.get(G);if(K===void 0){K=G.replace(/[\u200b\u00ad]/g,"").trim().replace(/\s+/g," ");rt?.set(G,K)}return K}function normalizeEscapedRegexQuotes(G){return G.replace(/(^|[^\\])(\\\\)*\\(['"`])/g,"$1$2$3")}function escapeRegexForSelector(G){if(G.unicode||G.unicodeSets)return String(G);return String(G).replace(/(^|[^\\])(\\\\)*(["'`])/g,"$1$2\\$3").replace(/>>/g,"\\>\\>")}function escapeForTextSelector(G,K){if(typeof G!=="string")return escapeRegexForSelector(G);return`${JSON.stringify(G)}${K?"s":"i"}`}function escapeForAttributeSelector(G,K){if(typeof G!=="string")return escapeRegexForSelector(G);return`"${G.replace(/\\/g,"\\\\").replace(/["]/g,'\\"')}"${K?"s":"i"}`}function trimString(G,K,je=""){if(G.length<=K)return G;const ze=[...G];if(ze.length>K)return ze.slice(0,K-je.length).join("")+je;return ze.join("")}function trimStringWithEllipsis(G,K){return trimString(G,K,"…")}function escapeRegExp(G){return G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const at={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function escapeHTMLAttribute(G){return G.replace(/[&<>"']/gu,(G=>at[G]))}function escapeHTML(G){return G.replace(/[&<]/gu,(G=>at[G]))}function longestCommonSubstring(G,K){const je=G.length;const ze=K.length;let We=0;let Xe=0;const rt=Array(je+1).fill(null).map((()=>Array(ze+1).fill(0)));for(let at=1;at<=je;at++){for(let je=1;je<=ze;je++){if(G[at-1]===K[je-1]){rt[at][je]=rt[at-1][je-1]+1;if(rt[at][je]>We){We=rt[at][je];Xe=at}}}}return G.slice(Xe-We,Xe)}function parseRegex(G){if(G[0]!=="/")throw new Error(`Invalid regex, must start with '/': ${G}`);const K=G.lastIndexOf("/");if(K<=0)throw new Error(`Invalid regex, must end with '/' followed by optional flags: ${G}`);const je=G.slice(1,K);const ze=G.slice(K+1);return new RegExp(je,ze)}const ft=new RegExp("([\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~])))","g");function stripAnsiEscapes(G){return G.replace(ft,"")}0&&0},29166:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT:()=>mt,DEFAULT_PLAYWRIGHT_TIMEOUT:()=>ft,monotonicTime:()=>monotonicTime,setTimeOrigin:()=>setTimeOrigin,timeOrigin:()=>timeOrigin});G.exports=__toCommonJS(Xe);let rt=performance.timeOrigin;let at=0;function setTimeOrigin(G){rt=G;at=performance.timeOrigin-G}function timeOrigin(){return rt}function monotonicTime(){return Math.floor((performance.now()+at)*1e3)/1e3}const ft=3e4;const mt=3*60*1e3;0&&0},44782:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{pollAgainstDeadline:()=>pollAgainstDeadline,raceAgainstDeadline:()=>raceAgainstDeadline});G.exports=__toCommonJS(at);var ft=je(29166);async function raceAgainstDeadline(G,K){let je;return Promise.race([G().then((G=>({result:G,timedOut:false}))),new Promise((G=>{const ze=2147483647;const We=(K||ze)-(0,ft.monotonicTime)();je=setTimeout((()=>G({timedOut:true})),We)}))]).finally((()=>{clearTimeout(je)}))}async function pollAgainstDeadline(G,K,je=[100,250,500,1e3]){const ze=je.pop()??1e3;let We;const wrappedCallback=()=>Promise.resolve().then(G);while(true){const G=(0,ft.monotonicTime)();if(K&&G>=K)break;const Xe=await raceAgainstDeadline(wrappedCallback,K);if(Xe.timedOut)break;We=Xe.result.result;if(!Xe.result.continuePolling)return{result:We,timedOut:false};const rt=je.shift()??ze;if(K&&K<=(0,ft.monotonicTime)()+rt)break;await new Promise((G=>setTimeout(G,rt)))}return{timedOut:true,result:We}}0&&0},69985:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{parseClientSideCallMetadata:()=>parseClientSideCallMetadata,serializeClientSideCallMetadata:()=>serializeClientSideCallMetadata});G.exports=__toCommonJS(Xe);function parseClientSideCallMetadata(G){const K=new Map;const{files:je,stacks:ze}=G;for(const G of ze){const[ze,We]=G;K.set(`call@${ze}`,We.map((G=>({file:je[G[0]],line:G[1],column:G[2],function:G[3]}))))}return K}function serializeClientSideCallMetadata(G){const K=new Map;const je=[];for(const ze of G){if(!ze.stack||!ze.stack.length)continue;const G=[];for(const je of ze.stack){let ze=K.get(je.file);if(typeof ze!=="number"){ze=K.size;K.set(je.file,ze)}const We=[ze,je.line||0,je.column||0,je.function||""];G.push(We)}je.push([ze.id,G])}return{files:[...K.keys()],stacks:je}}0&&0},78185:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{constructURLBasedOnBaseURL:()=>constructURLBasedOnBaseURL,globToRegexPattern:()=>globToRegexPattern,resolveGlobToRegexPattern:()=>resolveGlobToRegexPattern,urlMatches:()=>urlMatches,urlMatchesEqual:()=>urlMatchesEqual});G.exports=__toCommonJS(at);var ft=je(70017);const mt=new Set(["$","^","+",".","*","(",")","|","\\","?","{","}","[","]"]);function globToRegexPattern(G){const K=["^"];let je=false;for(let ze=0;ze<G.length;++ze){const We=G[ze];if(We==="\\"&&ze+1<G.length){const je=G[++ze];K.push(mt.has(je)?"\\"+je:je);continue}if(We==="*"){const je=G[ze-1];let We=1;while(G[ze+1]==="*"){We++;ze++}if(We>1){const We=G[ze+1];if(We==="/"){if(je==="/")K.push("((.+/)|)");else K.push("(.*/)");++ze}else{K.push("(.*)")}}else{K.push("([^/]*)")}continue}switch(We){case"{":je=true;K.push("(");break;case"}":je=false;K.push(")");break;case",":if(je){K.push("|");break}K.push("\\"+We);break;default:K.push(mt.has(We)?"\\"+We:We)}}K.push("$");return K.join("")}function isRegExp(G){return G instanceof RegExp||Object.prototype.toString.call(G)==="[object RegExp]"}function urlMatchesEqual(G,K){if(isRegExp(G)&&isRegExp(K))return G.source===K.source&&G.flags===K.flags;return G===K}function urlMatches(G,K,je,ze){if(je===void 0||je==="")return true;if((0,ft.isString)(je))je=new RegExp(resolveGlobToRegexPattern(G,je,ze));if(isRegExp(je)){const G=je.test(K);return G}const We=parseURL(K);if(!We)return false;if(typeof je!=="function")throw new Error("url parameter should be string, RegExp or function");return je(We)}function resolveGlobToRegexPattern(G,K,je){if(je)G=toWebSocketBaseUrl(G);K=resolveGlobBase(G,K);return globToRegexPattern(K)}function toWebSocketBaseUrl(G){if(G&&/^https?:\/\//.test(G))G=G.replace(/^http/,"ws");return G}function resolveGlobBase(G,K){if(!K.startsWith("*")){let mapToken2=function(G,K){if(G.length===0)return"";ze.set(K,G);return K};var je=mapToken2;const ze=new Map;K=K.replaceAll(/\\\\\?/g,"?");if(K.startsWith("about:")||K.startsWith("data:")||K.startsWith("chrome:")||K.startsWith("edge:")||K.startsWith("file:"))return K;const We=K.split("/").map(((G,K)=>{if(G==="."||G===".."||G==="")return G;if(K===0&&G.endsWith(":")){if(G.indexOf("*")!==-1||G.indexOf("{")!==-1)return mapToken2(G,"http:");return G}const je=G.indexOf("?");if(je===-1)return mapToken2(G,`$_${K}_$`);const ze=mapToken2(G.substring(0,je),`$_${K}_$`);const We=mapToken2(G.substring(je),`?$_${K}_$`);return ze+We})).join("/");const Xe=resolveBaseURL(G,We);let rt=Xe.resolved;for(const[G,K]of ze){const je=Xe.caseInsensitivePart?.includes(G);rt=rt.replace(G,je?K.toLowerCase():K)}K=rt}return K}function parseURL(G){try{return new URL(G)}catch(G){return null}}function constructURLBasedOnBaseURL(G,K){try{return resolveBaseURL(G,K).resolved}catch(G){return K}}function resolveBaseURL(G,K){try{const je=new URL(K,G);const ze=je.toString();const We=je.origin;return{resolved:ze,caseInsensitivePart:We}}catch(G){return{resolved:K}}}0&&0},29127:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{parseEvaluationResultValue:()=>parseEvaluationResultValue,serializeAsCallArgument:()=>serializeAsCallArgument});G.exports=__toCommonJS(Xe);function isRegExp(G){try{return G instanceof RegExp||Object.prototype.toString.call(G)==="[object RegExp]"}catch(G){return false}}function isDate(G){try{return G instanceof Date||Object.prototype.toString.call(G)==="[object Date]"}catch(G){return false}}function isURL(G){try{return G instanceof URL||Object.prototype.toString.call(G)==="[object URL]"}catch(G){return false}}function isError(G){try{return G instanceof Error||G&&Object.getPrototypeOf(G)?.name==="Error"}catch(G){return false}}function isTypedArray(G,K){try{return G instanceof K||Object.prototype.toString.call(G)===`[object ${K.name}]`}catch(G){return false}}const rt={i8:Int8Array,ui8:Uint8Array,ui8c:Uint8ClampedArray,i16:Int16Array,ui16:Uint16Array,i32:Int32Array,ui32:Uint32Array,f32:Float32Array,f64:Float64Array,bi64:BigInt64Array,bui64:BigUint64Array};function typedArrayToBase64(G){if("toBase64"in G)return G.toBase64();const K=Array.from(new Uint8Array(G.buffer,G.byteOffset,G.byteLength)).map((G=>String.fromCharCode(G))).join("");return btoa(K)}function base64ToTypedArray(G,K){const je=atob(G);const ze=new Uint8Array(je.length);for(let G=0;G<je.length;G++)ze[G]=je.charCodeAt(G);return new K(ze.buffer)}function parseEvaluationResultValue(G,K=[],je=new Map){if(Object.is(G,void 0))return void 0;if(typeof G==="object"&&G){if("ref"in G)return je.get(G.ref);if("v"in G){if(G.v==="undefined")return void 0;if(G.v==="null")return null;if(G.v==="NaN")return NaN;if(G.v==="Infinity")return Infinity;if(G.v==="-Infinity")return-Infinity;if(G.v==="-0")return-0;return void 0}if("d"in G){return new Date(G.d)}if("u"in G)return new URL(G.u);if("bi"in G)return BigInt(G.bi);if("e"in G){const K=new Error(G.e.m);K.name=G.e.n;K.stack=G.e.s;return K}if("r"in G)return new RegExp(G.r.p,G.r.f);if("a"in G){const ze=[];je.set(G.id,ze);for(const We of G.a)ze.push(parseEvaluationResultValue(We,K,je));return ze}if("o"in G){const ze={};je.set(G.id,ze);for(const{k:We,v:Xe}of G.o){if(We==="__proto__")continue;ze[We]=parseEvaluationResultValue(Xe,K,je)}return ze}if("h"in G)return K[G.h];if("ta"in G)return base64ToTypedArray(G.ta.b,rt[G.ta.k])}return G}function serializeAsCallArgument(G,K){return serialize(G,K,{visited:new Map,lastId:0})}function serialize(G,K,je){if(G&&typeof G==="object"){if(typeof globalThis.Window==="function"&&G instanceof globalThis.Window)return"ref: <Window>";if(typeof globalThis.Document==="function"&&G instanceof globalThis.Document)return"ref: <Document>";if(typeof globalThis.Node==="function"&&G instanceof globalThis.Node)return"ref: <Node>"}return innerSerialize(G,K,je)}function innerSerialize(G,K,je){const ze=K(G);if("fallThrough"in ze)G=ze.fallThrough;else return ze;if(typeof G==="symbol")return{v:"undefined"};if(Object.is(G,void 0))return{v:"undefined"};if(Object.is(G,null))return{v:"null"};if(Object.is(G,NaN))return{v:"NaN"};if(Object.is(G,Infinity))return{v:"Infinity"};if(Object.is(G,-Infinity))return{v:"-Infinity"};if(Object.is(G,-0))return{v:"-0"};if(typeof G==="boolean")return G;if(typeof G==="number")return G;if(typeof G==="string")return G;if(typeof G==="bigint")return{bi:G.toString()};if(isError(G)){let K;if(G.stack?.startsWith(G.name+": "+G.message)){K=G.stack}else{K=`${G.name}: ${G.message}\n${G.stack}`}return{e:{n:G.name,m:G.message,s:K}}}if(isDate(G))return{d:G.toJSON()};if(isURL(G))return{u:G.toJSON()};if(isRegExp(G))return{r:{p:G.source,f:G.flags}};for(const[K,je]of Object.entries(rt)){if(isTypedArray(G,je))return{ta:{b:typedArrayToBase64(G),k:K}}}const We=je.visited.get(G);if(We)return{ref:We};if(Array.isArray(G)){const ze=[];const We=++je.lastId;je.visited.set(G,We);for(let We=0;We<G.length;++We)ze.push(serialize(G[We],K,je));return{a:ze,id:We}}if(typeof G==="object"){const ze=[];const We=++je.lastId;je.visited.set(G,We);for(const We of Object.keys(G)){let Xe;try{Xe=G[We]}catch(G){continue}if(We==="toJSON"&&typeof Xe==="function")ze.push({k:We,v:{o:[],id:0}});else ze.push({k:We,v:serialize(Xe,K,je)})}let Xe;try{if(ze.length===0&&G.toJSON&&typeof G.toJSON==="function")Xe={value:G.toJSON()}}catch(G){}if(Xe)return innerSerialize(Xe.value,K,je);return{o:ze,id:We}}}0&&0},83432:G=>{"use strict";var K=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var __export=(G,je)=>{for(var ze in je)K(G,ze,{get:je[ze],enumerable:true})};var __copyProps=(G,Xe,rt,at)=>{if(Xe&&typeof Xe==="object"||typeof Xe==="function"){for(let ft of ze(Xe))if(!We.call(G,ft)&&ft!==rt)K(G,ft,{get:()=>Xe[ft],enumerable:!(at=je(Xe,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(K({},"__esModule",{value:true}),G);var Xe={};__export(Xe,{yamlEscapeKeyIfNeeded:()=>yamlEscapeKeyIfNeeded,yamlEscapeValueIfNeeded:()=>yamlEscapeValueIfNeeded});G.exports=__toCommonJS(Xe);function yamlEscapeKeyIfNeeded(G){if(!yamlStringNeedsQuotes(G))return G;return`'`+G.replace(/'/g,`''`)+`'`}function yamlEscapeValueIfNeeded(G){if(!yamlStringNeedsQuotes(G))return G;return'"'+G.replace(/[\\"\x00-\x1f\x7f-\x9f]/g,(G=>{switch(G){case"\\":return"\\\\";case'"':return'\\"';case"\b":return"\\b";case"\f":return"\\f";case"\n":return"\\n";case"\r":return"\\r";case"\t":return"\\t";default:const K=G.charCodeAt(0);return"\\x"+K.toString(16).padStart(2,"0")}}))+'"'}function yamlStringNeedsQuotes(G){if(G.length===0)return true;if(/^\s|\s$/.test(G))return true;if(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/.test(G))return true;if(/^-/.test(G))return true;if(/[\n:](\s|$)/.test(G))return true;if(/\s#/.test(G))return true;if(/[\n\r]/.test(G))return true;if(/^[&*\],?!>|@"'#%]/.test(G))return true;if(/[{}`]/.test(G))return true;if(/^\[/.test(G))return true;if(!isNaN(Number(G))||["y","n","yes","no","true","false","on","off","null"].includes(G.toLowerCase()))return true;return false}0&&0},45392:(G,K,je)=>{"use strict";var ze=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var __export=(G,K)=>{for(var je in K)ze(G,je,{get:K[je],enumerable:true})};var __copyProps=(G,K,je,at)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let ft of Xe(K))if(!rt.call(G,ft)&&ft!==je)ze(G,ft,{get:()=>K[ft],enumerable:!(at=We(K,ft))||at.enumerable})}return G};var __toCommonJS=G=>__copyProps(ze({},"__esModule",{value:true}),G);var at={};__export(at,{extract:()=>vt,yauzl:()=>mt,yazl:()=>ft});G.exports=__toCommonJS(at);const ft=je(15070).yazl;const mt=je(15070).yauzl;const vt=je(15070).extract;0&&0},15070:(G,K,je)=>{"use strict";var ze=Object.create;var We=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var at=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var v=(G,K)=>()=>(K||G((K={exports:{}}).exports,K),K.exports),Ct=(G,K)=>{for(var je in K)We(G,je,{get:K[je],enumerable:!0})},or=(G,K,je,ze)=>{if(K&&typeof K=="object"||typeof K=="function")for(let at of rt(K))!ft.call(G,at)&&at!==je&&We(G,at,{get:()=>K[at],enumerable:!(ze=Xe(K,at))||ze.enumerable});return G};var sr=(G,K,je)=>(je=G!=null?ze(at(G)):{},or(K||!G||!G.__esModule?We(je,"default",{value:G,enumerable:!0}):je,G)),bt=G=>or(We({},"__esModule",{value:!0}),G);var mt=v(((G,K)=>{var ze=je(20181).Buffer,We=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];typeof Int32Array!="undefined"&&(We=new Int32Array(We));function fr(G){if(ze.isBuffer(G))return G;var K=typeof ze.alloc=="function"&&typeof ze.from=="function";if(typeof G=="number")return K?ze.alloc(G):new ze(G);if(typeof G=="string")return K?ze.from(G):new ze(G);throw new Error("input must be buffer, number, or string, received "+typeof G)}function Ft(G){var K=fr(4);return K.writeInt32BE(G,0),K}function Ue(G,K){G=fr(G),ze.isBuffer(K)&&(K=K.readUInt32BE(0));for(var je=~~K^-1,Xe=0;Xe<G.length;Xe++)je=We[(je^G[Xe])&255]^je>>>8;return je^-1}function Te(){return Ft(Ue.apply(null,arguments))}Te.signed=function(){return Ue.apply(null,arguments)};Te.unsigned=function(){return Ue.apply(null,arguments)>>>0};K.exports=Te}));var vt=v((G=>{var K=je(79896),ze=je(2203).Transform,We=je(2203).PassThrough,Xe=je(43106),rt=je(39023),at=je(24434).EventEmitter,ft=mt();G.ZipFile=P;G.dateToDosDateTime=br;rt.inherits(P,at);function P(){this.outputStream=new We,this.entries=[],this.outputStreamCursor=0,this.ended=!1,this.allDone=!1,this.forceZip64Eocd=!1}P.prototype.addFile=function(G,je,ze){var We=this;je=de(je,!1),ze==null&&(ze={});var Xe=new m(je,!1,ze);We.entries.push(Xe),K.stat(G,(function(je,rt){if(je)return We.emit("error",je);if(!rt.isFile())return We.emit("error",new Error("not a file: "+G));Xe.uncompressedSize=rt.size,ze.mtime==null&&Xe.setLastModDate(rt.mtime),ze.mode==null&&Xe.setFileAttributesMode(rt.mode),Xe.setFileDataPumpFunction((function(){var je=K.createReadStream(G);Xe.state=m.FILE_DATA_IN_PROGRESS,je.on("error",(function(G){We.emit("error",G)})),hr(We,Xe,je)})),N(We)}))};P.prototype.addReadStream=function(G,K,je){var ze=this;K=de(K,!1),je==null&&(je={});var We=new m(K,!1,je);ze.entries.push(We),We.setFileDataPumpFunction((function(){We.state=m.FILE_DATA_IN_PROGRESS,hr(ze,We,G)})),N(ze)};P.prototype.addBuffer=function(G,K,je){var ze=this;if(K=de(K,!1),G.length>1073741823)throw new Error("buffer too large: "+G.length+" > 1073741823");if(je==null&&(je={}),je.size!=null)throw new Error("options.size not allowed");var We=new m(K,!1,je);We.uncompressedSize=G.length,We.crc32=ft.unsigned(G),We.crcAndFileSizeKnown=!0,ze.entries.push(We),We.compress?Xe.deflateRaw(G,(function(G,K){s(K)})):s(G);function s(G){We.compressedSize=G.length,We.setFileDataPumpFunction((function(){q(ze,G),q(ze,We.getDataDescriptor()),We.state=m.FILE_DATA_DONE,setImmediate((function(){N(ze)}))})),N(ze)}};P.prototype.addEmptyDirectory=function(G,K){var je=this;if(G=de(G,!0),K==null&&(K={}),K.size!=null)throw new Error("options.size not allowed");if(K.compress!=null)throw new Error("options.compress not allowed");var ze=new m(G,!0,K);je.entries.push(ze),ze.setFileDataPumpFunction((function(){q(je,ze.getDataDescriptor()),ze.state=m.FILE_DATA_DONE,N(je)})),N(je)};var vt=T([80,75,5,6]);P.prototype.end=function(G,K){if(typeof G=="function"&&(K=G,G=null),G==null&&(G={}),!this.ended){if(this.ended=!0,this.finalSizeCallback=K,this.forceZip64Eocd=!!G.forceZip64Format,G.comment){if(typeof G.comment=="string"?this.comment=zt(G.comment):this.comment=G.comment,this.comment.length>65535)throw new Error("comment is too large");if(J(this.comment,vt))throw new Error("comment contains end of central directory record signature")}else this.comment=Er;N(this)}};function q(G,K){G.outputStream.write(K),G.outputStreamCursor+=K.length}function hr(G,K,je){var ze=new Ze,rt=new ue,at=K.compress?new Xe.DeflateRaw:new We,ft=new ue;je.pipe(ze).pipe(rt).pipe(at).pipe(ft).pipe(G.outputStream,{end:!1}),ft.on("end",(function(){if(K.crc32=ze.crc32,K.uncompressedSize==null)K.uncompressedSize=rt.byteCount;else if(K.uncompressedSize!==rt.byteCount)return G.emit("error",new Error("file data stream has unexpected number of bytes"));K.compressedSize=ft.byteCount,G.outputStreamCursor+=K.compressedSize,q(G,K.getDataDescriptor()),K.state=m.FILE_DATA_DONE,N(G)}))}function N(G){if(G.allDone)return;if(G.ended&&G.finalSizeCallback!=null){var K=Lt(G);K!=null&&(G.finalSizeCallback(K),G.finalSizeCallback=null)}var je=n();function n(){for(var K=0;K<G.entries.length;K++){var je=G.entries[K];if(je.state<m.FILE_DATA_DONE)return je}return null}if(je!=null){if(je.state<m.READY_TO_PUMP_FILE_DATA||je.state===m.FILE_DATA_IN_PROGRESS)return;je.relativeOffsetOfLocalHeader=G.outputStreamCursor;var ze=je.getLocalFileHeader();q(G,ze),je.doFileDataPump()}else G.ended&&(G.offsetOfStartOfCentralDirectory=G.outputStreamCursor,G.entries.forEach((function(K){var je=K.getCentralDirectoryRecord();q(G,je)})),q(G,Ot(G)),G.outputStream.end(),G.allDone=!0)}function Lt(G){for(var K=0,je=0,ze=0;ze<G.entries.length;ze++){var We=G.entries[ze];if(We.compress)return-1;if(We.state>=m.READY_TO_PUMP_FILE_DATA){if(We.uncompressedSize==null)return-1}else if(We.uncompressedSize==null)return null;We.relativeOffsetOfLocalHeader=K;var Xe=We.useZip64Format();K+=Rr+We.utf8FileName.length,K+=We.uncompressedSize,We.crcAndFileSizeKnown||(Xe?K+=Ei:K+=Si),je+=ki+We.utf8FileName.length+We.fileComment.length,Xe&&(je+=Ci)}var rt=0;return(G.forceZip64Eocd||G.entries.length>=65535||je>=65535||K>=4294967295)&&(rt+=yt+wt),rt+=lr+G.comment.length,K+je+rt}var yt=56,wt=20,lr=22;function Ot(G,K){var je=!1,ze=G.entries.length;(G.forceZip64Eocd||G.entries.length>=65535)&&(ze=65535,je=!0);var We=G.outputStreamCursor-G.offsetOfStartOfCentralDirectory,Xe=We;(G.forceZip64Eocd||We>=4294967295)&&(Xe=4294967295,je=!0);var rt=G.offsetOfStartOfCentralDirectory;if((G.forceZip64Eocd||G.offsetOfStartOfCentralDirectory>=4294967295)&&(rt=4294967295,je=!0),K)return je?yt+wt+lr:lr;var at=g(lr+G.comment.length);if(at.writeUInt32LE(101010256,0),at.writeUInt16LE(0,4),at.writeUInt16LE(0,6),at.writeUInt16LE(ze,8),at.writeUInt16LE(ze,10),at.writeUInt32LE(Xe,12),at.writeUInt32LE(rt,16),at.writeUInt16LE(G.comment.length,20),G.comment.copy(at,22),!je)return at;var ft=g(yt);ft.writeUInt32LE(101075792,0),I(ft,yt-12,4),ft.writeUInt16LE(fi,12),ft.writeUInt16LE(zr,14),ft.writeUInt32LE(0,16),ft.writeUInt32LE(0,20),I(ft,G.entries.length,24),I(ft,G.entries.length,32),I(ft,We,40),I(ft,G.offsetOfStartOfCentralDirectory,48);var mt=g(wt);return mt.writeUInt32LE(117853008,0),mt.writeUInt32LE(0,4),I(mt,G.outputStreamCursor,8),mt.writeUInt32LE(1,16),Buffer.concat([ft,mt,at])}function de(G,K){if(G==="")throw new Error("empty metadataPath");if(G=G.replace(/\\/g,"/"),/^[a-zA-Z]:/.test(G)||/^\//.test(G))throw new Error("absolute path: "+G);if(G.split("/").indexOf("..")!==-1)throw new Error("invalid relative path: "+G);var je=/\/$/.test(G);if(K)je||(G+="/");else if(je)throw new Error("file path cannot end with '/': "+G);return G}var Er=g(0);function m(G,K,je){if(this.utf8FileName=T(G),this.utf8FileName.length>65535)throw new Error("utf8 file name too long. "+utf8FileName.length+" > 65535");if(this.isDirectory=K,this.state=m.WAITING_FOR_METADATA,this.setLastModDate(je.mtime!=null?je.mtime:new Date),je.mode!=null?this.setFileAttributesMode(je.mode):this.setFileAttributesMode(K?16893:33204),K?(this.crcAndFileSizeKnown=!0,this.crc32=0,this.uncompressedSize=0,this.compressedSize=0):(this.crcAndFileSizeKnown=!1,this.crc32=null,this.uncompressedSize=null,this.compressedSize=null,je.size!=null&&(this.uncompressedSize=je.size)),K?this.compress=!1:(this.compress=!0,je.compress!=null&&(this.compress=!!je.compress)),this.forceZip64Format=!!je.forceZip64Format,je.fileComment){if(typeof je.fileComment=="string"?this.fileComment=T(je.fileComment,"utf-8"):this.fileComment=je.fileComment,this.fileComment.length>65535)throw new Error("fileComment is too large")}else this.fileComment=Er}m.WAITING_FOR_METADATA=0;m.READY_TO_PUMP_FILE_DATA=1;m.FILE_DATA_IN_PROGRESS=2;m.FILE_DATA_DONE=3;m.prototype.setLastModDate=function(G){var K=br(G);this.lastModFileTime=K.time,this.lastModFileDate=K.date};m.prototype.setFileAttributesMode=function(G){if((G&65535)!==G)throw new Error("invalid mode. expected: 0 <= "+G+" <= 65535");this.externalFileAttributes=G<<16>>>0};m.prototype.setFileDataPumpFunction=function(G){this.doFileDataPump=G,this.state=m.READY_TO_PUMP_FILE_DATA};m.prototype.useZip64Format=function(){return this.forceZip64Format||this.uncompressedSize!=null&&this.uncompressedSize>4294967294||this.compressedSize!=null&&this.compressedSize>4294967294||this.relativeOffsetOfLocalHeader!=null&&this.relativeOffsetOfLocalHeader>4294967294};var Rr=30,jr=20,zr=45,fi=831,mi=2048,bi=8;m.prototype.getLocalFileHeader=function(){var G=0,K=0,je=0;this.crcAndFileSizeKnown&&(G=this.crc32,K=this.compressedSize,je=this.uncompressedSize);var ze=g(Rr),We=mi;return this.crcAndFileSizeKnown||(We|=bi),ze.writeUInt32LE(67324752,0),ze.writeUInt16LE(jr,4),ze.writeUInt16LE(We,6),ze.writeUInt16LE(this.getCompressionMethod(),8),ze.writeUInt16LE(this.lastModFileTime,10),ze.writeUInt16LE(this.lastModFileDate,12),ze.writeUInt32LE(G,14),ze.writeUInt32LE(K,18),ze.writeUInt32LE(je,22),ze.writeUInt16LE(this.utf8FileName.length,26),ze.writeUInt16LE(0,28),Buffer.concat([ze,this.utf8FileName])};var Si=16,Ei=24;m.prototype.getDataDescriptor=function(){if(this.crcAndFileSizeKnown)return Er;if(this.useZip64Format()){var G=g(Ei);return G.writeUInt32LE(134695760,0),G.writeUInt32LE(this.crc32,4),I(G,this.compressedSize,8),I(G,this.uncompressedSize,16),G}else{var G=g(Si);return G.writeUInt32LE(134695760,0),G.writeUInt32LE(this.crc32,4),G.writeUInt32LE(this.compressedSize,8),G.writeUInt32LE(this.uncompressedSize,12),G}};var ki=46,Ci=28;m.prototype.getCentralDirectoryRecord=function(){var G=g(ki),K=mi;this.crcAndFileSizeKnown||(K|=bi);var je=this.compressedSize,ze=this.uncompressedSize,We=this.relativeOffsetOfLocalHeader,Xe,rt;return this.useZip64Format()?(je=4294967295,ze=4294967295,We=4294967295,Xe=zr,rt=g(Ci),rt.writeUInt16LE(1,0),rt.writeUInt16LE(Ci-4,2),I(rt,this.uncompressedSize,4),I(rt,this.compressedSize,12),I(rt,this.relativeOffsetOfLocalHeader,20)):(Xe=jr,rt=Er),G.writeUInt32LE(33639248,0),G.writeUInt16LE(fi,4),G.writeUInt16LE(Xe,6),G.writeUInt16LE(K,8),G.writeUInt16LE(this.getCompressionMethod(),10),G.writeUInt16LE(this.lastModFileTime,12),G.writeUInt16LE(this.lastModFileDate,14),G.writeUInt32LE(this.crc32,16),G.writeUInt32LE(je,20),G.writeUInt32LE(ze,24),G.writeUInt16LE(this.utf8FileName.length,28),G.writeUInt16LE(rt.length,30),G.writeUInt16LE(this.fileComment.length,32),G.writeUInt16LE(0,34),G.writeUInt16LE(0,36),G.writeUInt32LE(this.externalFileAttributes,38),G.writeUInt32LE(We,42),Buffer.concat([G,this.utf8FileName,rt,this.fileComment])};m.prototype.getCompressionMethod=function(){var G=0,K=8;return this.compress?K:G};function br(G){var K=0;K|=G.getDate()&31,K|=(G.getMonth()+1&15)<<5,K|=(G.getFullYear()-1980&127)<<9;var je=0;return je|=Math.floor(G.getSeconds()/2),je|=(G.getMinutes()&63)<<5,je|=(G.getHours()&31)<<11,{date:K,time:je}}function I(G,K,je){var ze=Math.floor(K/4294967296),We=K%4294967296;G.writeUInt32LE(We,je),G.writeUInt32LE(ze,je+4)}rt.inherits(ue,ze);function ue(G){ze.call(this,G),this.byteCount=0}ue.prototype._transform=function(G,K,je){this.byteCount+=G.length,je(null,G)};rt.inherits(Ze,ze);function Ze(G){ze.call(this,G),this.crc32=0}Ze.prototype._transform=function(G,K,je){this.crc32=ft.unsigned(G,this.crc32),je(null,G)};var Ti="\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ";if(Ti.length!==256)throw new Error("assertion failure");var Pi=null;function zt(G){if(/^[\x20-\x7e]*$/.test(G))return T(G,"utf-8");if(Pi==null){Pi={};for(var K=0;K<Ti.length;K++)Pi[Ti[K]]=K}for(var je=g(G.length),K=0;K<G.length;K++){var ze=Pi[G[K]];if(ze==null)throw new Error("character not encodable in CP437: "+JSON.stringify(G[K]));je[K]=ze}return je}function g(G){g=r;try{return g(G)}catch{return g=t,g(G)}function r(G){return Buffer.allocUnsafe(G)}function t(G){return new Buffer(G)}}function T(G,K){T=t;try{return T(G,K)}catch{return T=n,T(G,K)}function t(G,K){return Buffer.from(G,K)}function n(G,K){return new Buffer(G,K)}}function J(G,K){J=t;try{return J(G,K)}catch{return J=n,J(G,K)}function t(G,K){return G.includes(K)}function n(G,K){for(var je=0;je<=G.length-K.length;je++)for(var ze=0;;ze++){if(ze===K.length)return!0;if(G[je+ze]!==K[ze])break}return!1}}}));var yt=v(((G,K)=>{K.exports=he;function he(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}he.prototype.go=function(G){this.pending<this.max?Sr(this,G):this.waiting.push(G)};he.prototype.wait=function(G){this.pending===0?G(this.error):this.listeners.push(G)};he.prototype.hold=function(){return Ir(this)};function Ir(G){G.pending+=1;var K=!1;return t;function t(je){if(K)throw new Error("callback called twice");if(K=!0,G.error=G.error||je,G.pending-=1,G.waiting.length>0&&G.pending<G.max)Sr(G,G.waiting.shift());else if(G.pending===0){var ze=G.listeners;G.listeners=[],ze.forEach(n)}}function n(K){K(G.error)}}function Sr(G,K){K(Ir(G))}}));var wt=v((G=>{var K=je(79896),ze=je(39023),We=je(2203),Xe=We.Readable,rt=We.Writable,at=We.PassThrough,ft=yt(),mt=je(24434).EventEmitter;G.createFromBuffer=Dt;G.createFromFd=At;G.BufferSlicer=D;G.FdSlicer=R;ze.inherits(R,mt);function R(G,K){K=K||{},mt.call(this),this.fd=G,this.pend=new ft,this.pend.max=1,this.refCount=0,this.autoClose=!!K.autoClose}R.prototype.read=function(G,je,ze,We,Xe){var rt=this;rt.pend.go((function(at){K.read(rt.fd,G,je,ze,We,(function(G,K,je){at(),Xe(G,K,je)}))}))};R.prototype.write=function(G,je,ze,We,Xe){var rt=this;rt.pend.go((function(at){K.write(rt.fd,G,je,ze,We,(function(G,K,je){at(),Xe(G,K,je)}))}))};R.prototype.createReadStream=function(G){return new xe(this,G)};R.prototype.createWriteStream=function(G){return new Ee(this,G)};R.prototype.ref=function(){this.refCount+=1};R.prototype.unref=function(){var G=this;if(G.refCount-=1,G.refCount>0)return;if(G.refCount<0)throw new Error("invalid unref");G.autoClose&&K.close(G.fd,r);function r(K){K?G.emit("error",K):G.emit("close")}};ze.inherits(xe,Xe);function xe(G,K){K=K||{},Xe.call(this,K),this.context=G,this.context.ref(),this.start=K.start||0,this.endOffset=K.end,this.pos=this.start,this.destroyed=!1}xe.prototype._read=function(G){var je=this;if(!je.destroyed){var ze=Math.min(je._readableState.highWaterMark,G);if(je.endOffset!=null&&(ze=Math.min(ze,je.endOffset-je.pos)),ze<=0){je.destroyed=!0,je.push(null),je.context.unref();return}je.context.pend.go((function(G){if(je.destroyed)return G();var We=Buffer.allocUnsafe(ze);K.read(je.context.fd,We,0,ze,je.pos,(function(K,ze){K?je.destroy(K):ze===0?(je.destroyed=!0,je.push(null),je.context.unref()):(je.pos+=ze,je.push(We.slice(0,ze))),G()}))}))}};xe.prototype.destroy=function(G){this.destroyed||(G=G||new Error("stream destroyed"),this.destroyed=!0,this.emit("error",G),this.context.unref())};ze.inherits(Ee,rt);function Ee(G,K){K=K||{},rt.call(this,K),this.context=G,this.context.ref(),this.start=K.start||0,this.endOffset=K.end==null?1/0:+K.end,this.bytesWritten=0,this.pos=this.start,this.destroyed=!1,this.on("finish",this.destroy.bind(this))}Ee.prototype._write=function(G,je,ze){var We=this;if(!We.destroyed){if(We.pos+G.length>We.endOffset){var Xe=new Error("maximum file length exceeded");Xe.code="ETOOBIG",We.destroy(),ze(Xe);return}We.context.pend.go((function(je){if(We.destroyed)return je();K.write(We.context.fd,G,0,G.length,We.pos,(function(G,K){G?(We.destroy(),je(),ze(G)):(We.bytesWritten+=K,We.pos+=K,We.emit("progress"),je(),ze())}))}))}};Ee.prototype.destroy=function(){this.destroyed||(this.destroyed=!0,this.context.unref())};ze.inherits(D,mt);function D(G,K){mt.call(this),K=K||{},this.refCount=0,this.buffer=G,this.maxChunkSize=K.maxChunkSize||Number.MAX_SAFE_INTEGER}D.prototype.read=function(G,K,je,ze,We){if(!(0<=K&&K<=G.length))throw new RangeError("offset outside buffer: 0 <= "+K+" <= "+G.length);if(ze<0)throw new RangeError("position is negative: "+ze);if(K+je>G.length&&(je=G.length-K),ze+je>this.buffer.length&&(je=this.buffer.length-ze),je<=0){setImmediate((function(){We(null,0)}));return}this.buffer.copy(G,K,ze,ze+je),setImmediate((function(){We(null,je)}))};D.prototype.write=function(G,K,je,ze,We){G.copy(this.buffer,ze,K,K+je),setImmediate((function(){We(null,je,G)}))};D.prototype.createReadStream=function(G){G=G||{};var K=new at(G);K.destroyed=!1,K.start=G.start||0,K.endOffset=G.end,K.pos=K.endOffset||this.buffer.length;for(var je=this.buffer.slice(K.start,K.pos),ze=0;;){var We=ze+this.maxChunkSize;if(We>=je.length){ze<je.length&&K.write(je.slice(ze,je.length));break}K.write(je.slice(ze,We)),ze=We}return K.end(),K.destroy=function(){K.destroyed=!0},K};D.prototype.createWriteStream=function(G){var K=this;G=G||{};var je=new rt(G);return je.start=G.start||0,je.endOffset=G.end==null?this.buffer.length:+G.end,je.bytesWritten=0,je.pos=je.start,je.destroyed=!1,je._write=function(G,ze,We){if(!je.destroyed){var Xe=je.pos+G.length;if(Xe>je.endOffset){var rt=new Error("maximum file length exceeded");rt.code="ETOOBIG",je.destroyed=!0,We(rt);return}G.copy(K.buffer,je.pos,0,G.length),je.bytesWritten+=G.length,je.pos=Xe,je.emit("progress"),We()}},je.destroy=function(){je.destroyed=!0},je};D.prototype.ref=function(){this.refCount+=1};D.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw new Error("invalid unref")};function Dt(G,K){return new D(G,K)}function At(G,K){return new R(G,K)}}));var lr=v((G=>{var K=je(79896),ze=je(43106),We=wt(),Xe=mt(),rt=je(39023),at=je(24434).EventEmitter,ft=je(2203).Transform,vt=je(2203).PassThrough,yt=je(2203).Writable;G.open=Mt;G.fromFd=Ar;G.fromBuffer=Bt;G.fromRandomAccessReader=Ve;G.dosDateTimeToDate=Nr;G.getFileNameLowLevel=Mr;G.validateFileName=Br;G.parseExtraFields=qr;G.ZipFile=_;G.Entry=ee;G.LocalFileHeader=Tr;G.RandomAccessReader=M;function Mt(G,je,ze){typeof je=="function"&&(ze=je,je=null),je==null&&(je={}),je.autoClose==null&&(je.autoClose=!0),je.lazyEntries==null&&(je.lazyEntries=!1),je.decodeStrings==null&&(je.decodeStrings=!0),je.validateEntrySizes==null&&(je.validateEntrySizes=!0),je.strictFileNames==null&&(je.strictFileNames=!1),ze==null&&(ze=we),K.open(G,"r",(function(G,We){if(G)return ze(G);Ar(We,je,(function(G,je){G&&K.close(We,we),ze(G,je)}))}))}function Ar(G,je,ze){typeof je=="function"&&(ze=je,je=null),je==null&&(je={}),je.autoClose==null&&(je.autoClose=!1),je.lazyEntries==null&&(je.lazyEntries=!1),je.decodeStrings==null&&(je.decodeStrings=!0),je.validateEntrySizes==null&&(je.validateEntrySizes=!0),je.strictFileNames==null&&(je.strictFileNames=!1),ze==null&&(ze=we),K.fstat(G,(function(K,Xe){if(K)return ze(K);var rt=We.createFromFd(G,{autoClose:!0});Ve(rt,Xe.size,je,ze)}))}function Bt(G,K,je){typeof K=="function"&&(je=K,K=null),K==null&&(K={}),K.autoClose=!1,K.lazyEntries==null&&(K.lazyEntries=!1),K.decodeStrings==null&&(K.decodeStrings=!0),K.validateEntrySizes==null&&(K.validateEntrySizes=!0),K.strictFileNames==null&&(K.strictFileNames=!1);var ze=We.createFromBuffer(G,{maxChunkSize:65536});Ve(ze,G.length,K,je)}function Ve(G,K,je,ze){typeof je=="function"&&(ze=je,je=null),je==null&&(je={}),je.autoClose==null&&(je.autoClose=!0),je.lazyEntries==null&&(je.lazyEntries=!1),je.decodeStrings==null&&(je.decodeStrings=!0);var We=!!je.decodeStrings;if(je.validateEntrySizes==null&&(je.validateEntrySizes=!0),je.strictFileNames==null&&(je.strictFileNames=!1),ze==null&&(ze=we),typeof K!="number")throw new Error("expected totalSize parameter to be a number");if(K>Number.MAX_SAFE_INTEGER)throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");G.ref();var Xe=22,rt=20,at=65535,ft=Math.min(rt+Xe+at,K),mt=Er(ft),vt=K-mt.length;j(G,mt,0,ft,vt,(function(at){if(at)return ze(at);for(var vt=ft-Xe;vt>=0;vt-=1)if(mt.readUInt32LE(vt)===101010256){var yt=mt.subarray(vt),wt=yt.readUInt16LE(4),lr=yt.readUInt16LE(10),Rr=yt.readUInt32LE(16),jr=yt.readUInt16LE(20),zr=yt.length-Xe;if(jr!==zr)return ze(new Error("Invalid comment length. Expected: "+zr+". Found: "+jr+". Are there extra bytes at the end of the file? Or is the end of central dir signature `PK☺☻` in the comment?"));var fi=We?ve(yt.subarray(22),!1):yt.subarray(22);if(vt-rt>=0&&mt.readUInt32LE(vt-rt)===117853008){var mi=mt.subarray(vt-rt,vt-rt+rt),bi=Y(mi,8),Si=Er(56);return j(G,Si,0,Si.length,bi,(function(Xe){return Xe?ze(Xe):Si.readUInt32LE(0)!==101075792?ze(new Error("invalid zip64 end of central directory record signature")):(wt=Si.readUInt32LE(16),wt!==0?ze(new Error("multi-disk zip files are not supported: found disk number: "+wt)):(lr=Y(Si,32),Rr=Y(Si,48),ze(null,new _(G,Rr,K,lr,fi,je.autoClose,je.lazyEntries,We,je.validateEntrySizes,je.strictFileNames))))}))}return wt!==0?ze(new Error("multi-disk zip files are not supported: found disk number: "+wt)):ze(null,new _(G,Rr,K,lr,fi,je.autoClose,je.lazyEntries,We,je.validateEntrySizes,je.strictFileNames))}ze(new Error("End of central directory record signature not found. Either not a zip file, or file is truncated."))}))}rt.inherits(_,at);function _(G,K,je,ze,We,Xe,rt,ft,mt,vt){var yt=this;at.call(yt),yt.reader=G,yt.reader.on("error",(function(G){Ur(yt,G)})),yt.reader.once("close",(function(){yt.emit("close")})),yt.readEntryCursor=K,yt.fileSize=je,yt.entryCount=ze,yt.comment=We,yt.entriesRead=0,yt.autoClose=!!Xe,yt.lazyEntries=!!rt,yt.decodeStrings=!!ft,yt.validateEntrySizes=!!mt,yt.strictFileNames=!!vt,yt.isOpen=!0,yt.emittedError=!1,yt.lazyEntries||yt._readEntry()}_.prototype.close=function(){this.isOpen&&(this.isOpen=!1,this.reader.unref())};function z(G,K){G.autoClose&&G.close(),Ur(G,K)}function Ur(G,K){G.emittedError||(G.emittedError=!0,G.emit("error",K))}_.prototype.readEntry=function(){if(!this.lazyEntries)throw new Error("readEntry() called without lazyEntries:true");this._readEntry()};_.prototype._readEntry=function(){var G=this;if(G.entryCount===G.entriesRead){setImmediate((function(){G.autoClose&&G.close(),!G.emittedError&&G.emit("end")}));return}if(!G.emittedError){var K=Er(46);j(G.reader,K,0,K.length,G.readEntryCursor,(function(je){if(je)return z(G,je);if(!G.emittedError){var ze=new ee,We=K.readUInt32LE(0);if(We!==33639248)return z(G,new Error("invalid central directory file header signature: 0x"+We.toString(16)));if(ze.versionMadeBy=K.readUInt16LE(4),ze.versionNeededToExtract=K.readUInt16LE(6),ze.generalPurposeBitFlag=K.readUInt16LE(8),ze.compressionMethod=K.readUInt16LE(10),ze.lastModFileTime=K.readUInt16LE(12),ze.lastModFileDate=K.readUInt16LE(14),ze.crc32=K.readUInt32LE(16),ze.compressedSize=K.readUInt32LE(20),ze.uncompressedSize=K.readUInt32LE(24),ze.fileNameLength=K.readUInt16LE(28),ze.extraFieldLength=K.readUInt16LE(30),ze.fileCommentLength=K.readUInt16LE(32),ze.internalFileAttributes=K.readUInt16LE(36),ze.externalFileAttributes=K.readUInt32LE(38),ze.relativeOffsetOfLocalHeader=K.readUInt32LE(42),ze.generalPurposeBitFlag&64)return z(G,new Error("strong encryption is not supported"));G.readEntryCursor+=46,K=Er(ze.fileNameLength+ze.extraFieldLength+ze.fileCommentLength),j(G.reader,K,0,K.length,G.readEntryCursor,(function(je){if(je)return z(G,je);if(!G.emittedError){ze.fileNameRaw=K.subarray(0,ze.fileNameLength);var We=ze.fileNameLength+ze.extraFieldLength;ze.extraFieldRaw=K.subarray(ze.fileNameLength,We),ze.fileCommentRaw=K.subarray(We,We+ze.fileCommentLength);try{ze.extraFields=qr(ze.extraFieldRaw)}catch(K){return z(G,K)}if(G.decodeStrings){var Xe=(ze.generalPurposeBitFlag&2048)!==0;ze.fileComment=ve(ze.fileCommentRaw,Xe),ze.fileName=Mr(ze.generalPurposeBitFlag,ze.fileNameRaw,ze.extraFields,G.strictFileNames);var rt=Br(ze.fileName);if(rt!=null)return z(G,new Error(rt))}else ze.fileComment=ze.fileCommentRaw,ze.fileName=ze.fileNameRaw;ze.comment=ze.fileComment,G.readEntryCursor+=K.length,G.entriesRead+=1;for(var at=0;at<ze.extraFields.length;at++){var ft=ze.extraFields[at];if(ft.id===1){var mt=ft.data,vt=0;if(ze.uncompressedSize===4294967295){if(vt+8>mt.length)return z(G,new Error("zip64 extended information extra field does not include uncompressed size"));ze.uncompressedSize=Y(mt,vt),vt+=8}if(ze.compressedSize===4294967295){if(vt+8>mt.length)return z(G,new Error("zip64 extended information extra field does not include compressed size"));ze.compressedSize=Y(mt,vt),vt+=8}if(ze.relativeOffsetOfLocalHeader===4294967295){if(vt+8>mt.length)return z(G,new Error("zip64 extended information extra field does not include relative header offset"));ze.relativeOffsetOfLocalHeader=Y(mt,vt),vt+=8}break}}if(G.validateEntrySizes&&ze.compressionMethod===0){var yt=ze.uncompressedSize;if(ze.isEncrypted()&&(yt+=12),ze.compressedSize!==yt){var wt="compressed/uncompressed size mismatch for stored file: "+ze.compressedSize+" != "+ze.uncompressedSize;return z(G,new Error(wt))}}G.emit("entry",ze),G.lazyEntries||G._readEntry()}}))}}))}};_.prototype.openReadStream=function(G,K,je){var ze=this,We=0,Xe=G.compressedSize;if(je==null&&(je=K,K=null),K==null)K={};else{if(K.decrypt!=null){if(!G.isEncrypted())throw new Error("options.decrypt can only be specified for encrypted entries");if(K.decrypt!==!1)throw new Error("invalid options.decrypt value: "+K.decrypt);if(G.isCompressed()&&K.decompress!==!1)throw new Error("entry is encrypted and compressed, and options.decompress !== false")}if(K.decompress!=null){if(!G.isCompressed())throw new Error("options.decompress can only be specified for compressed entries");if(!(K.decompress===!1||K.decompress===!0))throw new Error("invalid options.decompress value: "+K.decompress)}if(K.start!=null||K.end!=null){if(G.isCompressed()&&K.decompress!==!1)throw new Error("start/end range not allowed for compressed entry without options.decompress === false");if(G.isEncrypted()&&K.decrypt!==!1)throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false")}if(K.start!=null){if(We=K.start,We<0)throw new Error("options.start < 0");if(We>G.compressedSize)throw new Error("options.start > entry.compressedSize")}if(K.end!=null){if(Xe=K.end,Xe<0)throw new Error("options.end < 0");if(Xe>G.compressedSize)throw new Error("options.end > entry.compressedSize");if(Xe<We)throw new Error("options.end < options.start")}}if(!ze.isOpen)return je(new Error("closed"));if(G.isEncrypted()&&K.decrypt!==!1)return je(new Error("entry is encrypted, and options.decrypt !== false"));var rt;if(G.compressionMethod===0)rt=!1;else if(G.compressionMethod===8)rt=K.decompress!=null?K.decompress:!0;else return je(new Error("unsupported compression method: "+G.compressionMethod));ze.readLocalFileHeader(G,{minimal:!0},(function(K,at){if(K)return je(K);ze.openReadStreamLowLevel(at.fileDataStart,G.compressedSize,We,Xe,rt,G.uncompressedSize,je)}))};_.prototype.openReadStreamLowLevel=function(G,K,je,We,Xe,rt,at){var ft=this,mt=G+K,vt=ft.reader.createReadStream({start:G+je,end:G+We}),yt=vt;if(Xe){var wt=!1,lr=ze.createInflateRaw();vt.on("error",(function(G){setImmediate((function(){wt||lr.emit("error",G)}))})),vt.pipe(lr),ft.validateEntrySizes?(yt=new re(rt),lr.on("error",(function(G){setImmediate((function(){wt||yt.emit("error",G)}))})),lr.pipe(yt)):yt=lr,He(yt,(function(){wt=!0,lr!==yt&&lr.unpipe(yt),vt.unpipe(lr),vt.destroy()}))}at(null,yt)};_.prototype.readLocalFileHeader=function(G,K,je){var ze=this;je==null&&(je=K,K=null),K==null&&(K={}),ze.reader.ref();var We=Er(30);j(ze.reader,We,0,We.length,G.relativeOffsetOfLocalHeader,(function(Xe){try{if(Xe)return je(Xe);var rt=We.readUInt32LE(0);if(rt!==67324752)return je(new Error("invalid local file header signature: 0x"+rt.toString(16)));var at=We.readUInt16LE(26),ft=We.readUInt16LE(28),mt=G.relativeOffsetOfLocalHeader+30+at+ft;if(mt+G.compressedSize>ze.fileSize)return je(new Error("file data overflows file bounds: "+mt+" + "+G.compressedSize+" > "+ze.fileSize));if(K.minimal)return je(null,{fileDataStart:mt});var vt=new Tr;vt.fileDataStart=mt,vt.versionNeededToExtract=We.readUInt16LE(4),vt.generalPurposeBitFlag=We.readUInt16LE(6),vt.compressionMethod=We.readUInt16LE(8),vt.lastModFileTime=We.readUInt16LE(10),vt.lastModFileDate=We.readUInt16LE(12),vt.crc32=We.readUInt32LE(14),vt.compressedSize=We.readUInt32LE(18),vt.uncompressedSize=We.readUInt32LE(22),vt.fileNameLength=at,vt.extraFieldLength=ft,We=Er(at+ft),ze.reader.ref(),j(ze.reader,We,0,We.length,G.relativeOffsetOfLocalHeader+30,(function(G){try{return G?je(G):(vt.fileName=We.subarray(0,at),vt.extraField=We.subarray(at),je(null,vt))}finally{ze.reader.unref()}}))}finally{ze.reader.unref()}}))};function ee(){}ee.prototype.getLastModDate=function(G){if(G==null&&(G={}),!G.forceDosFormat)for(var K=0;K<this.extraFields.length;K++){var je=this.extraFields[K];if(je.id===21589){var ze=je.data;if(ze.length<5)continue;var We=ze[0],Xe=1;if(!(We&Xe))continue;var rt=ze.readInt32LE(1);return new Date(rt*1e3)}else if(je.id===10)for(var ze=je.data,at=4;at<ze.length+4;){var ft=ze.readUInt16LE(at);at+=2;var mt=ze.readUInt16LE(at);if(at+=2,ft!==1){at+=mt;continue}if(mt<8||at+mt>ze.length)break;var vt=4294967296*ze.readInt32LE(at+4)+ze.readUInt32LE(at),yt=vt/1e4-116444736e5;return new Date(yt)}}return Nr(this.lastModFileDate,this.lastModFileTime,G.timezone)};ee.prototype.isEncrypted=function(){return(this.generalPurposeBitFlag&1)!==0};ee.prototype.isCompressed=function(){return this.compressionMethod===8};function Tr(){}function Nr(G,K,je){var ze=G&31,We=(G>>5&15)-1,Xe=(G>>9&127)+1980,rt=0,at=(K&31)*2,ft=K>>5&63,mt=K>>11&31;if(je==null||je==="local")return new Date(Xe,We,ze,mt,ft,at,rt);if(je==="UTC")return new Date(Date.UTC(Xe,We,ze,mt,ft,at,rt));throw new Error("unrecognized options.timezone: "+options.timezone)}function Mr(G,K,je,ze){for(var We=null,rt=0;rt<je.length;rt++){var at=je[rt];if(at.id===28789){if(at.data.length<6||at.data.readUInt8(0)!==1)continue;var ft=at.data.readUInt32LE(1);if(Xe.unsigned(K)!==ft)continue;We=ve(at.data.subarray(5),!0);break}}if(We==null){var mt=(G&2048)!==0;We=ve(K,mt)}return ze||(We=We.replace(/\\/g,"/")),We}function Br(G){return G.indexOf("\\")!==-1?"invalid characters in fileName: "+G:/^[a-zA-Z]:/.test(G)||/^\//.test(G)?"absolute path: "+G:G.split("/").indexOf("..")!==-1?"invalid relative path: "+G:null}function qr(G){for(var K=[],je=0;je<G.length-3;){var ze=G.readUInt16LE(je+0),We=G.readUInt16LE(je+2),Xe=je+4,rt=Xe+We;if(rt>G.length)throw new Error("extra field length exceeds extra field buffer size");var at=G.subarray(Xe,rt);K.push({id:ze,data:at}),je=rt}return K}function j(G,K,je,ze,We,Xe){if(ze===0)return setImmediate((function(){Xe(null,Er(0))}));G.read(K,je,ze,We,(function(G,K){if(G)return Xe(G);if(K<ze)return Xe(new Error("unexpected EOF"));Xe()}))}rt.inherits(re,ft);function re(G){ft.call(this),this.actualByteCount=0,this.expectedByteCount=G}re.prototype._transform=function(G,K,je){if(this.actualByteCount+=G.length,this.actualByteCount>this.expectedByteCount){var ze="too many bytes in the stream. expected "+this.expectedByteCount+". got at least "+this.actualByteCount;return je(new Error(ze))}je(null,G)};re.prototype._flush=function(G){if(this.actualByteCount<this.expectedByteCount){var K="not enough bytes in the stream. expected "+this.expectedByteCount+". got only "+this.actualByteCount;return G(new Error(K))}G()};rt.inherits(M,at);function M(){at.call(this),this.refCount=0}M.prototype.ref=function(){this.refCount+=1};M.prototype.unref=function(){var G=this;if(G.refCount-=1,G.refCount>0)return;if(G.refCount<0)throw new Error("invalid unref");G.close(r);function r(K){if(K)return G.emit("error",K);G.emit("close")}};M.prototype.createReadStream=function(G){G==null&&(G={});var K=G.start,je=G.end;if(K===je){var ze=new vt;return setImmediate((function(){ze.end()})),ze}var We=this._readStreamForRange(K,je),Xe=!1,rt=new Ce(this);We.on("error",(function(G){setImmediate((function(){Xe||rt.emit("error",G)}))})),He(rt,(function(){We.unpipe(rt),rt.unref(),We.destroy()}));var at=new re(je-K);return rt.on("error",(function(G){setImmediate((function(){Xe||at.emit("error",G)}))})),He(at,(function(){Xe=!0,rt.unpipe(at),rt.destroy()})),We.pipe(rt).pipe(at)};M.prototype._readStreamForRange=function(G,K){throw new Error("not implemented")};M.prototype.read=function(G,K,je,ze,We){var Xe=this.createReadStream({start:ze,end:ze+je}),rt=new yt,at=0;rt._write=function(je,ze,We){je.copy(G,K+at,0,je.length),at+=je.length,We()},rt.on("finish",We),Xe.on("error",(function(G){We(G)})),Xe.pipe(rt)};M.prototype.close=function(G){setImmediate(G)};rt.inherits(Ce,vt);function Ce(G){vt.call(this),this.context=G,this.context.ref(),this.unreffedYet=!1}Ce.prototype._flush=function(G){this.unref(),G()};Ce.prototype.unref=function(G){this.unreffedYet||(this.unreffedYet=!0,this.context.unref())};var lr="\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ";function ve(G,K){if(K)return G.toString("utf8");for(var je="",ze=0;ze<G.length;ze++)je+=lr[G[ze]];return je}function Y(G,K){var je=G.readUInt32LE(K),ze=G.readUInt32LE(K+4);return ze*4294967296+je}var Er;typeof Buffer.allocUnsafe=="function"?Er=function(G){return Buffer.allocUnsafe(G)}:Er=function(G){return new Buffer(G)};function He(G,K){typeof G.destroy=="function"?G._destroy=function(G,je){K(),je!=null&&je(G)}:G.destroy=K}function we(G){if(G)throw G}}));var Er=v(((G,K)=>{var je=1e3,ze=je*60,We=ze*60,Xe=We*24,rt=Xe*7,at=Xe*365.25;K.exports=function(G,K){K=K||{};var je=typeof G;if(je==="string"&&G.length>0)return Wt(G);if(je==="number"&&isFinite(G))return K.long?Yt(G):Gt(G);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(G))};function Wt(G){if(G=String(G),!(G.length>100)){var K=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(G);if(K){var ft=parseFloat(K[1]),mt=(K[2]||"ms").toLowerCase();switch(mt){case"years":case"year":case"yrs":case"yr":case"y":return ft*at;case"weeks":case"week":case"w":return ft*rt;case"days":case"day":case"d":return ft*Xe;case"hours":case"hour":case"hrs":case"hr":case"h":return ft*We;case"minutes":case"minute":case"mins":case"min":case"m":return ft*ze;case"seconds":case"second":case"secs":case"sec":case"s":return ft*je;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return ft;default:return}}}}function Gt(G){var K=Math.abs(G);return K>=Xe?Math.round(G/Xe)+"d":K>=We?Math.round(G/We)+"h":K>=ze?Math.round(G/ze)+"m":K>=je?Math.round(G/je)+"s":G+"ms"}function Yt(G){var K=Math.abs(G);return K>=Xe?be(G,K,Xe,"day"):K>=We?be(G,K,We,"hour"):K>=ze?be(G,K,ze,"minute"):K>=je?be(G,K,je,"second"):G+" ms"}function be(G,K,je,ze){var We=K>=je*1.5;return Math.round(G/je)+" "+ze+(We?"s":"")}}));var Rr=v(((G,K)=>{function jt(G){t.debug=t,t.default=t,t.coerce=u,t.disable=o,t.enable=i,t.enabled=f,t.humanize=Er(),t.destroy=l,Object.keys(G).forEach((K=>{t[K]=G[K]})),t.names=[],t.skips=[],t.formatters={};function r(G){let K=0;for(let je=0;je<G.length;je++)K=(K<<5)-K+G.charCodeAt(je),K|=0;return t.colors[Math.abs(K)%t.colors.length]}t.selectColor=r;function t(G){let K,je=null,ze,We;function p(...G){if(!p.enabled)return;let je=p,ze=Number(new Date),We=ze-(K||ze);je.diff=We,je.prev=K,je.curr=ze,K=ze,G[0]=t.coerce(G[0]),typeof G[0]!="string"&&G.unshift("%O");let Xe=0;G[0]=G[0].replace(/%([a-zA-Z%])/g,((K,ze)=>{if(K==="%%")return"%";Xe++;let We=t.formatters[ze];if(typeof We=="function"){let ze=G[Xe];K=We.call(je,ze),G.splice(Xe,1),Xe--}return K})),t.formatArgs.call(je,G),(je.log||t.log).apply(je,G)}return p.namespace=G,p.useColors=t.useColors(),p.color=t.selectColor(G),p.extend=n,p.destroy=t.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>je!==null?je:(ze!==t.namespaces&&(ze=t.namespaces,We=t.enabled(G)),We),set:G=>{je=G}}),typeof t.init=="function"&&t.init(p),p}function n(G,K){let je=t(this.namespace+(typeof K=="undefined"?":":K)+G);return je.log=this.log,je}function i(G){t.save(G),t.namespaces=G,t.names=[],t.skips=[];let K=(typeof G=="string"?G:"").trim().replace(" ",",").split(",").filter(Boolean);for(let G of K)G[0]==="-"?t.skips.push(G.slice(1)):t.names.push(G)}function s(G,K){let je=0,ze=0,We=-1,Xe=0;for(;je<G.length;)if(ze<K.length&&(K[ze]===G[je]||K[ze]==="*"))K[ze]==="*"?(We=ze,Xe=je,ze++):(je++,ze++);else if(We!==-1)ze=We+1,Xe++,je=Xe;else return!1;for(;ze<K.length&&K[ze]==="*";)ze++;return ze===K.length}function o(){let G=[...t.names,...t.skips.map((G=>"-"+G))].join(",");return t.enable(""),G}function f(G){for(let K of t.skips)if(s(G,K))return!1;for(let K of t.names)if(s(G,K))return!0;return!1}function u(G){return G instanceof Error?G.stack||G.message:G}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}K.exports=jt}));var jr=v(((G,K)=>{G.formatArgs=Kt;G.save=Vt;G.load=Xt;G.useColors=Ht;G.storage=$t();G.destroy=(()=>{let G=!1;return()=>{G||(G=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();G.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Ht(){if(typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let G;return typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&(G=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(G[1],10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Kt(G){if(G[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+G[0]+(this.useColors?"%c ":" ")+"+"+K.exports.humanize(this.diff),!this.useColors)return;let je="color: "+this.color;G.splice(1,0,je,"color: inherit");let ze=0,We=0;G[0].replace(/%[a-zA-Z%]/g,(G=>{G!=="%%"&&(ze++,G==="%c"&&(We=ze))})),G.splice(We,0,je)}G.log=console.debug||console.log||(()=>{});function Vt(K){try{K?G.storage.setItem("debug",K):G.storage.removeItem("debug")}catch{}}function Xt(){let K;try{K=G.storage.getItem("debug")}catch{}return!K&&typeof process!="undefined"&&"env"in process&&(K=process.env.DEBUG),K}function $t(){try{return localStorage}catch{}}K.exports=Rr()(G);var{formatters:je}=K.exports;je.j=function(G){try{return JSON.stringify(G)}catch(G){return"[UnexpectedJSONParseError]: "+G.message}}}));var zr=v(((G,K)=>{"use strict";K.exports=(G,K=process.argv)=>{let je=G.startsWith("-")?"":G.length===1?"-":"--",ze=K.indexOf(je+G),We=K.indexOf("--");return ze!==-1&&(We===-1||ze<We)}}));var fi=v(((G,K)=>{"use strict";var ze=je(70857),We=je(52018),Xe=zr(),{env:rt}=process,at;Xe("no-color")||Xe("no-colors")||Xe("color=false")||Xe("color=never")?at=0:(Xe("color")||Xe("colors")||Xe("color=true")||Xe("color=always"))&&(at=1);function kt(){if("FORCE_COLOR"in rt)return rt.FORCE_COLOR==="true"?1:rt.FORCE_COLOR==="false"?0:rt.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(rt.FORCE_COLOR,10),3)}function en(G){return G===0?!1:{level:G,hasBasic:!0,has256:G>=2,has16m:G>=3}}function rn(G,{streamIsTTY:K,sniffFlags:je=!0}={}){let We=kt();We!==void 0&&(at=We);let ft=je?at:We;if(ft===0)return 0;if(je){if(Xe("color=16m")||Xe("color=full")||Xe("color=truecolor"))return 3;if(Xe("color=256"))return 2}if(G&&!K&&ft===void 0)return 0;let mt=ft||0;if(rt.TERM==="dumb")return mt;if(process.platform==="win32"){let G=ze.release().split(".");return Number(G[0])>=10&&Number(G[2])>=10586?Number(G[2])>=14931?3:2:1}if("CI"in rt)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some((G=>G in rt))||rt.CI_NAME==="codeship"?1:mt;if("TEAMCITY_VERSION"in rt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(rt.TEAMCITY_VERSION)?1:0;if(rt.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in rt){let G=Number.parseInt((rt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(rt.TERM_PROGRAM){case"iTerm.app":return G>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(rt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(rt.TERM)||"COLORTERM"in rt?1:mt}function Je(G,K={}){let je=rn(G,{streamIsTTY:G&&G.isTTY,...K});return en(je)}K.exports={supportsColor:Je,stdout:Je({isTTY:We.isatty(1)}),stderr:Je({isTTY:We.isatty(2)})}}));var mi=v(((G,K)=>{var ze=je(52018),We=je(39023);G.init=cn;G.log=fn;G.formatArgs=on;G.save=an;G.load=un;G.useColors=nn;G.destroy=We.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");G.colors=[6,2,3,4,5,1];try{let K=fi();K&&(K.stderr||K).level>=2&&(G.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}G.inspectOpts=Object.keys(process.env).filter((G=>/^debug_/i.test(G))).reduce(((G,K)=>{let je=K.substring(6).toLowerCase().replace(/_([a-z])/g,((G,K)=>K.toUpperCase())),ze=process.env[K];return/^(yes|on|true|enabled)$/i.test(ze)?ze=!0:/^(no|off|false|disabled)$/i.test(ze)?ze=!1:ze==="null"?ze=null:ze=Number(ze),G[je]=ze,G}),{});function nn(){return"colors"in G.inspectOpts?!!G.inspectOpts.colors:ze.isatty(process.stderr.fd)}function on(G){let{namespace:je,useColors:ze}=this;if(ze){let ze=this.color,We="[3"+(ze<8?ze:"8;5;"+ze),Xe=` ${We};1m${je} `;G[0]=Xe+G[0].split(`\n`).join(`\n`+Xe),G.push(We+"m+"+K.exports.humanize(this.diff)+"")}else G[0]=sn()+je+" "+G[0]}function sn(){return G.inspectOpts.hideDate?"":(new Date).toISOString()+" "}function fn(...K){return process.stderr.write(We.formatWithOptions(G.inspectOpts,...K)+`\n`)}function an(G){G?process.env.DEBUG=G:delete process.env.DEBUG}function un(){return process.env.DEBUG}function cn(K){K.inspectOpts={};let je=Object.keys(G.inspectOpts);for(let ze=0;ze<je.length;ze++)K.inspectOpts[je[ze]]=G.inspectOpts[je[ze]]}K.exports=Rr()(G);var{formatters:Xe}=K.exports;Xe.o=function(G){return this.inspectOpts.colors=this.useColors,We.inspect(G,this.inspectOpts).split(`\n`).map((G=>G.trim())).join(" ")};Xe.O=function(G){return this.inspectOpts.colors=this.useColors,We.inspect(G,this.inspectOpts)}}));var bi=v(((G,K)=>{typeof process=="undefined"||process.type==="renderer"||process.browser===!0||process.__nwjs?K.exports=jr():K.exports=mi()}));var Si=v(((G,K)=>{K.exports=Qr;function Qr(G,K){if(G&&K)return Qr(G)(K);if(typeof G!="function")throw new TypeError("need wrapper function");return Object.keys(G).forEach((function(K){t[K]=G[K]})),t;function t(){for(var K=new Array(arguments.length),je=0;je<K.length;je++)K[je]=arguments[je];var ze=G.apply(this,K),We=K[K.length-1];return typeof ze=="function"&&ze!==We&&Object.keys(We).forEach((function(G){ze[G]=We[G]})),ze}}}));var Ei=v(((G,K)=>{var je=Si();K.exports=je(Oe);K.exports.strict=je(tt);Oe.proto=Oe((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return Oe(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return tt(this)},configurable:!0})}));function Oe(G){var r=function(){return r.called?r.value:(r.called=!0,r.value=G.apply(this,arguments))};return r.called=!1,r}function tt(G){var r=function(){if(r.called)throw new Error(r.onceError);return r.called=!0,r.value=G.apply(this,arguments)},K=G.name||"Function wrapped with `once`";return r.onceError=K+" shouldn't be called more than once",r.called=!1,r}}));var ki=v(((G,K)=>{var je=Ei(),ln=function(){},hn=function(G){return G.setHeader&&typeof G.abort=="function"},mn=function(G){return G.stdio&&Array.isArray(G.stdio)&&G.stdio.length===3},nt=function(G,K,ze){if(typeof K=="function")return nt(G,null,K);K||(K={}),ze=je(ze||ln);var We=G._writableState,Xe=G._readableState,rt=K.readable||K.readable!==!1&&G.readable,at=K.writable||K.writable!==!1&&G.writable,ft=!1,u=function(){G.writable||l()},l=function(){at=!1,rt||ze.call(G)},a=function(){rt=!1,at||ze.call(G)},c=function(K){ze.call(G,K?new Error("exited with error code: "+K):null)},d=function(K){ze.call(G,K)},h=function(){process.nextTick(E)},E=function(){if(!ft){if(rt&&!(Xe&&Xe.ended&&!Xe.destroyed))return ze.call(G,new Error("premature close"));if(at&&!(We&&We.ended&&!We.destroyed))return ze.call(G,new Error("premature close"))}},p=function(){G.req.on("finish",l)};return hn(G)?(G.on("complete",l),G.on("abort",h),G.req?p():G.on("request",p)):at&&!We&&(G.on("end",u),G.on("close",u)),mn(G)&&G.on("exit",c),G.on("end",a),G.on("finish",l),K.error!==!1&&G.on("error",d),G.on("close",h),function(){ft=!0,G.removeListener("complete",l),G.removeListener("abort",h),G.removeListener("request",p),G.req&&G.req.removeListener("finish",l),G.removeListener("end",u),G.removeListener("close",u),G.removeListener("finish",l),G.removeListener("exit",c),G.removeListener("end",a),G.removeListener("error",d),G.removeListener("close",h)}};K.exports=nt}));var Ci=v(((G,K)=>{var ze=Ei(),We=ki(),Xe;try{Xe=je(79896)}catch{}var te=function(){},rt=/^v?\.0/.test(process.version),_e=function(G){return typeof G=="function"},vn=function(G){return!rt||!Xe?!1:(G instanceof(Xe.ReadStream||te)||G instanceof(Xe.WriteStream||te))&&_e(G.close)},wn=function(G){return G.setHeader&&_e(G.abort)},yn=function(G,K,je,Xe){Xe=ze(Xe);var rt=!1;G.on("close",(function(){rt=!0})),We(G,{readable:K,writable:je},(function(G){if(G)return Xe(G);rt=!0,Xe()}));var at=!1;return function(K){if(!rt&&!at){if(at=!0,vn(G))return G.close(te);if(wn(G))return G.abort();if(_e(G.destroy))return G.destroy();Xe(K||new Error("stream was destroyed"))}}},st=function(G){G()},gn=function(G,K){return G.pipe(K)},Cn=function(){var G=Array.prototype.slice.call(arguments),K=_e(G[G.length-1]||te)&&G.pop()||te;if(Array.isArray(G[0])&&(G=G[0]),G.length<2)throw new Error("pump requires two streams per minimum");var je,ze=G.map((function(We,Xe){var rt=Xe<G.length-1,at=Xe>0;return yn(We,rt,at,(function(G){je||(je=G),G&&ze.forEach(st),!rt&&(ze.forEach(st),K(je))}))}));return G.reduce(gn)};K.exports=Cn}));var Ti=v(((G,K)=>{"use strict";var{PassThrough:ze}=je(2203);K.exports=G=>{G={...G};let{array:K}=G,{encoding:je}=G,We=je==="buffer",Xe=!1;K?Xe=!(je||We):je=je||"utf8",We&&(je=null);let rt=new ze({objectMode:Xe});je&&rt.setEncoding(je);let at=0,ft=[];return rt.on("data",(G=>{ft.push(G),Xe?at=ft.length:at+=G.length})),rt.getBufferedValue=()=>K?ft:We?Buffer.concat(ft,at):ft.join(""),rt.getBufferedLength=()=>at,rt}}));var Pi=v(((G,K)=>{"use strict";var{constants:ze}=je(20181),We=Ci(),Xe=Ti(),rt=class extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};async function De(G,K){if(!G)return Promise.reject(new Error("Expected a stream"));K={maxBuffer:1/0,...K};let{maxBuffer:je}=K,at;return await new Promise(((ft,mt)=>{let o=G=>{G&&at.getBufferedLength()<=ze.MAX_LENGTH&&(G.bufferedData=at.getBufferedValue()),mt(G)};at=We(G,Xe(K),(G=>{if(G){o(G);return}ft()})),at.on("data",(()=>{at.getBufferedLength()>je&&o(new rt)}))})),at.getBufferedValue()}K.exports=De;K.exports.default=De;K.exports.buffer=(G,K)=>De(G,{...K,encoding:"buffer"});K.exports.array=(G,K)=>De(G,{...K,array:!0});K.exports.MaxBufferError=rt}));var Ii=v(((G,K)=>{"use strict";var ze=bi()("extract-zip"),{createWriteStream:We,promises:Xe}=je(79896),rt=Pi(),at=je(16928),{promisify:ft}=je(39023),mt=je(2203),vt=lr(),yt=ft(vt.open),wt=ft(mt.pipeline),Er=class{constructor(G,K){this.zipPath=G,this.opts=K}async extract(){return ze("opening",this.zipPath,"with opts",this.opts),this.zipfile=await yt(this.zipPath,{lazyEntries:!0}),this.canceled=!1,new Promise(((G,K)=>{this.zipfile.on("error",(G=>{this.canceled=!0,K(G)})),this.zipfile.readEntry(),this.zipfile.on("close",(()=>{this.canceled||(ze("zip extraction complete"),G())})),this.zipfile.on("entry",(async G=>{if(this.canceled){ze("skipping entry",G.fileName,{cancelled:this.canceled});return}if(ze("zipfile entry",G.fileName),G.fileName.startsWith("__MACOSX/")){this.zipfile.readEntry();return}let je=at.dirname(at.join(this.opts.dir,G.fileName));try{await Xe.mkdir(je,{recursive:!0});let K=await Xe.realpath(je);if(at.relative(this.opts.dir,K).split(at.sep).includes(".."))throw new Error(`Out of bound path "${K}" found while processing file ${G.fileName}`);await this.extractEntry(G),ze("finished processing",G.fileName),this.zipfile.readEntry()}catch(G){this.canceled=!0,this.zipfile.close(),K(G)}}))}))}async extractEntry(G){if(this.canceled){ze("skipping entry extraction",G.fileName,{cancelled:this.canceled});return}this.opts.onEntry&&this.opts.onEntry(G,this.zipfile);let K=at.join(this.opts.dir,G.fileName),je=G.externalFileAttributes>>16&65535,mt=61440,vt=16384,yt=(je&mt)===40960,lr=(je&mt)===vt;!lr&&G.fileName.endsWith("/")&&(lr=!0);let Er=G.versionMadeBy>>8;lr||(lr=Er===0&&G.externalFileAttributes===16),ze("extracting entry",{filename:G.fileName,isDir:lr,isSymlink:yt});let Rr=this.getExtractedMode(je,lr)&511,jr=lr?K:at.dirname(K),zr={recursive:!0};if(lr&&(zr.mode=Rr),ze("mkdir",{dir:jr,...zr}),await Xe.mkdir(jr,zr),lr)return;ze("opening read stream",K);let fi=await ft(this.zipfile.openReadStream.bind(this.zipfile))(G);if(yt){let G=await rt(fi);ze("creating symlink",G,K),await Xe.symlink(G,K)}else await wt(fi,We(K,{mode:Rr}))}getExtractedMode(G,K){let je=G;return je===0&&(K?(this.opts.defaultDirMode&&(je=parseInt(this.opts.defaultDirMode,10)),je||(je=493)):(this.opts.defaultFileMode&&(je=parseInt(this.opts.defaultFileMode,10)),je||(je=420))),je}};K.exports=async function(G,K){if(ze("creating target directory",K.dir),!at.isAbsolute(K.dir))throw new Error("Target directory is expected to be absolute");return await Xe.mkdir(K.dir,{recursive:!0}),K.dir=await Xe.realpath(K.dir),new Er(G,K).extract()}}));var Ri={};Ct(Ri,{extract:()=>ps,yauzl:()=>qi,yazl:()=>Mi});G.exports=bt(Ri);var Mi=sr(vt()),qi=sr(lr()),Xi=Ii(),ps=Xi;0&&0},47885:(G,K,je)=>{G.exports=je(92383)},34881:(G,K,je)=>{"use strict";const ze=je(51940);G.exports=(G="")=>{const K=G.match(ze);if(!K){return null}const[je,We]=K[0].replace(/#! ?/,"").split(" ");const Xe=je.split("/").pop();if(Xe==="env"){return We}return We?`${Xe} ${We}`:Xe}},51940:G=>{"use strict";G.exports=/^#!(.*)/},31192:(G,K,je)=>{const ze=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys";const We=je(16928);const Xe=ze?";":":";const rt=je(97105);const getNotFoundError=G=>Object.assign(new Error(`not found: ${G}`),{code:"ENOENT"});const getPathInfo=(G,K)=>{const je=K.colon||Xe;const We=G.match(/\//)||ze&&G.match(/\\/)?[""]:[...ze?[process.cwd()]:[],...(K.path||process.env.PATH||"").split(je)];const rt=ze?K.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"";const at=ze?rt.split(je):[""];if(ze){if(G.indexOf(".")!==-1&&at[0]!=="")at.unshift("")}return{pathEnv:We,pathExt:at,pathExtExe:rt}};const which=(G,K,je)=>{if(typeof K==="function"){je=K;K={}}if(!K)K={};const{pathEnv:ze,pathExt:Xe,pathExtExe:at}=getPathInfo(G,K);const ft=[];const step=je=>new Promise(((Xe,rt)=>{if(je===ze.length)return K.all&&ft.length?Xe(ft):rt(getNotFoundError(G));const at=ze[je];const mt=/^".*"$/.test(at)?at.slice(1,-1):at;const vt=We.join(mt,G);const yt=!mt&&/^\.[\\\/]/.test(G)?G.slice(0,2)+vt:vt;Xe(subStep(yt,je,0))}));const subStep=(G,je,ze)=>new Promise(((We,mt)=>{if(ze===Xe.length)return We(step(je+1));const vt=Xe[ze];rt(G+vt,{pathExt:at},((Xe,rt)=>{if(!Xe&&rt){if(K.all)ft.push(G+vt);else return We(G+vt)}return We(subStep(G,je,ze+1))}))}));return je?step(0).then((G=>je(null,G)),je):step(0)};const whichSync=(G,K)=>{K=K||{};const{pathEnv:je,pathExt:ze,pathExtExe:Xe}=getPathInfo(G,K);const at=[];for(let ft=0;ft<je.length;ft++){const mt=je[ft];const vt=/^".*"$/.test(mt)?mt.slice(1,-1):mt;const yt=We.join(vt,G);const wt=!vt&&/^\.[\\\/]/.test(G)?G.slice(0,2)+yt:yt;for(let G=0;G<ze.length;G++){const je=wt+ze[G];try{const G=rt.sync(je,{pathExt:Xe});if(G){if(K.all)at.push(je);else return je}}catch(G){}}}if(K.all&&at.length)return at;if(K.nothrow)return null;throw getNotFoundError(G)};G.exports=which;which.sync=whichSync},35440:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.ArchitectAgent=void 0;const ze=je(4843);const We=je(18984);const Xe=je(45037);const rt=je(21393);class ArchitectAgent{deps;constructor(G={}){this.deps=G}async run(G){let K;if(G.rawDocs?.length&&this.deps.llmIrGenerator){K=await this.deps.llmIrGenerator.generate(G.rawDocs.join("\n\n"))}else{K=(0,Xe.buildIRFromDiscovery)(G)}const je=(0,rt.planShards)(K.tools.map((G=>({name:G.name,domain:"default"}))),40);const at=(0,We.generateRuntimeConfig)(je);const ft=(0,ze.checkTokenBudget)(JSON.stringify(K.tools),8e3);return{ir:K,shards:je,config:at,budget:ft}}}K.ArchitectAgent=ArchitectAgent},18984:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.generateRuntimeConfig=generateRuntimeConfig;function generateRuntimeConfig(G){const K=['version: "3.9"',"services:"];for(const je of G){K.push(` ${je.id}:`);K.push(" image: mcp-claw/mcp-server:latest");K.push(` ports: ["${je.port}:${je.port}"]`)}const je=["server {"," listen 443 ssl;"];for(const K of G){je.push(` location /mcp/${K.id} {`);je.push(` proxy_pass http://127.0.0.1:${K.port};`);je.push(" }")}je.push("}");return{compose:`${K.join("\n")}\n`,nginx:`${je.join("\n")}\n`}}},45037:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.buildIRFromDiscovery=buildIRFromDiscovery;function toToolName(G){const K=G.replace(/^\/+/,"").replace(/[^a-zA-Z0-9]+/g,"_");return K||"root"}function toTool(G){const K=new URL(G.url);return{name:toToolName(K.pathname),description:`GET ${K.pathname}`,method:"GET",path:K.pathname||"/",needsConfirmation:false,isAsync:false,params:[]}}function buildIRFromDiscovery(G){const K=G.endpoints[0]?.url??"https://example.com";const je=new URL(K).origin;return{system:{code:"target-system",baseUrl:je,authType:"none"},tools:G.endpoints.map(toTool)}}},27275:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.LlmIrGenerator=void 0;const je={system:{code:"unknown",baseUrl:"https://api.example.com",authType:"none"},tools:[]};const ze=new Set(["GET","POST","PUT","DELETE"]);const We=new Set(["none","bearer","api-key"]);function stripMarkdownFences(G){const K=G.trim();const je=K.match(/^```[a-zA-Z0-9_-]*\s*([\s\S]*?)\s*```$/);return je?.[1]?.trim()??K}function normalizeMethod(G){const K=typeof G==="string"?G.toUpperCase():"";if(ze.has(K)){return K}return"GET"}function normalizeAuthType(G){const K=typeof G==="string"?G.toLowerCase():"";if(We.has(K)){return K}return"none"}function toSnakeCase(G){const K=G.trim().replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toLowerCase();return K||"generated_tool"}function normalizeParams(G){if(!Array.isArray(G)){return[]}return G.filter((G=>Boolean(G)&&typeof G==="object")).map((G=>({name:typeof G.name==="string"?G.name:"",type:typeof G.type==="string"?G.type:"string",required:G.required===true,description:typeof G.description==="string"?G.description:undefined}))).filter((G=>G.name.length>0))}function normalizeTools(G){if(!Array.isArray(G)){return[]}const K=[];for(const je of G){if(!je||typeof je!=="object"){continue}const G=je;const ze=normalizeMethod(G.method);const We=typeof G.path==="string"&&G.path.startsWith("/")?G.path:"/";const Xe=toSnakeCase(typeof G.name==="string"?G.name:We);const rt=normalizeParams(G.params);K.push({name:Xe,description:typeof G.description==="string"&&G.description.trim().length>0?G.description.trim():`${ze} ${We}`,method:ze,path:We,params:rt,needsConfirmation:false,isAsync:false})}return K}function normalizeIr(G){if(!G||typeof G!=="object"){return null}const K=G;const ze=typeof K.system?.code==="string"?K.system.code.trim():"";const We=typeof K.system?.baseUrl==="string"&&K.system.baseUrl.trim().length>0?K.system.baseUrl.trim():je.system.baseUrl;return{system:{code:ze||je.system.code,baseUrl:We,authType:normalizeAuthType(K.system?.authType)},tools:normalizeTools(K.tools)}}class LlmIrGenerator{llm;constructor(G){this.llm=G}async generate(G){const K=G.slice(0,8e4);const ze=["You are an API analyst that converts API documentation into MCP IR JSON.","Return ONLY valid JSON without markdown fences.","Use this exact schema:","{",' "system": {',' "code": "string",',' "baseUrl": "string",',' "authType": "none|bearer|api-key"'," },",' "tools": ['," {",' "name": "snake_case",',' "description": "string",',' "method": "GET|POST|PUT|DELETE",',' "path": "/path",',' "params": ['," {",' "name": "query",',' "type": "string",',' "required": true,',' "description": "Search query text"'," }"," ],",' "needsConfirmation": false,',' "isAsync": false'," }"," ]","}","","Source documentation:",K].join("\n");const We=await this.llm.complete(ze);const Xe=stripMarkdownFences(We);try{const G=JSON.parse(Xe);return normalizeIr(G)??je}catch{throw new Error(`LLM returned invalid JSON. First 200 chars: ${Xe.slice(0,200)}`)}}}K.LlmIrGenerator=LlmIrGenerator},21393:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.planShards=planShards;function planShards(G,K=40,je=8081){const ze=[];for(const We of G){let G=ze.find((G=>G.tools.length<K));if(!G){G={id:`shard-${ze.length+1}`,port:je+ze.length,tools:[]};ze.push(G)}G.tools.push(We.name)}return ze}},78536:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.BuilderAgent=void 0;const ze=je(4843);const We=je(44562);function isIr(G){if(!G||typeof G!=="object"){return false}const K=G;return typeof K.system?.code==="string"&&typeof K.system?.baseUrl==="string"&&typeof K.system?.authType==="string"&&Array.isArray(K.tools)}function parseIrPlanDoc(G){const K=G.trim();if(!K){return null}try{const G=JSON.parse(K);return isIr(G)?G:null}catch{return null}}function buildTemplateArtifact(G){const K=G.system.code||"package";return{archivePath:`/tmp/${K}.tgz`,manifestPath:`/tmp/${K}-manifest.json`,sbomPath:`/tmp/${K}-sbom.json`,signaturePath:`/tmp/${K}-signature.sig`}}class BuilderAgent{deps;constructor(G){this.deps=G}async run(G){const K=parseIrPlanDoc(G.planDoc);const je=K?{...buildTemplateArtifact(K),files:(0,ze.renderFromIR)(K)}:await this.deps.adapter.run(G.planDoc);const Xe=this.deps.writer??{write:We.writeGeneratedFiles};const rt=await Xe.write(G.root,je.files);await this.deps.installer.install(G.root);const{files:at,...ft}=je;return{artifact:ft,writtenFiles:rt}}}K.BuilderAgent=BuilderAgent},20052:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.CoreCodegenAdapter=void 0;class CoreCodegenAdapter{core;constructor(G){this.core=G}async run(G){const K=await this.core.generate({kind:"markdown",content:G});const je=K.files;return{...K,files:je??[]}}}K.CoreCodegenAdapter=CoreCodegenAdapter},65402:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.DependencyInstaller=void 0;const ze=je(31421);const We=je(57975);const Xe=(0,We.promisify)(ze.exec);async function defaultExec(G,K,je){return Xe(`${G} ${K.join(" ")}`,{cwd:je?.cwd,timeout:je?.timeout,windowsHide:true})}const rt=["pnpm","yarn","npm"];async function detectPm(G){for(const K of rt){try{await G(K,["--version"],{timeout:5e3});return K}catch{}}return"npm"}class DependencyInstaller{exec;constructor(G=defaultExec){this.exec=G}async install(G){const K=await detectPm(this.exec);await this.exec(K,["install"],{cwd:G,timeout:12e4})}}K.DependencyInstaller=DependencyInstaller},44562:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.writeGeneratedFiles=writeGeneratedFiles;const We=je(73024);const Xe=ze(je(76760));async function writeGeneratedFiles(G,K){const je=[];for(const ze of K){const K=Xe.default.resolve(G,ze.path);await We.promises.mkdir(Xe.default.dirname(K),{recursive:true});await We.promises.writeFile(K,ze.content,"utf8");je.push(K)}return je}},51792:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.ExplorerAgent=void 0;const ze=je(73024);const We=je(76760);const Xe=je(75364);const rt=je(65737);const at=je(20336);const ft=["*.md","*.txt","*.pdf","*.json","*.yaml","*.yml","*.ts","*.js","*.mjs","*.cjs","*.xml","*.toml","*.env","openapi*.json","openapi*.yaml","openapi*.yml","docker-compose*.yml"];function readTextFile(G){try{return(0,ze.readFileSync)(G,"utf8")}catch{return null}}class ExplorerAgent{deps;constructor(G={fsTool:new rt.FsTool,dockerTool:new Xe.DockerInspectTool,httpTool:new at.HttpFetchTool}){this.deps=G}async run(G){const[K,je]=await Promise.all([this.deps.fsTool.glob(G.root,ft),this.deps.dockerTool.listContainers()]);const ze=[];const Xe=[];const rt=[];for(const K of G.urls){if(this.deps.browserTool){const G=await this.deps.browserTool.fetch(K);Xe.push(G);ze.push({url:G.url,status:200,body:G.html});if(G.text.trim().length>0){rt.push(G.text)}continue}const G=await this.deps.httpTool.fetch(K);ze.push(G);if(G.body.trim().length>0){rt.push(G.body)}}for(const G of K){const K=(0,We.extname)(G).toLowerCase();if(K===".pdf"){if(this.deps.pdfTool){try{const K=await this.deps.pdfTool.extractFromFile(G);if(K.text.trim().length>0){rt.push(K.text)}}catch{}}continue}const je=readTextFile(G);if(je&&je.trim().length>0){rt.push(je)}}return{files:[...K].sort(),containers:[...je].sort(((G,K)=>G.id.localeCompare(K.id))),endpoints:[...ze].sort(((G,K)=>G.url.localeCompare(K.url))),rawDocs:rt,browserPages:[...Xe].sort(((G,K)=>G.url.localeCompare(K.url)))}}}K.ExplorerAgent=ExplorerAgent},78519:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.extractCoverage=extractCoverage;function readPercent(G,K){const je=G.match(new RegExp(`${K}\\s*:\\s*(\\d+(?:\\.\\d+)?)%`,"i"));return Number(je?.[1]??0)}function extractCoverage(G){return{lines:readPercent(G,"Lines"),statements:readPercent(G,"Statements"),functions:readPercent(G,"Functions"),branches:readPercent(G,"Branches")}}},19562:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.IntegrationTester=void 0;K.frameMcpMessage=frameMcpMessage;K.parseMcpMessages=parseMcpMessages;const ze=je(31421);const We=je(57975);const Xe=(0,We.promisify)(ze.exec);const rt=1500;const at=1e4;const ft=1e4;const mt=15e3;const vt=1e4;const yt=25;function sleep(G){return new Promise((K=>{setTimeout(K,G)}))}function errorMessage(G){return G instanceof Error?G.message:String(G)}function summarizePayload(G,K=300){let je;if(typeof G==="string"){je=G}else{try{je=JSON.stringify(G)}catch{je=String(G)}}if(je.length<=K){return je}return`${je.slice(0,K)}...`}function isAuthRelated(G){const K=G.toLowerCase();return/\b401\b/.test(K)||/\b403\b/.test(K)||K.includes("unauthorized")||K.includes("forbidden")||K.includes("api.key")||K.includes("api_key")||K.includes("api key")}function asRecord(G){if(G&&typeof G==="object"&&!Array.isArray(G)){return G}return{}}function sampleValue(G,K){const je=Array.isArray(K.enum)?K.enum:[];if(je.length>0){return je[0]}const ze=G.toLowerCase();const We=typeof K.type==="string"?K.type.toLowerCase():"string";if(ze.includes("url")){return"https://example.com"}if(ze==="q"||ze.includes("query")||ze.includes("keyword")||ze.includes("search")){return"test"}if(ze.includes("email")){return"test@example.com"}if(ze.includes("id")){return"1"}switch(We){case"integer":case"number":return 1;case"boolean":return true;case"array":return[];case"object":return{};default:return"test"}}function buildToolArgs(G){const K=asRecord(G.inputSchema);const je=asRecord(K.properties);const ze=Array.isArray(K.required)?K.required.filter((G=>typeof G==="string")):[];const We={};const Xe=new Set(ze);for(const[G,K]of Object.entries(je)){if(!Xe.has(G)){continue}We[G]=sampleValue(G,asRecord(K))}if(Object.keys(We).length===0){return{}}return We}function extractToolCallDetail(G){const K=G.error;if(K){return summarizePayload(K)}const je=G.result;if(typeof je==="string"){return summarizePayload(je)}if(je&&typeof je==="object"){const G=je;const K=G.content;if(Array.isArray(K)){for(const G of K){if(G&&typeof G==="object"){const K=G.text;if(typeof K==="string"&&K.trim().length>0){return summarizePayload(K)}}}}return summarizePayload(G)}return summarizePayload(je)}function isToolCallSuccessful(G){if(G.error){return false}const K=G.result;if(K&&typeof K==="object"&&!Array.isArray(K)){const G=K;if(G.isError===true){return false}}return true}function frameMcpMessage(G){const K=Buffer.from(JSON.stringify(G),"utf8");const je=Buffer.from(`Content-Length: ${String(K.length)}\r\n\r\n`,"utf8");return Buffer.concat([je,K])}function frameLegacyMcpMessage(G){return Buffer.from(`${JSON.stringify(G)}\n`,"utf8")}function parseMcpMessages(G){const K=[];let je=Buffer.from(G);const pushJson=G=>{const je=G.trim();if(!je){return}try{const G=JSON.parse(je);if(G&&typeof G==="object"&&!Array.isArray(G)){K.push(G)}}catch{}};while(je.length>0){const G=je.toString("utf8");const K=/content-length:/i.exec(G);const ze=K?.index??-1;if(ze>0){const K=G.slice(0,ze);for(const G of K.split(/\r?\n/)){pushJson(G)}const We=Buffer.byteLength(K,"utf8");je=je.subarray(We);continue}if(ze===0){const G=je.indexOf("\r\n\r\n");const K=je.indexOf("\n\n");let ze=-1;let We=0;if(G>=0&&(K<0||G<=K)){ze=G;We=4}else if(K>=0){ze=K;We=2}if(ze===-1){break}const Xe=je.subarray(0,ze).toString("utf8");const rt=/content-length:\s*(\d+)/i.exec(Xe);if(!rt){const G=je.indexOf("\n");if(G===-1){break}je=je.subarray(G+1);continue}const at=Number(rt[1]);if(!Number.isFinite(at)||at<0){const G=je.indexOf("\n");if(G===-1){break}je=je.subarray(G+1);continue}const ft=ze+We+at;if(je.length<ft){break}const mt=je.subarray(ze+We,ft).toString("utf8");pushJson(mt);je=je.subarray(ft);continue}const We=je.indexOf("\n");if(We===-1){break}const Xe=je.subarray(0,We).toString("utf8").replace(/\r$/,"");pushJson(Xe);je=je.subarray(We+1)}return{messages:K,rest:je}}class IntegrationTester{exec;spawn;startupWaitMs;initializeTimeoutMs;toolsListTimeoutMs;connectionTimeoutMs;authProbeTimeoutMs;pollIntervalMs;constructor(G={}){this.exec=G.exec??((G,K)=>Xe(G,{windowsHide:true,...K}));this.spawn=G.spawn??ze.spawn;this.startupWaitMs=G.startupWaitMs??rt;this.initializeTimeoutMs=G.initializeTimeoutMs??at;this.toolsListTimeoutMs=G.toolsListTimeoutMs??ft;this.connectionTimeoutMs=G.connectionTimeoutMs??mt;this.authProbeTimeoutMs=G.authProbeTimeoutMs??vt;this.pollIntervalMs=G.pollIntervalMs??yt}async run(G){try{await this.exec("pnpm install",{cwd:G.dir,timeout:12e4});await this.exec("pnpm run build",{cwd:G.dir,timeout:12e4})}catch(G){return{passed:false,toolsFound:0,toolsCalled:[],error:`Build failed: ${errorMessage(G)}`}}const K=[];const je=[];let ze;let We=false;let Xe=null;let rt=null;let at=null;try{const ft={...process.env,...G.authEnv,MCP_BASE_URL:G.baseUrl,BASE_URL:G.baseUrl};const pushLog=(G,K)=>{const je=K.trim();if(!je){return}G.push(je);if(G.length>40){G.splice(0,G.length-40)}};const diagnostics=()=>{const G=K.slice(-20).join("\n").trim();const ze=je.slice(-20).join("\n").trim();const We=[];if(G){We.push(`stderr:\n${G}`)}if(ze){We.push(`stdout(non-mcp):\n${ze}`)}return We.length>0?`\n${We.join("\n\n")}`:""};const buildExitError=G=>{const K=Xe===null?"null":String(Xe);const je=rt?`, signal ${rt}`:"";return`Server exited (code ${K}${je}) before responding to id=${G}${diagnostics()}`};ze=this.spawn("node",["dist/index.js"],{cwd:G.dir,env:ft,windowsHide:true});ze.on("error",(G=>{at=errorMessage(G)}));ze.on("exit",((G,K)=>{We=true;Xe=G;rt=K}));ze.stderr?.on("data",(G=>{pushLog(K,typeof G==="string"?G:G.toString("utf8"))}));const mt=[];let vt=Buffer.alloc(0);ze.stdout?.on("data",(G=>{const K=typeof G==="string"?Buffer.from(G):G;vt=Buffer.concat([vt,K]);const je=parseMcpMessages(vt);vt=je.rest;mt.push(...je.messages)}));if(this.startupWaitMs>0){await sleep(this.startupWaitMs)}const writeMessage=(G,K="framed")=>{if(!ze?.stdin){throw new Error("Server stdin is not available")}if(at){throw new Error(`Server process error: ${at}${diagnostics()}`)}if(We){throw new Error(buildExitError(Number(G.id??-1)))}const je=K==="legacy"?frameLegacyMcpMessage(G):frameMcpMessage(G);ze.stdin.write(je)};const waitForResponseById=async(G,K)=>{const je=Date.now();while(Date.now()-je<K){const K=mt.findIndex((K=>K.id===G));if(K>=0){const[G]=mt.splice(K,1);return G}if(at){throw new Error(`Server process error: ${at}${diagnostics()}`)}if(We){throw new Error(buildExitError(G))}await sleep(this.pollIntervalMs)}throw new Error(`Timeout waiting for MCP response id=${G}${diagnostics()}`)};const yt={jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"integration-test",version:"1.0.0"}}};const wt=Math.min(3e3,this.initializeTimeoutMs);const lr=Math.max(this.initializeTimeoutMs-wt,0);writeMessage(yt);try{await waitForResponseById(1,wt)}catch(G){const K=G instanceof Error&&G.message.includes("Timeout waiting for MCP response id=1");if(!K||We||at||lr===0){throw G}writeMessage(yt,"legacy");await waitForResponseById(1,lr)}writeMessage({jsonrpc:"2.0",method:"notifications/initialized"});writeMessage({jsonrpc:"2.0",id:2,method:"tools/list"});const Er=await waitForResponseById(2,this.toolsListTimeoutMs);const Rr=Er.result;const jr=Rr?.tools?.filter((G=>typeof G?.name==="string")).map((G=>({name:G.name,...typeof G.description==="string"?{description:G.description}:{},...G.inputSchema&&typeof G.inputSchema==="object"?{inputSchema:G.inputSchema}:{}})))??[];if(!Er.result&&Er.error){throw new Error(`tools/list failed: ${JSON.stringify(Er.error)}`)}const zr=[];const fi=[];let mi;let bi;let Si=3;const Ei=jr.some((G=>G.name==="test_connection"));if(Ei){const G=Si++;writeMessage({jsonrpc:"2.0",id:G,method:"tools/call",params:{name:"test_connection",arguments:{}}});zr.push("test_connection");const K=await waitForResponseById(G,this.connectionTimeoutMs);const je=isToolCallSuccessful(K);const ze=extractToolCallDetail(K);mi={ok:je,detail:ze};fi.push({name:"test_connection",ok:je,detail:ze,args:{}})}const ki=jr.find((G=>G.name!=="test_connection"));if(ki){try{const G=Si++;writeMessage({jsonrpc:"2.0",id:G,method:"tools/call",params:{name:ki.name,arguments:{}}});zr.push(ki.name);const K=await waitForResponseById(G,this.authProbeTimeoutMs);const je=K.error;const ze=K.result;const We=summarizePayload(je??ze);bi={authRequired:isAuthRelated(We),...We?{authHint:We}:{},toolName:ki.name}}catch(G){bi={authRequired:false,authHint:summarizePayload(`probe failed: ${errorMessage(G)}`),toolName:ki.name}}}for(const G of jr){if(G.name==="test_connection"){continue}const K=buildToolArgs(G);const je=Si++;writeMessage({jsonrpc:"2.0",id:je,method:"tools/call",params:{name:G.name,arguments:K}});zr.push(G.name);try{const ze=await waitForResponseById(je,this.connectionTimeoutMs);fi.push({name:G.name,ok:isToolCallSuccessful(ze),detail:extractToolCallDetail(ze),args:K})}catch(je){fi.push({name:G.name,ok:false,detail:`call failed: ${errorMessage(je)}`,args:K})}}const Ci=fi.filter((G=>G.name!=="test_connection"));const Ti=jr.length>0&&Ci.length>0&&Ci.every((G=>G.ok));const Pi=Ti&&(mi?mi.ok:true);return{passed:Pi,toolsFound:jr.length,toolsCalled:zr,tools:jr,toolResults:fi,allToolsPassed:Ti,...mi?{connectionTest:mi}:{},...bi?{authProbe:bi}:{},serverLog:[...K,...je].slice(-20).join("\n")}}catch(G){return{passed:false,toolsFound:0,toolsCalled:[],error:errorMessage(G),serverLog:[...K,...je].slice(-20).join("\n")}}finally{ze?.kill()}}}K.IntegrationTester=IntegrationTester},74664:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.TesterSandboxAdapter=void 0;class TesterSandboxAdapter{sandbox;constructor(G){this.sandbox=G}execute(G){return this.sandbox.runTests({files:G,timeoutMs:30*60*1e3})}}K.TesterSandboxAdapter=TesterSandboxAdapter},59159:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.parseTestResult=parseTestResult;function readNumber(G,K){const je=G.match(new RegExp(`(\\d+)\\s+${K}`,"i"));return Number(je?.[1]??0)}function parseTestResult(G){return{passed:readNumber(G,"passed"),failed:readNumber(G,"failed"),total:readNumber(G,"total")}}},60403:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.TestRunner=void 0;const ze=je(31421);const We=je(73024);const Xe=je(76760);const rt=je(57975);const at=(0,rt.promisify)(ze.exec);async function defaultExec(G,K,je){const ze=await at(`${G} ${K.join(" ")}`,{cwd:je?.cwd,timeout:je?.timeout,windowsHide:true});return{stdout:ze.stdout,stderr:ze.stderr}}const ft=["pnpm","yarn","npx"];async function detectPm(G){for(const K of ft){try{await G(K,["--version"],{timeout:5e3});return K}catch{}}return"npx"}function hasTestSetup(G){const K=(0,Xe.join)(G,"package.json");if(!(0,We.existsSync)(K)){return false}try{const G=JSON.parse((0,We.readFileSync)(K,"utf8"));if(G.scripts?.test&&!G.scripts.test.includes("no test specified")){return true}const je={...G.dependencies,...G.devDependencies};return Boolean(je?.jest||je?.vitest)}catch{return false}}class TestRunner{exec;constructor(G=defaultExec){this.exec=G}async run(G,K="jest"){if(hasTestSetup(G)){const je=await detectPm(this.exec);return this.exec(je,[K],{cwd:G,timeout:18e4})}return this.compileCheck(G)}async compileCheck(G){const K=(0,We.existsSync)((0,Xe.join)(G,"tsconfig.json"));try{if(K){const K=await this.exec("npx",["tsc","--noEmit"],{cwd:G,timeout:6e4});return{stdout:`Compile check PASS (tsc --noEmit)\n${K.stdout}`,stderr:K.stderr}}const je=(0,Xe.join)(G,"package.json");if((0,We.existsSync)(je)){const K=JSON.parse((0,We.readFileSync)(je,"utf8"));const ze=K.main??"index.js";if((0,We.existsSync)((0,Xe.join)(G,ze))){const K=await this.exec("node",["--check",ze],{cwd:G,timeout:3e4});return{stdout:`Compile check PASS (node --check ${ze})\n${K.stdout}`,stderr:K.stderr}}}return{stdout:"No testable files found. Skipping validation.",stderr:""}}catch(G){const K=G instanceof Error?G.message:String(G);return{stdout:`Compile check FAIL\n${K}`,stderr:K}}}}K.TestRunner=TestRunner},68100:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.TesterAgent=void 0;const ze=je(78519);const We=je(59159);class TesterAgent{deps;constructor(G){this.deps=G}async run(G){const K=await this.deps.sandboxAdapter.execute(G.files);const je=await this.deps.runner.run(G.root,"jest");return{passed:K.passed,summary:(0,We.parseTestResult)(je.stdout),coverage:(0,ze.extractCoverage)(je.stdout),logs:K.logs,failedTests:K.failedTests}}}K.TesterAgent=TesterAgent},66015:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.loadChatConfig=loadChatConfig;const ze=je(73024);const We=je(76760);const Xe=je(18296);const rt="google/gemini-3-flash-preview";const at="https://openrouter.ai/api/v1";function asString(G){if(typeof G!=="string"){return undefined}const K=G.trim();return K.length>0?K:undefined}function loadEnvFile(G,K=5){let je=(0,We.resolve)(G);for(let G=0;G<=K;G+=1){const G=(0,We.resolve)(je,".env");if((0,ze.existsSync)(G)){const K=new Map;for(const je of(0,ze.readFileSync)(G,"utf8").split(/\r?\n/)){const G=je.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);if(G)K.set(G[1],G[2])}return K}const K=(0,We.dirname)(je);if(K===je)break;je=K}return new Map}function loadChatConfig(G=process.cwd()){const K=loadEnvFile(G);const je=new Xe.SgaConfig;const ze=asString(je.get("model.coder"))??asString(je.get("model.default"))??K.get("LLM_CODER_MODEL")??process.env.LLM_CODER_MODEL??rt;const We=asString(je.get("openrouter.apiKey"))??K.get("OPENROUTER_API_KEY")??process.env.OPENROUTER_API_KEY??"";const ft=asString(je.get("openrouter.baseUrl"))??K.get("OPENROUTER_BASE_URL")??process.env.OPENROUTER_BASE_URL??at;return{model:ze,apiKey:We,baseUrl:ft,workDir:G}}},48347:function(G,K,je){"use strict";var ze=this&&this.__createBinding||(Object.create?function(G,K,je,ze){if(ze===undefined)ze=je;var We=Object.getOwnPropertyDescriptor(K,je);if(!We||("get"in We?!K.__esModule:We.writable||We.configurable)){We={enumerable:true,get:function(){return K[je]}}}Object.defineProperty(G,ze,We)}:function(G,K,je,ze){if(ze===undefined)ze=je;G[ze]=K[je]});var We=this&&this.__setModuleDefault||(Object.create?function(G,K){Object.defineProperty(G,"default",{enumerable:true,value:K})}:function(G,K){G["default"]=K});var Xe=this&&this.__importStar||function(){var ownKeys=function(G){ownKeys=Object.getOwnPropertyNames||function(G){var K=[];for(var je in G)if(Object.prototype.hasOwnProperty.call(G,je))K[K.length]=je;return K};return ownKeys(G)};return function(G){if(G&&G.__esModule)return G;var K={};if(G!=null)for(var je=ownKeys(G),Xe=0;Xe<je.length;Xe++)if(je[Xe]!=="default")ze(K,G,je[Xe]);We(K,G);return K}}();var rt=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.startChatLoop=startChatLoop;const at=Xe(je(26848));const ft=rt(je(39559));const mt=je(18296);const vt=je(40381);const yt=[{alias:"gemini-flash",id:"google/gemini-3-flash-preview",label:"Gemini 3 Flash"},{alias:"minimax",id:"minimax/minimax-m2.5",label:"MiniMax M2.5"}];function createRl(){process.stdin.resume();if(typeof process.stdin.ref==="function"){process.stdin.ref()}return at.createInterface({input:process.stdin,output:process.stdout})}function pickModel(G,K){return new Promise((je=>{G.pause();const ze=process.stdin;const We=process.stdout;const Xe=ze.isRaw;if(typeof ze.setRawMode==="function"){ze.setRawMode(true)}ze.resume();let rt=Math.max(0,yt.findIndex((G=>G.id===K)));const at=yt.length;const draw=()=>{We.write(`\n ${ft.default.white.bold("Select model")} ${ft.default.gray("(↑/↓ choose, Enter confirm, Esc cancel)")}\n`);for(let G=0;G<at;G+=1){const K=yt[G];const je=G===rt;const ze=je?ft.default.cyan(">"):" ";const Xe=je?ft.default.cyan.bold(K.alias):ft.default.white(K.alias);const at=je?ft.default.white(K.label):ft.default.gray(K.label);const mt=ft.default.gray.dim(K.id);We.write(` ${ze} ${Xe.padEnd(16)} ${at.padEnd(18)} ${mt}\n`)}We.write(` ${ft.default.gray("-".repeat(72))}\n`)};const redraw=()=>{We.write(`[${at+3}A`);draw()};const cleanup=()=>{ze.removeListener("data",onKey);if(typeof ze.setRawMode==="function"){ze.setRawMode(Xe??false)}ze.resume();G.resume()};const onKey=G=>{const K=G.toString();if(K===""||K===""){cleanup();je(null);return}if(K==="\r"||K==="\n"){cleanup();je(yt[rt].id);return}if(K===""||K==="k"){rt=(rt-1+at)%at;redraw();return}if(K===""||K==="j"){rt=(rt+1)%at;redraw();return}const ze=Number.parseInt(K,10);if(Number.isInteger(ze)&&ze>=1&&ze<=at){rt=ze-1;redraw()}};draw();ze.on("data",onKey)}))}function printBanner(G){const K=[" ███╗ ███╗ ██████╗██████╗ ██████╗██╗ █████╗ ██╗ ██╗"," ████╗ ████║██╔════╝██╔══██╗ ██╔════╝██║ ██╔══██╗██║ ██║"," ██╔████╔██║██║ ██████╔╝ ██║ ██║ ███████║██║ █╗ ██║"," ██║╚██╔╝██║██║ ██╔═══╝ ██║ ██║ ██╔══██║██║███╗██║"," ██║ ╚═╝ ██║╚██████╗██║ ╚██████╗███████╗██║ ██║╚███╔███╔╝"," ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═════╝╚══════╝╚═╝ ╚═╝ ╚══╝╚══╝ "];console.log("");for(const G of K){console.log(ft.default.cyan(G))}console.log("");console.log(ft.default.white(" AI-powered MCP Server Generator")+" · "+ft.default.yellow("by SGA 中文社区"));console.log(ft.default.gray(" "+"─".repeat(55)));console.log(" "+ft.default.gray("Model")+" "+ft.default.green(G.model));const je=G.apiKey?ft.default.green("sk-or-..."+G.apiKey.slice(-4)):ft.default.red("未配置 (mcp-claw config set-env --key YOUR_KEY)");console.log(" "+ft.default.gray("Key")+" "+je);console.log(ft.default.gray(" /help · /model · /history · /clear · Ctrl+C 退出"));console.log("")}function printRestoredHistory(G){const K=G.restoredCount;if(K===0){return}const je=Math.floor(K/2);console.log(` ${ft.default.dim("->")} ${ft.default.gray(`restored previous chat (${je} turns)`)}`);const ze=G.getRecentRounds(3);if(ze.length>0){console.log(ft.default.gray(" "+"-".repeat(50)));for(const G of ze){const K=G.userText.replace(/\s+/g," ").slice(0,60);const je=G.assistantText.replace(/\s+/g," ").slice(0,70);const ze=G.toolCount>0?ft.default.dim(` [${G.toolCount} tools]`):"";console.log(` ${ft.default.cyan("you")} ${ft.default.white(K)}${G.userText.length>60?ft.default.dim("..."):""}`);if(je){console.log(` ${ft.default.green("bot")} ${ft.default.dim(je)}${G.assistantText.length>70?ft.default.dim("..."):""}${ze}`)}else if(G.toolCount>0){console.log(` ${ft.default.green("bot")}${ze}`)}}console.log(ft.default.gray(" "+"-".repeat(50)))}console.log("")}let wt="";async function startChatLoop(G){let K=G;const je={rl:createRl()};const rejectionHandler=G=>{const K=G instanceof Error?G.message:String(G);console.error(`\n ${ft.default.red("unhandled rejection")} ${ft.default.red(K)}\n`)};process.on("unhandledRejection",rejectionHandler);const exceptionHandler=G=>{console.error(`\n ${ft.default.red("uncaught exception")} ${ft.default.red(G.message)}\n`)};process.on("uncaughtException",exceptionHandler);const exitHandler=G=>{if(G!==0){console.error(ft.default.dim(` [exit code ${G}]`))}};process.on("exit",exitHandler);if(!K.apiKey){console.log(ft.default.yellow("\n No API key configured."));console.log(ft.default.gray(" Get one free at: https://openrouter.ai/settings/keys"));console.log("");let G="";try{G=(await je.rl.question(" Enter OpenRouter API Key (sk-or-...): ")).trim()}catch{je.rl.close();cleanup();return}if(!G){console.log(ft.default.red(" API key is required. Exiting."));je.rl.close();cleanup();return}const ze=new mt.SgaConfig;ze.set("openrouter.apiKey",G);K={...K,apiKey:G};console.log(ft.default.green(" Saved to ~/.sga/config.yaml\n"))}const ze=new vt.ChatSession(K);wt=K.model;printBanner(K);printRestoredHistory(ze);let We=0;let Xe=false;const handleSigint=()=>{if(Xe){We=0;return}We++;if(We>=2){console.log(ft.default.gray("\n bye.\n"));je.rl.close();process.exit(0)}console.log(ft.default.gray("\n (Ctrl+C again to exit)\n"));process.stdout.write(ft.default.cyan.bold("> "))};process.on("SIGINT",handleSigint);const rt=ft.default.cyan.bold("> ");const at=ft.default.gray(" "+"-".repeat(50));function cleanup(){process.off("SIGINT",handleSigint);process.off("unhandledRejection",rejectionHandler);process.off("uncaughtException",exceptionHandler);process.off("exit",exitHandler)}try{for(;;){We=0;if(process.stdin.destroyed||!process.stdin.readable){console.error(ft.default.red("\n stdin destroyed, cannot continue.\n"));break}process.stdin.resume();if(typeof process.stdin.ref==="function"){process.stdin.ref()}let G;try{G=await je.rl.question(rt)}catch{try{je.rl.close()}catch{}if(process.stdin.destroyed||!process.stdin.readable){console.error(ft.default.red("\n stdin closed, exiting.\n"));break}console.error(ft.default.yellow("\n readline reset, retrying...\n"));je.rl=createRl();try{G=await je.rl.question(rt)}catch{console.error(ft.default.red("\n readline unrecoverable, exiting.\n"));break}}const K=G.trim();if(!K){continue}if(K==="/help"){console.log(ft.default.gray(" /help | /model | /model <alias|id> | /history | /clear"));console.log("");continue}if(K==="/clear"){ze.clearHistory();console.log(` ${ft.default.green("ok")} ${ft.default.gray("history cleared")}\n`);continue}if(K==="/history"){printRestoredHistory(ze);continue}if(K==="/model"||K==="/models"){const G=await pickModel(je.rl,wt);if(G){wt=G;ze.setModel(G);console.log(` ${ft.default.green("ok")} model switched to ${ft.default.green(G)}\n`)}else{console.log(` ${ft.default.gray("cancelled")}\n`)}continue}if(K.startsWith("/model ")){const G=K.slice("/model ".length).trim();if(!G){console.log(` ${ft.default.yellow("usage: /model <alias|id>")}\n`);continue}const je=yt.find((K=>K.alias===G));const We=je?je.id:G;wt=We;ze.setModel(We);console.log(` ${ft.default.green("ok")} model switched to ${ft.default.green(We)}\n`);continue}console.log(at);Xe=true;try{await ze.send(K)}catch(G){const K=G instanceof Error?G.message:String(G);console.error(`\n ${ft.default.red("error")} ${ft.default.red(K)}`);if(G instanceof Error&&G.cause){console.error(` ${ft.default.gray(G.cause.message??String(G.cause))}`)}console.error("")}finally{Xe=false}}}finally{cleanup();je.rl.close()}}},40381:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.ChatSession=void 0;const We=je(31421);const Xe=je(73024);const rt=je(51455);const at=je(76760);const ft=je(57975);const mt=ze(je(39559));const vt=je(19562);const yt=je(60403);const wt=je(72966);const lr=je(26120);const Er=je(18296);const Rr=je(49904);const jr=je(29441);const zr=je(61108);const fi=je(65737);const mi=je(20336);const bi=je(15158);const Si=je(59265);const Ei=je(2330);const ki=je(66191);const Ci=(0,ft.promisify)(We.exec);const Ti=["*"];const Pi=new Set([".md",".txt",".json",".yaml",".yml",".ts",".js",".mjs",".cjs",".xml",".toml",".env"]);const Ii=30;const Ri=2e5;const Mi=6e3;const qi=1e5;const Xi=2e4;const ps=50;const Ls=15e4;const qs=10;const Ws=30;const Js=5;const eo=50;const to=100;const ro=new Set(["get","post","put","delete","patch","options","head","trace"]);function truncate(G,K){if(G.length<=K){return G}return`${G.slice(0,K)}...`}function asRecord(G){if(G&&typeof G==="object"&&!Array.isArray(G)){return G}return{}}function parseToolArguments(G){try{return asRecord(JSON.parse(G))}catch{return{}}}function formatError(G){return G instanceof Error?G.message:String(G)}function toStringValue(G){return typeof G==="string"?G:""}function toNumber(G,K){if(typeof G!=="number"||!Number.isFinite(G)){return K}return G}function toStringArray(G){if(!Array.isArray(G)){return[]}return G.filter((G=>typeof G==="string"))}function deriveSgaSearchEndpoint(G){const K=new URL(G);return`${K.protocol}//${K.host}/v1/agent/search`}function parseSearchPayload(G,K){const je=asRecord(G);const ze=Array.isArray(je.results)?je.results:[];const We=[];for(const G of ze){const K=asRecord(G);const je=toStringValue(K.title);const ze=toStringValue(K.url);if(!ze){continue}const Xe=toStringValue(K.content);const rt=Xe.length>0?Xe.slice(0,300):toStringValue(K.snippet).slice(0,300);const at=toStringValue(K.published_date);const ft=toStringValue(K.domain);We.push({title:je,url:ze,snippet:rt,...at?{published_date:at}:{},...ft?{domain:ft}:{}})}return{total:toNumber(je.total_results,We.length),results:We.slice(0,K),suggestions:toStringArray(je.suggestions)}}function parseYamlScalar(G){const K=G.trim();if(K.startsWith('"')&&K.endsWith('"')||K.startsWith("'")&&K.endsWith("'")){return K.slice(1,-1)}return K}function parseMinimalOpenApiYaml(G){const K=G.split(/\r?\n/);const je={info:{},servers:[],paths:{},components:{securitySchemes:{},schemas:{}}};let ze="";let We=false;let Xe=false;let rt="";let at="";let ft=-1;for(const G of K){const K=G.replace(/\s+#.*$/,"");if(!K.trim()){continue}const mt=K.match(/^ */)?.[0].length??0;const vt=K.trim();if(mt===0){if(vt.startsWith("openapi:")){je.openapi=parseYamlScalar(vt.slice("openapi:".length))}else if(vt.startsWith("swagger:")){je.swagger=parseYamlScalar(vt.slice("swagger:".length))}else if(vt==="info:"){ze="info"}else if(vt==="servers:"){ze="servers"}else if(vt==="paths:"){ze="paths"}else if(vt==="components:"){ze="components"}else{ze=""}We=false;Xe=false;rt="";at="";ft=-1;continue}if(ze==="info"&&mt===2){const G=vt.match(/^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/);if(G){const K=asRecord(je.info);K[G[1]]=parseYamlScalar(G[2]);je.info=K}continue}if(ze==="servers"){if(mt===2&&vt.startsWith("-")){const G=vt.slice(1).trim();const K={};const ze=G.match(/^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/);if(ze){K[ze[1]]=parseYamlScalar(ze[2])}const We=Array.isArray(je.servers)?je.servers:[];We.push(K);je.servers=We;ft=We.length-1}else if(mt===4&&ft>=0){const G=vt.match(/^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/);if(G){const K=Array.isArray(je.servers)?je.servers:[];const ze=asRecord(K[ft]);ze[G[1]]=parseYamlScalar(G[2]);K[ft]=ze;je.servers=K}}continue}if(ze==="components"){if(mt===2&&vt==="securitySchemes:"){We=true;Xe=false;continue}if(mt===2&&vt==="schemas:"){Xe=true;We=false;continue}if(mt===4&&We&&vt.endsWith(":")){const G=vt.slice(0,-1).trim();const K=asRecord(je.components);const ze=asRecord(K.securitySchemes);ze[G]={};K.securitySchemes=ze;je.components=K;continue}if(mt===6&&We){const G=vt.match(/^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/);if(G){const K=asRecord(je.components);const ze=asRecord(K.securitySchemes);const We=Object.entries(ze);if(We.length>0){const[Xe]=We[We.length-1];const rt=asRecord(ze[Xe]);rt[G[1]]=parseYamlScalar(G[2]);ze[Xe]=rt;K.securitySchemes=ze;je.components=K}}continue}if(mt===4&&Xe&&vt.endsWith(":")){const G=vt.slice(0,-1).trim();const K=asRecord(je.components);const ze=asRecord(K.schemas);ze[G]={};K.schemas=ze;je.components=K;continue}continue}if(ze==="paths"){if(mt===2&&vt.endsWith(":")){rt=vt.slice(0,-1).trim();const G=asRecord(je.paths);G[rt]={};je.paths=G;at="";continue}if(mt===4&&vt.endsWith(":")&&rt){const G=vt.slice(0,-1).trim().toLowerCase();if(ro.has(G)){at=G;const K=asRecord(je.paths);const ze=asRecord(K[rt]);ze[at]={};K[rt]=ze;je.paths=K}continue}if(mt===6&&rt&&at){const G=vt.match(/^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/);if(G){const K=asRecord(je.paths);const ze=asRecord(K[rt]);const We=asRecord(ze[at]);We[G[1]]=parseYamlScalar(G[2]);ze[at]=We;K[rt]=ze;je.paths=K}}}}return je}function summarizeSchema(G){const K=asRecord(G);const je=toStringValue(K.type);const ze=toStringValue(K.$ref);if(ze){return ze}if(je){return je}return"object"}function extractAuthSchemes(G){const K=asRecord(G.components);const je=asRecord(K.securitySchemes);const ze=new Set;for(const G of Object.values(je)){const K=asRecord(G);const je=toStringValue(K.type).toLowerCase();if(je==="apikey"){ze.add("apiKey")}else if(je==="oauth2"){ze.add("oauth2")}else if(je==="http"){const G=toStringValue(K.scheme).toLowerCase();if(G==="bearer"){ze.add("bearer")}else if(G==="basic"){ze.add("basic")}}}return[...ze]}function extractOpenApiEndpoints(G,K){const je=asRecord(G.paths);const ze=[];let We=0;for(const[G,Xe]of Object.entries(je)){const je=asRecord(Xe);const rt=Array.isArray(je.parameters)?je.parameters:[];for(const[Xe,at]of Object.entries(je)){const je=Xe.toLowerCase();if(!ro.has(je)){continue}We+=1;if(ze.length>=K){continue}const ft=asRecord(at);const mt=Array.isArray(ft.parameters)?ft.parameters:[];const vt=[...rt,...mt];const yt=vt.map((G=>asRecord(G))).map((G=>{const K=asRecord(G.schema);return{name:toStringValue(G.name),in:toStringValue(G.in),required:Boolean(G.required),type:toStringValue(K.type)||summarizeSchema(K)}})).filter((G=>G.name.length>0));let wt;const lr=asRecord(ft.requestBody);const Er=asRecord(lr.content);const Rr=Object.keys(Er);if(Rr.length>0){const G=Rr[0];const K=asRecord(Er[G]);wt={contentType:G,schema:summarizeSchema(K.schema)}}const jr=asRecord(ft.responses);const zr={};for(const[G,K]of Object.entries(jr)){const je=asRecord(K);zr[G]=toStringValue(je.description)}ze.push({method:je.toUpperCase(),path:G,operationId:toStringValue(ft.operationId),summary:toStringValue(ft.summary),description:toStringValue(ft.description),parameters:yt,...wt?{requestBody:wt}:{},responses:zr})}}return{endpointCount:We,endpoints:ze}}function findNearestFile(G,K,je=6){let ze=(0,at.resolve)(G);for(let G=0;G<=je;G+=1){const G=(0,at.join)(ze,K);if((0,Xe.existsSync)(G)){return G}const je=(0,at.resolve)(ze,"..");if(je===ze){break}ze=je}return undefined}async function runGit(G,K){try{const{stdout:je}=await Ci(`git ${K.join(" ")}`,{cwd:G,windowsHide:true});const ze=je.trim();return ze.length>0?ze:undefined}catch{return undefined}}async function readProjectName(G){const K=findNearestFile(G,"package.json");if(!K){return undefined}try{const G=await(0,rt.readFile)(K,"utf8");const je=JSON.parse(G);return typeof je.name==="string"?je.name:undefined}catch{return undefined}}async function readGitContext(G){const K=await runGit(G,["rev-parse","--is-inside-work-tree"]);if(K!=="true"){return{isRepo:false}}const[je,ze]=await Promise.all([runGit(G,["branch","--show-current"]),runGit(G,["log","-1","--pretty=format:%h %s"])]);return{isRepo:true,branch:je,latestCommit:ze}}async function buildSystemPrompt(G,K=0,je=18){const[ze,We]=await Promise.all([readProjectName(G),readGitContext(G)]);const Xe=(new Date).toISOString();const rt=We.isRepo?We.branch??"detached":"n/a";const at=We.isRepo?We.latestCommit??"n/a":"n/a";return["# Environment",`cwd: ${G}`,`platform: ${process.platform}`,`time: ${Xe}`,`project: ${ze??"unknown"}`,`git: ${rt} | ${at}`,...K>0?[`chat_history: ${K} messages restored from previous session 鈥?you HAVE full context`,""]:[],"","# Role","You are mcp-claw, a specialist AI for generating MCP (Model Context Protocol) servers.","You are NOT a generic coding assistant. Your domain is MCP server creation.","","# MCP Protocol Specification","","## Core Primitives","MCP servers expose capabilities to AI hosts (Claude Desktop, Cursor, Windsurf, etc.) via:","","### Tools (functions the AI can invoke)","- name: snake_case, verb_noun pattern (get_user, create_order, list_products)","- description: one-sentence purpose, mention side effects if any","- inputSchema: JSON Schema with required/optional params, each with description","- One tool = one atomic API operation. Do NOT merge multiple endpoints into one tool.","- Return structured JSON. Include relevant fields, not raw API response.","","### Resources (read-only data the AI can access)","- Exposed via URI: resource://users/{id}, resource://config","- Use for reference data, configs, documentation. Use tools for mutations.","","## Server Structure (TypeScript, best practice)","```","src/"," index.ts # McpServer + StdioServerTransport entry"," tools/ # One file per tool group"," users.ts # registerUserTools(server, client)"," orders.ts"," lib/"," api-client.ts # Shared HTTP client: base URL, auth, error handling"," types.ts # Shared TypeScript interfaces",'package.json # type: "module", bin: { "mcp-server-xxx": "./dist/index.js" }',"tsconfig.json # target: ES2022, module: NodeNext","README.md # Install, configure, use with Claude/Cursor","```","","## Authentication Patterns","- API Key: read from env var (e.g., XXX_API_KEY), inject into headers","- Bearer Token: env var, Authorization: Bearer ${token}","- OAuth2: implement token refresh, store in memory or file","- NEVER hardcode secrets. Always use env vars: {SERVICE}_API_KEY","- Server must fail fast with clear error if required env var is missing","- Document all required env vars in README with examples","","## Error Handling","- Wrap every tool handler in try/catch",'- Return { error: "Human-readable message" } on failure, not stack traces',"- Handle HTTP 401/403 specifically: suggest checking API key","- Handle network errors: suggest checking connectivity","- Handle rate limits (429): include retry-after info if available","","## Publishing Checklist",'- package.json: name starts with "mcp-server-", keywords include "mcp-server"',"- bin field points to compiled entry","- README includes claude_desktop_config.json example:",' { "mcpServers": { "name": { "command": "npx", "args": ["-y", "mcp-server-xxx"], "env": { "API_KEY": "..." } } } }',"- Server starts cleanly with: npx mcp-server-xxx","- All env vars documented with descriptions and defaults","","## Quality Standards","- Generated code must compile with strict TypeScript (no any, no implicit)","- Each tool must handle missing/invalid params gracefully","- Include at least one integration test per tool","- Use zod or JSON Schema validation on tool inputs","","# Behavior Rules","- Act first, explain briefly. Call tools instead of asking questions.","- Keep responses to 1-4 sentences. Expand only when user asks.",'- When user says "project dir" / "current folder" / "here" -> use cwd, no questions.','- When user mentions a specific file (e.g., "agent_api.md") -> call read_file with that filename.','- When user says "I put a file" without name -> call read_folder on cwd to discover it, then read_file to read fully.',"- If read_folder preview is truncated, ALWAYS follow up with read_file to get the complete content.","- Relative paths resolve from cwd.","- IMPORTANT: Only call fetch_url when user gives an explicit http/https URL."," Local files/folders -> always read_folder. Never mix fetch_url with local file operations.","- Call ONE tool at a time. Do not call multiple tools in parallel unless clearly needed.","- After reading docs, summarize what tools you would generate BEFORE generating.","","# CRITICAL: read_folder vs read_file","- read_folder returns ONLY a file listing (names and sizes). It does NOT return file content.","- You MUST call read_file for EACH documentation file you need to analyze.","- Workflow: read_folder (discover files) → read_file (read each relevant file FULLY) → analyze → generate.","- NEVER skip read_file. NEVER assume you have file content from read_folder alone.","- If there are multiple doc files (.md, .txt, .json, .yaml), read ALL of them before generating.","","# Available Tools Summary",`You have ${String(je)} tools. Use them in combination:`,"","Discovery flow:",' "make MCP for Stripe" -> sga_search("Stripe API documentation") -> discover best docs URL -> fetch_url or crawl_docs -> generate_mcp',"","OpenAPI fast path:"," User provides URL -> http_request(url + /openapi.json) to probe -> if found, parse_openapi -> generate_mcp","","Editing flow:",' After generate_mcp -> search_files("error") -> write_file to fix -> run_command("npx tsc --noEmit")',"","PDF docs:"," User drops a PDF -> read_pdf -> generate_mcp","","The sga_search tool searches the web with Chinese/WeChat support. prefer it over fetch_url for discovery.","Configure with: mcp-claw config set search.url http://<host>/v1/agent/search","","# Shell Access (run_command)","You have full shell access via run_command. Critical rules for Windows compatibility:","",'## NEVER do this (causes "Command failed" with no useful error):',' WRONG: run_command("cd generated && npx tsc --noEmit")',' WRONG: run_command("cd generated && npx jest 2>&1")',' WRONG: run_command("node_modules/.bin/tsc --noEmit")',' WRONG: run_command("node_modules\\.bin\\tsc")',"","## ALWAYS do this instead (use the cwd parameter):",' RIGHT: run_command("npx tsc --noEmit", cwd: "generated")',' RIGHT: run_command("npx jest --no-coverage", cwd: "generated")',' RIGHT: run_command("pnpm install", cwd: "generated")',' RIGHT: run_command("dir src", cwd: "generated") // Windows: use dir not ls',"","## Key rules:","- NEVER use `cd path && command` 鈥?use cwd parameter instead","- NEVER use `2>&1` 鈥?stderr is captured automatically on errors","- NEVER use `node_modules/.bin/` or `node_modules\\.bin\\` 鈥?use `npx <tool>` instead","- On Windows use `dir` not `ls`, use `type` not `cat`","- The cwd defaults to the last generated project dir automatically",'- To compile: run_command("npx tsc --noEmit") 鈥?no cd needed if cwd is already right','- To install deps: run_command("pnpm install") in project cwd',"","## When run_command returns status: error 鈥?MANDATORY debug protocol:","1. STOP. Do NOT immediately retry the same command.",'2. READ the full "output" field 鈥?it contains the actual error messages.',' TypeScript errors: "src/file.ts(10,5): error TS2345: Argument of type..."'," Missing module: \"Cannot find module 'zod' or its type declarations\"","3. Identify WHICH file and line number has the error.","4. read_file the problematic file to understand the code.","5. write_file to fix the error.",'6. run_command("npx tsc --noEmit") again to verify the fix.',"","## Special case: Empty output from run_command (V8 crash)","If run_command returns status: error with empty or missing output for a TypeScript command:"," CAUSE: JavaScript heap out of memory - TypeScript type checker crashed.",' ALWAYS check server.ts for: zodToJsonSchema(schema) as Tool["inputSchema"]',' FIX: Replace with toInputSchema helper (see below) or use (zodToJsonSchema as (s: unknown) => Tool["inputSchema"])(schema)'," DO NOT retry the same tsc command - it will always crash until the code is fixed.","","## NEVER do these when you see an error:",'- NEVER add 2>&1 to capture stderr (stderr is already in "output")',"- NEVER add || true to suppress exit codes (hides real errors)","- NEVER retry the exact same command without first fixing root cause","When something fails, DO NOT give up. Analyze 鈫?Fix 鈫?Verify.","","# Workflow","1) Discover files: call read_folder to get file listing (names + sizes only).","2) Read each file: call read_file for EVERY documentation file found. Do NOT skip any."," IMPORTANT: read_folder does NOT return file content. You MUST call read_file individually."," For web sources: use fetch_url or crawl_docs.","3) Analyze: identify ALL endpoints, params, auth method, data models.","4) Propose: tell user what MCP tools you will generate and why. Wait for user confirmation.","5) Generate: call generate_mcp to produce the server code.","6) Validate: use run_command to compile and verify the generated project:",' - run_command("npx tsc --noEmit") to check TypeScript compilation'," - If errors, fix them with run_command (install deps, etc.)",' - run_command("npx jest") if tests exist',"7) **STOP here.** Report generation result ACCURATELY:"," - Use search_files or read_file on the generated src/ to count the EXACT number of tools."," - Report the exact tool count, tool names, file list, and output directory."," - Do NOT guess or estimate the tool count. Count them from the source code."," Then ask the user:",' - "瑕佽繘琛岄泦鎴愭祴璇曞悧锛熻鎻愪緵锛?) API base URL 2) 闇€瑕佺殑 credentials (濡?API key)"'," - Do NOT call test_integration until the user provides the URL and credentials."," - If user says skip, go directly to step 10.","8) Integration test: call test_integration with the user-provided base_url and auth_env."," - test_integration MUST execute every discovered tool at least once."," - Publishing is allowed only when all tools pass (allToolsPassed=true)."," - If test_integration fails, report the exact failed tools and errors to the user."," - Do NOT retry blindly."," - Do NOT modify generated server source code just to silence test failures.",'9) **STOP again.** Show test results. Ask: "要发布到 MCP Market 吗?"'," - Do NOT call publish_mcp until user confirms."," - publish_mcp requires market_url (e.g. http://localhost:3000) and token (access token)."," - Token is saved after first use; market_url is saved after first use."," - On success, show the returned packageUrl to the user as a clickable link.","","10) Publish: call publish_mcp.","","# CRITICAL: Never auto-proceed past step 7. Always pause for user input before integration testing and publishing.","","# Self-Evolution Protocol","When you complete an error鈫抐ix鈫抳erify cycle (run_command failed 鈫?you fixed it 鈫?run_command passed):"," ALWAYS call record_learning immediately after the fix is confirmed."," This saves the pattern to .mcp-claw/patterns.md and helps future sessions avoid the same mistake."," Good triggers: missing dependency, TypeScript type error, wrong import path, config issue.","","# Chat History vs Run History 鈥?IMPORTANT DISTINCTION","Your conversation messages are ALWAYS loaded at startup from .mcp-claw/chat-history.json.",'If you can see prior "user" and "assistant" messages in your context, that IS the real history.','NEVER say "I have no context" or "I cannot find previous conversation" when history is present.',"NEVER use show_history to look for chat content 鈥?it only returns MCP generation run logs, NOT chat.",'show_history is for: "what MCPs have I generated before?" NOT for: "what did we discuss?"',"","Default language: Chinese. Keep technical terms in English (MCP, tool, schema, API, etc.).",...loadLearnedPatterns(G)].join("\n")}function loadLearnedPatterns(G){const K=(0,at.join)(G,".mcp-claw","patterns.md");if(!(0,Xe.existsSync)(K))return[];try{const G=(0,Xe.readFileSync)(K,"utf8").trim();if(G.length<10)return[];return["","# Learned Patterns (from this project 鈥?apply these automatically)",G]}catch{return[]}}function historyPath(G){return(0,at.join)(G,".mcp-claw","chat-history.json")}function loadPersistedState(G){const K=historyPath(G);if(!(0,Xe.existsSync)(K)){return null}try{const G=(0,Xe.readFileSync)(K,"utf8");return JSON.parse(G)}catch{return null}}function savePersistedState(G,K){const je=historyPath(G);const ze=(0,at.join)(G,".mcp-claw");if(!(0,Xe.existsSync)(ze)){(0,Xe.mkdirSync)(ze,{recursive:true})}const We={...K,history:K.history.slice(-40)};(0,Xe.writeFileSync)(je,JSON.stringify(We,null,2),"utf8")}class ChatSession{config;history=[];tools;llm;fsTool;browserTool;httpTool;pdfTool;sessionReader;generate;testRunner;output;toolHandlers;sgaConfig;lastSource;lastGeneratedDir;lastIntegrationDir;lastIntegrationSummary;cachedSystemPrompt;constructor(G,K={}){this.config=G;this.tools=(0,ki.buildToolDefinitions)(this.config);this.llm=K.llm??new Rr.OpenRouterProvider("openrouter-chat",this.config.model,this.config.apiKey,this.config.baseUrl);this.fsTool=K.fsTool??new fi.FsTool;this.browserTool=K.browserTool??new zr.BrowserTool;this.httpTool=K.httpTool??new mi.HttpFetchTool;this.pdfTool=K.pdfTool??new bi.PdfTool;this.sessionReader=K.sessionReader??new jr.SessionReader;this.generate=K.generate??wt.generateCommand;this.testRunner=K.testRunner??new yt.TestRunner;this.output=K.output??process.stdout;this.toolHandlers=K.toolHandlers??{};this.sgaConfig=new Er.SgaConfig;const je=loadPersistedState(this.config.workDir);if(je){this.history.push(...je.history);this.lastSource=je.lastSource;this.lastGeneratedDir=je.lastGeneratedDir;this.lastIntegrationDir=je.lastIntegrationDir;this.lastIntegrationSummary=je.lastIntegrationSummary}}get restoredCount(){return this.history.length}async send(G){this.cachedSystemPrompt=await buildSystemPrompt(this.config.workDir,this.history.length,this.tools.length);const K=this.history.length;this.history.push({role:"user",content:G});try{for(;;){const G=await this.callLlm();if(G.finish_reason==="stop"){const K=G.content.trim();if(K.length>0){this.writeAssistant(K)}this.history.push({role:"assistant",content:G.content});this.persistState();return}const K=G.content.trim();if(K.length>0){this.writeAssistant(K)}const je=G.tool_calls??[];this.history.push({role:"assistant",content:G.content,...je.length>0?{tool_calls:je}:{}});for(const G of je){const K=parseToolArguments(G.function.arguments);this.writeToolStart(G.function.name,K);const je=await this.executeTool(G);this.writeToolDone(G.function.name,je);this.history.push({role:"tool",content:je,tool_call_id:G.id})}}}catch(G){this.history.length=K;throw G}}async callLlm(){const G=this.cachedSystemPrompt??await buildSystemPrompt(this.config.workDir,this.history.length,this.tools.length);const K=[{role:"system",content:G},...this.history];return this.llm.chat(K,this.tools)}async executeTool(G){const K=G.function.name;const je=parseToolArguments(G.function.arguments);const ze=this.toolHandlers[K];if(ze){return ze(je)}try{switch(K){case"read_folder":return this.readFolder(je);case"read_file":return this.readSingleFile(je);case"fetch_url":return this.fetchUrl(je);case"write_file":return this.writeFile(je);case"search_files":return this.searchFiles(je);case"read_pdf":return this.readPdf(je);case"http_request":return this.httpRequest(je);case"crawl_docs":return this.crawlDocs(je);case"discover_docs":return this.discoverDocs(je);case"sga_search":return this.sgaSearch(je);case"parse_openapi":return this.parseOpenApi(je);case"run_command":return this.runShellCommand(je);case"generate_mcp":return this.generateMcp(je);case"run_tests":return this.runTests(je);case"test_integration":return this.testIntegration(je);case"publish_mcp":return this.publishMcp(je);case"show_history":return this.showHistory();case"record_learning":return this.recordLearning(je);default:return JSON.stringify({error:`Unknown tool: ${G.function.name}`})}}catch(G){return JSON.stringify({error:formatError(G)})}}resolvePath(G){return(0,at.isAbsolute)(G)?G:(0,at.resolve)(this.config.workDir,G)}async readFolder(G){const K=typeof G.path==="string"&&G.path.trim()?G.path.trim():this.config.workDir;const je=this.resolvePath(K);if(!(0,Xe.existsSync)(je)){return JSON.stringify({error:`Path not found: ${je}`})}const ze=await this.fsTool.glob(je,Ti);const We=await Promise.all(ze.slice(0,Ii).map((async G=>{const K=(0,at.relative)(this.config.workDir,G)||G;let je=0;try{const K=await this.fsTool.readFile(G);je=K.length}catch{}const ze=(0,at.extname)(G).toLowerCase();const We=Pi.has(ze);return{path:K,size:je,isText:We}})));this.lastSource=K;return JSON.stringify({path:je,fileCount:ze.length,listing:We,hint:"This is a file listing only. Call read_file on each relevant file to get its full content."},null,2)}async readSingleFile(G){const K=typeof G.path==="string"?G.path.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: path"})}const je=this.resolvePath(K);if(!(0,Xe.existsSync)(je)){return JSON.stringify({error:`File not found: ${je}`})}const ze=await this.fsTool.readFile(je);this.lastSource=K;return JSON.stringify({path:je,length:ze.length,content:truncate(ze,Ri)},null,2)}async fetchUrl(G){const K=typeof G.url==="string"?G.url:"";if(!K){return JSON.stringify({error:"Missing required argument: url"})}const je=await this.browserTool.fetch(K);this.lastSource=K;return JSON.stringify({url:je.url,title:je.title,links:je.links.slice(0,100),openApiUrls:je.openApiUrls,text:truncate(je.text,8e3)},null,2)}async writeFile(G){const K=typeof G.path==="string"?G.path.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: path"})}if(typeof G.content!=="string"){return JSON.stringify({error:"Missing required argument: content"})}const je=this.resolvePath(K);(0,Xe.mkdirSync)((0,at.dirname)(je),{recursive:true});await this.fsTool.writeFile(je,G.content);return JSON.stringify({status:"ok",path:je,bytes:G.content.length},null,2)}async searchFiles(G){const K=typeof G.pattern==="string"?G.pattern.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: pattern"})}const je=typeof G.path==="string"&&G.path.trim()?G.path.trim():this.lastGeneratedDir??this.config.workDir;const ze=this.resolvePath(je);const We=typeof G.glob==="string"&&G.glob.trim()?G.glob.trim():"*";let Xe;try{Xe=new RegExp(K,"i")}catch(G){return JSON.stringify({error:`Invalid pattern: ${formatError(G)}`})}const rt=await this.fsTool.glob(ze,[We]);const ft=[];let mt=0;for(const G of rt){let K;try{K=await this.fsTool.readFile(G)}catch{continue}const je=K.split(/\r?\n/);for(let K=0;K<je.length;K+=1){const ze=je[K];if(!Xe.test(ze)){continue}mt+=1;if(ft.length<ps){ft.push({file:(0,at.relative)(this.config.workDir,G)||G,line:K+1,text:ze})}}}return JSON.stringify({matches:ft,totalMatches:mt},null,2)}async readPdf(G){const K=typeof G.path==="string"?G.path.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: path"})}const je=this.resolvePath(K);if(!(0,Xe.existsSync)(je)){return JSON.stringify({error:`File not found: ${je}`})}const ze=await this.pdfTool.extract(je);return JSON.stringify({path:je,length:ze.length,content:truncate(ze,qi)},null,2)}async httpRequest(G){const K=typeof G.url==="string"?G.url.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: url"})}const je=typeof G.method==="string"&&G.method.trim()?G.method.trim().toUpperCase():"GET";const ze=typeof G.timeout_ms==="number"&&Number.isFinite(G.timeout_ms)?Math.max(1,Math.floor(G.timeout_ms)):1e4;const We={};if(G.headers&&typeof G.headers==="object"&&!Array.isArray(G.headers)){for(const[K,je]of Object.entries(G.headers)){if(typeof je==="string"){We[K]=je}}}const Xe=typeof G.body==="string"?G.body:undefined;try{const G=await this.httpTool.request({url:K,method:je,headers:We,body:Xe,timeoutMs:ze});return JSON.stringify({status:G.status,statusText:G.statusText,headers:G.headers,body:truncate(G.body,Xi),url:G.url},null,2)}catch(G){return JSON.stringify({error:formatError(G),url:K},null,2)}}async crawlDocs(G){const K=typeof G.start_url==="string"?G.start_url.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: start_url"})}let je;try{je=new URL(K)}catch{return JSON.stringify({error:`Invalid URL: ${K}`})}const ze=typeof G.max_pages==="number"&&Number.isFinite(G.max_pages)?Math.floor(G.max_pages):qs;const We=Math.min(Ws,Math.max(1,ze));let Xe;if(typeof G.link_pattern==="string"&&G.link_pattern.trim()){try{Xe=new RegExp(G.link_pattern,"i")}catch(G){return JSON.stringify({error:`Invalid link_pattern: ${formatError(G)}`})}}const rt=[je.href];const at=new Set;const ft=new Set([je.href]);const mt=[];const vt=[];while(rt.length>0&&at.size<We){const G=rt.shift();if(!G||at.has(G)){continue}at.add(G);let K;try{K=await this.browserTool.fetch(G)}catch{continue}mt.push({url:K.url,title:K.title,textLength:K.text.length});vt.push(K.text);for(const G of K.links){let K;try{K=new URL(G)}catch{continue}const ze=K.href;ft.add(ze);if(K.hostname!==je.hostname){continue}if(Xe&&!Xe.test(ze)){continue}if(at.has(ze)||rt.includes(ze)){continue}rt.push(ze)}}const yt=truncate(vt.join("\n\n"),Ls);return JSON.stringify({pagesVisited:mt.length,pages:mt,combinedText:yt,discoveredUrls:[...ft]},null,2)}async discoverDocs(G){const K=typeof G.query==="string"?G.query.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: query"})}const je=typeof G.max_results==="number"&&Number.isFinite(G.max_results)?Math.max(1,Math.floor(G.max_results)):5;const ze=this.sgaConfig.get("search.url");const We=typeof ze==="string"&&ze.trim().length>0?ze.trim():process.env.SEARCH_ENGINE_URL?.trim();if(!We){return JSON.stringify({error:"No search engine configured. Set search.url in config: mcp-claw config set search.url https://your-search-engine/search"},null,2)}let Xe;try{Xe=deriveSgaSearchEndpoint(We)}catch{return JSON.stringify({error:`Invalid search.url: ${We}`},null,2)}const rt=new URL(Xe);rt.searchParams.set("q",K);rt.searchParams.set("limit",String(je));rt.searchParams.set("preset","general");rt.searchParams.set("sort","relevance");rt.searchParams.set("depth","basic");const at=await this.httpTool.request({url:rt.toString(),method:"GET",timeoutMs:1e4});if(at.status>=400){return JSON.stringify({query:K,error:`Search request failed with HTTP ${at.status}`},null,2)}let ft;try{ft=JSON.parse(at.body)}catch{return JSON.stringify({query:K,error:"Search engine returned non-JSON response"},null,2)}const mt=parseSearchPayload(ft,je);return JSON.stringify({query:K,results:mt.results,suggestions:mt.suggestions},null,2)}async sgaSearch(G){const K=typeof G.q==="string"?G.q.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: q"})}const je=typeof G.preset==="string"&&["chinese","wechat","general"].includes(G.preset)?G.preset:"chinese";const ze=Math.min(eo,Math.max(1,Math.floor(toNumber(G.limit,Js))));const We=typeof G.sort==="string"&&["time","relevance"].includes(G.sort)?G.sort:"time";const Xe=typeof G.depth==="string"&&["basic","enriched"].includes(G.depth)?G.depth:"basic";const rt=this.sgaConfig.get("search.url");const at=typeof rt==="string"&&rt.trim().length>0?rt.trim():process.env.SEARCH_ENGINE_URL?.trim();if(!at){return JSON.stringify({error:"No search engine configured. Set search.url in config: mcp-claw config set search.url https://your-search-engine/search"},null,2)}let ft;try{ft=deriveSgaSearchEndpoint(at)}catch{return JSON.stringify({error:`Invalid search.url: ${at}`},null,2)}const mt=new URL(ft);mt.searchParams.set("q",K);mt.searchParams.set("preset",je);mt.searchParams.set("limit",String(ze));mt.searchParams.set("sort",We);mt.searchParams.set("depth",Xe);const vt=await this.httpTool.request({url:mt.toString(),method:"GET",timeoutMs:1e4});if(vt.status>=400){return JSON.stringify({query:K,error:`Search request failed with HTTP ${vt.status}`},null,2)}let yt;try{yt=JSON.parse(vt.body)}catch{return JSON.stringify({query:K,error:"Search engine returned non-JSON response"},null,2)}const wt=parseSearchPayload(yt,ze);return JSON.stringify({query:K,total:wt.total,results:wt.results,suggestions:wt.suggestions},null,2)}async parseOpenApi(G){const K=typeof G.source==="string"?G.source.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: source"})}const je=Math.max(1,Math.floor(typeof G.max_endpoints==="number"&&Number.isFinite(G.max_endpoints)?G.max_endpoints:to));let ze="";try{if(/^https?:\/\//i.test(K)){const G=await this.httpTool.request({url:K,method:"GET",timeoutMs:1e4});ze=G.body}else{const G=this.resolvePath(K);ze=await this.fsTool.readFile(G)}}catch(G){return JSON.stringify({error:formatError(G),rawPreview:""},null,2)}let We=null;try{const G=JSON.parse(ze);if(G&&typeof G==="object"&&!Array.isArray(G)){We=G}}catch{}if(!We){const G=ze.trimStart();if(/^(openapi|swagger)\s*:/i.test(G)){We=parseMinimalOpenApiYaml(ze)}else{return JSON.stringify({error:"Failed to parse as JSON or recognizable OpenAPI YAML",rawPreview:ze.slice(0,1e3)},null,2)}}const Xe=asRecord(We.info);const rt=Array.isArray(We.servers)?We.servers.map((G=>{const K=asRecord(G);return{url:toStringValue(K.url),description:toStringValue(K.description)}})):[];const at=rt.filter((G=>G.url.length>0));const ft=extractAuthSchemes(We);const mt=extractOpenApiEndpoints(We,je);const vt=asRecord(We.components);const yt=Object.keys(asRecord(vt.schemas));return JSON.stringify({title:toStringValue(Xe.title),version:toStringValue(Xe.version),description:toStringValue(Xe.description),baseUrl:at[0]?.url??"",auth:ft,endpointCount:mt.endpointCount,endpoints:mt.endpoints,models:yt},null,2)}async runShellCommand(G){const K=typeof G.command==="string"?G.command.trim():"";if(!K){return JSON.stringify({error:"Missing required argument: command"})}const je=typeof G.cwd==="string"&&G.cwd.trim()?G.cwd.trim():this.lastGeneratedDir??this.config.workDir;const ze=this.resolvePath(je);try{const{stdout:G,stderr:je}=await Ci(K,{cwd:ze,timeout:12e4,windowsHide:true,maxBuffer:10*1024*1024});const We=[G,je].filter(Boolean).join("\n");return JSON.stringify({status:"ok",cwd:ze,command:K,output:truncate(We,Mi)},null,2)}catch(G){const je=G;const We=(je.stdout??"").trim();const Xe=(je.stderr??"").trim();const rt=(je.message??"").split("\n");const at=rt.slice(1).join("\n").trim();let ft=[We,Xe,at].filter(Boolean).join("\n").trim();if(!ft||ft===je.message){const ze=je.code===null||je.code===undefined||String(je.code)==="null"||je.killed===false&&!We&&!Xe;if(ze&&(K.includes("tsc")||K.includes("npx"))){ft=["Command crashed with no output - likely JavaScript heap out of memory (V8 OOM).","","DIAGNOSIS: TypeScript type-checking consumed too much memory.","COMMON CAUSE: zodToJsonSchema() called with complex Zod schemas causes recursive type inference.","FIX: In server.ts, replace:",' zodToJsonSchema(mySchema) as Tool["inputSchema"]',"with:",' (zodToJsonSchema as (s: unknown) => Tool["inputSchema"])(mySchema)',"","Or add this helper before the tools array:",' function toInputSchema(schema: unknown): Tool["inputSchema"] {',' return zodToJsonSchema(schema as Parameters<typeof zodToJsonSchema>[0]) as Tool["inputSchema"];'," }","Then use: toInputSchema(mySchema)"].join("\n")}else{ft=je.message??String(G)}}return JSON.stringify({status:"error",cwd:ze,command:K,output:truncate(ft,Mi)},null,2)}}async generateMcp(G){const K=typeof G.source==="string"&&G.source.trim()?G.source:this.lastSource;const je=typeof G.output_dir==="string"&&G.output_dir.trim()?G.output_dir:undefined;if(!K){return JSON.stringify({error:"Missing required argument: source"})}const ze=[];const We=je??(0,at.resolve)(this.config.workDir,"generated",(0,wt.deriveProjectName)(K));const Xe=await this.generate({source:K,output:We,logger:{log:G=>ze.push(G)}});this.lastSource=K;this.lastGeneratedDir=Xe.root;return JSON.stringify({status:"ok",source:K,outputDir:this.lastGeneratedDir,logs:ze},null,2)}async runTests(G){const K=typeof G.dir==="string"&&G.dir.trim()?G.dir:this.lastGeneratedDir;if(!K){return JSON.stringify({error:"Missing required argument: dir"})}const je=this.resolvePath(K);const ze=await this.testRunner.run(je);const We=[ze.stdout,ze.stderr].filter(Boolean).join("\n");return JSON.stringify({dir:je,output:truncate(We,Mi)},null,2)}async testIntegration(G){const K=typeof G.dir==="string"&&G.dir.trim()?G.dir.trim():this.lastGeneratedDir??this.config.workDir;const je=typeof G.base_url==="string"?G.base_url.trim():"";if(!je){return JSON.stringify({error:"base_url is required"})}const ze={};if(G.auth_env&&typeof G.auth_env==="object"&&!Array.isArray(G.auth_env)){for(const[K,je]of Object.entries(G.auth_env)){if(typeof je==="string"){ze[K]=je}}}const We=new vt.IntegrationTester;const rt=this.resolvePath(K);const ft=await We.run({dir:rt,baseUrl:je,authEnv:ze});this.lastIntegrationDir=rt;this.lastIntegrationSummary={passed:ft.passed===true,allToolsPassed:ft.allToolsPassed===true,toolsFound:typeof ft.toolsFound==="number"?ft.toolsFound:undefined,failedTools:Array.isArray(ft.toolResults)?ft.toolResults.filter((G=>Boolean(G)&&typeof G.name==="string"&&G.ok===false)).map((G=>({name:G.name,...typeof G.detail==="string"?{detail:G.detail}:{}}))):[]};if(ft.tools&&ft.tools.length>0){const G=(0,at.join)(rt,"manifest.json");try{const K=(0,Xe.existsSync)(G)?JSON.parse((0,Xe.readFileSync)(G,"utf8")):{};K.tools=ft.tools;K.toolsCount=ft.tools.length;(0,Xe.writeFileSync)(G,JSON.stringify(K,null,2)+"\n","utf8")}catch{}}this.persistState();return JSON.stringify(ft,null,2)}async publishMcp(G){const K=typeof G.dir==="string"&&G.dir.trim()?G.dir.trim():this.lastGeneratedDir??this.config.workDir;const je=typeof G.market_url==="string"?G.market_url.trim():"";const ze=typeof G.token==="string"?G.token.trim():"";const We=(0,Si.getToken)();if(ze){(0,Si.saveToken)(ze,je||(0,Si.getMarketUrl)())}else if(je&&We){(0,Si.saveToken)(We,je)}const Xe=this.resolvePath(K);const rt=this.lastIntegrationSummary?.passed===true&&this.lastIntegrationSummary?.allToolsPassed===true&&this.lastIntegrationDir===Xe;if(!rt){return JSON.stringify({error:"Publish blocked: run test_integration on this directory and ensure all discovered tools pass before publish.",expectedDir:Xe,lastIntegrationDir:this.lastIntegrationDir??null,lastIntegration:this.lastIntegrationSummary??null},null,2)}try{const G=await(0,lr.publishCommand)({},Xe);const K=`${G.marketUrl}/repository`;return JSON.stringify({status:"ok",name:G.name,version:G.version,packageUrl:K,marketUrl:G.marketUrl,dir:Xe})}catch(G){return JSON.stringify({error:formatError(G)})}}async showHistory(){const G=this.sessionReader.listSessions(10).map((G=>({file:G.file,time:G.mtime.toISOString(),title:G.preview.replace(/^#\s*/,"").trim()})));const K=this.sessionReader.lastRun(this.config.workDir);return JSON.stringify({recentSessions:G,lastRun:K?{source:K.source,status:K.status,finishedAt:K.finishedAt,toolCount:K.ir?.toolCount??0}:null},null,2)}async recordLearning(G){const K=typeof G.title==="string"?G.title.trim():"";const je=typeof G.problem==="string"?G.problem.trim():"";const ze=typeof G.fix==="string"?G.fix.trim():"";if(!K||!je||!ze){return JSON.stringify({error:"title, problem, and fix are all required"})}const We=(0,at.join)(this.config.workDir,".mcp-claw");const rt=(0,at.join)(We,"patterns.md");if(!(0,Xe.existsSync)(We)){(0,Xe.mkdirSync)(We,{recursive:true})}const ft=Array.isArray(G.tags)?G.tags.filter((G=>typeof G==="string")):[];const mt=(new Date).toISOString().split("T")[0];const vt=[`\n## ${K} (${mt})`,`**Problem**: ${je}`,`**Fix**: ${ze}`,...ft.length>0?[`**Tags**: ${ft.join(", ")}`]:[],""].join("\n");const yt=(0,Xe.existsSync)(rt)?(0,Xe.readFileSync)(rt,"utf8"):"# Learned Patterns\n";(0,Xe.writeFileSync)(rt,yt+vt,"utf8");return JSON.stringify({status:"ok",message:`Pattern "${K}" saved`,file:rt},null,2)}getRecentRounds(G){const K=[];let je=0;while(je<this.history.length){const G=this.history[je];if(G.role==="user"){const ze=typeof G.content==="string"?G.content:"";let We="";let Xe=0;let rt=je+1;while(rt<this.history.length&&this.history[rt].role!=="user"){const G=this.history[rt];if(G.role==="assistant"){if(typeof G.content==="string"&&G.content.trim()){We=G.content}Xe+=Array.isArray(G.tool_calls)?G.tool_calls.length:0}rt++}K.push({userText:ze,assistantText:We,toolCount:Xe});je=rt}else{je++}}return K.slice(-G)}setModel(G){this.llm=new Rr.OpenRouterProvider("openrouter-chat",G,this.config.apiKey,this.config.baseUrl);this.cachedSystemPrompt=undefined;return G}clearHistory(){this.history.length=0;this.lastSource=undefined;this.lastGeneratedDir=undefined;this.lastIntegrationDir=undefined;this.lastIntegrationSummary=undefined;this.persistState()}persistState(){try{savePersistedState(this.config.workDir,{history:this.history,lastSource:this.lastSource,lastGeneratedDir:this.lastGeneratedDir,lastIntegrationDir:this.lastIntegrationDir,lastIntegrationSummary:this.lastIntegrationSummary})}catch{}}writeAssistant(G){this.output.write("\n");this.output.write((0,Ei.renderMarkdown)(G));this.output.write("\n\n")}writeToolStart(G,K){const je=this.toolArgsSummary(G,K);this.output.write(` ${mt.default.dim("...")} ${mt.default.cyan(G)}${je?mt.default.gray(` ${je}`):""}\n`)}writeToolDone(G,K){try{const je=JSON.parse(K);const ze=je.error||je.status==="error"||je.passed===false;if(ze){const K=je.error?String(je.error):this.toolResultSummary(G,je);this.output.write(` ${mt.default.red("x")} ${mt.default.red(K)}\n`)}else{const K=this.toolResultSummary(G,je);this.output.write(` ${mt.default.green("ok")} ${mt.default.dim(K)}\n`)}}catch{const G=K.length>80?`${K.slice(0,80)}...`:K;this.output.write(` ${mt.default.green("ok")} ${mt.default.dim(G)}\n`)}}toolArgsSummary(G,K){switch(G){case"read_folder":case"read_file":case"write_file":case"read_pdf":return typeof K.path==="string"?K.path:"";case"search_files":{const G=typeof K.pattern==="string"?K.pattern:"";const je=typeof K.path==="string"?K.path:"project";return`${G} in ${je}`.trim()}case"fetch_url":return typeof K.url==="string"?K.url:"";case"http_request":{const G=typeof K.method==="string"?K.method.toUpperCase():"GET";const je=typeof K.url==="string"?K.url:"";return`${G} ${je}`.trim()}case"crawl_docs":{const G=typeof K.start_url==="string"?K.start_url:"";const je=typeof K.max_pages==="number"?K.max_pages:qs;return`${G} (max ${je} pages)`}case"discover_docs":return typeof K.query==="string"?K.query:"";case"sga_search":{const G=typeof K.q==="string"?K.q:"";const je=typeof K.preset==="string"?K.preset:"chinese";return`${G} (${je})`.trim()}case"parse_openapi":return typeof K.source==="string"?K.source:"";case"run_command":return typeof K.command==="string"?K.command:"";case"generate_mcp":return typeof K.source==="string"?K.source:"";case"run_tests":case"test_integration":return typeof K.dir==="string"?K.dir:"";case"record_learning":return typeof K.title==="string"?K.title:"";default:return""}}toolResultSummary(G,K){switch(G){case"read_folder":{const G=typeof K.fileCount==="number"?K.fileCount:"?";return`${G} files`}case"read_file":{const G=typeof K.length==="number"?K.length:"?";return`${G} chars`}case"write_file":{const G=typeof K.bytes==="number"?K.bytes:"?";return`${G} bytes written`}case"search_files":{const G=typeof K.totalMatches==="number"?K.totalMatches:0;return`${G} matches`}case"read_pdf":{const G=typeof K.length==="number"?K.length:0;return`${G} chars extracted`}case"fetch_url":return typeof K.title==="string"?K.title:"fetched";case"http_request":{const G=typeof K.status==="number"?K.status:"?";return`HTTP ${G}`}case"crawl_docs":{const G=typeof K.pagesVisited==="number"?K.pagesVisited:0;const je=typeof K.combinedText==="string"?K.combinedText.length:0;return`${G} pages, ${je} chars`}case"discover_docs":{const G=Array.isArray(K.results)?K.results:[];const je=G.length;const ze=G.map((G=>G&&typeof G==="object"?G.url:undefined)).filter((G=>typeof G==="string")).slice(0,3);return`${je} results found${ze.length>0?`: ${ze.join(", ")}`:""}`}case"sga_search":{const G=typeof K.total==="number"?K.total:0;return`${G} results`}case"parse_openapi":{const G=typeof K.endpointCount==="number"?K.endpointCount:0;const je=Array.isArray(K.auth)?K.auth.filter((G=>typeof G==="string")):[];return`${G} endpoints, ${je.length>0?je.join("+"):"no auth"}`}case"run_command":{if(K.status==="ok"){const G=typeof K.output==="string"?(K.output.split("\n").find((G=>G.trim()))??"").slice(0,60):"";return`exit 0${G?` | ${G}`:""}`}const G=typeof K.output==="string"?K.output:"";const je=G.split("\n").map((G=>G.trim())).filter((G=>G&&!G.startsWith("Command failed")&&!G.startsWith("npm warn")&&!G.startsWith("npm notice")));const ze=je.slice(0,3).join(" | ");return`error · ${(ze||G).slice(0,300)}`}case"generate_mcp":{const G=Array.isArray(K.logs)?K.logs:[];return G.length>0?String(G[G.length-1]):"done"}case"run_tests":return typeof K.output==="string"?K.output.split("\n")[0]??"done":"done";case"test_integration":{const G=K.passed===true?"PASS":"FAIL";const je=typeof K.toolsFound==="number"?K.toolsFound:0;const ze=K.allToolsPassed===true;const We=Array.isArray(K.toolResults)?K.toolResults.filter((G=>Boolean(G)&&typeof G==="object"&&G.ok===false)).length:0;const Xe=K.authProbe;const rt=Xe?Xe.authRequired?" | AUTH REQUIRED":" | no auth needed":"";const at=ze?" | all tools passed":` | failed tools: ${We}`;return`${G} · ${je} tools${at}${rt}`}case"publish_mcp":return K.status==="ok"?`published → ${String(K.packageUrl??K.marketUrl??"market")}`:"done";case"show_history":return"loaded";case"record_learning":return K.status==="ok"?`recorded: ${String(K.message??"done")}`:"done";default:return"done"}}}K.ChatSession=ChatSession},2330:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.renderMarkdown=renderMarkdown;const We=ze(je(39559));const Xe=" ";function stripAnsi(G){return G.replace(/\x1b\[[0-9;]*m/g,"")}function visibleLength(G){return stripAnsi(G).length}function padEnd(G,K){const je=K-visibleLength(G);return je>0?G+" ".repeat(je):G}function formatInline(G){let K=G;K=K.replace(/`([^`]+)`/g,((G,K)=>We.default.cyan(K)));K=K.replace(/\*\*([^*]+)\*\*/g,((G,K)=>We.default.bold(K)));K=K.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,((G,K)=>We.default.italic(K)));return K}function isTableSeparator(G){return/^\|[\s:*-]+\|$/.test(G.trim().replace(/[\s:-]+/g,(G=>G)))}function isSeparatorRow(G){const K=G.trim();if(!K.startsWith("|")||!K.endsWith("|"))return false;const je=K.slice(1,-1).split("|");return je.every((G=>/^\s*:?-+:?\s*$/.test(G)))}function parseTableRow(G){const K=G.trim();const je=K.startsWith("|")?K.slice(1):K;const ze=je.endsWith("|")?je.slice(0,-1):je;return ze.split("|").map((G=>G.trim()))}function renderTable(G,K){const je=G.headers.length;const ze=[G.headers,...G.rows];const rt=new Array(je).fill(0);for(const G of ze){for(let K=0;K<je;K++){const je=(G[K]??"").length;if(je>rt[K]){rt[K]=je}}}const at=Xe.length+je*3+1;const ft=Math.max(K-at,je*8);const mt=rt.reduce(((G,K)=>G+K),0);const vt=mt<=ft?rt:rt.map((G=>Math.max(6,Math.floor(G/mt*ft))));const yt=[];const wt=Xe+"┌"+vt.map((G=>"─".repeat(G+2))).join("┬")+"┐";yt.push(We.default.gray(wt));const lr=G.headers.map(((G,K)=>{const je=We.default.bold(truncateCell(G,vt[K]));return" "+padEnd(je,vt[K])+" "}));yt.push(Xe+We.default.gray("│")+lr.join(We.default.gray("│"))+We.default.gray("│"));const Er=Xe+"├"+vt.map((G=>"─".repeat(G+2))).join("┼")+"┤";yt.push(We.default.gray(Er));for(const K of G.rows){const G=K.map(((G,K)=>{const je=formatInline(truncateCell(G,vt[K]));return" "+padEnd(je,vt[K])+" "}));yt.push(Xe+We.default.gray("│")+G.join(We.default.gray("│"))+We.default.gray("│"))}const Rr=Xe+"└"+vt.map((G=>"─".repeat(G+2))).join("┴")+"┘";yt.push(We.default.gray(Rr));return yt}function truncateCell(G,K){if(G.length<=K)return G;return G.slice(0,K-1)+"…"}function renderMarkdown(G){const K=process.stdout.columns||100;const je=G.split("\n");const ze=[];let rt=0;while(rt<je.length){const G=je[rt];const at=G.trim();if(at.startsWith("```")){const G=at.slice(3).trim();if(G){ze.push(Xe+We.default.gray(` ── ${G} ──`))}rt++;const ft=[];while(rt<je.length&&!je[rt].trim().startsWith("```")){ft.push(je[rt]);rt++}for(const G of ft){ze.push(Xe+We.default.green(" "+G))}if(G){ze.push(Xe+We.default.gray(" "+"─".repeat(Math.min(50,K-6))))}rt++;continue}if(at.startsWith("|")&&at.endsWith("|")){const G=[];while(rt<je.length&&je[rt].trim().startsWith("|")&&je[rt].trim().endsWith("|")){G.push(je[rt]);rt++}if(G.length>=2){const je=parseTableRow(G[0]);const We=isSeparatorRow(G[1])?2:1;const Xe=G.slice(We).filter((G=>!isSeparatorRow(G))).map(parseTableRow);const rt=je.length;const at=Xe.map((G=>{while(G.length<rt)G.push("");return G.slice(0,rt)}));ze.push(...renderTable({headers:je,rows:at},K))}else{ze.push(Xe+formatInline(at))}continue}const ft=at.match(/^(#{1,4})\s+(.+)$/);if(ft){const G=ft[1].length;const K=ft[2];ze.push("");if(G===1){ze.push(Xe+We.default.cyan.bold.underline(K))}else if(G===2){ze.push(Xe+We.default.cyan.bold(K))}else if(G===3){ze.push(Xe+We.default.white.bold(K))}else{ze.push(Xe+We.default.white(K))}rt++;continue}if(/^[-*_]{3,}$/.test(at)){ze.push(Xe+We.default.gray("─".repeat(Math.min(50,K-4))));rt++;continue}const mt=G.match(/^(\s*)[-*+]\s+(.+)$/);if(mt){const G=Math.floor(mt[1].length/2);const K=G===0?"•":G===1?"◦":"‣";ze.push(Xe+" ".repeat(G)+We.default.gray(K)+" "+formatInline(mt[2]));rt++;continue}const vt=G.match(/^(\s*)(\d+)\.\s+(.+)$/);if(vt){const G=Math.floor(vt[1].length/2);ze.push(Xe+" ".repeat(G)+We.default.gray(vt[2]+".")+" "+formatInline(vt[3]));rt++;continue}if(at.startsWith(">")){const G=at.replace(/^>\s*/,"");ze.push(Xe+We.default.gray("│ ")+We.default.italic(formatInline(G)));rt++;continue}if(!at){ze.push("");rt++;continue}ze.push(Xe+formatInline(at));rt++}return ze.join("\n")}},66191:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.buildToolDefinitions=buildToolDefinitions;function buildToolDefinitions(G){return[{type:"function",function:{name:"read_folder",description:["List files in a local directory. Returns ONLY file names, sizes, and types — NO file content.","Use this first to discover what files exist, then call read_file on each relevant file.",`If path is omitted, default to current working directory: ${G.workDir}.`].join(" "),parameters:{type:"object",properties:{path:{type:"string",description:`Optional folder path. Relative paths are resolved from ${G.workDir}.`}},required:[],additionalProperties:false}}},{type:"function",function:{name:"read_file",description:["Read the FULL content of a single file. ALWAYS call this after read_folder to get actual file content.","read_folder only lists file names — this tool reads the content.","Call this for EVERY relevant file discovered by read_folder."].join(" "),parameters:{type:"object",properties:{path:{type:"string",description:`File path. Relative paths are resolved from ${G.workDir}.`}},required:["path"],additionalProperties:false}}},{type:"function",function:{name:"fetch_url",description:["Fetch content from a remote http/https URL.","ONLY use when the user explicitly provides a URL starting with http:// or https://.","Do NOT call this for local files, folders, or paths. Use read_folder instead for anything local."].join(" "),parameters:{type:"object",properties:{url:{type:"string",description:"Target documentation URL"}},required:["url"],additionalProperties:false}}},{type:"function",function:{name:"write_file",description:["Create or overwrite a file with the given content.","Use this to create config files, fix generated code, or add missing files."].join(" "),parameters:{type:"object",properties:{path:{type:"string",description:`Target file path. Relative paths are resolved from ${G.workDir}.`},content:{type:"string",description:"Full file content to write."}},required:["path","content"],additionalProperties:false}}},{type:"function",function:{name:"search_files",description:["Search for a pattern in files within a directory and return matching lines.","Use this like grep to quickly locate endpoints, auth keys, or code symbols."].join(" "),parameters:{type:"object",properties:{pattern:{type:"string",description:"Pattern to search (case-insensitive regex)."},path:{type:"string",description:"Optional root directory. Defaults to last generated directory or current project."},glob:{type:"string",description:"Optional file glob, for example *.ts, *.md. Defaults to *."}},required:["pattern"],additionalProperties:false}}},{type:"function",function:{name:"read_pdf",description:"Extract text content from a PDF file, useful for PDF API documentation.",parameters:{type:"object",properties:{path:{type:"string",description:`PDF file path. Relative paths are resolved from ${G.workDir}.`}},required:["path"],additionalProperties:false}}},{type:"function",function:{name:"http_request",description:["Make an HTTP request to probe or test an API endpoint.","Use this to test endpoint behavior or check if a URL returns an OpenAPI spec."].join(" "),parameters:{type:"object",properties:{url:{type:"string",description:"Target URL."},method:{type:"string",description:"HTTP method. Defaults to GET."},headers:{type:"object",description:"Optional request headers.",additionalProperties:{type:"string"}},body:{type:"string",description:"Optional request body as string."},timeout_ms:{type:"number",description:"Request timeout in milliseconds. Defaults to 10000."}},required:["url"],additionalProperties:false}}},{type:"function",function:{name:"crawl_docs",description:["Crawl multiple pages of API documentation starting from a URL.","Follows same-domain links, optionally filtered by a link regex pattern."].join(" "),parameters:{type:"object",properties:{start_url:{type:"string",description:"Starting documentation URL."},max_pages:{type:"number",description:"Maximum pages to crawl. Default 10, max 30."},link_pattern:{type:"string",description:"Optional regex to filter links to follow, for example /docs/ or /api/."}},required:["start_url"],additionalProperties:false}}},{type:"function",function:{name:"discover_docs",description:["Search the web for official API documentation by product/service name.","Use when the user does not provide a docs URL."].join(" "),parameters:{type:"object",properties:{query:{type:"string",description:"Search query, for example Stripe API documentation."},max_results:{type:"number",description:"Maximum number of results to return. Defaults to 5."}},required:["query"],additionalProperties:false}}},{type:"function",function:{name:"sga_search",description:"Search the web using the SGA search engine. Supports Chinese search, WeChat articles, and enriched full-text extraction. Use this when you need to find information, research APIs, or look up documentation.",parameters:{type:"object",properties:{q:{type:"string",description:"Search query"},preset:{type:"string",enum:["chinese","wechat","general"],description:"Search preset. Defaults to chinese."},limit:{type:"number",description:"Result limit. Defaults to 5, max 50."},sort:{type:"string",enum:["time","relevance"],description:"Sort mode. Defaults to time."},depth:{type:"string",enum:["basic","enriched"],description:"Result depth. Defaults to basic."}},required:["q"],additionalProperties:false}}},{type:"function",function:{name:"parse_openapi",description:"Parse an OpenAPI/Swagger specification from a URL or file path. Extracts endpoints, parameters, auth schemes, and data models in a structured format.",parameters:{type:"object",properties:{source:{type:"string",description:"URL (http/https) or local file path to OpenAPI JSON/YAML"},max_endpoints:{type:"number",description:"Maximum endpoints returned. Defaults to 100."}},required:["source"],additionalProperties:false}}},{type:"function",function:{name:"run_command",description:["Execute a shell command in the project directory.","Use this to install dependencies (npm install), compile code (npx tsc),","run tests (npx jest), check project structure (ls, cat), fix issues, etc.","You can run ANY command needed to set up, build, test, or debug the generated server.","Always check the output and fix problems iteratively, just like a human developer would."].join(" "),parameters:{type:"object",properties:{command:{type:"string",description:'Shell command to execute, e.g. "npm install jest --save-dev" or "npx tsc --noEmit"'},cwd:{type:"string",description:`Working directory. Defaults to last generated project or ${G.workDir}.`}},required:["command"],additionalProperties:false}}},{type:"function",function:{name:"generate_mcp",description:["Generate MCP server code from analyzed source content.","Use after enough documentation context is collected and the user confirms generation."].join(" "),parameters:{type:"object",properties:{source:{type:"string",description:"Source folder path or URL"},output_dir:{type:"string",description:"Optional output directory for generated files"}},required:["source"],additionalProperties:false}}},{type:"function",function:{name:"run_tests",description:["Run tests against a generated MCP server project.","Use this after generation or when the user asks to verify quality."].join(" "),parameters:{type:"object",properties:{dir:{type:"string",description:"Directory containing generated server code"}},required:["dir"],additionalProperties:false}}},{type:"function",function:{name:"test_integration",description:["Build the generated MCP server, start it as a subprocess, then perform real MCP tools/list and tools/call connectivity checks.","Use this after generate_mcp and run_tests.","Requires base_url; auth_env is optional key/value credentials.","This test validates every discovered tool. Publish only after all tools pass."].join(" "),parameters:{type:"object",properties:{dir:{type:"string",description:"Path to generated MCP server. Defaults to last generated directory."},base_url:{type:"string",description:"Real upstream API base URL, for example https://api.myservice.com"},auth_env:{type:"object",description:'Optional credentials as env vars, for example {"MY_API_KEY":"sk-xxx"}',additionalProperties:{type:"string"}}},required:["base_url"],additionalProperties:false}}},{type:"function",function:{name:"publish_mcp",description:["Publish generated MCP package to SGA Market using manifest.json in the target directory.","Use after successful integration testing.","Can accept market_url/token overrides; otherwise defaults to local login config."].join(" "),parameters:{type:"object",properties:{dir:{type:"string",description:"Path containing generated manifest.json. Defaults to last generated directory."},market_url:{type:"string",description:"Optional market URL override."},token:{type:"string",description:"Optional auth token override."}},required:[],additionalProperties:false}}},{type:"function",function:{name:"show_history",description:"Show previous MCP SERVER GENERATION RUNS (not chat history). Use this to see: which MCPs were generated, their status (pass/fail), tool counts. Do NOT use this to find chat context — your conversation history is already in your message context.",parameters:{type:"object",properties:{},additionalProperties:false}}},{type:"function",function:{name:"record_learning",description:["Record a lesson learned from fixing a bug or error.","ALWAYS call this after completing an error→fix→verify cycle:"," - run_command failed → you diagnosed the cause → write_file fixed it → run_command passed","The pattern gets saved to .mcp-claw/patterns.md and loaded in future sessions.","This is how the agent evolves and avoids repeating the same mistakes."].join(" "),parameters:{type:"object",properties:{title:{type:"string",description:'Short title of the problem, < 60 chars. e.g. "Missing zod dependency in generated project"'},problem:{type:"string",description:"What the error was. Include error message or code if helpful."},fix:{type:"string",description:"What fixed it. Be specific: which file was changed, what command was run."},tags:{type:"array",items:{type:"string"},description:'Optional tags e.g. ["typescript", "windows", "pnpm", "missing-dep"]'}},required:["title","problem","fix"],additionalProperties:false}}}]}},28123:function(__unused_webpack_module,exports,__nccwpck_require__){"use strict";var __importDefault=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(exports,"__esModule",{value:true});exports.createCli=createCli;exports.main=main;const commander_1=__nccwpck_require__(61414);const chalk_1=__importDefault(__nccwpck_require__(39559));const chat_config_1=__nccwpck_require__(66015);const chat_loop_1=__nccwpck_require__(48347);const config_command_1=__nccwpck_require__(77855);const generate_command_1=__nccwpck_require__(72966);const hub_command_1=__nccwpck_require__(15372);const install_command_1=__nccwpck_require__(98160);const login_command_1=__nccwpck_require__(81198);const logout_command_1=__nccwpck_require__(44731);const memory_command_1=__nccwpck_require__(55418);const publish_command_1=__nccwpck_require__(26120);const run_command_1=__nccwpck_require__(60390);const test_command_1=__nccwpck_require__(28713);function createCli(){const G=new commander_1.Command;G.name("mcp-claw").description("AI-powered MCP server generator").version("0.2.0");G.command("run").description("Run MCP Claw agent loop").requiredOption("--root <path>","Workspace root path").option("--report-to <url>","Backend URL for progress reporting").action((async G=>{await(0,run_command_1.runCommand)({root:G.root,logger:console,reportTo:G.reportTo})}));G.command("generate <source>").description("Generate an MCP server from a folder or URL").option("-o, --output <dir>").option("--publish").action((async(G,K)=>{await(0,generate_command_1.generateCommand)({source:G,output:K.output,publish:K.publish,logger:console})}));(0,config_command_1.registerConfigCommand)(G);(0,login_command_1.registerLoginCommand)(G);(0,logout_command_1.registerLogoutCommand)(G);(0,memory_command_1.registerMemoryCommand)(G);(0,publish_command_1.registerPublishCommand)(G);(0,install_command_1.registerInstallCommand)(G);(0,hub_command_1.registerHubCommand)(G);(0,test_command_1.registerTestCommand)(G);G.action((async()=>{const G=(0,chat_config_1.loadChatConfig)();await(0,chat_loop_1.startChatLoop)(G)}));return G}async function main(G=process.argv){const K=createCli();await K.parseAsync(G)}if(require.main===require.cache[eval("__filename")]){main().catch((G=>{const K=G instanceof Error?G.message:String(G);console.error(chalk_1.default.red(K));process.exitCode=1}))}},77855:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.showConfig=showConfig;K.setConfig=setConfig;K.setSgaConfig=setSgaConfig;K.testConfig=testConfig;K.registerConfigCommand=registerConfigCommand;const We=je(73024);const Xe=je(76760);const rt=ze(je(39559));const at=je(18296);const ft=je(49904);const mt=["google/gemini-3-flash-preview","minimax/minimax-m2.5"];const vt=new Set(mt);const yt="https://openrouter.ai/api/v1";function findEnvPath(G,K=4){let je=(0,Xe.resolve)(G);for(let G=0;G<=K;G+=1){const G=(0,Xe.resolve)(je,".env");if((0,We.existsSync)(G)){return G}const K=(0,Xe.dirname)(je);if(K===je){break}je=K}throw new Error("Unable to locate .env file from current directory (searched up to 4 levels).")}function parseEnvState(G){const K=(0,We.readFileSync)(G,"utf8");const je=K.split(/\r?\n/);const ze=new Map;for(const G of je){const K=G.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);if(!K){continue}ze.set(K[1],K[2])}return{path:G,lines:je,values:ze}}function writeEnvState(G){(0,We.writeFileSync)(G.path,`${G.lines.join("\n")}\n`,"utf8")}function upsertEnvKey(G,K,je){const ze=new RegExp(`^${K}=.*$`);const We=`${K}=${je}`;const Xe=G.lines.findIndex((G=>ze.test(G)));if(Xe>=0){G.lines[Xe]=We}else{G.lines.push(We)}G.values.set(K,je)}function currentConfig(G){return{parserModel:G.values.get("LLM_PARSER_MODEL")??"",coderModel:G.values.get("LLM_CODER_MODEL")??"",agentModel:G.values.get("LLM_AGENT_MODEL")??"",apiKey:G.values.get("OPENROUTER_API_KEY")??"",baseUrl:G.values.get("OPENROUTER_BASE_URL")??yt}}function validateModel(G,K){if(!vt.has(G)){throw new Error(`Invalid ${K} model: ${G}\nAllowed models:\n- ${mt.join("\n- ")}`)}}function parseConfigValue(G){const K=G.trim();const je=K.toLowerCase();if(je==="true"){return true}if(je==="false"){return false}if(/^-?\d+(\.\d+)?$/.test(K)){return Number(K)}return G}function showConfig(G=console,K=process.cwd()){const je=findEnvPath(K);const ze=parseEnvState(je);const We=currentConfig(ze);const Xe=[["OPENROUTER_BASE_URL",We.baseUrl],["LLM_PARSER_MODEL",We.parserModel],["LLM_CODER_MODEL",We.coderModel],["LLM_AGENT_MODEL",We.agentModel],["OPENROUTER_API_KEY",We.apiKey]];const ft=Math.max(...Xe.map((([G])=>G.length)));G.log(rt.default.gray(`.env: ${je}`));for(const[K,je]of Xe){const ze=je.length>0?je:"(empty)";G.log(`${rt.default.cyan(K.padEnd(ft))} = ${rt.default.green(ze)}`)}const mt=new at.SgaConfig;const vt=mt.getAll();G.log("");G.log(rt.default.gray(`~/.sga/config.yaml: ${at.DEFAULT_CONFIG_PATH}`));if(Object.keys(vt).length===0){G.log(rt.default.yellow("(empty)"))}else{G.log(rt.default.green(JSON.stringify(vt,null,2)))}}function setConfig(G,K=console,je=process.cwd()){const ze=findEnvPath(je);const We=parseEnvState(ze);const Xe=[];if(typeof G.parser==="string"){validateModel(G.parser,"--parser");Xe.push(["LLM_PARSER_MODEL",G.parser])}if(typeof G.coder==="string"){validateModel(G.coder,"--coder");Xe.push(["LLM_CODER_MODEL",G.coder])}if(typeof G.agent==="string"){validateModel(G.agent,"--agent");Xe.push(["LLM_AGENT_MODEL",G.agent])}if(typeof G.key==="string"){Xe.push(["OPENROUTER_API_KEY",G.key])}if(Xe.length===0){throw new Error("No config field specified. Use --parser, --coder, --agent, or --key.")}for(const[G,K]of Xe){upsertEnvKey(We,G,K)}writeEnvState(We);K.log(rt.default.green(`Updated ${Xe.length} setting(s) in ${ze}`));const ft=new at.SgaConfig;if(typeof G.key==="string"){ft.set("openrouter.apiKey",G.key)}if(typeof G.parser==="string"){ft.set("model.parser",G.parser)}if(typeof G.coder==="string"){ft.set("model.coder",G.coder)}if(typeof G.agent==="string"){ft.set("model.agent",G.agent)}K.log(rt.default.green(`Synced to ${at.DEFAULT_CONFIG_PATH}`))}function setSgaConfig(G,K,je=console){const ze=new at.SgaConfig;ze.set(G,K);je.log(rt.default.green(`Updated ${G} in ${at.DEFAULT_CONFIG_PATH}`))}async function testConfig(G=console,K=process.cwd()){const je=findEnvPath(K);const ze=parseEnvState(je);const We=currentConfig(ze);const Xe=We.parserModel||"anthropic/claude-haiku-4.5";const at=We.apiKey;const mt=We.baseUrl||yt;if(!at){G.error(rt.default.red("Connection failed: OPENROUTER_API_KEY is empty"));process.exitCode=1;return}const vt=new ft.OpenRouterProvider("openrouter-test",Xe,at,mt);try{await vt.complete("Reply with exactly: pong");G.log(rt.default.green(`OpenRouter reachable, model: ${Xe}`))}catch(K){const je=K instanceof Error?K.message:String(K);G.error(rt.default.red(`Connection failed: ${je}`));process.exitCode=1}}function registerConfigCommand(G){const K=G.command("config").description("Show and update LLM/OpenRouter configuration");K.command("show").description("Show settings from .env and ~/.sga/config.yaml").action((()=>{showConfig(console)}));K.command("set <key> <value>").description("Set a key in ~/.sga/config.yaml (supports dot notation)").action(((G,K)=>{setSgaConfig(G,parseConfigValue(K),console)}));K.command("set-env").description("Update one or more model settings in .env").option("--parser <model>","Set LLM_PARSER_MODEL").option("--coder <model>","Set LLM_CODER_MODEL").option("--agent <model>","Set LLM_AGENT_MODEL").option("--key <apiKey>","Set OPENROUTER_API_KEY").action((G=>{setConfig(G,console)}));K.command("test").description("Test OpenRouter connectivity").action((async()=>{await testConfig(console)}))}},72966:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.isUrl=isUrl;K.deriveProjectName=deriveProjectName;K.generateCommand=generateCommand;const ze=je(73024);const We=je(76760);const Xe=je(60390);function isUrl(G){return/^https?:\/\//i.test(G)}function deriveProjectName(G){let K;if(isUrl(G)){try{const je=new URL(G);const ze=je.hostname.replace(/^www\./,"");const We=je.pathname.split("/").filter(Boolean)[0]??"";K=We?`${ze}-${We}`:ze}catch{K="api"}}else{K=(0,We.basename)(G,(0,We.extname)(G))}const je=K.replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-+|-+$/g,"").toLowerCase();return`mcp-server-${je||"generated"}`}async function generateCommand(G){const K=G.logger??console;const je=G.source;let rt;let at;let ft;if(isUrl(je)){const K=deriveProjectName(je);rt=G.output??(0,We.resolve)(process.cwd(),K);at=[je]}else{const K=(0,We.resolve)(je);if(!(0,ze.existsSync)(K)){throw new Error(`Source path not found: ${K}`)}if((0,ze.statSync)(K).isFile()){const je=deriveProjectName(K);rt=G.output??(0,We.resolve)((0,We.dirname)(K),je);ft=[(0,ze.readFileSync)(K,"utf8")];at=[]}else{rt=G.output??K;at=[]}}await(0,Xe.runCommand)({root:rt,urls:at,rawDocs:ft,logger:K,dryRun:G.dryRun});if(G.publish){K.log("Publish requested. Use `sga publish` after generation completes.")}return{root:rt}}},15372:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.hubConnectCommand=hubConnectCommand;K.hubStatusCommand=hubStatusCommand;K.registerHubCommand=registerHubCommand;const We=je(31421);const Xe=je(73024);const rt=ze(je(76760));const at=ze(je(39559));const ft=je(18296);const mt="http://localhost:3000/api/mcp";function isRecord(G){return Boolean(G)&&typeof G==="object"&&!Array.isArray(G)}function readConfiguredHubUrl(){const G=new ft.SgaConfig;const K=G.get("hub.url");if(typeof K!=="string"){return null}const je=K.trim();return je.length>0?je:null}function normalizeHubUrl(G){const K=new URL(G);const je=K.pathname.replace(/\/+$/,"");if(je===""||je==="/"){K.pathname="/api/mcp"}else if(je.endsWith("/api/mcp/connect")){K.pathname=je.slice(0,-"/connect".length)}else if(je.endsWith("/api/mcp")){K.pathname=je}else{K.pathname=`${je}/api/mcp`}K.search="";K.hash="";return K.toString().replace(/\/$/,"")}function getConnectEndpoint(G){const K=new URL(G);K.pathname=`${K.pathname.replace(/\/+$/,"")}/connect`;K.search="";K.hash="";return K.toString()}async function fetchConnectConfig(G){const K=await fetch(getConnectEndpoint(G),{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!K.ok){throw new Error(`Hub responded with HTTP ${K.status}`)}const je=await K.json();const ze=isRecord(je)&&"data"in je?je.data:je;if(!isRecord(ze)||typeof ze.hubName!=="string"||typeof ze.hubSseUrl!=="string"||typeof ze.toolCount!=="number"||!isRecord(ze.clients)){throw new Error("Invalid Hub connect response")}return ze}function saveHubUrl(G){const K=new ft.SgaConfig;K.set("hub.url",G)}function mergeCursorConfig(G,K){const je=isRecord(G)?G:{};const ze={...je,...K};const We=isRecord(je.mcpServers)?je.mcpServers:{};const Xe=isRecord(K.mcpServers)?K.mcpServers:{};ze.mcpServers={...We,...Xe};return ze}function autoConfigureCursor(G){const K=rt.default.resolve(process.cwd(),".cursor","mcp.json");(0,Xe.mkdirSync)(rt.default.dirname(K),{recursive:true});let je={};if((0,Xe.existsSync)(K)){try{je=JSON.parse((0,Xe.readFileSync)(K,"utf8"))}catch{je={}}}const ze=mergeCursorConfig(je,G.clients.cursor.config);(0,Xe.writeFileSync)(K,`${JSON.stringify(ze,null,2)}\n`,"utf8");return K}function printConnectSummary(G){console.log(at.default.bold("\nHub Connect Configuration"));console.log(`${at.default.cyan("Hub")}: ${G.hubName}`);console.log(`${at.default.cyan("SSE URL")}: ${G.hubSseUrl}`);console.log(`${at.default.cyan("Tool Count")}: ${G.toolCount}`);console.log(at.default.bold("\nClient Commands"));console.log(`${at.default.green("Claude Code")}: ${G.clients.claudeCode.command}`);console.log(`${at.default.green("mcp-claw")}: ${G.clients.mcpClaw.command}`);console.log(`${at.default.green("Generic SSE")}: ${G.clients.genericSse.url}`);console.log(at.default.bold("\nClient Config Paths"));console.log(`${at.default.green("Claude Desktop")}: ${G.clients.claudeDesktop.filePath}`);console.log(`${at.default.green("Cursor")}: ${G.clients.cursor.filePath}`);console.log(`${at.default.green("Windsurf")}: ${G.clients.windsurf.filePath}`);console.log(`${at.default.green("VS Code (Copilot)")}: ${G.clients.vscode.filePath}`);console.log(at.default.bold("\nOther Integrations"));console.log(`${at.default.green("Augment")}: ${G.clients.augment.instruction}`);console.log(`${at.default.green("Dify")}: ${G.clients.dify.instruction}`);console.log(`${at.default.green("HiAgent")}: ${G.clients.hiagent.instruction}`);console.log("")}function resolveTargetHubUrl(G){const K=readConfiguredHubUrl();const je=G?.trim()||K||mt;return normalizeHubUrl(je)}async function hubConnectCommand(G,K={}){const je=resolveTargetHubUrl(G);const ze=await fetchConnectConfig(je);const Xe=normalizeHubUrl(ze.hubSseUrl||je);saveHubUrl(Xe);console.log(at.default.green(`Connected to Hub: ${Xe}`));printConnectSummary(ze);if(K.claude){try{console.log(at.default.dim(`Running: ${ze.clients.claudeCode.command}`));(0,We.execSync)(ze.clients.claudeCode.command,{stdio:"inherit"});console.log(at.default.green("Claude Code configured successfully."))}catch(G){const K=G instanceof Error?G.message:String(G);console.warn(at.default.yellow(`Failed to configure Claude Code automatically: ${K}`))}}if(K.cursor){try{const G=autoConfigureCursor(ze);console.log(at.default.green(`Cursor config written to ${G}`))}catch(G){const K=G instanceof Error?G.message:String(G);console.warn(at.default.yellow(`Failed to write Cursor config: ${K}`))}}}async function hubStatusCommand(){const G=readConfiguredHubUrl();if(!G){console.log(at.default.yellow("Hub is not configured. Run: mcp-claw hub connect"));process.exitCode=1;return}const K=normalizeHubUrl(G);try{const G=await fetchConnectConfig(K);console.log(at.default.green("Hub status: connected"));console.log(`${at.default.cyan("URL")}: ${normalizeHubUrl(G.hubSseUrl||K)}`);console.log(`${at.default.cyan("Hub")}: ${G.hubName}`);console.log(`${at.default.cyan("Tool Count")}: ${G.toolCount}`)}catch(G){const K=G instanceof Error?G.message:String(G);console.log(at.default.red("Hub status: disconnected"));console.log(at.default.red(K));process.exitCode=1}}function registerHubCommand(G){const K=G.command("hub").description("Connect and manage MCP Hub settings");K.command("connect [url]").description("Connect to an MCP Hub and save hub.url in config").option("--claude","Automatically run Claude Code setup command").option("--cursor","Automatically write .cursor/mcp.json").action((async(G,K)=>{await hubConnectCommand(G,K)}));K.command("status").description("Check Hub connectivity using configured hub.url").action((async()=>{await hubStatusCommand()}))}},98160:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.installCommand=installCommand;K.registerInstallCommand=registerInstallCommand;const ze=je(26848);const We=je(18296);const Xe=je(72966);const rt=je(26120);function looksLikeFilePath(G){return/[\\/]/.test(G)||/\.[A-Za-z0-9]+$/.test(G)}function toSearchEndpoint(G){const K=new URL(G);return`${K.protocol}//${K.host}/v1/agent/search`}async function ask(G){const K=(0,ze.createInterface)({input:process.stdin,output:process.stdout});try{return(await K.question(G)).trim()}finally{K.close()}}async function discoverSourceByName(G){const K=new We.SgaConfig;const je=K.get("search.url");const ze=typeof je==="string"&&je.trim().length>0?je.trim():process.env.SEARCH_ENGINE_URL?.trim();if(!ze){return null}let Xe;try{Xe=toSearchEndpoint(ze)}catch{return null}const rt=new URL(Xe);rt.searchParams.set("q",`${G} API documentation`);rt.searchParams.set("preset","general");rt.searchParams.set("limit","3");const at=await fetch(rt.toString(),{method:"GET"});if(!at.ok){return null}const ft=await at.json();const mt=ft.results?.find((G=>typeof G.url==="string"&&G.url.length>0))?.url;return typeof mt==="string"?mt:null}async function installCommand(G){const K=G.trim();let je;if((0,Xe.isUrl)(K)){je=K}else if(looksLikeFilePath(K)){je=K}else{const G=await discoverSourceByName(K).catch((()=>null));if(G){je=G;console.log(`Auto-discovered docs URL: ${je}`)}else{const G=await ask("Could not auto-discover docs. Please provide the API docs URL: ");if(!G){throw new Error("Install aborted: no docs URL provided.")}je=G}}const ze=await(0,Xe.generateCommand)({source:je,logger:console});console.log(`Generation completed. Output directory: ${ze.root}`);const We=await ask("Publish to MCP Market? (y/N) ");if(/^y(es)?$/i.test(We)){await(0,rt.publishCommand)({},ze.root)}}function registerInstallCommand(G){G.command("install <name>").description("Generate an MCP server from an API name, URL, or local file").action((async G=>{await installCommand(G)}))}},81198:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.runLogin=runLogin;K.registerLoginCommand=registerLoginCommand;const We=ze(je(80481));const Xe=ze(je(39559));const rt=je(59265);function normalizeMarketUrl(G){return G.replace(/\/+$/,"")}async function verifyToken(G,K){const je=`${normalizeMarketUrl(G)}/auth/verify`;const ze=await fetch(je,{method:"GET",headers:{Authorization:`Bearer ${K}`}});if(!ze.ok){const G=await ze.text();throw new Error(`Token verification failed (${ze.status}): ${G}`)}}function promptHiddenToken(G="Token: "){return new Promise((K=>{const je=We.default.createInterface({input:process.stdin,output:process.stdout,terminal:true});const ze=je;ze.stdoutMuted=false;ze._writeToOutput=G=>{if(ze.stdoutMuted){process.stdout.write("*");return}process.stdout.write(G)};ze.stdoutMuted=false;je.question(G,(G=>{je.close();process.stdout.write("\n");K(G.trim())}));ze.stdoutMuted=true}))}async function runLogin(G){const K=(0,rt.getMarketUrl)();const je=G.token?.trim()||await promptHiddenToken();if(!je){console.error(Xe.default.red("Token is required."));process.exitCode=1;return}try{await verifyToken(K,je);(0,rt.saveToken)(je,K);console.log(Xe.default.green("登录成功"))}catch(G){const K=G instanceof Error?G.message:String(G);console.error(Xe.default.red(K));process.exitCode=1}}function registerLoginCommand(G){G.command("login").description("Login to MCP Market").option("--token <token>","Access token").action((async G=>{await runLogin(G)}))}},44731:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.runLogout=runLogout;K.registerLogoutCommand=registerLogoutCommand;const We=ze(je(39559));const Xe=je(59265);function runLogout(){(0,Xe.clearToken)();console.log(We.default.green("已退出登录"))}function registerLogoutCommand(G){G.command("logout").description("Logout from MCP Market").action((()=>{runLogout()}))}},55418:function(G,K,je){"use strict";var ze=this&&this.__createBinding||(Object.create?function(G,K,je,ze){if(ze===undefined)ze=je;var We=Object.getOwnPropertyDescriptor(K,je);if(!We||("get"in We?!K.__esModule:We.writable||We.configurable)){We={enumerable:true,get:function(){return K[je]}}}Object.defineProperty(G,ze,We)}:function(G,K,je,ze){if(ze===undefined)ze=je;G[ze]=K[je]});var We=this&&this.__setModuleDefault||(Object.create?function(G,K){Object.defineProperty(G,"default",{enumerable:true,value:K})}:function(G,K){G["default"]=K});var Xe=this&&this.__importStar||function(){var ownKeys=function(G){ownKeys=Object.getOwnPropertyNames||function(G){var K=[];for(var je in G)if(Object.prototype.hasOwnProperty.call(G,je))K[K.length]=je;return K};return ownKeys(G)};return function(G){if(G&&G.__esModule)return G;var K={};if(G!=null)for(var je=ownKeys(G),Xe=0;Xe<je.length;Xe++)if(je[Xe]!=="default")ze(K,G,je[Xe]);We(K,G);return K}}();var rt=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.clearSessions=clearSessions;K.registerMemoryCommand=registerMemoryCommand;const at=Xe(je(73024));const ft=je(76760);const mt=rt(je(39559));const vt=je(29441);const yt=je(64109);function shortDate(G,K){const je=Number.isNaN(Date.parse(G))?K:new Date(G);const ze=je.getFullYear();const We=String(je.getMonth()+1).padStart(2,"0");const Xe=String(je.getDate()).padStart(2,"0");const rt=String(je.getHours()).padStart(2,"0");const at=String(je.getMinutes()).padStart(2,"0");return`${ze}-${We}-${Xe} ${rt}:${at}`}function parseSessionFile(G,K,je){const ze=at.readFileSync(G,"utf8");const We=K.replace(/^#\s*/,"").trim()||"(unknown)";const Xe=ze.match(/- 状态:\s*(✅ success|❌ failed)/);const rt=ze.match(/- 工具数:\s*(\d+)/);const ft=ze.match(/- 时间:\s*(.+)/);return{source:We,status:Xe?.[1]==="❌ failed"?"failed":"success",toolCount:Number(rt?.[1]??"0"),time:shortDate(ft?.[1]??"",je)}}function statusLabel(G){return G==="success"?mt.default.green("✅ success"):mt.default.red("❌ failed")}function showLastRun(G,K){const je=G.ir?.toolNames.join(", ")||"(none)";const ze=G.filesWritten.join(", ")||"(none)";K.log("Last run in this project (.sga/last-run.json):");K.log(` Source: ${G.source}`);K.log(` Status: ${statusLabel(G.status)}`);K.log(` Tools: ${je}`);K.log(` Files: ${ze}`);K.log(` Time: ${G.finishedAt} (${G.durationMs}ms)`)}function clearSessions(){const G=(0,yt.resolveGlobalSessionsDir)();at.mkdirSync(G,{recursive:true});const K=at.readdirSync(G).filter((G=>G.endsWith(".md")));for(const je of K){at.unlinkSync((0,ft.join)(G,je))}return K.length}function registerMemoryCommand(G){const K=G.command("memory").description("Inspect and manage SGA memory");K.command("show").description("Show recent sessions").action((()=>{const G=new vt.SessionReader;const K=G.listSessions(10);console.log(mt.default.cyan("Recent sessions (10):"));if(K.length===0){console.log(mt.default.gray(" (none)"));return}K.forEach(((G,K)=>{const je=parseSessionFile(G.file,G.preview,G.mtime);const ze=je.source.length>30?`${je.source.slice(0,27)}...`:je.source;console.log(` ${K+1}. ${ze.padEnd(30)} [${statusLabel(je.status)}] ${je.toolCount} tools ${je.time}`)}))}));K.command("last").description("Show last run for this project").action((()=>{const G=(new vt.SessionReader).lastRun();if(!G){console.log(mt.default.yellow("No run history found in this project."));return}showLastRun(G,console)}));K.command("clear").description("Delete all global session files").action((()=>{const G=clearSessions();console.log(mt.default.green(`Cleared ${G} session file(s).`))}))}},26120:function(G,K,je){"use strict";var ze=this&&this.__createBinding||(Object.create?function(G,K,je,ze){if(ze===undefined)ze=je;var We=Object.getOwnPropertyDescriptor(K,je);if(!We||("get"in We?!K.__esModule:We.writable||We.configurable)){We={enumerable:true,get:function(){return K[je]}}}Object.defineProperty(G,ze,We)}:function(G,K,je,ze){if(ze===undefined)ze=je;G[ze]=K[je]});var We=this&&this.__setModuleDefault||(Object.create?function(G,K){Object.defineProperty(G,"default",{enumerable:true,value:K})}:function(G,K){G["default"]=K});var Xe=this&&this.__importStar||function(){var ownKeys=function(G){ownKeys=Object.getOwnPropertyNames||function(G){var K=[];for(var je in G)if(Object.prototype.hasOwnProperty.call(G,je))K[K.length]=je;return K};return ownKeys(G)};return function(G){if(G&&G.__esModule)return G;var K={};if(G!=null)for(var je=ownKeys(G),Xe=0;Xe<je.length;Xe++)if(je[Xe]!=="default")ze(K,G,je[Xe]);We(K,G);return K}}();var rt=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.publishCommand=publishCommand;K.registerPublishCommand=registerPublishCommand;const at=je(77598);const ft=je(73024);const mt=rt(je(76760));const vt=je(57075);const yt=rt(je(39559));const wt=je(66015);const lr=je(49904);const Er=je(59265);function normalizeBaseUrl(G){return G.replace(/\/+$/,"")}function slugify(G){const K=G.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return K||"generated-package"}async function createTarball(G){const K=await Promise.resolve().then((()=>Xe(je(29200))));return new Promise(((je,ze)=>{const We=[];const Xe=new vt.Writable({write(G,K,je){We.push(Buffer.isBuffer(G)?G:Buffer.from(G));je()}});const rt=K.default("tar",{gzip:true});rt.on("error",ze);Xe.on("finish",(()=>je(Buffer.concat(We))));rt.pipe(Xe);rt.directory(G,false);rt.finalize().catch(ze)}))}function readManifest(G=process.cwd()){const K=mt.default.join(G,"manifest.json");if(!(0,ft.existsSync)(K)){throw new Error(`manifest.json not found at ${K}`)}const je=(0,ft.readFileSync)(K,"utf8");const ze=JSON.parse(je);if(!ze||typeof ze!=="object"){throw new Error("manifest.json must contain a JSON object")}const We=ze;const Xe=Array.isArray(We.tools)?We.tools.map((G=>{if(!G||typeof G!=="object"){return null}const K=G;if(typeof K.name!=="string"||K.name.trim().length===0){return null}return{name:K.name,...typeof K.description==="string"?{description:K.description}:{},...K.inputSchema&&typeof K.inputSchema==="object"?{inputSchema:K.inputSchema}:{}}})).filter((G=>G!==null)):undefined;return{name:typeof We.name==="string"?We.name:undefined,version:typeof We.version==="string"?We.version:undefined,category:typeof We.category==="string"?We.category:undefined,description:typeof We.description==="string"?We.description:undefined,toolsCount:typeof We.toolsCount==="number"?We.toolsCount:undefined,tools:Xe,credentials:Array.isArray(We.credentials)?We.credentials:undefined}}function resolvePublishPayload(G,K){const je=K.name??G.name;const ze=K.version??G.version;const We=K.category??G.category??"other";const Xe=K.description??G.description??"";if(!je||!ze){throw new Error("name and version are required (from options or manifest.json)")}return{name:je,version:ze,category:We,description:Xe,toolsCount:G.toolsCount,tools:G.tools,credentials:G.credentials}}function estimateToolsCount(G){if(!(0,ft.existsSync)(G)){return 0}const K=new Set([".ts",".js",".py"]);const je=[/server\.tool\(/gi,/tools\.add\(/gi,/addTool\(/gi,/@tool/gi,/def\s+tool_/gi];const ze=[G];let We=0;while(ze.length>0){const G=ze.pop();if(!G){continue}let Xe;try{Xe=(0,ft.readdirSync)(G,{withFileTypes:true,encoding:"utf8"})}catch{continue}for(const rt of Xe){const Xe=mt.default.join(G,rt.name);if(rt.isDirectory()){ze.push(Xe);continue}if(!rt.isFile()){continue}const at=mt.default.extname(rt.name).toLowerCase();if(!K.has(at)){continue}try{const G=(0,ft.readFileSync)(Xe,"utf8");for(const K of je){const je=G.match(K);if(je){We+=je.length}}}catch{continue}}}return We}function extractJsonObject(G){const K=G.indexOf("{");const je=G.lastIndexOf("}");if(K===-1||je===-1||je<=K){return null}try{const ze=JSON.parse(G.slice(K,je+1));if(!ze||typeof ze!=="object"||Array.isArray(ze)){return null}return ze}catch{return null}}async function autoEnhanceManifest(G,K){const je=(0,wt.loadChatConfig)(G);if(!je.apiKey){return{}}const ze=mt.default.join(G,"README.md");const We=(0,ft.existsSync)(ze)?(0,ft.readFileSync)(ze,"utf8").slice(0,3e3):"";const Xe=mt.default.join(G,"src");const rt=estimateToolsCount(Xe);const at=new lr.OpenRouterProvider("publish-enhance",je.model,je.apiKey,je.baseUrl);const vt=["You are enhancing MCP package metadata for publishing.","Return JSON only with shape:",'{ "description": string, "category": string, "toolsCount": number }',"category must be one of ['productivity', 'developer-tools', 'data', 'communication', 'ai', 'security', 'other'].","",`Package name: ${K.name}`,`Version: ${K.version}`,`Current category: ${K.category}`,`Current description: ${K.description||"(empty)"}`,`Estimated tools count from source scan: ${rt}`,`Credentials fields count: ${Array.isArray(K.credentials)?K.credentials.length:0}`,"","README excerpt (may be empty):",We||"(empty)","","Rules:","- description should be concise, practical, and at least 20 characters.","- toolsCount should be a non-negative integer.",'- If uncertain, choose category "other".'].join("\n");const yt=await at.complete(vt);const Er=extractJsonObject(yt);if(!Er){return{}}const Rr=typeof Er.description==="string"&&Er.description.trim().length>0?Er.description.trim():undefined;const jr=typeof Er.category==="string"&&Er.category.trim().length>0?Er.category.trim():undefined;const zr=typeof Er.toolsCount==="number"?Er.toolsCount:typeof Er.toolsCount==="string"?Number(Er.toolsCount):Number.NaN;const fi=Number.isFinite(zr)&&zr>=0?Math.floor(zr):rt>0?rt:undefined;return{...Rr?{description:Rr}:{},...jr?{category:jr}:{},...typeof fi==="number"?{toolsCount:fi}:{}}}async function publishCommand(G,K=process.cwd()){const je=(0,Er.getToken)();if(!je){throw new Error("Not logged in. Run `mcp-claw login` first.")}const ze=normalizeBaseUrl((0,Er.getMarketUrl)());const We=readManifest(K);const Xe=resolvePublishPayload(We,G);const rt=G.enhance!==false;if(rt&&Xe.description.trim().length<20){try{const je=await autoEnhanceManifest(K,Xe);let ze=false;if(!G.description&&je.description){Xe.description=je.description;ze=true}if(!G.category&&je.category){Xe.category=je.category;ze=true}if(typeof Xe.toolsCount!=="number"&&typeof je.toolsCount==="number"){Xe.toolsCount=je.toolsCount;ze=true}if(ze){console.log(yt.default.dim("AI enhanced: description + toolsCount"))}}catch(G){const K=G instanceof Error?G.message:String(G);console.warn(yt.default.yellow(`AI enhance skipped: ${K}`))}}const ft=await createTarball(K);const mt=(0,at.createHash)("sha256").update(ft).digest("hex");const vt=slugify(`${Xe.name}-${Xe.version}`);const wt={id:vt,name:Xe.name,version:Xe.version,description:Xe.description||"",category:Xe.category,toolCount:Xe.toolsCount??0,...Xe.tools?{tools:Xe.tools}:{},serverCount:1,sha256:mt,signed:false,downloads:0,publishedAt:(new Date).toISOString(),...Xe.credentials?{credentials:Xe.credentials}:{}};const lr=new FormData;lr.append("file",new Blob([new Uint8Array(ft)],{type:"application/gzip"}),`${vt}.tgz`);lr.append("metadata",JSON.stringify({packageId:vt,manifest:wt,autoDeploy:false}));const Rr=await fetch(`${ze}/packages/sync/push`,{method:"POST",headers:{Authorization:`Bearer ${je}`},body:lr});if(!Rr.ok){const G=await Rr.text();throw new Error(`Publish failed: HTTP ${Rr.status} ${G}`)}const jr=`${ze}/repository`;console.log(yt.default.green(`Published package ${Xe.name}@${Xe.version}`));console.log(yt.default.cyan(`View at: ${jr}`));return{name:Xe.name,version:Xe.version,marketUrl:ze,packageUrl:jr}}function registerPublishCommand(G){G.command("publish").description("Publish local manifest.json to SGA Market").option("--name <name>","Override package name").option("--version <version>","Override package version").option("--category <category>","Override package category").option("--description <description>","Override package description").option("--no-enhance","Skip LLM metadata enhancement before upload").action((async G=>{await publishCommand(G)}))}},60390:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.runCommand=runCommand;const ze=je(73024);const We=je(76760);const Xe=je(18296);const rt=je(4843);const at=je(35440);const ft=je(27275);const mt=je(78536);const vt=je(20052);const yt=je(65402);const wt=je(51792);const lr=je(64109);const Er=je(60403);const Rr=je(74664);const jr=je(68100);const zr=je(49904);const fi=je(61108);const mi=je(75364);const bi=je(65737);const Si=je(20336);const Ei=je(15158);const ki=je(30244);const Ci=je(61301);const Ti="anthropic/claude-sonnet-4.5";const Pi="https://openrouter.ai/api/v1";function normalizeBaseUrl(G){return G.replace(/\/+$/,"")}function loadEnvConfig(G,K=5){let je=(0,We.resolve)(G);for(let G=0;G<=K;G+=1){const G=(0,We.resolve)(je,".env");if((0,ze.existsSync)(G)){const K=(0,ze.readFileSync)(G,"utf8");const je=new Map;for(const G of K.split(/\r?\n/)){const K=G.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);if(K){je.set(K[1],K[2])}}return je}const K=(0,We.dirname)(je);if(K===je){break}je=K}return new Map}function defaultIr(){return{system:{code:"generated-system",baseUrl:"https://example.local",authType:"none"},tools:[{name:"default_tool",description:"Fallback generated tool",method:"GET",path:"/health",needsConfirmation:false,isAsync:false,params:[]}]}}function isIR(G){if(!G||typeof G!=="object"){return false}const K=G;return typeof K.system?.code==="string"&&typeof K.system?.baseUrl==="string"&&typeof K.system?.authType==="string"&&Array.isArray(K.tools)}function parsePlanDoc(G){const K=G.trim();if(!K){return defaultIr()}try{const G=JSON.parse(K);if(isIR(G)){return G}}catch{}return defaultIr()}function createCore(G){const K=new rt.InMemoryPackager;return new rt.McpClawCore({parse:async G=>parsePlanDoc(G.content),codegen:async K=>{if(G.dryRun||!G.llmProvider){return[]}const je=(0,rt.buildCodegenPrompt)(K);const ze=await G.llmProvider.complete(je);return(0,rt.parseGeneratedFiles)(ze)},sandbox:{runTests:async()=>({passed:true,logs:[],failedTests:[]})},packager:{build:async G=>{const je=await K.build(G);return{...je,files:G.files}}}})}function createExplorer(G){if(!G){return new wt.ExplorerAgent({fsTool:new bi.FsTool,dockerTool:new mi.DockerInspectTool,httpTool:new Si.HttpFetchTool,browserTool:new fi.BrowserTool,pdfTool:new Ei.PdfTool})}return new wt.ExplorerAgent({fsTool:{glob:async()=>[]},dockerTool:{listContainers:async()=>[]},httpTool:{fetch:async G=>({url:G,status:200,body:""})}})}async function postJson(G,K){const je=await fetch(G,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(K)});if(!je.ok){const G=await je.text();throw new Error(`HTTP ${je.status}: ${G}`)}return await je.json()}function nowIso(){return(new Date).toISOString()}async function createReporter(G,K){if(!G){return{reportEvent:async()=>Promise.resolve()}}const je=normalizeBaseUrl(G);try{const G=await postJson(`${je}/monitor/cli-runs`,{root:K});const ze=G.data.runId;return{runId:ze,reportEvent:async G=>{try{await postJson(`${je}/monitor/cli-runs/${ze}/events`,G)}catch{}}}}catch{return{reportEvent:async()=>Promise.resolve()}}}async function runCommand(G){const K=Date.now();const je=G.urls?.[0]??G.root;const We=new lr.SessionWriter;const rt=await createReporter(G.reportTo,G.root);await rt.reportEvent({type:"log",level:"info",message:`CLI run started for ${G.root}`,timestamp:nowIso()});const wt=new Ci.PipelineProgress({silent:Boolean(G.dryRun)});let fi;let mi;let bi=[];try{const lr=loadEnvConfig(G.root);const Si=new Xe.SgaConfig;const Ei=lr.get("OPENROUTER_API_KEY")??process.env.OPENROUTER_API_KEY??Si.get("openrouter.apiKey")??"";const Ci=lr.get("LLM_CODER_MODEL")??process.env.LLM_CODER_MODEL??Si.get("model.coder")??Ti;const Ii=lr.get("OPENROUTER_BASE_URL")??process.env.OPENROUTER_BASE_URL??Si.get("openrouter.baseUrl")??Pi;const Ri=G.urls??[];const Mi=!G.dryRun&&Ei?new zr.OpenRouterProvider("openrouter-coder",Ci,Ei,Ii):undefined;if(!G.dryRun&&!Mi){G.logger.log("Warning: No API key configured. LLM analysis disabled — results will be limited.");G.logger.log(" Run: mcp-claw config set-env --key YOUR_OPENROUTER_KEY")}if(!(0,ze.existsSync)(G.root)){(0,ze.mkdirSync)(G.root,{recursive:true})}fi="Explorer";wt.start("Explorer","scanning sources...");const qi=createExplorer(Boolean(G.dryRun));const Xi=await qi.run({root:G.root,urls:Ri});if(G.rawDocs?.length){Xi.rawDocs=[...G.rawDocs,...Xi.rawDocs??[]]}const ps=Xi.rawDocs?.length??0;const Ls=`found ${Xi.files.length} files`;const qs=ps>0?`, ${ps} docs loaded`:"";const Ws=`${Ls}${qs}`;wt.done("Explorer",Ws);G.logger.log(`Explorer - ${Ws}`);fi="Architect";wt.start("Architect","designing MCP tools...");const Js=new at.ArchitectAgent(Mi?{llmIrGenerator:new ft.LlmIrGenerator(Mi)}:undefined);const eo=await Js.run(Xi);const to=`planned ${eo.ir.tools.length} tools`;wt.done("Architect",to);G.logger.log(`Architect - ${to}`);mi={system:eo.ir.system,toolCount:eo.ir.tools.length,toolNames:eo.ir.tools.map((G=>G.name))};fi="Builder";wt.start("Builder","generating code...");const ro=createCore({dryRun:Boolean(G.dryRun),llmProvider:Mi});const no=new vt.CoreCodegenAdapter(ro);const io=G.dryRun?{install:async()=>Promise.resolve()}:new yt.DependencyInstaller;const so=new mt.BuilderAgent({adapter:no,installer:io});const oo=await so.run({root:G.root,planDoc:G.dryRun?"":JSON.stringify(eo.ir,null,2)});if(!G.dryRun){const K=await(0,ki.writeManifest)(G.root,eo.ir);G.logger.log(`Builder - wrote manifest: ${K}`)}const ao=`wrote ${oo.writtenFiles.length} files`;wt.done("Builder",ao);G.logger.log(`Builder - ${ao}`);bi=oo.writtenFiles;fi="Tester";wt.start("Tester","validating generated server...");let co=false;try{const K=G.dryRun?{run:async()=>({stdout:"Tests: 0 passed, 0 failed, 0 total\nLines : 0%"})}:new Er.TestRunner;const je=new jr.TesterAgent({sandboxAdapter:new Rr.TesterSandboxAdapter({runTests:async()=>({passed:true,logs:[],failedTests:[]})}),runner:K});const ze=await je.run({root:G.root,files:oo.writtenFiles.map((G=>({path:G,content:""})))});co=ze.passed;if(co){wt.done("Tester","PASS");G.logger.log("Tester - PASS")}else{wt.done("Tester","FAIL (non-blocking)");G.logger.log("Tester - FAIL (non-blocking)")}}catch(K){const je=K instanceof Error?K.message:String(K);wt.done("Tester","SKIPPED");G.logger.log(`Tester - skipped: ${je}`)}if(!G.dryRun){const ze={id:`${Date.now()}`,source:je,startedAt:new Date(K).toISOString(),finishedAt:(new Date).toISOString(),status:co?"success":"failed",ir:mi,filesWritten:bi,durationMs:Date.now()-K};We.write(ze,G.root)}fi=undefined;await rt.reportEvent({type:"done",projectId:rt.runId??"cli-run",artifactCount:oo.writtenFiles.length})}catch(ze){const Xe=ze instanceof Error?ze.message:String(ze);if(fi){wt.fail(fi,Xe);G.logger.log(`${fi} - ${Xe}`)}if(!G.dryRun){const ze={id:`${Date.now()}`,source:je,startedAt:new Date(K).toISOString(),finishedAt:(new Date).toISOString(),status:"failed",ir:mi,filesWritten:bi,errorMessage:Xe,durationMs:Date.now()-K};try{We.write(ze,G.root)}catch{}}const at={type:"error",message:Xe};await rt.reportEvent(at);throw ze}}},28713:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.testCommand=testCommand;K.registerTestCommand=registerTestCommand;const We=je(31421);const Xe=je(73024);const rt=je(76760);const at=je(26848);const ft=je(57975);const mt=ze(je(39559));const vt=je(19562);const yt=(0,ft.promisify)(We.exec);function asRecord(G){if(G&&typeof G==="object"&&!Array.isArray(G)){return G}return{}}function sampleValue(G,K){const je=Array.isArray(K.enum)?K.enum:[];if(je.length>0){return je[0]}const ze=G.toLowerCase();const We=typeof K.type==="string"?K.type.toLowerCase():"string";if(ze.includes("url"))return"https://example.com";if(ze==="q"||ze.includes("query")||ze.includes("keyword")||ze.includes("search")){return"test"}if(ze.includes("id"))return"1";switch(We){case"integer":case"number":return 1;case"boolean":return true;case"array":return[];case"object":return{};default:return"test"}}function buildToolArgs(G){const K=asRecord(G);const je=asRecord(K.properties);const ze=Array.isArray(K.required)?K.required.filter((G=>typeof G==="string")):[];const We={};for(const G of ze){We[G]=sampleValue(G,asRecord(je[G]))}return We}function sleep(G){return new Promise((K=>setTimeout(K,G)))}async function ask(G){const K=(0,at.createInterface)({input:process.stdin,output:process.stdout});try{return(await K.question(G)).trim()}finally{K.close()}}async function askHidden(G){if(!process.stdin.isTTY||typeof process.stdin.setRawMode!=="function"){return ask(G)}return new Promise(((K,je)=>{const ze=process.stdin;const We=process.stdout;const Xe=ze.isRaw;let rt="";const cleanup=()=>{ze.off("data",onData);ze.setRawMode(Xe??false);ze.pause();We.write("\n")};const onData=G=>{const ze=G.toString("utf8");if(ze==="\r"||ze==="\n"){cleanup();K(rt.trim());return}if(ze===""){cleanup();je(new Error("Input interrupted"));return}if(ze==="\b"||ze===""){rt=rt.slice(0,-1);return}rt+=ze};We.write(G);ze.setRawMode(true);ze.resume();ze.on("data",onData)}))}function readManifest(G){const K=(0,rt.resolve)(G,"manifest.json");if(!(0,Xe.existsSync)(K)){throw new Error(`manifest.json not found: ${K}`)}const je=(0,Xe.readFileSync)(K,"utf8");const ze=JSON.parse(je);if(!ze||typeof ze!=="object"){throw new Error("manifest.json must be a JSON object")}return ze}async function collectCredentialEnv(G){const K={};for(const je of G){if(!je||typeof je.key!=="string"||je.key.trim().length===0){continue}const G=je.key.trim();const ze=typeof je.label==="string"&&je.label.trim().length>0?je.label.trim():G;const We=je.required===true;const Xe=typeof je.defaultValue==="string"&&je.defaultValue.trim().length>0?je.defaultValue:"";for(;;){const rt=We?" (required)":"";const at=Xe?` [default: ${Xe}]`:"";const ft=` ${ze} (${G})${rt}${at}: `;const vt=je.type==="password"?await askHidden(ft):await ask(ft);const yt=vt||Xe;if(We&&!yt){console.log(mt.default.red(` ${G} is required.`));continue}if(yt){K[G]=yt}break}}return K}function createWaitForResponse(G){return async(K,je=5e3)=>{const ze=Date.now();while(Date.now()-ze<je){const je=G.findIndex((G=>G.id===K));if(je>=0){const[K]=G.splice(je,1);return K}await sleep(25)}throw new Error(`Timeout waiting for MCP response id=${K}`)}}function responseError(G){return Object.prototype.hasOwnProperty.call(G,"error")?G.error:undefined}function responseResult(G){return Object.prototype.hasOwnProperty.call(G,"result")?G.result:undefined}function summarizeConnectionResult(G){if(!G){return"empty result"}if(typeof G==="string"){return G}if(typeof G==="object"&&G!==null){const K=G.content;if(Array.isArray(K)){const G=K.find((G=>G&&typeof G==="object"&&typeof G.text==="string"));if(G?.text){return G.text}}}return JSON.stringify(G)}function ensureEntrypoint(G,K){const je=typeof K.entrypoint==="string"&&K.entrypoint.trim().length>0?K.entrypoint.trim():"dist/index.js";return(0,rt.resolve)(G,je)}async function buildIfNeeded(G,K){if((0,Xe.existsSync)(K)){return}await yt("pnpm install",{cwd:G,timeout:12e4,windowsHide:true});await yt("pnpm run build",{cwd:G,timeout:12e4,windowsHide:true})}async function testCommand(G){const K=(0,rt.resolve)(G);console.log(mt.default.cyan(" Reading manifest.json..."));const je=readManifest(K);const ze=Array.isArray(je.credentials)?je.credentials:[];console.log(mt.default.gray(` Found ${ze.length} credentials`));const at=await collectCredentialEnv(ze);let ft=ensureEntrypoint(K,je);if(!(0,Xe.existsSync)(ft)){console.log(mt.default.cyan(" Entrypoint missing, running pnpm install && pnpm run build..."));await buildIfNeeded(K,ft);ft=ensureEntrypoint(K,je)}if(!(0,Xe.existsSync)(ft)){throw new Error(`Entrypoint not found after build: ${ft}`)}console.log(mt.default.cyan(" Starting MCP server..."));const yt=[];const wt=[];const lr=createWaitForResponse(wt);let Er;let Rr=Buffer.alloc(0);try{Er=(0,We.spawn)("node",[ft],{cwd:K,env:{...process.env,...at},windowsHide:true,stdio:["pipe","pipe","pipe"]});Er.stderr.on("data",(G=>{yt.push(typeof G==="string"?G:G.toString("utf8"))}));Er.stdout.on("data",(G=>{const K=typeof G==="string"?Buffer.from(G):G;Rr=Buffer.concat([Rr,K]);const je=(0,vt.parseMcpMessages)(Rr);Rr=je.rest;wt.push(...je.messages)}));await sleep(2e3);const writeMessage=G=>{if(!Er?.stdin){throw new Error("Server stdin is not available")}Er.stdin.write((0,vt.frameMcpMessage)(G))};writeMessage({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"mcp-claw-test",version:"1.0.0"}}});const G=await lr(1,1e4);if(responseError(G)){throw new Error(`initialize failed: ${JSON.stringify(responseError(G))}`)}console.log(mt.default.green(" OK initialize"));writeMessage({jsonrpc:"2.0",method:"notifications/initialized"});writeMessage({jsonrpc:"2.0",id:2,method:"tools/list"});const je=await lr(2,1e4);if(responseError(je)){throw new Error(`tools/list failed: ${JSON.stringify(responseError(je))}`)}const ze=responseResult(je);const Xe=ze?.tools?.filter((G=>typeof G?.name==="string"))??[];console.log(mt.default.green(` OK tools/list: ${Xe.length} tools`));if(Xe.length>0){console.log(mt.default.gray(` ${Xe.map((G=>G.name)).join(", ")}`))}let rt=3;const jr=Xe.some((G=>G.name==="test_connection"));if(jr){const G=rt++;writeMessage({jsonrpc:"2.0",id:G,method:"tools/call",params:{name:"test_connection",arguments:{}}});const K=await lr(G,1e4);if(responseError(K)){console.log(mt.default.red(` FAIL test_connection: ${JSON.stringify(responseError(K))}`));throw new Error("test_connection failed")}const je=summarizeConnectionResult(responseResult(K));console.log(mt.default.green(` OK test_connection: ${je}`))}const zr=Xe.filter((G=>G.name!=="test_connection"));let fi=0;for(const G of zr){const K=buildToolArgs(G.inputSchema);const je=rt++;writeMessage({jsonrpc:"2.0",id:je,method:"tools/call",params:{name:G.name,arguments:K}});const ze=await lr(je,1e4);const We=responseError(ze);const Xe=responseResult(ze);const at=Boolean(Xe&&Xe.isError===true);if(We||at){fi+=1;console.log(mt.default.red(` FAIL ${G.name}: ${We?JSON.stringify(We):summarizeConnectionResult(Xe)}`))}else{console.log(mt.default.green(` OK ${G.name}`))}}if(fi>0){throw new Error(`${fi}/${zr.length} tools failed`)}console.log("");console.log(mt.default.green(" All checks passed."))}finally{Er?.kill();if(yt.length>0&&process.env.DEBUG){console.log(mt.default.gray("\n Server logs:"));console.log(mt.default.gray(yt.slice(-20).join("")))}}}function registerTestCommand(G){G.command("test [dir]").description("Test MCP server connectivity and credentials").action((async G=>{try{await testCommand(G??process.cwd())}catch(G){const K=G instanceof Error?G.message:String(G);console.error(mt.default.red(` ${K}`));process.exitCode=1}}))}},18296:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.SgaConfig=K.DEFAULT_CONFIG_PATH=void 0;const We=je(73024);const Xe=je(48161);const rt=je(76760);const at=ze(je(15309));K.DEFAULT_CONFIG_PATH=(0,rt.join)((0,Xe.homedir)(),".sga","config.yaml");function isRecord(G){return Boolean(G)&&typeof G==="object"&&!Array.isArray(G)}class SgaConfig{path;constructor(G=K.DEFAULT_CONFIG_PATH){this.path=G}get(G){const K=this.load();const je=G.split(".").filter(Boolean);let ze=K;for(const G of je){if(!isRecord(ze)||!(G in ze)){return undefined}ze=ze[G]}return ze}set(G,K){const je=this.load();const ze=G.split(".").filter(Boolean);if(ze.length===0){throw new Error("Config key must not be empty")}let We=je;for(let G=0;G<ze.length-1;G+=1){const K=ze[G];const je=We[K];if(!isRecord(je)){We[K]={}}We=We[K]}We[ze[ze.length-1]]=K;this.save(je)}getAll(){return this.load()}load(){if(!(0,We.existsSync)(this.path)){return{}}const G=(0,We.readFileSync)(this.path,"utf8");const K=at.default.load(G);if(!isRecord(K)){return{}}return K}save(G){(0,We.mkdirSync)((0,rt.dirname)(this.path),{recursive:true});const K=at.default.dump(G,{lineWidth:-1});(0,We.writeFileSync)(this.path,K,"utf8")}}K.SgaConfig=SgaConfig},49904:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.LlmClientRouter=K.OpenRouterProvider=void 0;function sleep(G){return new Promise((K=>setTimeout(K,G)))}function extractTextContent(G){if(typeof G==="string"){return G}if(Array.isArray(G)){return G.map((G=>typeof G?.text==="string"?G.text:"")).join("\n").trim()}return""}function extractToolCalls(G){if(!Array.isArray(G)){return[]}return G.filter((G=>typeof G?.id==="string"&&(G?.type==="function"||typeof G?.type==="undefined")&&typeof G?.function?.name==="string")).map((G=>({id:G.id,type:"function",function:{name:G.function?.name,arguments:typeof G.function?.arguments==="string"?G.function.arguments:"{}"}})))}class OpenRouterProvider{model;apiKey;baseUrl;name;constructor(G,K,je,ze="https://openrouter.ai/api/v1"){this.model=K;this.apiKey=je;this.baseUrl=ze;this.name=G}async chat(G,K){const je=`${this.baseUrl.replace(/\/+$/,"")}/chat/completions`;const ze=this.model.toLowerCase().includes("minimax");const We=JSON.stringify({model:this.model,messages:G.map((G=>({role:G.role,content:G.content,...G.tool_call_id?{tool_call_id:G.tool_call_id}:{},...G.tool_calls?{tool_calls:G.tool_calls}:{}}))),...!ze&&K&&K.length>0?{tools:K,tool_choice:"auto"}:{},max_tokens:8192});const Xe=3;let rt;for(let G=0;G<Xe;G++){try{const K=new AbortController;const ze=setTimeout((()=>K.abort()),12e4);const Xe=await fetch(je,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","HTTP-Referer":"https://github.com/mcp-claw","X-Title":"MCP-Claw"},body:We,signal:K.signal});clearTimeout(ze);if(Xe.status>=500||Xe.status===429){rt=new Error(`OpenRouter error: ${Xe.status} ${await Xe.text()}`);await sleep(1e3*Math.pow(2,G));continue}if(!Xe.ok){throw new Error(`OpenRouter error: ${Xe.status} ${await Xe.text()}`)}const at=await Xe.json();const ft=at.choices?.[0];const mt=extractTextContent(ft?.message?.content);const vt=extractToolCalls(ft?.message?.tool_calls);const yt=vt.length>0||ft?.finish_reason==="tool_calls"?"tool_calls":"stop";return{content:mt,finish_reason:yt,...vt.length>0?{tool_calls:vt}:{}}}catch(K){rt=K instanceof Error?K:new Error(String(K));const je=rt.message;if(je.includes("fetch failed")||je.includes("Timeout")||je.includes("abort")||je.includes("ECONNRESET")||je.includes("ECONNREFUSED")){await sleep(1e3*Math.pow(2,G));continue}throw rt}}throw rt??new Error("OpenRouter request failed after retries")}async complete(G){const K=await this.chat([{role:"user",content:G}]);return K.content}}K.OpenRouterProvider=OpenRouterProvider;class LlmClientRouter{providers=new Map;constructor(G){for(const K of G){this.providers.set(K.name,K)}}async complete(G){const K=this.providers.get(G.provider);if(!K){throw new Error("provider not found")}return K.complete(G.prompt)}}K.LlmClientRouter=LlmClientRouter},29441:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.SessionReader=void 0;const ze=je(73024);const We=je(76760);const Xe=je(64109);class SessionReader{lastRun(G=process.cwd()){const K=(0,Xe.resolveProjectLastRunPath)(G);if(!(0,ze.existsSync)(K)){return null}try{return JSON.parse((0,ze.readFileSync)(K,"utf8"))}catch{return null}}listSessions(G=20){const K=(0,Xe.resolveGlobalSessionsDir)();if(!(0,ze.existsSync)(K)){return[]}const je=(0,ze.readdirSync)(K).filter((G=>G.endsWith(".md"))).map((G=>(0,We.join)(K,G))).map((G=>({file:G,mtime:(0,ze.statSync)(G).mtime}))).sort(((G,K)=>K.mtime.getTime()-G.mtime.getTime())).slice(0,G);return je.map((G=>{const K=(0,ze.readFileSync)(G.file,"utf8");const je=K.split(/\r?\n/,1)[0]??"";return{file:G.file,mtime:G.mtime,preview:je}}))}}K.SessionReader=SessionReader},64109:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.SessionWriter=void 0;K.resolveProjectStateDir=resolveProjectStateDir;K.resolveProjectLastRunPath=resolveProjectLastRunPath;K.resolveGlobalSessionsDir=resolveGlobalSessionsDir;const ze=je(73024);const We=je(48161);const Xe=je(76760);function pad(G){return String(G).padStart(2,"0")}function toSlug(G){const K=G.trim().replace(/^https?:\/\//i,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").toLowerCase();if(!K){return"run"}return K.slice(0,40)}function formatSessionFileName(G){const K=new Date(G.startedAt);const je=[K.getFullYear(),pad(K.getMonth()+1),pad(K.getDate())].join("-");const ze=[pad(K.getHours()),pad(K.getMinutes())].join("-");return`${je}-${ze}-${toSlug(G.source)}.md`}function formatSessionMarkdown(G){const K=G.status==="success"?"✅ success":"❌ failed";const je=G.ir?.toolCount??0;const ze=G.ir?.toolNames.join(", ")||"(none)";const We=G.filesWritten.length>0?G.filesWritten.join(", "):"(none)";const Xe=[`# ${G.source}`,`- 时间:${G.startedAt}`,`- 状态:${K}`,`- 工具数:${je}`,`- 工具列表:${ze}`,`- 生成文件:${We}`,`- 耗时:${G.durationMs}ms`];if(G.errorMessage){Xe.push(`- 错误:${G.errorMessage}`)}return`${Xe.join("\n")}\n`}function resolveProjectStateDir(G=process.cwd()){return(0,Xe.join)(G,".sga")}function resolveProjectLastRunPath(G=process.cwd()){return(0,Xe.join)(resolveProjectStateDir(G),"last-run.json")}function resolveHomeDir(){return process.env.SGA_HOME||(0,We.homedir)()}function resolveGlobalSessionsDir(G=resolveHomeDir()){return(0,Xe.join)(G,".sga","sessions")}class SessionWriter{write(G,K=process.cwd()){const je=resolveProjectStateDir(K);(0,ze.mkdirSync)(je,{recursive:true});(0,ze.writeFileSync)(resolveProjectLastRunPath(K),JSON.stringify(G,null,2),"utf8");const We=resolveGlobalSessionsDir();(0,ze.mkdirSync)(We,{recursive:true});(0,ze.writeFileSync)((0,Xe.join)(We,formatSessionFileName(G)),formatSessionMarkdown(G),"utf8")}}K.SessionWriter=SessionWriter},61108:function(G,K,je){"use strict";var ze=this&&this.__createBinding||(Object.create?function(G,K,je,ze){if(ze===undefined)ze=je;var We=Object.getOwnPropertyDescriptor(K,je);if(!We||("get"in We?!K.__esModule:We.writable||We.configurable)){We={enumerable:true,get:function(){return K[je]}}}Object.defineProperty(G,ze,We)}:function(G,K,je,ze){if(ze===undefined)ze=je;G[ze]=K[je]});var We=this&&this.__setModuleDefault||(Object.create?function(G,K){Object.defineProperty(G,"default",{enumerable:true,value:K})}:function(G,K){G["default"]=K});var Xe=this&&this.__importStar||function(){var ownKeys=function(G){ownKeys=Object.getOwnPropertyNames||function(G){var K=[];for(var je in G)if(Object.prototype.hasOwnProperty.call(G,je))K[K.length]=je;return K};return ownKeys(G)};return function(G){if(G&&G.__esModule)return G;var K={};if(G!=null)for(var je=ownKeys(G),Xe=0;Xe<je.length;Xe++)if(je[Xe]!=="default")ze(K,G,je[Xe]);We(K,G);return K}}();Object.defineProperty(K,"__esModule",{value:true});K.BrowserTool=void 0;function normalizeText(G){return G.replace(/\s+/g," ").trim()}function isOpenApiLink(G){return/(openapi|swagger|api-docs|api\.json|api\.ya?ml)/i.test(G)}function unique(G){return[...new Set(G)]}function extractLinksFromHtml(G,K){const je=/href=["']([^"']+)["']/gi;const ze=[];let We;while((We=je.exec(G))!==null){try{ze.push(new URL(We[1],K).href)}catch{}}return unique(ze)}function extractTextFromHtml(G){return G.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<nav[\s\S]*?<\/nav>/gi,"").replace(/<header[\s\S]*?<\/header>/gi,"").replace(/<footer[\s\S]*?<\/footer>/gi,"").replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/\s+/g," ").trim()}function extractTitleFromHtml(G){const K=G.match(/<title[^>]*>([\s\S]*?)<\/title>/i);return K?normalizeText(K[1]):""}async function fetchWithNative(G,K){const je=new AbortController;const ze=setTimeout((()=>je.abort()),K);try{const K=await fetch(G,{signal:je.signal,headers:{"User-Agent":"mcp-claw/1.0"}});const ze=await K.text();const We=K.url||G;const Xe=extractLinksFromHtml(ze,We);return{url:We,html:ze,text:extractTextFromHtml(ze),title:extractTitleFromHtml(ze),links:Xe,openApiUrls:Xe.filter(isOpenApiLink)}}finally{clearTimeout(ze)}}class BrowserTool{async launchBrowser(){const{chromium:G}=await Promise.resolve().then((()=>Xe(je(47885))));return G.launch({headless:true})}async fetch(G,K=3e4){try{return await this.fetchWithBrowser(G,K)}catch(je){const ze=je instanceof Error?je.message:"";if(ze.includes("Executable")||ze.includes("browserType.launch")||ze.includes("Cannot find module")){return fetchWithNative(G,K)}throw je}}async fetchWithBrowser(G,K){const je=await this.launchBrowser();const ze=await je.newContext();const We=await ze.newPage();try{await We.goto(G,{waitUntil:"domcontentloaded",timeout:K});const je=await We.content();const ze=await We.evaluate((()=>{const G=document.title||"";const K=Array.from(document.querySelectorAll("a[href]")).map((G=>G.href)).filter(Boolean);const je=document.body.cloneNode(true);if(je){je.querySelectorAll("script,style,nav,header,footer").forEach((G=>G.remove()))}return{title:G,text:je?.innerText??"",links:K}}));const Xe=unique(ze.links);return{url:We.url(),html:je,text:normalizeText(ze.text),title:normalizeText(ze.title),links:Xe,openApiUrls:Xe.filter(isOpenApiLink)}}finally{await ze.close();await je.close()}}}K.BrowserTool=BrowserTool},75364:function(G,K,je){"use strict";var ze=this&&this.__createBinding||(Object.create?function(G,K,je,ze){if(ze===undefined)ze=je;var We=Object.getOwnPropertyDescriptor(K,je);if(!We||("get"in We?!K.__esModule:We.writable||We.configurable)){We={enumerable:true,get:function(){return K[je]}}}Object.defineProperty(G,ze,We)}:function(G,K,je,ze){if(ze===undefined)ze=je;G[ze]=K[je]});var We=this&&this.__setModuleDefault||(Object.create?function(G,K){Object.defineProperty(G,"default",{enumerable:true,value:K})}:function(G,K){G["default"]=K});var Xe=this&&this.__importStar||function(){var ownKeys=function(G){ownKeys=Object.getOwnPropertyNames||function(G){var K=[];for(var je in G)if(Object.prototype.hasOwnProperty.call(G,je))K[K.length]=je;return K};return ownKeys(G)};return function(G){if(G&&G.__esModule)return G;var K={};if(G!=null)for(var je=ownKeys(G),Xe=0;Xe<je.length;Xe++)if(je[Xe]!=="default")ze(K,G,je[Xe]);We(K,G);return K}}();Object.defineProperty(K,"__esModule",{value:true});K.DockerInspectTool=void 0;async function defaultDockerExec(G){const{execa:K}=await Promise.resolve().then((()=>Xe(je(10978))));const{stdout:ze}=await K("docker",G,{timeout:1e4});return{stdout:ze}}class DockerInspectTool{dockerExec;constructor(G=G=>defaultDockerExec(G)){this.dockerExec=G}async listContainers(){try{const{stdout:G}=await this.dockerExec(["ps","--format","{{json .}}"]);return G.split(/\r?\n/).filter(Boolean).map((G=>JSON.parse(G))).map((G=>({id:G.ID,image:G.Image,status:G.Status})))}catch{return[]}}}K.DockerInspectTool=DockerInspectTool},65737:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.FsTool=void 0;const We=je(73024);const Xe=ze(je(76760));const rt=new Set(["node_modules",".git","dist","build",".next",".nuxt","out","coverage",".cache","__pycache__",".venv","venv",".idea",".vscode","vendor","target"]);const at=8;function globToRegex(G){const K=G.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${K}$`,"i")}async function walk(G,K=0){if(K>at)return[];let je;try{je=await We.promises.readdir(G,{withFileTypes:true})}catch{return[]}const ze=[];for(const We of je){const je=We.name;const at=Xe.default.join(G,je);if(We.isDirectory()){if(rt.has(je)||je.startsWith("."))continue;ze.push(...await walk(at,K+1))}else{ze.push(at)}}return ze}class FsTool{async readFile(G){return We.promises.readFile(G,"utf8")}async writeFile(G,K){await We.promises.writeFile(G,K,"utf8")}async glob(G,K){const je=await walk(G);const ze=K.map(globToRegex);return je.filter((G=>{const K=Xe.default.basename(G);return ze.some((G=>G.test(K)))}))}}K.FsTool=FsTool},20336:(G,K)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.HttpFetchTool=void 0;class HttpFetchTool{fetchImpl;constructor(G=fetch){this.fetchImpl=G}async fetch(G,K=5e3){const je=await this.request({url:G,method:"GET",headers:{accept:"application/json,application/yaml,text/plain,*/*"},timeoutMs:K});return{url:je.url,status:je.status,body:je.body}}async request(G){const K=new AbortController;const je=setTimeout((()=>K.abort()),G.timeoutMs??5e3);try{const je=await this.fetchImpl(G.url,{method:G.method??"GET",signal:K.signal,headers:G.headers,body:G.body});const ze={};je.headers?.forEach(((G,K)=>{ze[K]=G}));return{url:je.url||G.url,status:je.status,statusText:je.statusText||"",headers:ze,body:await je.text()}}finally{clearTimeout(je)}}}K.HttpFetchTool=HttpFetchTool},15158:function(G,K,je){"use strict";var ze=this&&this.__createBinding||(Object.create?function(G,K,je,ze){if(ze===undefined)ze=je;var We=Object.getOwnPropertyDescriptor(K,je);if(!We||("get"in We?!K.__esModule:We.writable||We.configurable)){We={enumerable:true,get:function(){return K[je]}}}Object.defineProperty(G,ze,We)}:function(G,K,je,ze){if(ze===undefined)ze=je;G[ze]=K[je]});var We=this&&this.__setModuleDefault||(Object.create?function(G,K){Object.defineProperty(G,"default",{enumerable:true,value:K})}:function(G,K){G["default"]=K});var Xe=this&&this.__importStar||function(){var ownKeys=function(G){ownKeys=Object.getOwnPropertyNames||function(G){var K=[];for(var je in G)if(Object.prototype.hasOwnProperty.call(G,je))K[K.length]=je;return K};return ownKeys(G)};return function(G){if(G&&G.__esModule)return G;var K={};if(G!=null)for(var je=ownKeys(G),Xe=0;Xe<je.length;Xe++)if(je[Xe]!=="default")ze(K,G,je[Xe]);We(K,G);return K}}();Object.defineProperty(K,"__esModule",{value:true});K.PdfTool=void 0;const rt=je(51455);class PdfTool{async extract(G){const K=await this.extractFromFile(G);return K.text}async extractFromFile(G){const K=await(0,rt.readFile)(G);return this.extractFromBuffer(K)}async extractFromBuffer(G){const{PDFParse:K}=await Promise.resolve().then((()=>Xe(je(95074))));const ze=new K({data:new Uint8Array(G)});try{const[G,K]=await Promise.all([ze.getText(),ze.getInfo()]);return{text:G.text,pages:G.total,info:K.info??{}}}finally{await ze.destroy()}}}K.PdfTool=PdfTool},59265:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.getToken=getToken;K.saveToken=saveToken;K.clearToken=clearToken;K.getMarketUrl=getMarketUrl;const We=je(73024);const Xe=ze(je(48161));const rt=ze(je(76760));const at="https://market.sga.dev";const ft=rt.default.join(Xe.default.homedir(),".sga","config.json");function readConfig(){if(!(0,We.existsSync)(ft)){return{}}try{const G=(0,We.readFileSync)(ft,"utf8");const K=JSON.parse(G);if(!K||typeof K!=="object"){return{}}const je=K;return{token:typeof je.token==="string"?je.token:undefined,marketUrl:typeof je.marketUrl==="string"?je.marketUrl:undefined}}catch{return{}}}function writeConfig(G){(0,We.mkdirSync)(rt.default.dirname(ft),{recursive:true});(0,We.writeFileSync)(ft,`${JSON.stringify(G,null,2)}\n`,"utf8")}function getToken(){const G=readConfig().token?.trim();return G&&G.length>0?G:null}function saveToken(G,K){const je={token:G.trim(),marketUrl:K.trim()||at};writeConfig(je)}function clearToken(){const G=readConfig();const K={marketUrl:G.marketUrl?.trim()||at};writeConfig(K)}function getMarketUrl(){const G=readConfig().marketUrl?.trim();return G&&G.length>0?G:at}},30244:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});K.writeManifest=writeManifest;const ze=je(73024);const We=je(76760);function toKebab(G){const K=G.replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-|-$/g,"").toLowerCase();return K||"generated"}function toUpperSnake(G){const K=G.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"");return K||"SERVICE"}function buildCredentials(G){const K=toUpperSnake(G.system.code);const je=[];je.push({key:`${K}_BASE_URL`,label:"服务地址",type:"string",required:true,description:`${G.system.code} 的 API 基础地址`});if(G.system.authType!=="none"){je.push({key:`${K}_API_KEY`,label:"API Key",type:"secret",required:true,description:`API key for ${G.system.code}`})}return je}function buildManifest(G){return{name:`mcp-server-${toKebab(G.system.code)}`,version:"1.0.0",description:`MCP server for ${G.system.code} API`,category:"api",toolsCount:G.tools.length,credentials:buildCredentials(G)}}async function writeManifest(G,K,je=ze.promises){const Xe=buildManifest(K);const rt=(0,We.join)(G,"manifest.json");await je.writeFile(rt,JSON.stringify(Xe,null,2),"utf8");return rt}},61301:function(G,K,je){"use strict";var ze=this&&this.__importDefault||function(G){return G&&G.__esModule?G:{default:G}};Object.defineProperty(K,"__esModule",{value:true});K.PipelineProgress=void 0;const We=ze(je(39559));const Xe=ze(je(84492));class PipelineProgress{spinner;silent;constructor(G={}){this.silent=Boolean(G.silent)}start(G,K){const je=this.formatMessage(G,K);if(this.silent){console.log(je);return}if(this.spinner?.isSpinning){this.spinner.stop()}this.spinner=(0,Xe.default)(je).start()}done(G,K){const je=this.formatMessage(G,K);if(this.silent){console.log(`${We.default.green("✔")} ${je}`);return}if(this.spinner?.isSpinning){this.spinner.stopAndPersist({symbol:We.default.green("✔"),text:je});return}console.log(`${We.default.green("✔")} ${je}`)}fail(G,K){const je=this.formatMessage(G,K);if(this.silent){console.log(`${We.default.red("✘")} ${je}`);return}if(this.spinner?.isSpinning){this.spinner.stopAndPersist({symbol:We.default.red("✘"),text:je});return}console.log(`${We.default.red("✘")} ${je}`)}formatMessage(G,K){return`${We.default.cyan(G)} ${K}`}}K.PipelineProgress=PipelineProgress},11029:(G,K,je)=>{"use strict";Object.defineProperty(K,"__esModule",{value:true});var ze=je(55825);class AbortSignal extends ze.EventTarget{constructor(){super();throw new TypeError("AbortSignal cannot be constructed directly")}get aborted(){const G=We.get(this);if(typeof G!=="boolean"){throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this===null?"null":typeof this}`)}return G}}ze.defineEventAttribute(AbortSignal.prototype,"abort");function createAbortSignal(){const G=Object.create(AbortSignal.prototype);ze.EventTarget.call(G);We.set(G,false);return G}function abortSignal(G){if(We.get(G)!==false){return}We.set(G,true);G.dispatchEvent({type:"abort"})}const We=new WeakMap;Object.defineProperties(AbortSignal.prototype,{aborted:{enumerable:true}});if(typeof Symbol==="function"&&typeof Symbol.toStringTag==="symbol"){Object.defineProperty(AbortSignal.prototype,Symbol.toStringTag,{configurable:true,value:"AbortSignal"})}class AbortController{constructor(){Xe.set(this,createAbortSignal())}get signal(){return getSignal(this)}abort(){abortSignal(getSignal(this))}}const Xe=new WeakMap;function getSignal(G){const K=Xe.get(G);if(K==null){throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${G===null?"null":typeof G}`)}return K}Object.defineProperties(AbortController.prototype,{signal:{enumerable:true},abort:{enumerable:true}});if(typeof Symbol==="function"&&typeof Symbol.toStringTag==="symbol"){Object.defineProperty(AbortController.prototype,Symbol.toStringTag,{configurable:true,value:"AbortController"})}K.AbortController=AbortController;K.AbortSignal=AbortSignal;K["default"]=AbortController;G.exports=AbortController;G.exports.AbortController=G.exports["default"]=AbortController;G.exports.AbortSignal=AbortSignal},78352:(G,K,je)=>{var ze=je(25744);var We=je(16928);var Xe=je(55207);var rt=je(27294);var at=je(52838);var ft=je(93294);var mt=je(98875);var vt=G.exports={};var yt=/[\/\\]/g;var processPatterns=function(G,K){var je=[];Xe(G).forEach((function(G){var ze=G.indexOf("!")===0;if(ze){G=G.slice(1)}var We=K(G);if(ze){je=rt(je,We)}else{je=at(je,We)}}));return je};vt.exists=function(){var G=We.join.apply(We,arguments);return ze.existsSync(G)};vt.expand=function(...G){var K=ft(G[0])?G.shift():{};var je=Array.isArray(G[0])?G[0]:G;if(je.length===0){return[]}var Xe=processPatterns(je,(function(G){return mt.sync(G,K)}));if(K.filter){Xe=Xe.filter((function(G){G=We.join(K.cwd||"",G);try{if(typeof K.filter==="function"){return K.filter(G)}else{return ze.statSync(G)[K.filter]()}}catch(G){return false}}))}return Xe};vt.expandMapping=function(G,K,je){je=Object.assign({rename:function(G,K){return We.join(G||"",K)}},je);var ze=[];var Xe={};vt.expand(je,G).forEach((function(G){var rt=G;if(je.flatten){rt=We.basename(rt)}if(je.ext){rt=rt.replace(/(\.[^\/]*)?$/,je.ext)}var at=je.rename(K,rt,je);if(je.cwd){G=We.join(je.cwd,G)}at=at.replace(yt,"/");G=G.replace(yt,"/");if(Xe[at]){Xe[at].src.push(G)}else{ze.push({src:[G],dest:at});Xe[at]=ze[ze.length-1]}}));return ze};vt.normalizeFilesArray=function(G){var K=[];G.forEach((function(G){var je;if("src"in G||"dest"in G){K.push(G)}}));if(K.length===0){return[]}K=_(K).chain().forEach((function(G){if(!("src"in G)||!G.src){return}if(Array.isArray(G.src)){G.src=Xe(G.src)}else{G.src=[G.src]}})).map((function(G){var K=Object.assign({},G);delete K.src;delete K.dest;if(G.expand){return vt.expandMapping(G.src,G.dest,K).map((function(K){var je=Object.assign({},G);je.orig=Object.assign({},G);je.src=K.src;je.dest=K.dest;["expand","cwd","flatten","rename","ext"].forEach((function(G){delete je[G]}));return je}))}var je=Object.assign({},G);je.orig=Object.assign({},G);if("src"in je){Object.defineProperty(je,"src",{enumerable:true,get:function fn(){var je;if(!("result"in fn)){je=G.src;je=Array.isArray(je)?Xe(je):[je];fn.result=vt.expand(K,je)}return fn.result}})}if("dest"in je){je.dest=G.dest}return je})).flatten().value();return K}},57504:(G,K,je)=>{var ze=je(25744);var We=je(16928);var Xe=je(35855);var rt=je(20718);var at=je(90229);var ft=je(12743);var mt=je(2203).Stream;var vt=je(35355).PassThrough;var yt=G.exports={};yt.file=je(78352);yt.collectStream=function(G,K){var je=[];var ze=0;G.on("error",K);G.on("data",(function(G){je.push(G);ze+=G.length}));G.on("end",(function(){var G=Buffer.alloc(ze);var We=0;je.forEach((function(K){K.copy(G,We);We+=K.length}));K(null,G)}))};yt.dateify=function(G){G=G||new Date;if(G instanceof Date){G=G}else if(typeof G==="string"){G=new Date(G)}else{G=new Date}return G};yt.defaults=function(G,K,je){var ze=arguments;ze[0]=ze[0]||{};return ft(...ze)};yt.isStream=function(G){return Xe(G)};yt.lazyReadStream=function(G){return new rt.Readable((function(){return ze.createReadStream(G)}))};yt.normalizeInputSource=function(G){if(G===null){return Buffer.alloc(0)}else if(typeof G==="string"){return Buffer.from(G)}else if(yt.isStream(G)){return G.pipe(new vt)}return G};yt.sanitizePath=function(G){return at(G,false).replace(/^\w+:/,"").replace(/^(\.\.\/|\/)+/,"")};yt.trailingSlashIt=function(G){return G.slice(-1)!=="/"?G+"/":G};yt.unixifyPath=function(G){return at(G,false).replace(/^\w+:/,"")};yt.walkdir=function(G,K,je){var Xe=[];if(typeof K==="function"){je=K;K=G}ze.readdir(G,(function(rt,at){var ft=0;var mt;var vt;if(rt){return je(rt)}(function next(){mt=at[ft++];if(!mt){return je(null,Xe)}vt=We.join(G,mt);ze.stat(vt,(function(G,ze){Xe.push({path:vt,relative:We.relative(K,vt).replace(/\\/g,"/"),stats:ze});if(ze&&ze.isDirectory()){yt.walkdir(vt,K,(function(G,K){if(G){return je(G)}K.forEach((function(G){Xe.push(G)}));next()}))}else{next()}}))})()}))}},29200:(G,K,je)=>{
58
58
  /**
59
59
  * Archiver Vending
60
60
  *