@fabriziosalmi/slopless 1.15.0 → 1.15.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/engine/api.js +1 -1
- package/dist/index.js +2 -2
- package/package.json +2 -2
- package/rules/VBC-503.yaml +4 -0
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ Slopless is a static analysis tool designed to identify and mitigate unstructure
|
|
|
14
14
|
- **Lexical Scoping**: Every string, comment and regular expression literal is mapped before a rule reads a byte — with the TypeScript scanner where it can, and a declarative tokeniser for Python, Go, Rust, shell, Java, C, C++, C#, Kotlin, Swift and Ruby. Each rule declares what it looks at (`code`, `strings`, `comments`, `regex`, `all`). A rule about `eval()` stays quiet inside a comment; a rule about insecure URLs does not read the pattern that validates them; a Python docstring is documentation rather than a string value.
|
|
15
15
|
- **Exceptions That Say Why**: A rule can skip test code that lives inside the file it tests (`#[cfg(test)] mod tests`), skip documentation comments in languages that mandate them, and be excused by name on one line with `// slopless-disable-next-line VBC-001 -- reason`. A project can claim its own vocabulary, so `blacklist` in a firewall is the domain rather than a finding — and the run reports how many findings that excused.
|
|
16
16
|
- **Rule Precedence**: A specific rule declares the general ones it `supersedes`, so a single `// TODO: implement this` produces one finding, not four.
|
|
17
|
-
- **In the editor, and while writing
|
|
17
|
+
- **In the editor, and while writing** ([how](https://fabriziosalmi.github.io/slopless/editor)): [`packages/vscode-slopless`](packages/vscode-slopless) is a language server and a Slopless panel — diagnostics as you type, and a list of what the rules found across the workspace, errors first, clicking one goes to the line. Build the `.vsix` and install it; it is not on the Marketplace. [`packages/mcp-slopless`](packages/mcp-slopless) is an MCP server, so a coding agent can check a buffer *before* it writes the file: `lint_text` takes the text and the path it will have, and the path is what decides whether it counts as test code. Both run the same engine and the same rules as the CLI.
|
|
18
18
|
|
|
19
19
|
## GitHub Action
|
|
20
20
|
|
package/dist/engine/api.js
CHANGED
|
@@ -518,7 +518,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
518
518
|
`)?1:0),k=sne(d,u);if(k.length===0)return S;let m=k.reduce((T,F)=>T+u.slice(F.start,F.end).split(`
|
|
519
519
|
`).length-1,0);return S-m}var vCe=new Set(["empty-file","file-length-limit"]),une=class{static check(d,S,k){var X,be;let m=[],T=k!==void 0?k:WHe.readFileSync(d,"utf8");for(let Pe of S){let Be=(X=Pe.match.ast_check)==null?void 0:X.type;!Be||!vCe.has(Be)||WE(d,Pe)||Pe.match.file_types&&!Pe.match.file_types.includes(K5(d))||m.push(...this.checkByCounting(Be,T,{rule:Pe,file:d,threshold:Pe.match.threshold??((be=Pe.match.ast_check)==null?void 0:be.threshold)}))}if(!cne.has(K5(d)))return m;let F=va.createSourceFile(d,T,va.ScriptTarget.Latest,!0);for(let Pe of S){if(!Pe.match.ast_check||WE(d,Pe))continue;let Be=Pe.match.ast_check.type,at=Pe.match.threshold??Pe.match.ast_check.threshold,pe={rule:Pe,sourceFile:F,file:d,violations:m};vCe.has(Be)||this.traverse(F,Zt=>{Be==="function-params-limit"&&at&&this.checkFunctionParams(Zt,at,pe),Be==="function-length-limit"&&at&&this.checkFunctionLength(Zt,at,pe),Be==="empty-catch"&&this.checkEmptyCatch(Zt,pe),Be==="nested-blocks-limit"&&at&&this.checkNestedBlocks(Zt,at,pe),Be==="empty-block"&&this.checkEmptyBlock(Zt,pe),Be==="one-liner-limit"&&this.checkOneLiner(Zt,pe),Be==="redundant-if-true"&&this.checkRedundantIfTrue(Zt,pe),Be==="lying-function-names"&&this.checkLyingFunctionName(Zt,pe),Be==="empty-interface"&&this.checkEmptyInterface(Zt,pe),Be==="async-without-await"&&this.checkAsyncWithoutAwait(Zt,pe)})}return m}static checkFunctionParams(d,S,k){if(!va.isFunctionDeclaration(d)&&!va.isMethodDeclaration(d)&&!va.isArrowFunction(d)||d.parameters.length<=S)return;let{line:m}=k.sourceFile.getLineAndCharacterOfPosition(d.getStart());k.violations.push({ruleId:k.rule.id,name:k.rule.name,severity:k.rule.severity,message:this.formatMessage(k.rule.message,{threshold:S,count:d.parameters.length,line:m+1}),file:k.file,line:m+1})}static checkFunctionLength(d,S,k){if(!va.isFunctionDeclaration(d)&&!va.isMethodDeclaration(d)&&!va.isArrowFunction(d))return;let m=k.sourceFile.getLineAndCharacterOfPosition(d.getStart()).line,F=k.sourceFile.getLineAndCharacterOfPosition(d.getEnd()).line-m+1;F<=S||k.violations.push({ruleId:k.rule.id,name:k.rule.name,severity:k.rule.severity,message:this.formatMessage(k.rule.message,{threshold:S,count:F,line:m+1}),file:k.file,line:m+1})}static checkEmptyCatch(d,S){if(!va.isCatchClause(d)||d.block.statements.length>0||/\/\/|\/\*/.test(d.block.getText()))return;let{line:k}=S.sourceFile.getLineAndCharacterOfPosition(d.getStart());S.violations.push({ruleId:S.rule.id,name:S.rule.name,severity:S.rule.severity,message:this.formatMessage(S.rule.message,{line:k+1}),file:S.file,line:k+1})}static checkEmptyBlock(d,S){if(!va.isBlock(d)||d.statements.length>0||va.isCatchClause(d.parent)||va.isConstructorDeclaration(d.parent))return;let{line:k}=S.sourceFile.getLineAndCharacterOfPosition(d.getStart());S.violations.push({ruleId:S.rule.id,name:S.rule.name,severity:S.rule.severity,message:this.formatMessage(S.rule.message,{line:k+1}),file:S.file,line:k+1})}static checkOneLiner(d,S){if(!va.isBlock(d))return;let k=new Map;if(d.statements.forEach(F=>{let{line:X}=S.sourceFile.getLineAndCharacterOfPosition(F.getStart());k.set(X,(k.get(X)??0)+1)}),d.statements.length<=k.size)return;let T=[...k.entries()].filter(([,F])=>F>1).map(([F])=>F).sort((F,X)=>F-X)[0]??S.sourceFile.getLineAndCharacterOfPosition(d.getStart()).line;S.violations.push({ruleId:S.rule.id,name:S.rule.name,severity:S.rule.severity,message:this.formatMessage(S.rule.message,{line:T+1}),file:S.file,line:T+1})}static checkRedundantIfTrue(d,S){if(!va.isIfStatement(d))return;let k=d.expression;if(!(k.kind===va.SyntaxKind.TrueKeyword||va.isBinaryExpression(k)&&k.left.kind===va.SyntaxKind.TrueKeyword&&k.operatorToken.kind===va.SyntaxKind.EqualsEqualsEqualsToken))return;let{line:T}=S.sourceFile.getLineAndCharacterOfPosition(d.getStart());S.violations.push({ruleId:S.rule.id,name:S.rule.name,severity:S.rule.severity,message:this.formatMessage(S.rule.message,{line:T+1}),file:S.file,line:T+1})}static checkLyingFunctionName(d,S){var Pe,Be;if(!va.isFunctionDeclaration(d)&&!va.isMethodDeclaration(d))return;let k=(Pe=d.name)==null?void 0:Pe.getText();if(!k||!new RegExp("^(get|is|has|retrieve)","i").test(k))return;let T=(Be=d.body)==null?void 0:Be.getText();if(!T)return;let F=/\bthis\.[\w.]*\.(?:set|delete|remove|update|write|modify|pop|push|shift|unshift|splice|clear|add|sort|reverse)\s*\(/,X=/\bObject\.assign\s*\(\s*this\b|\bdelete\s+this\./;if(!F.test(T)&&!z3t(d.body)&&!X.test(T))return;let{line:be}=S.sourceFile.getLineAndCharacterOfPosition(d.getStart());S.violations.push({ruleId:S.rule.id,name:S.rule.name,severity:S.rule.severity,message:this.formatMessage(S.rule.message,{name:k,line:be+1}),file:S.file,line:be+1})}static checkByCounting(d,S,k){let{rule:m,file:T,threshold:F}=k;if(d==="empty-file"&&S.trim().length===0)return[{ruleId:m.id,name:m.name,severity:m.severity,message:this.formatMessage(m.message,{file:T,line:0}),file:T,line:0}];if(d==="file-length-limit"&&F){let X=V3t(S,K5(T));if(X>F)return[{ruleId:m.id,name:m.name,severity:m.severity,message:this.formatMessage(m.message,{threshold:F,count:X}),file:T,line:0}]}return[]}static checkEmptyInterface(d,S){if(!va.isInterfaceDeclaration(d)||d.members.length>0||d.heritageClauses&&d.heritageClauses.length>0)return;let{line:k}=S.sourceFile.getLineAndCharacterOfPosition(d.getStart());S.violations.push({ruleId:S.rule.id,name:S.rule.name,severity:S.rule.severity,message:this.formatMessage(S.rule.message,{line:k+1}),file:S.file,line:k+1})}static checkAsyncWithoutAwait(d,S){let k=qHe(d);if(!k)return;let m=va.canHaveModifiers(d)?va.getModifiers(d):void 0;if(!((m==null?void 0:m.some(X=>X.kind===va.SyntaxKind.AsyncKeyword))??!1)||va.isCallExpression(d.parent)&&d.parent.arguments.includes(d)||U3t(k))return;let{line:F}=S.sourceFile.getLineAndCharacterOfPosition(d.getStart());S.violations.push({ruleId:S.rule.id,name:S.rule.name,severity:S.rule.severity,message:this.formatMessage(S.rule.message,{line:F+1}),file:S.file,line:F+1})}static checkNestedBlocks(d,S,k){if(!lne(d))return;let m=0,T=(X,be)=>{m=Math.max(m,be),va.forEachChild(X,Pe=>{if(lne(Pe)){T(Pe,0);return}let at=!(va.isIfStatement(Pe)&&va.isIfStatement(X)&&X.elseStatement===Pe)&&(va.isIfStatement(Pe)||va.isForStatement(Pe)||va.isForOfStatement(Pe)||va.isForInStatement(Pe)||va.isWhileStatement(Pe)||va.isDoStatement(Pe)||va.isSwitchStatement(Pe)||va.isTryStatement(Pe));T(Pe,at?be+1:be)})};if(T(d,0),m<=S)return;let{line:F}=k.sourceFile.getLineAndCharacterOfPosition(d.getStart());k.violations.push({ruleId:k.rule.id,name:k.rule.name,severity:k.rule.severity,message:this.formatMessage(k.rule.message,{threshold:S,count:m,line:F+1}),file:k.file,line:F+1})}static traverse(d,S){S(d),va.forEachChild(d,k=>this.traverse(k,S))}static formatMessage(d,S){let k=d;for(let[m,T]of Object.entries(S))k=k.replace(new RegExp(`\\{${m}\\}`,"g"),String(T));return k}};var KHe=ly(require("fs"));var GHe=ly(require("dns")),W3t=ly(require("http")),q3t=ly(require("https")),X5=ly(require("net")),hB="ESLOPLESSBLOCKED";function HHe(u){return(u==null?void 0:u.code)===hB}function bCe(u){let d=u.replace(/^\[|\]$/g,"");if(X5.isIPv4(d)){let[T,F]=d.split(".").map(Number);return T===0||T===10||T===127||T===169&&F===254||T===172&&F>=16&&F<=31||T===192&&F===168||T===100&&F>=64&&F<=127||T===192&&F===0||T===198&&(F===18||F===19)||T===198&&F===51||T===203&&F===0||T>=224}if(!X5.isIPv6(d))return!0;let S=G3t(d);if(!S||S.every(T=>T===0)||S.slice(0,7).every(T=>T===0)&&S[7]===1)return!0;let k=S.slice(0,5).every(T=>T===0)&&S[5]===65535,m=S[0]===100&&S[1]===65435&&S.slice(2,6).every(T=>T===0);if(k||m){let T=[S[6]>>8,S[6]&255,S[7]>>8,S[7]&255].join(".");return bCe(T)}return(S[0]&65472)===65152||(S[0]&65024)===64512||(S[0]&65280)===65280||S[0]===8193&&S[1]===3512}function G3t(u){let[d,S,...k]=u.toLowerCase().split("::");if(k.length)return null;let m=be=>be?be.split(":").map(Pe=>parseInt(Pe,16)):[],T=m(d),F=S===void 0?[]:m(S),X=S===void 0?T:[...T,...new Array(8-T.length-F.length).fill(0),...F];return X.length===8&&X.every(be=>Number.isInteger(be)&&be>=0&&be<=65535)?X:null}var H3t=(u,d,S)=>{GHe.lookup(u,d,(k,m,T)=>{if(k)return S(k);let X=(Array.isArray(m)?m:[{address:m,family:T}]).find(be=>bCe(be.address));if(X){let be=new Error(`${u} resolves to ${X.address}, which is not a public address`);return be.code=hB,S(be)}S(null,m,T)})};function ZHe(u,d,S){return new Promise((k,m)=>{let T;try{T=new URL(u)}catch{let Pe=new Error(`not a URL: ${u}`);return Pe.code=hB,m(Pe)}if(T.protocol!=="http:"&&T.protocol!=="https:"){let Pe=new Error(`refusing ${T.protocol}`);return Pe.code=hB,m(Pe)}let F=T.hostname.replace(/^\[|\]$/g,"");if(X5.isIP(F)&&bCe(F)){let Pe=new Error(`${F} is not a public address`);return Pe.code=hB,m(Pe)}let be=(T.protocol==="https:"?q3t:W3t).request(T,{method:d,lookup:H3t,timeout:S,headers:{"user-agent":"slopless (+https://github.com/fabriziosalmi/slopless)"}},Pe=>{Pe.resume(),k(Pe.statusCode??0)});be.on("timeout",()=>{let Pe=new Error("timed out");Pe.code="ETIMEDOUT",be.destroy(Pe)}),be.on("error",m),be.end()})}var _ne=class{static async check(d,S,k){let m=[],T=k!==void 0?k:KHe.readFileSync(d,"utf8");for(let F of S)WE(d,F)||(F.match.heuristic_check==="link-checker"&&d.endsWith(".md")&&m.push(...await this.findBrokenLinks(d,T,F)),F.match.heuristic_check==="stale-copyright-year"&&m.push(...this.findStaleCopyright(d,T,F)));return m}static findStaleCopyright(d,S,k){let m=[],T=new Date().getFullYear(),F=/(?:©|\(c\)|copyright)\s*((?:19|20)\d{2})(?:\s*[-–—]\s*((?:19|20)?\d{2}|present|\$?\{|<%))?/gi;return S.split(`
|
|
520
520
|
`).forEach((X,be)=>{for(let Pe of X.matchAll(F)){let[,Be,at]=Pe;at&&(/present/i.test(at)||/^(?:\$?\{|<%)/.test(at))||Number(at?at.length===2?Be.slice(0,2)+at:at:Be)>=T||m.push({ruleId:k.id,name:k.name,severity:k.severity,message:k.message.replace("{line}",String(be+1)).replace("{match}",Pe[0]).replace("{year}",String(T)),file:d,line:be+1})}}),m}static async findBrokenLinks(d,S,k){let m=[];for(let T of this.extractLinks(S)){if(await this.checkLink(T)!=="broken")continue;let F=this.getLineNumber(S,T);m.push({ruleId:k.id,name:k.name,severity:k.severity,message:this.formatMessage(k.message,{url:T,match:T,line:F}),file:d,line:F})}return m}static extractLinks(d){let S=/\[.*?\]\((https?:\/\/.*?)\)/g,k=[],m;for(;(m=S.exec(d))!==null;)k.push(m[1]);return k}static async checkLink(d){for(let S of["HEAD","GET"])try{let k=await ZHe(d,S,5e3);if(k>=200&&k<400)return"ok";if(S==="GET")return k===404||k===410?"broken":"unknown"}catch(k){if(HHe(k))return"unknown";if(this.isUnknownHost(k))return"broken"}return"unknown"}static isUnknownHost(d){var m;let S=d,k=(S==null?void 0:S.code)??((m=S==null?void 0:S.cause)==null?void 0:m.code);return k==="ENOTFOUND"||k==="EAI_AGAIN"}static getLineNumber(d,S){let k=d.indexOf(S);return k===-1?0:d.substring(0,k).split(`
|
|
521
|
-
`).length}static formatMessage(d,S){let k=d;for(let[m,T]of Object.entries(S))k=k.replace(new RegExp(`\\{${m}\\}`,"g"),String(T));return k}};var hp=ly(rne()),XHe=ly(require("fs"));var fne=class{static check(d,S,k){let m=[];if(!cne.has(K5(d)))return[];let T=k!==void 0?k:XHe.readFileSync(d,"utf8"),F=hp.createSourceFile(d,T,hp.ScriptTarget.Latest,!0);for(let X of S){if(!X.match.semantic_check||WE(d,X))continue;let be=X.match.semantic_check;this.traverse(F,Pe=>{if(be==="boolean-naming"&&hp.isVariableDeclaration(Pe)&&Pe.initializer){let Be=Pe.name.getText();if(this.isBooleanType(Pe)&&!new RegExp("^(is|has|can|should|was|did|do|will)","i").test(Be)){let{line:pe}=F.getLineAndCharacterOfPosition(Pe.getStart());m.push({ruleId:X.id,name:X.name,severity:X.severity,message:this.formatMessage(X.message,{name:Be,line:pe+1}),file:d,line:pe+1})}}if(be==="boolean-redundancy"&&hp.isIfStatement(Pe)){let Be=Pe.thenStatement,at=Pe.elseStatement;if(Be&&at&&this.isReturnBoolean(Be)&&this.isReturnBoolean(at)){let{line:pe}=F.getLineAndCharacterOfPosition(Pe.getStart());m.push({ruleId:X.id,name:X.name,severity:X.severity,message:this.formatMessage(X.message,{line:pe+1}),file:d,line:pe+1})}}if(be==="collection-suffix"&&hp.isVariableDeclaration(Pe)&&Pe.initializer){let Be=Pe.name.getText(),at=this.isArrayType(Pe),pe
|
|
521
|
+
`).length}static formatMessage(d,S){let k=d;for(let[m,T]of Object.entries(S))k=k.replace(new RegExp(`\\{${m}\\}`,"g"),String(T));return k}};var hp=ly(rne()),XHe=ly(require("fs"));var fne=class{static check(d,S,k){let m=[];if(!cne.has(K5(d)))return[];let T=k!==void 0?k:XHe.readFileSync(d,"utf8"),F=hp.createSourceFile(d,T,hp.ScriptTarget.Latest,!0);for(let X of S){if(!X.match.semantic_check||WE(d,X))continue;let be=X.match.semantic_check;this.traverse(F,Pe=>{if(be==="boolean-naming"&&hp.isVariableDeclaration(Pe)&&Pe.initializer){let Be=Pe.name.getText();if(this.isBooleanType(Pe)&&!new RegExp("^(is|has|can|should|was|did|do|will)","i").test(Be)){let{line:pe}=F.getLineAndCharacterOfPosition(Pe.getStart());m.push({ruleId:X.id,name:X.name,severity:X.severity,message:this.formatMessage(X.message,{name:Be,line:pe+1}),file:d,line:pe+1})}}if(be==="boolean-redundancy"&&hp.isIfStatement(Pe)){let Be=Pe.thenStatement,at=Pe.elseStatement;if(Be&&at&&this.isReturnBoolean(Be)&&this.isReturnBoolean(at)){let{line:pe}=F.getLineAndCharacterOfPosition(Pe.getStart());m.push({ruleId:X.id,name:X.name,severity:X.severity,message:this.formatMessage(X.message,{line:pe+1}),file:d,line:pe+1})}}if(be==="collection-suffix"&&hp.isVariableDeclaration(Pe)&&Pe.initializer){let Be=Pe.name.getText(),at=this.isArrayType(Pe),pe=!/s$/i.test(Be)&&!new RegExp("(List|Map|Set|Collection|Array)$","i").test(Be);if(at&&pe){let{line:Zt}=F.getLineAndCharacterOfPosition(Pe.getStart());m.push({ruleId:X.id,name:X.name,severity:X.severity,message:this.formatMessage(X.message,{name:Be,line:Zt+1}),file:d,line:Zt+1})}}if(be==="semantic-shadowing"&&hp.isVariableDeclaration(Pe)){let Be=Pe.name.getText();if(["fs","path","crypto","http","https","express","os","child_process","cluster","dns"].includes(Be)){let{line:pe}=F.getLineAndCharacterOfPosition(Pe.getStart());m.push({ruleId:X.id,name:X.name,severity:X.severity,message:this.formatMessage(X.message,{name:Be,line:pe+1,match:Be}),file:d,line:pe+1})}}})}return m}static traverse(d,S){S(d),hp.forEachChild(d,k=>this.traverse(k,S))}static formatMessage(d,S){let k=d;for(let[m,T]of Object.entries(S))k=k.replace(new RegExp(`\\{${m}\\}`,"g"),String(T));return k}static isBooleanType(d){var S,k,m;return((S=d.type)==null?void 0:S.kind)===hp.SyntaxKind.BooleanKeyword||((k=d.initializer)==null?void 0:k.kind)===hp.SyntaxKind.TrueKeyword||((m=d.initializer)==null?void 0:m.kind)===hp.SyntaxKind.FalseKeyword}static isArrayType(d){var S,k;return((S=d.type)==null?void 0:S.kind)===hp.SyntaxKind.ArrayType||((k=d.initializer)==null?void 0:k.kind)===hp.SyntaxKind.ArrayLiteralExpression}static isReturnBoolean(d){let S=d;return hp.isBlock(S)&&S.statements.length===1&&(S=S.statements[0]),hp.isReturnStatement(S)&&S.expression?S.expression.kind===hp.SyntaxKind.TrueKeyword||S.expression.kind===hp.SyntaxKind.FalseKeyword:!1}};function QHe(u,d){var m;let S=new Map;for(let T of d)(m=T.supersedes)!=null&&m.length&&S.set(T.id,T.supersedes);if(S.size===0)return u;let k=new Map;for(let T of u){let F=S.get(T.ruleId);if(!F)continue;let X=`${T.file}:${T.line}`,be=k.get(X);be||(be=new Set,k.set(X,be));for(let Pe of F)be.add(Pe)}return k.size===0?u:u.filter(T=>{var F;return!((F=k.get(`${T.file}:${T.line}`))!=null&&F.has(T.ruleId))})}var pne=ly(require("path")),Z3t=pne.join(__dirname,"..","..","rules");function YHe(u){let d=jUe(u),S=[Z3t];if(d.customRulesPaths)for(let T of d.customRulesPaths)S.push(pne.resolve(process.cwd(),T));let k=Yte.loadRules(S);d.rules&&(k=k.map(T=>{let F=d.rules[T.id];return F?{...T,severity:F}:T}).filter(T=>T.severity!=="off"));let m=new Set(Object.keys(d.rules??{}));return k.filter(T=>!T.opt_in||m.has(T.id))}async function K3t(u,d,S){let k=YHe(S),m=[];return m=m.concat(one.check(d,k,u)),m=m.concat(une.check(d,k,u)),m=m.concat(fne.check(d,k,u)),m=m.concat(await _ne.check(d,k,u)),QHe(m,k)}0&&(module.exports={lintText,resolveRules});
|
|
522
522
|
/*! Bundled license information:
|
|
523
523
|
|
|
524
524
|
typescript/lib/typescript.js:
|
package/dist/index.js
CHANGED
|
@@ -431,7 +431,7 @@ Project '${m.projectName}' (${yN[m.projectKind]}) ${o}
|
|
|
431
431
|
`,o++};this.projectService.externalProjects.forEach(u),this.projectService.configuredProjects.forEach(u),this.projectService.inferredProjects.forEach(u)}}this.logger.msg(s,"Err")}send(t){if(t.type==="event"&&!this.canUseEvents){this.logger.hasLevel(3)&&this.logger.info(`Session does not support events: ignored event: ${Kb(t)}`);return}this.writeMessage(t)}writeMessage(t){let n=Sve(t,this.logger,this.byteLength,this.host.newLine);this.host.write(n)}event(t,n){this.send(xve(n,t))}doOutput(t,n,i,s,o,u){let m={seq:0,type:"response",command:n,request_seq:i,success:s,performanceData:o&&n$e(o)};if(s){let p;if(Ps(t))m.body=t,p=t.metadata,delete t.metadata;else if(typeof t=="object")if(t.metadata){let{metadata:x,...b}=t;m.body=b,p=x}else m.body=t;else m.body=t;p&&(m.metadata=p)}else O.assert(t===void 0);u&&(m.message=u),this.send(m)}semanticCheck(t,n){var i,s;let o=Fo();(i=kn)==null||i.push(kn.Phase.Session,"semanticCheck",{file:t,configFilePath:n.canonicalConfigFilePath});let u=qje(n,t)?Yl:n.getLanguageService().getSemanticDiagnostics(t).filter(m=>!!m.file);this.sendDiagnosticsEvent(t,n,u,"semanticDiag",o),(s=kn)==null||s.pop()}syntacticCheck(t,n){var i,s;let o=Fo();(i=kn)==null||i.push(kn.Phase.Session,"syntacticCheck",{file:t,configFilePath:n.canonicalConfigFilePath}),this.sendDiagnosticsEvent(t,n,n.getLanguageService().getSyntacticDiagnostics(t),"syntaxDiag",o),(s=kn)==null||s.pop()}suggestionCheck(t,n){var i,s;let o=Fo();(i=kn)==null||i.push(kn.Phase.Session,"suggestionCheck",{file:t,configFilePath:n.canonicalConfigFilePath}),this.sendDiagnosticsEvent(t,n,n.getLanguageService().getSuggestionDiagnostics(t),"suggestionDiag",o),(s=kn)==null||s.pop()}regionSemanticCheck(t,n,i){var s,o,u;let m=Fo();(s=kn)==null||s.push(kn.Phase.Session,"regionSemanticCheck",{file:t,configFilePath:n.canonicalConfigFilePath});let p;if(!this.shouldDoRegionCheck(t)||!(p=n.getLanguageService().getRegionSemanticDiagnostics(t,i))){(o=kn)==null||o.pop();return}this.sendDiagnosticsEvent(t,n,p.diagnostics,"regionSemanticDiag",m,p.spans),(u=kn)==null||u.pop()}shouldDoRegionCheck(t){var n;let i=(n=this.projectService.getScriptInfoForNormalizedPath(t))==null?void 0:n.textStorage.getLineInfo().getLineCount();return!!(i&&i>=this.regionDiagLineCountThreshold)}sendDiagnosticsEvent(t,n,i,s,o,u){try{let m=O.checkDefined(n.getScriptInfo(t)),p=Fo()-o,x={file:t,diagnostics:i.map(b=>Gje(t,n,b)),spans:u==null?void 0:u.map(b=>Tg(b,m))};this.event(x,s),this.addDiagnosticsPerformanceData(t,s,p)}catch(m){this.logError(m,s)}}updateErrorCheck(t,n,i,s=!0){if(n.length===0)return;O.assert(!this.suppressDiagnosticEvents);let o=this.changeSeq,u=Math.min(i,200),m=0,p=()=>{if(m++,n.length>m)return t.delay("checkOne",u,b)},x=(T,E)=>{if(this.semanticCheck(T,E),this.changeSeq===o){if(this.getPreferences(T).disableSuggestions)return p();t.immediate("suggestionCheck",()=>{this.suggestionCheck(T,E),p()})}},b=()=>{if(this.changeSeq!==o)return;let T,E=n[m];if(zs(E)?E=this.toPendingErrorCheck(E):"ranges"in E&&(T=E.ranges,E=this.toPendingErrorCheck(E.file)),!E)return p();let{fileName:P,project:N}=E;if($d(N),!!N.containsFile(P,s)&&(this.syntacticCheck(P,N),this.changeSeq===o)){if(N.projectService.serverMode!==0)return p();if(T)return t.immediate("regionSemanticCheck",()=>{let F=this.projectService.getScriptInfoForNormalizedPath(P);F&&this.regionSemanticCheck(P,N,T.map(M=>this.getRange({file:P,...M},F))),this.changeSeq===o&&t.immediate("semanticCheck",()=>x(P,N))});t.immediate("semanticCheck",()=>x(P,N))}};n.length>m&&this.changeSeq===o&&t.delay("checkOne",i,b)}cleanProjects(t,n){if(n){this.logger.info(`cleaning ${t}`);for(let i of n)i.getLanguageService(!1).cleanupSemanticCache(),i.cleanupProgram()}}cleanup(){this.cleanProjects("inferred projects",this.projectService.inferredProjects),this.cleanProjects("configured projects",Es(this.projectService.configuredProjects.values())),this.cleanProjects("external projects",this.projectService.externalProjects),this.host.gc&&(this.logger.info("host.gc()"),this.host.gc())}getEncodedSyntacticClassifications(t){let{file:n,languageService:i}=this.getFileAndLanguageServiceForSyntacticOperation(t);return i.getEncodedSyntacticClassifications(n,t)}getEncodedSemanticClassifications(t){let{file:n,project:i}=this.getFileAndProject(t),s=t.format==="2020"?"2020":"original";return i.getLanguageService().getEncodedSemanticClassifications(n,t,s)}getProject(t){return t===void 0?void 0:this.projectService.findProject(t)}getConfigFileAndProject(t){let n=this.getProject(t.projectFileName),i=Po(t.file);return{configFile:n&&n.hasConfigFile(i)?i:void 0,project:n}}getConfigFileDiagnostics(t,n,i){let s=n.getAllProjectErrors(),o=n.getLanguageService().getCompilerOptionsDiagnostics(),u=Jn(os(s,o),m=>!!m.file&&m.file.fileName===t);return i?this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(u):Nr(u,m=>Z7(m,!1))}convertToDiagnosticsWithLinePositionFromDiagnosticFile(t){return t.map(n=>({message:yg(n.messageText,this.host.newLine),start:n.start,length:n.length,category:j2(n),code:n.code,source:n.source,startLocation:n.file&&v6(oa(n.file,n.start)),endLocation:n.file&&v6(oa(n.file,n.start+n.length)),reportsUnnecessary:n.reportsUnnecessary,reportsDeprecated:n.reportsDeprecated,relatedInformation:Nr(n.relatedInformation,XQ)}))}getCompilerOptionsDiagnostics(t){let n=this.getProject(t.projectFileName);return this.convertToDiagnosticsWithLinePosition(Jn(n.getLanguageService().getCompilerOptionsDiagnostics(),i=>!i.file),void 0)}convertToDiagnosticsWithLinePosition(t,n){return t.map(i=>({message:yg(i.messageText,this.host.newLine),start:i.start,length:i.length,category:j2(i),code:i.code,source:i.source,startLocation:n&&n.positionToLineOffset(i.start),endLocation:n&&n.positionToLineOffset(i.start+i.length),reportsUnnecessary:i.reportsUnnecessary,reportsDeprecated:i.reportsDeprecated,relatedInformation:Nr(i.relatedInformation,XQ)}))}getDiagnosticsWorker(t,n,i,s){let{project:o,file:u}=this.getFileAndProject(t);if(n&&qje(o,u))return Yl;let m=o.getScriptInfoForNormalizedPath(u),p=i(o,u);return s?this.convertToDiagnosticsWithLinePosition(p,m):p.map(x=>Gje(u,o,x))}getDefinition(t,n){let{file:i,project:s}=this.getFileAndProject(t),o=this.getPositionInFile(t,i),u=this.mapDefinitionInfoLocations(s.getLanguageService().getDefinitionAtPosition(i,o)||Yl,s);return n?this.mapDefinitionInfo(u,s):u.map(Hne.mapToOriginalLocation)}mapDefinitionInfoLocations(t,n){return t.map(i=>{let s=e$e(i,n);return s?{...s,containerKind:i.containerKind,containerName:i.containerName,kind:i.kind,name:i.name,failedAliasResolution:i.failedAliasResolution,...i.unverified&&{unverified:i.unverified}}:i})}getDefinitionAndBoundSpan(t,n){let{file:i,project:s}=this.getFileAndProject(t),o=this.getPositionInFile(t,i),u=O.checkDefined(s.getScriptInfo(i)),m=s.getLanguageService().getDefinitionAndBoundSpan(i,o);if(!m||!m.definitions)return{definitions:Yl,textSpan:void 0};let p=this.mapDefinitionInfoLocations(m.definitions,s),{textSpan:x}=m;return n?{definitions:this.mapDefinitionInfo(p,s),textSpan:Tg(x,u)}:{definitions:p.map(Hne.mapToOriginalLocation),textSpan:x}}findSourceDefinition(t){var n;let{file:i,project:s}=this.getFileAndProject(t),o=this.getPositionInFile(t,i),u=s.getLanguageService().getDefinitionAtPosition(i,o),m=this.mapDefinitionInfoLocations(u||Yl,s).slice();if(this.projectService.serverMode===0&&(!St(m,P=>Po(P.fileName)!==i&&!P.isAmbient)||St(m,P=>!!P.failedAliasResolution))){let P=YJ(j=>j.textSpan.start,_K(this.host.useCaseSensitiveFileNames));m==null||m.forEach(j=>P.add(j));let N=s.getNoDtsResolutionProject(i),F=N.getLanguageService(),M=(n=F.getDefinitionAtPosition(i,o,!0,!1))==null?void 0:n.filter(j=>Po(j.fileName)!==i);if(St(M))for(let j of M){if(j.unverified){let U=T(j,s.getLanguageService().getProgram(),F.getProgram());if(St(U)){for(let J of U)P.add(J);continue}}P.add(j)}else{let j=m.filter(U=>Po(U.fileName)!==i&&U.isAmbient);for(let U of St(j)?j:b()){let J=x(U.fileName,i,N);if(!J)continue;let q=this.projectService.getOrCreateScriptInfoNotOpenedByClient(J,N.currentDirectory,N.directoryStructureHost,!1);if(!q)continue;N.containsScriptInfo(q)||(N.addRoot(q),N.updateGraph());let H=F.getProgram(),te=O.checkDefined(H.getSourceFile(J));for(let ie of E(U.name,te,H))P.add(ie)}}m=Es(P.values())}return m=m.filter(P=>!P.isAmbient&&!P.failedAliasResolution),this.mapDefinitionInfo(m,s);function x(P,N,F){var M,j,U;let J=gM(P);if(J&&P.lastIndexOf(qh)===J.topLevelNodeModulesIndex){let q=P.substring(0,J.packageRootIndex),H=(M=s.getModuleResolutionCache())==null?void 0:M.getPackageJsonInfoCache(),te=s.getCompilationSettings(),ie=k4(ys(q,s.getCurrentDirectory()),T4(H,s,te));if(!ie)return;let X=OG(ie,{moduleResolution:2},s,s.getModuleResolutionCache()),Te=P.substring(J.topLevelPackageNameIndex+1,J.packageRootIndex),ue=C4(yO(Te)),Q=s.toPath(P);if(X&&St(X,ye=>s.toPath(ye)===Q))return(j=F.resolutionCache.resolveSingleModuleNameWithoutWatching(ue,N).resolvedModule)==null?void 0:j.resolvedFileName;{let ye=P.substring(J.packageRootIndex+1),he=`${ue}/${N_(ye)}`;return(U=F.resolutionCache.resolveSingleModuleNameWithoutWatching(he,N).resolvedModule)==null?void 0:U.resolvedFileName}}}function b(){let P=s.getLanguageService(),N=P.getProgram(),F=mf(N.getSourceFile(i),o);return(lo(F)||Ke(F))&&Zo(F.parent)&&wce(F,M=>{var j;if(M===F)return;let U=(j=P.getDefinitionAtPosition(i,M.getStart(),!0,!1))==null?void 0:j.filter(J=>Po(J.fileName)!==i&&J.isAmbient).map(J=>({fileName:J.fileName,name:Xp(F)}));if(St(U))return U})||Yl}function T(P,N,F){var M;let j=F.getSourceFile(P.fileName);if(!j)return;let U=mf(N.getSourceFile(i),o),J=N.getTypeChecker().getSymbolAtLocation(U),q=J&&oc(J,277);if(!q)return;let H=((M=q.propertyName)==null?void 0:M.text)||q.name.text;return E(H,j,F)}function E(P,N,F){let M=Xo.Core.getTopMostDeclarationNamesInFile(P,N);return rs(M,j=>{let U=F.getTypeChecker().getSymbolAtLocation(j),J=SI(j);if(U&&J)return d6.createDefinitionInfo(J,F.getTypeChecker(),U,J,!0)})}}getEmitOutput(t){let{file:n,project:i}=this.getFileAndProject(t);if(!i.shouldEmitFile(i.getScriptInfo(n)))return{emitSkipped:!0,outputFiles:[],diagnostics:[]};let s=i.getLanguageService().getEmitOutput(n);return t.richResponse?{...s,diagnostics:t.includeLinePosition?this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(s.diagnostics):s.diagnostics.map(o=>Z7(o,!0))}:s}mapJSDocTagInfo(t,n,i){return t?t.map(s=>{var o;return{...s,text:i?this.mapDisplayParts(s.text,n):(o=s.text)==null?void 0:o.map(u=>u.text).join("")}}):[]}mapDisplayParts(t,n){return t?t.map(i=>i.kind!=="linkName"?i:{...i,target:this.toFileSpan(i.target.fileName,i.target.textSpan,n)}):[]}mapSignatureHelpItems(t,n,i){return t.map(s=>({...s,documentation:this.mapDisplayParts(s.documentation,n),parameters:s.parameters.map(o=>({...o,documentation:this.mapDisplayParts(o.documentation,n)})),tags:this.mapJSDocTagInfo(s.tags,n,i)}))}mapDefinitionInfo(t,n){return t.map(i=>({...this.toFileSpanWithContext(i.fileName,i.textSpan,i.contextSpan,n),...i.unverified&&{unverified:i.unverified}}))}static mapToOriginalLocation(t){return t.originalFileName?(O.assert(t.originalTextSpan!==void 0,"originalTextSpan should be present if originalFileName is"),{...t,fileName:t.originalFileName,textSpan:t.originalTextSpan,targetFileName:t.fileName,targetTextSpan:t.textSpan,contextSpan:t.originalContextSpan,targetContextSpan:t.contextSpan}):t}toFileSpan(t,n,i){let s=i.getLanguageService(),o=s.toLineColumnOffset(t,n.start),u=s.toLineColumnOffset(t,Pc(n));return{file:t,start:{line:o.line+1,offset:o.character+1},end:{line:u.line+1,offset:u.character+1}}}toFileSpanWithContext(t,n,i,s){let o=this.toFileSpan(t,n,s),u=i&&this.toFileSpan(t,i,s);return u?{...o,contextStart:u.start,contextEnd:u.end}:o}getTypeDefinition(t){let{file:n,project:i}=this.getFileAndProject(t),s=this.getPositionInFile(t,n),o=this.mapDefinitionInfoLocations(i.getLanguageService().getTypeDefinitionAtPosition(n,s)||Yl,i);return this.mapDefinitionInfo(o,i)}mapImplementationLocations(t,n){return t.map(i=>{let s=e$e(i,n);return s?{...s,kind:i.kind,displayParts:i.displayParts}:i})}getImplementation(t,n){let{file:i,project:s}=this.getFileAndProject(t),o=this.getPositionInFile(t,i),u=this.mapImplementationLocations(s.getLanguageService().getImplementationAtPosition(i,o)||Yl,s);return n?u.map(({fileName:m,textSpan:p,contextSpan:x})=>this.toFileSpanWithContext(m,p,x,s)):u.map(Hne.mapToOriginalLocation)}getSyntacticDiagnosticsSync(t){let{configFile:n}=this.getConfigFileAndProject(t);return n?Yl:this.getDiagnosticsWorker(t,!1,(i,s)=>i.getLanguageService().getSyntacticDiagnostics(s),!!t.includeLinePosition)}getSemanticDiagnosticsSync(t){let{configFile:n,project:i}=this.getConfigFileAndProject(t);return n?this.getConfigFileDiagnostics(n,i,!!t.includeLinePosition):this.getDiagnosticsWorker(t,!0,(s,o)=>s.getLanguageService().getSemanticDiagnostics(o).filter(u=>!!u.file),!!t.includeLinePosition)}getSuggestionDiagnosticsSync(t){let{configFile:n}=this.getConfigFileAndProject(t);return n?Yl:this.getDiagnosticsWorker(t,!0,(i,s)=>i.getLanguageService().getSuggestionDiagnostics(s),!!t.includeLinePosition)}getJsxClosingTag(t){let{file:n,languageService:i}=this.getFileAndLanguageServiceForSyntacticOperation(t),s=this.getPositionInFile(t,n),o=i.getJsxClosingTagAtPosition(n,s);return o===void 0?void 0:{newText:o.newText,caretOffset:0}}getLinkedEditingRange(t){let{file:n,languageService:i}=this.getFileAndLanguageServiceForSyntacticOperation(t),s=this.getPositionInFile(t,n),o=i.getLinkedEditingRangeAtPosition(n,s),u=this.projectService.getScriptInfoForNormalizedPath(n);if(!(u===void 0||o===void 0))return E1t(o,u)}getDocumentHighlights(t,n){let{file:i,project:s}=this.getFileAndProject(t),o=this.getPositionInFile(t,i),u=s.getLanguageService().getDocumentHighlights(i,o,t.filesToSearch);return u?n?u.map(({fileName:m,highlightSpans:p})=>{let x=s.getScriptInfo(m);return{file:m,highlightSpans:p.map(({textSpan:b,kind:T,contextSpan:E})=>({...kve(b,E,x),kind:T}))}}):u:Yl}provideInlayHints(t){let{file:n,project:i}=this.getFileAndProject(t),s=this.projectService.getScriptInfoForNormalizedPath(n);return i.getLanguageService().provideInlayHints(n,t,this.getPreferences(n)).map(u=>{let{position:m,displayParts:p}=u;return{...u,position:s.positionToLineOffset(m),displayParts:p==null?void 0:p.map(({text:x,span:b,file:T})=>{if(b){O.assertIsDefined(T,"Target file should be defined together with its span.");let E=this.projectService.getScriptInfo(T);return{text:x,span:{start:E.positionToLineOffset(b.start),end:E.positionToLineOffset(b.start+b.length),file:T}}}else return{text:x}})}})}mapCode(t){var n;let i=this.getHostFormatOptions(),s=this.getHostPreferences(),{file:o,languageService:u}=this.getFileAndLanguageServiceForSyntacticOperation(t),m=this.projectService.getScriptInfoForNormalizedPath(o),p=(n=t.mapping.focusLocations)==null?void 0:n.map(b=>b.map(T=>{let E=m.lineOffsetToPosition(T.start.line,T.start.offset),P=m.lineOffsetToPosition(T.end.line,T.end.offset);return{start:E,length:P-E}})),x=u.mapCode(o,t.mapping.contents,p,i,s);return this.mapTextChangesToCodeEdits(x)}getCopilotRelatedInfo(){return{relatedFiles:[]}}setCompilerOptionsForInferredProjects(t){this.projectService.setCompilerOptionsForInferredProjects(t.options,t.projectRootPath)}getProjectInfo(t){return this.getProjectInfoWorker(t.file,t.projectFileName,t.needFileNameList,t.needDefaultConfiguredProjectInfo,!1)}getProjectInfoWorker(t,n,i,s,o){let{project:u}=this.getFileAndProjectWorker(t,n);return $d(u),{configFileName:u.getProjectName(),languageServiceDisabled:!u.languageServiceEnabled,fileNames:i?u.getFileNames(!1,o):void 0,configuredProjectInfo:s?this.getDefaultConfiguredProjectInfo(t):void 0}}getDefaultConfiguredProjectInfo(t){var n;let i=this.projectService.getScriptInfo(t);if(!i)return;let s=this.projectService.findDefaultConfiguredProjectWorker(i,3);if(!s)return;let o,u;return s.seenProjects.forEach((m,p)=>{p!==s.defaultProject&&(m!==3?(o??(o=[])).push(Po(p.getConfigFilePath())):(u??(u=[])).push(Po(p.getConfigFilePath())))}),(n=s.seenConfigs)==null||n.forEach(m=>(o??(o=[])).push(m)),{notMatchedByConfig:o,notInProject:u,defaultProject:s.defaultProject&&Po(s.defaultProject.getConfigFilePath())}}getRenameInfo(t){let{file:n,project:i}=this.getFileAndProject(t),s=this.getPositionInFile(t,n),o=this.getPreferences(n);return i.getLanguageService().getRenameInfo(n,s,o)}getProjects(t,n,i){let s,o;if(t.projectFileName){let u=this.getProject(t.projectFileName);u&&(s=[u])}else{let u=n?this.projectService.getScriptInfoEnsuringProjectsUptoDate(t.file):this.projectService.getScriptInfo(t.file);if(u)n||this.projectService.ensureDefaultProjectForFile(u);else return i?Yl:(this.projectService.logErrorForScriptInfoNotFound(t.file),Wy.ThrowNoProject());s=u.containingProjects,o=this.projectService.getSymlinkedProjects(u)}return s=Jn(s,u=>u.languageServiceEnabled&&!u.isOrphan()),!i&&(!s||!s.length)&&!o?(this.projectService.logErrorForScriptInfoNotFound(t.file??t.projectFileName),Wy.ThrowNoProject()):o?{projects:s,symLinkedProjects:o}:s}getDefaultProject(t){if(t.projectFileName){let i=this.getProject(t.projectFileName);if(i)return i;if(!t.file)return Wy.ThrowNoProject()}return this.projectService.getScriptInfo(t.file).getDefaultProject()}getRenameLocations(t,n){let i=Po(t.file),s=this.getPositionInFile(t,i),o=this.getProjects(t),u=this.getDefaultProject(t),m=this.getPreferences(i),p=this.mapRenameInfo(u.getLanguageService().getRenameInfo(i,s,m),O.checkDefined(this.projectService.getScriptInfo(i)));if(!p.canRename)return n?{info:p,locs:[]}:[];let x=S1t(o,u,{fileName:t.file,pos:s},!!t.findInStrings,!!t.findInComments,m,this.host.useCaseSensitiveFileNames);return n?{info:p,locs:this.toSpanGroups(x)}:x}mapRenameInfo(t,n){if(t.canRename){let{canRename:i,fileToRename:s,displayName:o,fullDisplayName:u,kind:m,kindModifiers:p,triggerSpan:x}=t;return{canRename:i,fileToRename:s,displayName:o,fullDisplayName:u,kind:m,kindModifiers:p,triggerSpan:Tg(x,n)}}else return t}toSpanGroups(t){let n=new Map;for(let{fileName:i,textSpan:s,contextSpan:o,originalContextSpan:u,originalTextSpan:m,originalFileName:p,...x}of t){let b=n.get(i);b||n.set(i,b={file:i,locs:[]});let T=O.checkDefined(this.projectService.getScriptInfo(i));b.locs.push({...kve(s,o,T),...x})}return Es(n.values())}getReferences(t,n){let i=Po(t.file),s=this.getProjects(t),o=this.getPositionInFile(t,i),u=x1t(s,this.getDefaultProject(t),{fileName:t.file,pos:o},this.host.useCaseSensitiveFileNames,this.logger);if(!n)return u;let m=this.getPreferences(i),p=this.getDefaultProject(t),x=p.getScriptInfoForNormalizedPath(i),b=p.getLanguageService().getQuickInfoAtPosition(i,o),T=b?v7(b.displayParts):"",E=b&&b.textSpan,P=E?x.positionToLineOffset(E.start).offset:0,N=E?x.getSnapshot().getText(E.start,Pc(E)):"";return{refs:Ha(u,M=>M.references.map(j=>s$e(this.projectService,j,m))),symbolName:N,symbolStartOffset:P,symbolDisplayString:T}}getFileReferences(t,n){let i=this.getProjects(t),s=Po(t.file),o=this.getPreferences(s),u={fileName:s,pos:0},m=Tve(i,this.getDefaultProject(t),u,u,Xje,b=>(this.logger.info(`Finding references to file ${s} in project ${b.getProjectName()}`),b.getLanguageService().getFileReferences(s))),p;if(Ps(m))p=m;else{p=[];let b=QQ(this.host.useCaseSensitiveFileNames);m.forEach(T=>{for(let E of T)b.has(E)||(p.push(E),b.add(E))})}return n?{refs:p.map(b=>s$e(this.projectService,b,o)),symbolName:`"${t.file}"`}:p}openClientFile(t,n,i,s){this.projectService.openClientFileWithNormalizedPath(t,n,i,!1,s)}getPosition(t,n){return t.position!==void 0?t.position:n.lineOffsetToPosition(t.line,t.offset)}getPositionInFile(t,n){let i=this.projectService.getScriptInfoForNormalizedPath(n);return this.getPosition(t,i)}getFileAndProject(t){return this.getFileAndProjectWorker(t.file,t.projectFileName)}getFileAndLanguageServiceForSyntacticOperation(t){let{file:n,project:i}=this.getFileAndProject(t);return{file:n,languageService:i.getLanguageService(!1)}}getFileAndProjectWorker(t,n){let i=Po(t),s=this.getProject(n)||this.projectService.ensureDefaultProjectForFile(i);return{file:i,project:s}}getOutliningSpans(t,n){let{file:i,languageService:s}=this.getFileAndLanguageServiceForSyntacticOperation(t),o=s.getOutliningSpans(i);if(n){let u=this.projectService.getScriptInfoForNormalizedPath(i);return o.map(m=>({textSpan:Tg(m.textSpan,u),hintSpan:Tg(m.hintSpan,u),bannerText:m.bannerText,autoCollapse:m.autoCollapse,kind:m.kind}))}else return o}getTodoComments(t){let{file:n,project:i}=this.getFileAndProject(t);return i.getLanguageService().getTodoComments(n,t.descriptors)}getDocCommentTemplate(t){let{file:n,languageService:i}=this.getFileAndLanguageServiceForSyntacticOperation(t),s=this.getPositionInFile(t,n);return i.getDocCommentTemplateAtPosition(n,s,this.getPreferences(n),this.getFormatOptions(n))}getSpanOfEnclosingComment(t){let{file:n,languageService:i}=this.getFileAndLanguageServiceForSyntacticOperation(t),s=t.onlyMultiLine,o=this.getPositionInFile(t,n);return i.getSpanOfEnclosingComment(n,o,s)}getIndentation(t){let{file:n,languageService:i}=this.getFileAndLanguageServiceForSyntacticOperation(t),s=this.getPositionInFile(t,n),o=t.options?y6(t.options):this.getFormatOptions(n),u=i.getIndentationAtPosition(n,s,o);return{position:s,indentation:u}}getBreakpointStatement(t){let{file:n,languageService:i}=this.getFileAndLanguageServiceForSyntacticOperation(t),s=this.getPositionInFile(t,n);return i.getBreakpointStatementAtPosition(n,s)}getNameOrDottedNameSpan(t){let{file:n,languageService:i}=this.getFileAndLanguageServiceForSyntacticOperation(t),s=this.getPositionInFile(t,n);return i.getNameOrDottedNameSpan(n,s,s)}isValidBraceCompletion(t){let{file:n,languageService:i}=this.getFileAndLanguageServiceForSyntacticOperation(t),s=this.getPositionInFile(t,n);return i.isValidBraceCompletionAtPosition(n,s,t.openingBrace.charCodeAt(0))}getQuickInfoWorker(t,n){let{file:i,project:s}=this.getFileAndProject(t),o=this.projectService.getScriptInfoForNormalizedPath(i),u=this.getPreferences(i),m=s.getLanguageService().getQuickInfoAtPosition(i,this.getPosition(t,o),u.maximumHoverLength,t.verbosityLevel);if(!m)return;let p=!!u.displayPartsForJSDoc;if(n){let x=v7(m.displayParts);return{kind:m.kind,kindModifiers:m.kindModifiers,start:o.positionToLineOffset(m.textSpan.start),end:o.positionToLineOffset(Pc(m.textSpan)),displayString:x,documentation:p?this.mapDisplayParts(m.documentation,s):v7(m.documentation),tags:this.mapJSDocTagInfo(m.tags,s,p),canIncreaseVerbosityLevel:m.canIncreaseVerbosityLevel}}else return p?m:{...m,tags:this.mapJSDocTagInfo(m.tags,s,!1)}}getFormattingEditsForRange(t){let{file:n,languageService:i}=this.getFileAndLanguageServiceForSyntacticOperation(t),s=this.projectService.getScriptInfoForNormalizedPath(n),o=s.lineOffsetToPosition(t.line,t.offset),u=s.lineOffsetToPosition(t.endLine,t.endOffset),m=i.getFormattingEditsForRange(n,o,u,this.getFormatOptions(n));if(m)return m.map(p=>this.convertTextChangeToCodeEdit(p,s))}getFormattingEditsForRangeFull(t){let{file:n,languageService:i}=this.getFileAndLanguageServiceForSyntacticOperation(t),s=t.options?y6(t.options):this.getFormatOptions(n);return i.getFormattingEditsForRange(n,t.position,t.endPosition,s)}getFormattingEditsForDocumentFull(t){let{file:n,languageService:i}=this.getFileAndLanguageServiceForSyntacticOperation(t),s=t.options?y6(t.options):this.getFormatOptions(n);return i.getFormattingEditsForDocument(n,s)}getFormattingEditsAfterKeystrokeFull(t){let{file:n,languageService:i}=this.getFileAndLanguageServiceForSyntacticOperation(t),s=t.options?y6(t.options):this.getFormatOptions(n);return i.getFormattingEditsAfterKeystroke(n,t.position,t.key,s)}getFormattingEditsAfterKeystroke(t){let{file:n,languageService:i}=this.getFileAndLanguageServiceForSyntacticOperation(t),s=this.projectService.getScriptInfoForNormalizedPath(n),o=s.lineOffsetToPosition(t.line,t.offset),u=this.getFormatOptions(n),m=i.getFormattingEditsAfterKeystroke(n,o,t.key,u);if(t.key===`
|
|
432
432
|
`&&(!m||m.length===0||y1t(m,o))){let{lineText:p,absolutePosition:x}=s.textStorage.getAbsolutePositionAndLineText(t.line);if(p&&p.search("\\S")<0){let b=i.getIndentationAtPosition(n,o,u),T=0,E,P;for(E=0,P=p.length;E<P;E++)if(p.charAt(E)===" ")T++;else if(p.charAt(E)===" ")T+=u.tabSize;else break;if(b!==T){let N=x+E;m.push({span:al(x,N),newText:Ll.getIndentationString(b,u)})}}}if(m)return m.map(p=>({start:s.positionToLineOffset(p.span.start),end:s.positionToLineOffset(Pc(p.span)),newText:p.newText?p.newText:""}))}getCompletions(t,n){let{file:i,project:s}=this.getFileAndProject(t),o=this.projectService.getScriptInfoForNormalizedPath(i),u=this.getPosition(t,o),m=s.getLanguageService().getCompletionsAtPosition(i,u,{...sve(this.getPreferences(i)),triggerCharacter:t.triggerCharacter,triggerKind:t.triggerKind,includeExternalModuleExports:t.includeExternalModuleExports,includeInsertTextCompletions:t.includeInsertTextCompletions},s.projectService.getFormatCodeOptions(i));if(m===void 0)return;if(n==="completions-full")return m;let p=t.prefix||"",x=rs(m.entries,T=>{if(m.isMemberCompletion||us(T.name.toLowerCase(),p.toLowerCase())){let E=T.replacementSpan?Tg(T.replacementSpan,o):void 0;return{...T,replacementSpan:E,hasAction:T.hasAction||void 0,symbol:void 0}}});return n==="completions"?(m.metadata&&(x.metadata=m.metadata),x):{...m,optionalReplacementSpan:m.optionalReplacementSpan&&Tg(m.optionalReplacementSpan,o),entries:x}}getCompletionEntryDetails(t,n){let{file:i,project:s}=this.getFileAndProject(t),o=this.projectService.getScriptInfoForNormalizedPath(i),u=this.getPosition(t,o),m=s.projectService.getFormatCodeOptions(i),p=!!this.getPreferences(i).displayPartsForJSDoc,x=rs(t.entryNames,b=>{let{name:T,source:E,data:P}=typeof b=="string"?{name:b,source:void 0,data:void 0}:b;return s.getLanguageService().getCompletionEntryDetails(i,u,T,m,E,this.getPreferences(i),P?fa(P,A1t):void 0)});return n?p?x:x.map(b=>({...b,tags:this.mapJSDocTagInfo(b.tags,s,!1)})):x.map(b=>({...b,codeActions:Nr(b.codeActions,T=>this.mapCodeAction(T)),documentation:this.mapDisplayParts(b.documentation,s),tags:this.mapJSDocTagInfo(b.tags,s,p)}))}getCompileOnSaveAffectedFileList(t){let n=this.getProjects(t,!0,!0),i=this.projectService.getScriptInfo(t.file);return i?b1t(i,s=>this.projectService.getScriptInfoForPath(s),n,(s,o)=>{if(!s.compileOnSaveEnabled||!s.languageServiceEnabled||s.isOrphan())return;let u=s.getCompilationSettings();if(!(u.noEmit||_u(o.fileName)&&!h1t(u)))return{projectFileName:s.getProjectName(),fileNames:s.getCompileOnSaveAffectedFileList(o),projectUsesOutFile:!!u.outFile}}):Yl}emitFile(t){let{file:n,project:i}=this.getFileAndProject(t);if(i||Wy.ThrowNoProject(),!i.languageServiceEnabled)return t.richResponse?{emitSkipped:!0,diagnostics:[]}:!1;let s=i.getScriptInfo(n),{emitSkipped:o,diagnostics:u}=i.emitFile(s,(m,p,x)=>this.host.writeFile(m,p,x));return t.richResponse?{emitSkipped:o,diagnostics:t.includeLinePosition?this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(u):u.map(m=>Z7(m,!0))}:!o}getSignatureHelpItems(t,n){let{file:i,project:s}=this.getFileAndProject(t),o=this.projectService.getScriptInfoForNormalizedPath(i),u=this.getPosition(t,o),m=s.getLanguageService().getSignatureHelpItems(i,u,t),p=!!this.getPreferences(i).displayPartsForJSDoc;if(m&&n){let x=m.applicableSpan;return{...m,applicableSpan:{start:o.positionToLineOffset(x.start),end:o.positionToLineOffset(x.start+x.length)},items:this.mapSignatureHelpItems(m.items,s,p)}}else return p||!m?m:{...m,items:m.items.map(x=>({...x,tags:this.mapJSDocTagInfo(x.tags,s,!1)}))}}toPendingErrorCheck(t){let n=Po(t),i=this.projectService.tryGetDefaultProjectForFile(n);return i&&{fileName:n,project:i}}getDiagnostics(t,n,i){this.suppressDiagnosticEvents||i.length>0&&this.updateErrorCheck(t,i,n)}change(t){let n=this.projectService.getScriptInfo(t.file);O.assert(!!n),n.textStorage.switchToScriptVersionCache();let i=n.lineOffsetToPosition(t.line,t.offset),s=n.lineOffsetToPosition(t.endLine,t.endOffset);i>=0&&(this.changeSeq++,this.projectService.applyChangesToFile(n,lie({span:{start:i,length:s-i},newText:t.insertString})))}reload(t){let n=Po(t.file),i=t.tmpfile===void 0?void 0:Po(t.tmpfile),s=this.projectService.getScriptInfoForNormalizedPath(n);s&&(this.changeSeq++,s.reloadFromFile(i))}saveToTmp(t,n){let i=this.projectService.getScriptInfo(t);i&&i.saveTo(n)}closeClientFile(t){if(!t)return;let n=ma(t);this.projectService.closeClientFile(n)}mapLocationNavigationBarItems(t,n){return Nr(t,i=>({text:i.text,kind:i.kind,kindModifiers:i.kindModifiers,spans:i.spans.map(s=>Tg(s,n)),childItems:this.mapLocationNavigationBarItems(i.childItems,n),indent:i.indent}))}getNavigationBarItems(t,n){let{file:i,languageService:s}=this.getFileAndLanguageServiceForSyntacticOperation(t),o=s.getNavigationBarItems(i);return o?n?this.mapLocationNavigationBarItems(o,this.projectService.getScriptInfoForNormalizedPath(i)):o:void 0}toLocationNavigationTree(t,n){return{text:t.text,kind:t.kind,kindModifiers:t.kindModifiers,spans:t.spans.map(i=>Tg(i,n)),nameSpan:t.nameSpan&&Tg(t.nameSpan,n),childItems:Nr(t.childItems,i=>this.toLocationNavigationTree(i,n))}}getNavigationTree(t,n){let{file:i,languageService:s}=this.getFileAndLanguageServiceForSyntacticOperation(t),o=s.getNavigationTree(i);return o?n?this.toLocationNavigationTree(o,this.projectService.getScriptInfoForNormalizedPath(i)):o:void 0}getNavigateToItems(t,n){let i=this.getFullNavigateToItems(t);return n?Ha(i,({project:s,navigateToItems:o})=>o.map(u=>{let m=s.getScriptInfo(u.fileName),p={name:u.name,kind:u.kind,kindModifiers:u.kindModifiers,isCaseSensitive:u.isCaseSensitive,matchKind:u.matchKind,file:u.fileName,start:m.positionToLineOffset(u.textSpan.start),end:m.positionToLineOffset(Pc(u.textSpan))};return u.kindModifiers&&u.kindModifiers!==""&&(p.kindModifiers=u.kindModifiers),u.containerName&&u.containerName.length>0&&(p.containerName=u.containerName),u.containerKind&&u.containerKind.length>0&&(p.containerKind=u.containerKind),p})):Ha(i,({navigateToItems:s})=>s)}getFullNavigateToItems(t){let{currentFileOnly:n,searchValue:i,maxResultCount:s,projectFileName:o}=t;if(n){O.assertIsDefined(t.file);let{file:E,project:P}=this.getFileAndProject(t);return[{project:P,navigateToItems:P.getLanguageService().getNavigateToItems(i,s,E)}]}let u=this.getHostPreferences(),m=[],p=new Map;if(!t.file&&!o)this.projectService.loadAncestorProjectTree(),this.projectService.forEachEnabledProject(E=>x(E));else{let E=this.getProjects(t);Kje(E,void 0,P=>x(P))}return m;function x(E){let P=E.getLanguageService().getNavigateToItems(i,s,void 0,E.isNonTsProject(),u.excludeLibrarySymbolsInNavTo),N=Jn(P,F=>b(F)&&!YQ(vN(F),E));N.length&&m.push({project:E,navigateToItems:N})}function b(E){let P=E.name;if(!p.has(P))return p.set(P,[E]),!0;let N=p.get(P);for(let F of N)if(T(F,E))return!1;return N.push(E),!0}function T(E,P){return E===P?!0:!E||!P?!1:E.containerKind===P.containerKind&&E.containerName===P.containerName&&E.fileName===P.fileName&&E.isCaseSensitive===P.isCaseSensitive&&E.kind===P.kind&&E.kindModifiers===P.kindModifiers&&E.matchKind===P.matchKind&&E.name===P.name&&E.textSpan.start===P.textSpan.start&&E.textSpan.length===P.textSpan.length}}getSupportedCodeFixes(t){if(!t)return gX();if(t.file){let{file:i,project:s}=this.getFileAndProject(t);return s.getLanguageService().getSupportedCodeFixes(i)}let n=this.getProject(t.projectFileName);return n||Wy.ThrowNoProject(),n.getLanguageService().getSupportedCodeFixes()}isLocation(t){return t.line!==void 0}extractPositionOrRange(t,n){let i,s;return this.isLocation(t)?i=o(t):s=this.getRange(t,n),O.checkDefined(i===void 0?s:i);function o(u){return u.position!==void 0?u.position:n.lineOffsetToPosition(u.line,u.offset)}}getRange(t,n){let{startPosition:i,endPosition:s}=this.getStartAndEndPosition(t,n);return{pos:i,end:s}}getApplicableRefactors(t){let{file:n,project:i}=this.getFileAndProject(t),s=i.getScriptInfoForNormalizedPath(n);return i.getLanguageService().getApplicableRefactors(n,this.extractPositionOrRange(t,s),this.getPreferences(n),t.triggerReason,t.kind,t.includeInteractiveActions).map(u=>({...u,actions:u.actions.map(m=>({...m,range:m.range?{start:v6({line:m.range.start.line,character:m.range.start.offset}),end:v6({line:m.range.end.line,character:m.range.end.offset})}:void 0}))}))}getEditsForRefactor(t,n){let{file:i,project:s}=this.getFileAndProject(t),o=s.getScriptInfoForNormalizedPath(i),u=s.getLanguageService().getEditsForRefactor(i,this.getFormatOptions(i),this.extractPositionOrRange(t,o),t.refactor,t.action,this.getPreferences(i),t.interactiveRefactorArguments);if(u===void 0)return{edits:[]};if(n){let{renameFilename:m,renameLocation:p,edits:x}=u,b;if(m!==void 0&&p!==void 0){let T=s.getScriptInfoForNormalizedPath(Po(m));b=Cve(mw(T.getSnapshot()),m,p,x)}return{renameLocation:b,renameFilename:m,edits:this.mapTextChangesToCodeEdits(x),notApplicableReason:u.notApplicableReason}}return u}getMoveToRefactoringFileSuggestions(t){let{file:n,project:i}=this.getFileAndProject(t),s=i.getScriptInfoForNormalizedPath(n);return i.getLanguageService().getMoveToRefactoringFileSuggestions(n,this.extractPositionOrRange(t,s),this.getPreferences(n))}preparePasteEdits(t){let{file:n,project:i}=this.getFileAndProject(t);return i.getLanguageService().preparePasteEditsForFile(n,t.copiedTextSpan.map(s=>this.getRange({file:n,startLine:s.start.line,startOffset:s.start.offset,endLine:s.end.line,endOffset:s.end.offset},this.projectService.getScriptInfoForNormalizedPath(n))))}getPasteEdits(t){let{file:n,project:i}=this.getFileAndProject(t);if(hN(n))return;let s=t.copiedFrom?{file:t.copiedFrom.file,range:t.copiedFrom.spans.map(u=>this.getRange({file:t.copiedFrom.file,startLine:u.start.line,startOffset:u.start.offset,endLine:u.end.line,endOffset:u.end.offset},i.getScriptInfoForNormalizedPath(Po(t.copiedFrom.file))))}:void 0,o=i.getLanguageService().getPasteEdits({targetFile:n,pastedText:t.pastedText,pasteLocations:t.pasteLocations.map(u=>this.getRange({file:n,startLine:u.start.line,startOffset:u.start.offset,endLine:u.end.line,endOffset:u.end.offset},i.getScriptInfoForNormalizedPath(n))),copiedFrom:s,preferences:this.getPreferences(n)},this.getFormatOptions(n));return o&&this.mapPasteEditsAction(o)}organizeImports(t,n){O.assert(t.scope.type==="file");let{file:i,project:s}=this.getFileAndProject(t.scope.args),o=s.getLanguageService().organizeImports({fileName:i,mode:t.mode??(t.skipDestructiveCodeActions?"SortAndCombine":void 0),type:"file"},this.getFormatOptions(i),this.getPreferences(i));return n?this.mapTextChangesToCodeEdits(o):o}getEditsForFileRename(t,n){let i=Po(t.oldFilePath),s=Po(t.newFilePath),o=this.getHostFormatOptions(),u=this.getHostPreferences(),m=new Set,p=[];return this.projectService.loadAncestorProjectTree(),this.projectService.forEachEnabledProject(x=>{let b=x.getLanguageService().getEditsForFileRename(i,s,o,u),T=[];for(let E of b)m.has(E.fileName)||(p.push(E),T.push(E.fileName));for(let E of T)m.add(E)}),n?p.map(x=>this.mapTextChangeToCodeEdit(x)):p}getCodeFixes(t,n){let{file:i,project:s}=this.getFileAndProject(t),o=s.getScriptInfoForNormalizedPath(i),{startPosition:u,endPosition:m}=this.getStartAndEndPosition(t,o),p;try{p=s.getLanguageService().getCodeFixesAtPosition(i,u,m,t.errorCodes,this.getFormatOptions(i),this.getPreferences(i))}catch(x){let b=x instanceof Error?x:new Error(x),T=s.getLanguageService(),E=[...T.getSyntacticDiagnostics(i),...T.getSemanticDiagnostics(i),...T.getSuggestionDiagnostics(i)].filter(N=>c3(u,m-u,N.start,N.length)).map(N=>N.code),P=t.errorCodes.find(N=>!E.includes(N));throw P!==void 0&&(b.message+=`
|
|
433
433
|
Additional information: BADCLIENT: Bad error code, ${P} not found in range ${u}..${m} (found: ${E.join(", ")})`),b}return n?p.map(x=>this.mapCodeFixAction(x)):p}getCombinedCodeFix({scope:t,fixId:n},i){O.assert(t.type==="file");let{file:s,project:o}=this.getFileAndProject(t.args),u=o.getLanguageService().getCombinedCodeFix({type:"file",fileName:s},n,this.getFormatOptions(s),this.getPreferences(s));return i?{changes:this.mapTextChangesToCodeEdits(u.changes),commands:u.commands}:u}applyCodeActionCommand(t){let n=t.command;for(let i of Yk(n)){let{file:s,project:o}=this.getFileAndProject(i);o.getLanguageService().applyCodeActionCommand(i,this.getFormatOptions(s)).then(u=>{},u=>{})}return{}}getStartAndEndPosition(t,n){let i,s;return t.startPosition!==void 0?i=t.startPosition:(i=n.lineOffsetToPosition(t.startLine,t.startOffset),t.startPosition=i),t.endPosition!==void 0?s=t.endPosition:(s=n.lineOffsetToPosition(t.endLine,t.endOffset),t.endPosition=s),{startPosition:i,endPosition:s}}mapCodeAction({description:t,changes:n,commands:i}){return{description:t,changes:this.mapTextChangesToCodeEdits(n),commands:i}}mapCodeFixAction({fixName:t,description:n,changes:i,commands:s,fixId:o,fixAllDescription:u}){return{fixName:t,description:n,changes:this.mapTextChangesToCodeEdits(i),commands:s,fixId:o,fixAllDescription:u}}mapPasteEditsAction({edits:t,fixId:n}){return{edits:this.mapTextChangesToCodeEdits(t),fixId:n}}mapTextChangesToCodeEdits(t){return t.map(n=>this.mapTextChangeToCodeEdit(n))}mapTextChangeToCodeEdit(t){let n=this.projectService.getScriptInfoOrConfig(t.fileName);return!!t.isNewFile==!!n&&(n||this.projectService.logErrorForScriptInfoNotFound(t.fileName),O.fail("Expected isNewFile for (only) new files. "+JSON.stringify({isNewFile:!!t.isNewFile,hasScriptInfo:!!n}))),n?{fileName:t.fileName,textChanges:t.textChanges.map(i=>w1t(i,n))}:P1t(t)}convertTextChangeToCodeEdit(t,n){return{start:n.positionToLineOffset(t.span.start),end:n.positionToLineOffset(t.span.start+t.span.length),newText:t.newText?t.newText:""}}getBraceMatching(t,n){let{file:i,languageService:s}=this.getFileAndLanguageServiceForSyntacticOperation(t),o=this.projectService.getScriptInfoForNormalizedPath(i),u=this.getPosition(t,o),m=s.getBraceMatchingAtPosition(i,u);return m?n?m.map(p=>Tg(p,o)):m:void 0}getDiagnosticsForProject(t,n,i){if(this.suppressDiagnosticEvents)return;let{fileNames:s,languageServiceDisabled:o}=this.getProjectInfoWorker(i,void 0,!0,void 0,!0);if(o)return;let u=s.filter(F=>!F.includes("lib.d.ts"));if(u.length===0)return;let m=[],p=[],x=[],b=[],T=Po(i),E=this.projectService.ensureDefaultProjectForFile(T);for(let F of u)this.getCanonicalFileName(F)===this.getCanonicalFileName(i)?m.push(F):this.projectService.getScriptInfo(F).isScriptOpen()?p.push(F):_u(F)?b.push(F):x.push(F);let N=[...m,...p,...x,...b].map(F=>({fileName:F,project:E}));this.updateErrorCheck(t,N,n,!1)}configurePlugin(t){this.projectService.configurePlugin(t)}getSmartSelectionRange(t,n){let{locations:i}=t,{file:s,languageService:o}=this.getFileAndLanguageServiceForSyntacticOperation(t),u=O.checkDefined(this.projectService.getScriptInfo(s));return Nr(i,m=>{let p=this.getPosition(m,u),x=o.getSmartSelectionRange(s,p);return n?this.mapSelectionRange(x,u):x})}toggleLineComment(t,n){let{file:i,languageService:s}=this.getFileAndLanguageServiceForSyntacticOperation(t),o=this.projectService.getScriptInfo(i),u=this.getRange(t,o),m=s.toggleLineComment(i,u);if(n){let p=this.projectService.getScriptInfoForNormalizedPath(i);return m.map(x=>this.convertTextChangeToCodeEdit(x,p))}return m}toggleMultilineComment(t,n){let{file:i,languageService:s}=this.getFileAndLanguageServiceForSyntacticOperation(t),o=this.projectService.getScriptInfoForNormalizedPath(i),u=this.getRange(t,o),m=s.toggleMultilineComment(i,u);if(n){let p=this.projectService.getScriptInfoForNormalizedPath(i);return m.map(x=>this.convertTextChangeToCodeEdit(x,p))}return m}commentSelection(t,n){let{file:i,languageService:s}=this.getFileAndLanguageServiceForSyntacticOperation(t),o=this.projectService.getScriptInfoForNormalizedPath(i),u=this.getRange(t,o),m=s.commentSelection(i,u);if(n){let p=this.projectService.getScriptInfoForNormalizedPath(i);return m.map(x=>this.convertTextChangeToCodeEdit(x,p))}return m}uncommentSelection(t,n){let{file:i,languageService:s}=this.getFileAndLanguageServiceForSyntacticOperation(t),o=this.projectService.getScriptInfoForNormalizedPath(i),u=this.getRange(t,o),m=s.uncommentSelection(i,u);if(n){let p=this.projectService.getScriptInfoForNormalizedPath(i);return m.map(x=>this.convertTextChangeToCodeEdit(x,p))}return m}mapSelectionRange(t,n){let i={textSpan:Tg(t.textSpan,n)};return t.parent&&(i.parent=this.mapSelectionRange(t.parent,n)),i}getScriptInfoFromProjectService(t){let n=Po(t),i=this.projectService.getScriptInfoForNormalizedPath(n);return i||(this.projectService.logErrorForScriptInfoNotFound(n),Wy.ThrowNoProject())}toProtocolCallHierarchyItem(t){let n=this.getScriptInfoFromProjectService(t.file);return{name:t.name,kind:t.kind,kindModifiers:t.kindModifiers,file:t.file,containerName:t.containerName,span:Tg(t.span,n),selectionSpan:Tg(t.selectionSpan,n)}}toProtocolCallHierarchyIncomingCall(t){let n=this.getScriptInfoFromProjectService(t.from.file);return{from:this.toProtocolCallHierarchyItem(t.from),fromSpans:t.fromSpans.map(i=>Tg(i,n))}}toProtocolCallHierarchyOutgoingCall(t,n){return{to:this.toProtocolCallHierarchyItem(t.to),fromSpans:t.fromSpans.map(i=>Tg(i,n))}}prepareCallHierarchy(t){let{file:n,project:i}=this.getFileAndProject(t),s=this.projectService.getScriptInfoForNormalizedPath(n);if(s){let o=this.getPosition(t,s),u=i.getLanguageService().prepareCallHierarchy(n,o);return u&&wK(u,m=>this.toProtocolCallHierarchyItem(m))}}provideCallHierarchyIncomingCalls(t){let{file:n,project:i}=this.getFileAndProject(t),s=this.getScriptInfoFromProjectService(n);return i.getLanguageService().provideCallHierarchyIncomingCalls(n,this.getPosition(t,s)).map(u=>this.toProtocolCallHierarchyIncomingCall(u))}provideCallHierarchyOutgoingCalls(t){let{file:n,project:i}=this.getFileAndProject(t),s=this.getScriptInfoFromProjectService(n);return i.getLanguageService().provideCallHierarchyOutgoingCalls(n,this.getPosition(t,s)).map(u=>this.toProtocolCallHierarchyOutgoingCall(u,s))}getCanonicalFileName(t){let n=this.host.useCaseSensitiveFileNames?t:$v(t);return ma(n)}exit(){}notRequired(t){return t&&this.doOutput(void 0,t.command,t.seq,!0,this.performanceData),{responseRequired:!1,performanceData:this.performanceData}}requiredResponse(t){return{response:t,responseRequired:!0,performanceData:this.performanceData}}addProtocolHandler(t,n){if(this.handlers.has(t))throw new Error(`Protocol handler already exists for command "${t}"`);this.handlers.set(t,n)}setCurrentRequest(t){O.assert(this.currentRequestId===void 0),this.currentRequestId=t,this.cancellationToken.setRequest(t)}resetCurrentRequest(t){O.assert(this.currentRequestId===t),this.currentRequestId=void 0,this.cancellationToken.resetRequest(t)}executeWithRequestId(t,n,i){let s=this.performanceData;try{return this.performanceData=i,this.setCurrentRequest(t),n()}finally{this.resetCurrentRequest(t),this.performanceData=s}}executeCommand(t){let n=this.handlers.get(t.command);if(n){let i=this.executeWithRequestId(t.seq,()=>n(t),void 0);return this.projectService.enableRequestedPlugins(),i}else return this.logger.msg(`Unrecognized JSON command:${Kb(t)}`,"Err"),this.doOutput(void 0,"unknown",t.seq,!1,void 0,`Unrecognized JSON command: ${t.command}`),{responseRequired:!1}}onMessage(t){var n,i,s,o,u,m,p;this.gcTimer.scheduleCollect();let x,b=this.performanceData;this.logger.hasLevel(2)&&(x=this.hrtime(),this.logger.hasLevel(3)&&this.logger.info(`request:${U4(this.toStringMessage(t))}`));let T,E;try{T=this.parseMessage(t),E=T.arguments&&T.arguments.file?T.arguments:void 0,(n=kn)==null||n.instant(kn.Phase.Session,"request",{seq:T.seq,command:T.command}),(i=kn)==null||i.push(kn.Phase.Session,"executeCommand",{seq:T.seq,command:T.command},!0);let{response:P,responseRequired:N,performanceData:F}=this.executeCommand(T);if((s=kn)==null||s.pop(),this.logger.hasLevel(2)){let M=g1t(this.hrtime(x)).toFixed(4);N?this.logger.perftrc(`${T.seq}::${T.command}: elapsed time (in milliseconds) ${M}`):this.logger.perftrc(`${T.seq}::${T.command}: async elapsed time (in milliseconds) ${M}`)}(o=kn)==null||o.instant(kn.Phase.Session,"response",{seq:T.seq,command:T.command,success:!!P}),P?this.doOutput(P,T.command,T.seq,!0,F):N&&this.doOutput(void 0,T.command,T.seq,!1,F,"No content available.")}catch(P){if((u=kn)==null||u.popAll(),P instanceof $P){(m=kn)==null||m.instant(kn.Phase.Session,"commandCanceled",{seq:T==null?void 0:T.seq,command:T==null?void 0:T.command}),this.doOutput({canceled:!0},T.command,T.seq,!0,this.performanceData);return}this.logErrorWorker(P,this.toStringMessage(t),E),(p=kn)==null||p.instant(kn.Phase.Session,"commandError",{seq:T==null?void 0:T.seq,command:T==null?void 0:T.command,message:P.message}),this.doOutput(void 0,T?T.command:"unknown",T?T.seq:0,!1,this.performanceData,"Error processing request. "+P.message+`
|
|
434
|
-
`+P.stack)}finally{this.performanceData=b}}parseMessage(t){return JSON.parse(t)}toStringMessage(t){return t}getFormatOptions(t){return this.projectService.getFormatCodeOptions(t)}getPreferences(t){return this.projectService.getPreferences(t)}getHostFormatOptions(){return this.projectService.getHostFormatCodeOptions()}getHostPreferences(){return this.projectService.getHostPreferences()}};function n$e(e){let t=e.diagnosticsDuration&&Es(e.diagnosticsDuration,([n,i])=>({...i,file:n}));return{...e,diagnosticsDuration:t}}function Tg(e,t){return{start:t.positionToLineOffset(e.start),end:t.positionToLineOffset(Pc(e))}}function kve(e,t,n){let i=Tg(e,n),s=t&&Tg(t,n);return s?{...i,contextStart:s.start,contextEnd:s.end}:i}function w1t(e,t){return{start:i$e(t,e.span.start),end:i$e(t,Pc(e.span)),newText:e.newText}}function i$e(e,t){return hve(e)?D1t(e.getLineAndCharacterOfPosition(t)):e.positionToLineOffset(t)}function E1t(e,t){let n=e.ranges.map(i=>({start:t.positionToLineOffset(i.start),end:t.positionToLineOffset(i.start+i.length)}));return e.wordPattern?{ranges:n,wordPattern:e.wordPattern}:{ranges:n}}function D1t(e){return{line:e.line+1,offset:e.character+1}}function P1t(e){O.assert(e.textChanges.length===1);let t=Za(e.textChanges);return O.assert(t.span.start===0&&t.span.length===0),{fileName:e.fileName,textChanges:[{start:{line:0,offset:0},end:{line:0,offset:0},newText:t.newText}]}}function Cve(e,t,n,i){let s=I1t(e,t,i),{line:o,character:u}=FE(aC(s),n);return{line:o+1,offset:u+1}}function I1t(e,t,n){for(let{fileName:i,textChanges:s}of n)if(i===t)for(let o=s.length-1;o>=0;o--){let{newText:u,span:{start:m,length:p}}=s[o];e=e.slice(0,m)+u+e.slice(m+p)}return e}function s$e(e,{fileName:t,textSpan:n,contextSpan:i,isWriteAccess:s,isDefinition:o},{disableLineTextInReferences:u}){let m=O.checkDefined(e.getScriptInfo(t)),p=kve(n,i,m),x=u?void 0:N1t(m,p);return{file:t,...p,lineText:x,isWriteAccess:s,isDefinition:o}}function N1t(e,t){let n=e.lineToTextSpan(t.start.line-1);return e.getSnapshot().getText(n.start,Pc(n)).replace(/\r|\n/g,"")}function A1t(e){return e===void 0||e&&typeof e=="object"&&typeof e.exportName=="string"&&(e.fileName===void 0||typeof e.fileName=="string")&&(e.ambientModuleName===void 0||typeof e.ambientModuleName=="string"&&(e.isPackageJsonImport===void 0||typeof e.isPackageJsonImport=="boolean"))}var b6=4,wve=(e=>(e[e.PreStart=0]="PreStart",e[e.Start=1]="Start",e[e.Entire=2]="Entire",e[e.Mid=3]="Mid",e[e.End=4]="End",e[e.PostEnd=5]="PostEnd",e))(wve||{}),O1t=class{constructor(){this.goSubtree=!0,this.lineIndex=new K7,this.endBranch=[],this.state=2,this.initialText="",this.trailingText="",this.lineIndex.root=new S6,this.startPath=[this.lineIndex.root],this.stack=[this.lineIndex.root]}get done(){return!1}insertLines(e,t){t&&(this.trailingText=""),e?e=this.initialText+e+this.trailingText:e=this.initialText+this.trailingText;let i=K7.linesFromText(e).lines;i.length>1&&i[i.length-1]===""&&i.pop();let s,o;for(let m=this.endBranch.length-1;m>=0;m--)this.endBranch[m].updateCounts(),this.endBranch[m].charCount()===0&&(o=this.endBranch[m],m>0?s=this.endBranch[m-1]:s=this.branchNode);o&&s.remove(o);let u=this.startPath[this.startPath.length-1];if(i.length>0)if(u.text=i[0],i.length>1){let m=new Array(i.length-1),p=u;for(let T=1;T<i.length;T++)m[T-1]=new Q$(i[T]);let x=this.startPath.length-2;for(;x>=0;){let T=this.startPath[x];m=T.insertAt(p,m),x--,p=T}let b=m.length;for(;b>0;){let T=new S6;T.add(this.lineIndex.root),m=T.insertAt(this.lineIndex.root,m),b=m.length,this.lineIndex.root=T}this.lineIndex.root.updateCounts()}else for(let m=this.startPath.length-2;m>=0;m--)this.startPath[m].updateCounts();else{this.startPath[this.startPath.length-2].remove(u);for(let p=this.startPath.length-2;p>=0;p--)this.startPath[p].updateCounts()}return this.lineIndex}post(e,t,n){n===this.lineCollectionAtBranch&&(this.state=4),this.stack.pop()}pre(e,t,n,i,s){let o=this.stack[this.stack.length-1];this.state===2&&s===1&&(this.state=1,this.branchNode=o,this.lineCollectionAtBranch=n);let u;function m(p){return p.isLeaf()?new Q$(""):new S6}switch(s){case 0:this.goSubtree=!1,this.state!==4&&o.add(n);break;case 1:this.state===4?this.goSubtree=!1:(u=m(n),o.add(u),this.startPath.push(u));break;case 2:this.state!==4?(u=m(n),o.add(u),this.startPath.push(u)):n.isLeaf()||(u=m(n),o.add(u),this.endBranch.push(u));break;case 3:this.goSubtree=!1;break;case 4:this.state!==4?this.goSubtree=!1:n.isLeaf()||(u=m(n),o.add(u),this.endBranch.push(u));break;case 5:this.goSubtree=!1,this.state!==1&&o.add(n);break}this.goSubtree&&this.stack.push(u)}leaf(e,t,n){this.state===1?this.initialText=n.text.substring(0,e):this.state===2?(this.initialText=n.text.substring(0,e),this.trailingText=n.text.substring(e+t)):this.trailingText=n.text.substring(e+t)}},F1t=class{constructor(e,t,n){this.pos=e,this.deleteLen=t,this.insertedText=n}getTextChangeRange(){return l3(Ou(this.pos,this.deleteLen),this.insertedText?this.insertedText.length:0)}},eY=class Hk{constructor(){this.changes=[],this.versions=new Array(Hk.maxVersions),this.minVersion=0,this.currentVersion=0}versionToIndex(t){if(!(t<this.minVersion||t>this.currentVersion))return t%Hk.maxVersions}currentVersionToIndex(){return this.currentVersion%Hk.maxVersions}edit(t,n,i){this.changes.push(new F1t(t,n,i)),(this.changes.length>Hk.changeNumberThreshold||n>Hk.changeLengthThreshold||i&&i.length>Hk.changeLengthThreshold)&&this.getSnapshot()}getSnapshot(){return this._getSnapshot()}_getSnapshot(){let t=this.versions[this.currentVersionToIndex()];if(this.changes.length>0){let n=t.index;for(let i of this.changes)n=n.edit(i.pos,i.deleteLen,i.insertedText);t=new a$e(this.currentVersion+1,this,n,this.changes),this.currentVersion=t.version,this.versions[this.currentVersionToIndex()]=t,this.changes=[],this.currentVersion-this.minVersion>=Hk.maxVersions&&(this.minVersion=this.currentVersion-Hk.maxVersions+1)}return t}getSnapshotVersion(){return this._getSnapshot().version}getAbsolutePositionAndLineText(t){return this._getSnapshot().index.lineNumberToInfo(t)}lineOffsetToPosition(t,n){return this._getSnapshot().index.absolutePositionOfStartOfLine(t)+(n-1)}positionToLineOffset(t){return this._getSnapshot().index.positionToLineOffset(t)}lineToTextSpan(t){let n=this._getSnapshot().index,{lineText:i,absolutePosition:s}=n.lineNumberToInfo(t+1),o=i!==void 0?i.length:n.absolutePositionOfStartOfLine(t+2)-s;return Ou(s,o)}getTextChangesBetweenVersions(t,n){if(t<n)if(t>=this.minVersion){let i=[];for(let s=t+1;s<=n;s++){let o=this.versions[this.versionToIndex(s)];for(let u of o.changesSincePreviousVersion)i.push(u.getTextChangeRange())}return lae(i)}else return;else return C9}getLineCount(){return this._getSnapshot().index.getLineCount()}static fromString(t){let n=new Hk,i=new a$e(0,n,new K7);n.versions[n.currentVersion]=i;let s=K7.linesFromText(t);return i.index.load(s.lines),n}};eY.changeNumberThreshold=8,eY.changeLengthThreshold=256,eY.maxVersions=8;var tY=eY,a$e=class kQe{constructor(t,n,i,s=Yl){this.version=t,this.cache=n,this.index=i,this.changesSincePreviousVersion=s}getText(t,n){return this.index.getText(t,n-t)}getLength(){return this.index.getLength()}getChangeRange(t){if(t instanceof kQe&&this.cache===t.cache)return this.version<=t.version?C9:this.cache.getTextChangesBetweenVersions(t.version,this.version)}},K7=class NEe{constructor(){this.checkEdits=!1}absolutePositionOfStartOfLine(t){return this.lineNumberToInfo(t).absolutePosition}positionToLineOffset(t){let{oneBasedLine:n,zeroBasedColumn:i}=this.root.charOffsetToLineInfo(1,t);return{line:n,offset:i+1}}positionToColumnAndLineText(t){return this.root.charOffsetToLineInfo(1,t)}getLineCount(){return this.root.lineCount()}lineNumberToInfo(t){let n=this.getLineCount();if(t<=n){let{position:i,leaf:s}=this.root.lineNumberToInfo(t,0);return{absolutePosition:i,lineText:s&&s.text}}else return{absolutePosition:this.root.charCount(),lineText:void 0}}load(t){if(t.length>0){let n=[];for(let i=0;i<t.length;i++)n[i]=new Q$(t[i]);this.root=NEe.buildTreeFromBottom(n)}else this.root=new S6}walk(t,n,i){this.root.walk(t,n,i)}getText(t,n){let i="";return n>0&&t<this.root.charCount()&&this.walk(t,n,{goSubtree:!0,done:!1,leaf:(s,o,u)=>{i=i.concat(u.text.substring(s,s+o))}}),i}getLength(){return this.root.charCount()}every(t,n,i){i||(i=this.root.charCount());let s={goSubtree:!0,done:!1,leaf(o,u,m){t(m,o,u)||(this.done=!0)}};return this.walk(n,i-n,s),!s.done}edit(t,n,i){if(this.root.charCount()===0)return O.assert(n===0),i!==void 0?(this.load(NEe.linesFromText(i).lines),this):void 0;{let s;if(this.checkEdits){let m=this.getText(0,this.root.charCount());s=m.slice(0,t)+i+m.slice(t+n)}let o=new O1t,u=!1;if(t>=this.root.charCount()){t=this.root.charCount()-1;let m=this.getText(t,1);i?i=m+i:i=m,n=0,u=!0}else if(n>0){let m=t+n,{zeroBasedColumn:p,lineText:x}=this.positionToColumnAndLineText(m);p===0&&(n+=x.length,i=i?i+x:x)}if(this.root.walk(t,n,o),o.insertLines(i,u),this.checkEdits){let m=o.lineIndex.getText(0,o.lineIndex.getLength());O.assert(s===m,"buffer edit mismatch")}return o.lineIndex}}static buildTreeFromBottom(t){if(t.length<b6)return new S6(t);let n=new Array(Math.ceil(t.length/b6)),i=0;for(let s=0;s<n.length;s++){let o=Math.min(i+b6,t.length);n[s]=new S6(t.slice(i,o)),i=o}return this.buildTreeFromBottom(n)}static linesFromText(t){let n=aC(t);if(n.length===0)return{lines:[],lineMap:n};let i=new Array(n.length),s=n.length-1;for(let u=0;u<s;u++)i[u]=t.substring(n[u],n[u+1]);let o=t.substring(n[s]);return o.length>0?i[s]=o:i.pop(),{lines:i,lineMap:n}}},S6=class AEe{constructor(t=[]){this.children=t,this.totalChars=0,this.totalLines=0,t.length&&this.updateCounts()}isLeaf(){return!1}updateCounts(){this.totalChars=0,this.totalLines=0;for(let t of this.children)this.totalChars+=t.charCount(),this.totalLines+=t.lineCount()}execWalk(t,n,i,s,o){return i.pre&&i.pre(t,n,this.children[s],this,o),i.goSubtree?(this.children[s].walk(t,n,i),i.post&&i.post(t,n,this.children[s],this,o)):i.goSubtree=!0,i.done}skipChild(t,n,i,s,o){s.pre&&!s.done&&(s.pre(t,n,this.children[i],this,o),s.goSubtree=!0)}walk(t,n,i){if(this.children.length===0)return;let s=0,o=this.children[s].charCount(),u=t;for(;u>=o;)this.skipChild(u,n,s,i,0),u-=o,s++,o=this.children[s].charCount();if(u+n<=o){if(this.execWalk(u,n,i,s,2))return}else{if(this.execWalk(u,o-u,i,s,1))return;let m=n-(o-u);for(s++,o=this.children[s].charCount();m>o;){if(this.execWalk(0,o,i,s,3))return;m-=o,s++,o=this.children[s].charCount()}if(m>0&&this.execWalk(0,m,i,s,4))return}if(i.pre){let m=this.children.length;if(s<m-1)for(let p=s+1;p<m;p++)this.skipChild(0,0,p,i,5)}}charOffsetToLineInfo(t,n){if(this.children.length===0)return{oneBasedLine:t,zeroBasedColumn:n,lineText:void 0};for(let o of this.children){if(o.charCount()>n)return o.isLeaf()?{oneBasedLine:t,zeroBasedColumn:n,lineText:o.text}:o.charOffsetToLineInfo(t,n);n-=o.charCount(),t+=o.lineCount()}let i=this.lineCount();if(i===0)return{oneBasedLine:1,zeroBasedColumn:0,lineText:void 0};let s=O.checkDefined(this.lineNumberToInfo(i,0).leaf);return{oneBasedLine:i,zeroBasedColumn:s.charCount(),lineText:void 0}}lineNumberToInfo(t,n){for(let i of this.children){let s=i.lineCount();if(s>=t)return i.isLeaf()?{position:n,leaf:i}:i.lineNumberToInfo(t,n);t-=s,n+=i.charCount()}return{position:n,leaf:void 0}}splitAfter(t){let n,i=this.children.length;t++;let s=t;if(t<i){for(n=new AEe;t<i;)n.add(this.children[t]),t++;n.updateCounts()}return this.children.length=s,n}remove(t){let n=this.findChildIndex(t),i=this.children.length;if(n<i-1)for(let s=n;s<i-1;s++)this.children[s]=this.children[s+1];this.children.pop()}findChildIndex(t){let n=this.children.indexOf(t);return O.assert(n!==-1),n}insertAt(t,n){let i=this.findChildIndex(t),s=this.children.length,o=n.length;if(s<b6&&i===s-1&&o===1)return this.add(n[0]),this.updateCounts(),[];{let u=this.splitAfter(i),m=0;for(i++;i<b6&&m<o;)this.children[i]=n[m],i++,m++;let p=[],x=0;if(m<o){x=Math.ceil((o-m)/b6),p=new Array(x);let b=0;for(let E=0;E<x;E++)p[E]=new AEe;let T=p[0];for(;m<o;)T.add(n[m]),m++,T.children.length===b6&&(b++,T=p[b]);for(let E=p.length-1;E>=0;E--)p[E].children.length===0&&p.pop()}u&&p.push(u),this.updateCounts();for(let b=0;b<x;b++)p[b].updateCounts();return p}}add(t){this.children.push(t),O.assert(this.children.length<=b6)}charCount(){return this.totalChars}lineCount(){return this.totalLines}},Q$=class{constructor(e){this.text=e}isLeaf(){return!0}walk(e,t,n){n.leaf(e,t,this)}charCount(){return this.text.length}lineCount(){return 1}},o$e=class CQe{constructor(t,n,i,s,o,u){this.telemetryEnabled=t,this.logger=n,this.host=i,this.globalTypingsCacheLocation=s,this.event=o,this.maxActiveRequestCount=u,this.activeRequestCount=0,this.requestQueue=GA(),this.requestMap=new Map,this.requestedRegistry=!1,this.packageInstallId=0}isKnownTypesPackageName(t){var n;return C1.validatePackageName(t)!==C1.NameValidationResult.Ok?!1:(this.requestedRegistry||(this.requestedRegistry=!0,this.installer.send({kind:"typesRegistry"})),!!((n=this.typesRegistryCache)!=null&&n.has(t)))}installPackage(t){this.packageInstallId++;let n={kind:"installPackage",...t,id:this.packageInstallId},i=new Promise((s,o)=>{(this.packageInstalledPromise??(this.packageInstalledPromise=new Map)).set(this.packageInstallId,{resolve:s,reject:o})});return this.installer.send(n),i}attach(t){this.projectService=t,this.installer=this.createInstallerProcess()}onProjectClosed(t){this.installer.send({projectName:t.getProjectName(),kind:"closeProject"})}enqueueInstallTypingsRequest(t,n,i){let s=O0e(t,n,i);this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Scheduling throttled operation:${Kb(s)}`),this.activeRequestCount<this.maxActiveRequestCount?this.scheduleRequest(s):(this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Deferring request for: ${s.projectName}`),this.requestQueue.enqueue(s),this.requestMap.set(s.projectName,s))}handleMessage(t){var n,i;switch(this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Received response:${Kb(t)}`),t.kind){case CZ:this.typesRegistryCache=new Map(Object.entries(t.typesRegistry));break;case hj:{let s=(n=this.packageInstalledPromise)==null?void 0:n.get(t.id);O.assertIsDefined(s,"Should find the promise for package install"),(i=this.packageInstalledPromise)==null||i.delete(t.id),t.success?s.resolve({successMessage:t.message}):s.reject(t.message),this.projectService.updateTypingsForProject(t),this.event(t,"setTypings");break}case $pe:{let s={message:t.message};this.event(s,"typesInstallerInitializationFailed");break}case wZ:{let s={eventId:t.eventId,packages:t.packagesToInstall};this.event(s,"beginInstallTypes");break}case EZ:{if(this.telemetryEnabled){let u={telemetryEventName:"typingsInstalled",payload:{installedPackages:t.packagesToInstall.join(","),installSuccess:t.installSuccess,typingsInstallerVersion:t.typingsInstallerVersion}};this.event(u,"telemetry")}let s={eventId:t.eventId,packages:t.packagesToInstall,success:t.installSuccess};this.event(s,"endInstallTypes");break}case gj:{this.projectService.updateTypingsForProject(t);break}case mj:{for(this.activeRequestCount>0?this.activeRequestCount--:O.fail("TIAdapter:: Received too many responses");!this.requestQueue.isEmpty();){let s=this.requestQueue.dequeue();if(this.requestMap.get(s.projectName)===s){this.requestMap.delete(s.projectName),this.scheduleRequest(s);break}this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Skipping defunct request for: ${s.projectName}`)}this.projectService.updateTypingsForProject(t),this.event(t,"setTypings");break}case VO:this.projectService.watchTypingLocations(t);break;default:}}scheduleRequest(t){this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Scheduling request for: ${t.projectName}`),this.activeRequestCount++,this.host.setTimeout(()=>{this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Sending request:${Kb(t)}`),this.installer.send(t)},CQe.requestDelayMillis,`${t.projectName}::${t.kind}`)}};o$e.requestDelayMillis=100;var c$e=o$e,l$e={};v(l$e,{ActionInvalidate:()=>gj,ActionPackageInstalled:()=>hj,ActionSet:()=>mj,ActionWatchTypingLocations:()=>VO,Arguments:()=>DZ,AutoImportProviderProject:()=>eve,AuxiliaryProject:()=>Q0e,CharRangeSection:()=>wve,CloseFileWatcherEvent:()=>UQ,CommandNames:()=>Hje,ConfigFileDiagEvent:()=>jQ,ConfiguredProject:()=>tve,ConfiguredProjectLoadKind:()=>ove,CreateDirectoryWatcherEvent:()=>JQ,CreateFileWatcherEvent:()=>BQ,Errors:()=>Wy,EventBeginInstallTypes:()=>wZ,EventEndInstallTypes:()=>EZ,EventInitializationFailed:()=>$pe,EventTypesRegistry:()=>CZ,ExternalProject:()=>AQ,GcTimer:()=>z0e,InferredProject:()=>X0e,LargeFileReferencedEvent:()=>RQ,LineIndex:()=>K7,LineLeaf:()=>Q$,LineNode:()=>S6,LogLevel:()=>N0e,Msg:()=>A0e,OpenFileInfoTelemetryEvent:()=>rve,Project:()=>Pw,ProjectInfoTelemetryEvent:()=>zQ,ProjectKind:()=>yN,ProjectLanguageServiceStateEvent:()=>$Q,ProjectLoadingFinishEvent:()=>MQ,ProjectLoadingStartEvent:()=>LQ,ProjectService:()=>gve,ProjectsUpdatedInBackgroundEvent:()=>Z$,ScriptInfo:()=>W0e,ScriptVersionCache:()=>tY,Session:()=>r$e,TextStorage:()=>U0e,ThrottledOperations:()=>$0e,TypingsInstallerAdapter:()=>c$e,allFilesAreJsOrDts:()=>H0e,allRootFilesAreJsOrDts:()=>G0e,asNormalizedPath:()=>bje,convertCompilerOptions:()=>K$,convertFormatOptions:()=>y6,convertScriptKindName:()=>VQ,convertTypeAcquisition:()=>ive,convertUserPreferences:()=>sve,convertWatchOptions:()=>H7,countEachFileTypes:()=>W7,createInstallTypingsRequest:()=>O0e,createModuleSpecifierCache:()=>vve,createNormalizedPathMap:()=>Sje,createPackageJsonCache:()=>bve,createSortedArray:()=>j0e,emptyArray:()=>Yl,findArgument:()=>SAe,formatDiagnosticToProtocol:()=>Z7,formatMessage:()=>Sve,getBaseConfigFileName:()=>NQ,getDetailWatchInfo:()=>ZQ,getLocationInNewDocument:()=>Cve,hasArgument:()=>bAe,hasNoTypeScriptSource:()=>Z0e,indent:()=>U4,isBackgroundProject:()=>q7,isConfigFile:()=>hve,isConfiguredProject:()=>Z0,isDynamicFileName:()=>hN,isExternalProject:()=>V7,isInferredProject:()=>h6,isInferredProjectName:()=>F0e,isProjectDeferredClose:()=>G7,makeAutoImportProviderProjectName:()=>M0e,makeAuxiliaryProjectName:()=>R0e,makeInferredProjectName:()=>L0e,maxFileSize:()=>FQ,maxProgramSizeForNonTsFiles:()=>OQ,normalizedPathToPath:()=>g6,nowString:()=>xAe,nullCancellationToken:()=>Vje,nullTypingsInstaller:()=>X$,protocol:()=>B0e,scriptInfoIsContainedByBackgroundProject:()=>V0e,scriptInfoIsContainedByDeferredClosedProject:()=>q0e,stringifyIndented:()=>Kb,toEvent:()=>xve,toNormalizedPath:()=>Po,tryConvertScriptKindName:()=>WQ,typingsInstaller:()=>I0e,updateProjectIfDirty:()=>$d}),typeof console<"u"&&(O.loggingHost={log(e,t){switch(e){case 1:return console.error(t);case 2:return console.warn(t);case 3:return console.log(t);case 4:return console.log(t)}}})})({get exports(){return yQe},set exports(c){yQe=c,typeof Zne<"u"&&Zne.exports&&(Zne.exports=c)}})});var cYe=dxe(($Jt,LLt)=>{LLt.exports={name:"@fabriziosalmi/slopless",version:"1.15.0",description:"",main:"dist/index.js",bin:{slopless:"dist/index.js"},files:["dist","rules"],scripts:{test:"vitest run","test:watch":"vitest","test:coverage":"vitest run --coverage",build:"tsup","docs:dev":"npm run docs:gen && vitepress dev docs","docs:gen":"ts-node scripts/generate-rule-docs.ts","docs:build":"npm run docs:gen && vitepress build docs","docs:preview":"vitepress preview docs","verify:bundle":"node scripts/verify-bundle.js","verify:action":"bash scripts/run-action-locally.sh . 'src/**/*.ts'","release:prep":"npm run docs:gen && npm run build && npm test && npm run verify:bundle",version:"node scripts/check-changelog.js && npm run docs:gen && npm run build && git add dist docs README.md"},keywords:["linter","static-analysis","anti-vibecoding","sarif"],author:"Fabrizio Salmi",license:"MIT",repository:{type:"git",url:"git+https://github.com/fabriziosalmi/slopless.git"},homepage:"https://fabriziosalmi.github.io/slopless/",bugs:{url:"https://github.com/fabriziosalmi/slopless/issues"},type:"commonjs",devDependencies:{"@types/glob":"^9.0.0","@types/js-yaml":"^4.0.9","@types/node":"^26.4.0","@vitest/coverage-v8":"^4.0.18",commander:"^15.0.0",glob:"^13.0.6",ignore:"^7.0.5","js-yaml":"^5.4.1",minimatch:"^10.2.6","ts-node":"^10.9.2",tsup:"^8.5.1",typescript:"^5.9.3",vitepress:"^1.6.4",vitest:"^4.1.11",zod:"^4.3.6"},allowScripts:{esbuild:!0,fsevents:!0},publishConfig:{access:"public"}}});var ULt={};Mk(ULt,{NEVER_YOURS:()=>_Ye,UsageError:()=>$J,applyIgnoreRules:()=>BLt,partitionIgnored:()=>REe,selectRules:()=>fYe});module.exports=wIt(ULt);var sP=class extends Error{constructor(l,d,h){super(h),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=d,this.exitCode=l,this.nestedError=void 0}},fA=class extends sP{constructor(l){super(1,"commander.invalidArgument",l),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var DB=class{constructor(l,d){switch(this.description=d||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,l[0]){case"<":this.required=!0,this._name=l.slice(1,-1);break;case"[":this.required=!1,this._name=l.slice(1,-1);break;default:this.required=!0,this._name=l;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(l,d){return d===this.defaultValue||!Array.isArray(d)?[l]:(d.push(l),d)}default(l,d){return this.defaultValue=l,this.defaultValueDescription=d,this}argParser(l){return this.parseArg=l,this}choices(l){return this.argChoices=l.slice(),this.parseArg=(d,h)=>{if(!this.argChoices.includes(d))throw new fA(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(d,h):d},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function ute(c){let l=c.name()+(c.variadic===!0?"...":"");return c.required?"<"+l+">":"["+l+"]"}var aqe=require("events"),fte=wl(require("child_process"),1),Rk=wl(require("path"),1),IB=wl(require("fs"),1),Vu=wl(require("process"),1),oqe=require("util");var rqe=require("util"),PB=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(l){this.helpWidth=this.helpWidth??l.helpWidth??80}visibleCommands(l){let d=l.commands.filter(f=>!f._hidden),h=l._getHelpCommand();return h&&!h._hidden&&d.push(h),this.sortSubcommands&&d.sort((f,v)=>f.name().localeCompare(v.name())),d}compareOptions(l,d){let h=f=>f.short?f.short.replace(/^-/,""):f.long.replace(/^--/,"");return h(l).localeCompare(h(d))}visibleOptions(l){let d=l.options.filter(f=>!f.hidden),h=l._getHelpOption();if(h&&!h.hidden){let f=h.short&&l._findOption(h.short),v=h.long&&l._findOption(h.long);!f&&!v?d.push(h):h.long&&!v?d.push(l.createOption(h.long,h.description)):h.short&&!f&&d.push(l.createOption(h.short,h.description))}return this.sortOptions&&d.sort(this.compareOptions),d}visibleGlobalOptions(l){if(!this.showGlobalOptions)return[];let d=[];for(let h=l.parent;h;h=h.parent){let f=h.options.filter(v=>!v.hidden);d.push(...f)}return this.sortOptions&&d.sort(this.compareOptions),d}visibleArguments(l){return l._argsDescription&&l.registeredArguments.forEach(d=>{d.description=d.description||l._argsDescription[d.name()]||""}),l.registeredArguments.find(d=>d.description)?l.registeredArguments:[]}subcommandTerm(l){let d=l.registeredArguments.map(h=>ute(h)).join(" ");return l._name+(l._aliases[0]?"|"+l._aliases[0]:"")+(l.options.length?" [options]":"")+(d?" "+d:"")}optionTerm(l){return l.flags}argumentTerm(l){return l.name()}longestSubcommandTermLength(l,d){return d.visibleCommands(l).reduce((h,f)=>Math.max(h,this.displayWidth(d.styleSubcommandTerm(d.subcommandTerm(f)))),0)}longestOptionTermLength(l,d){return d.visibleOptions(l).reduce((h,f)=>Math.max(h,this.displayWidth(d.styleOptionTerm(d.optionTerm(f)))),0)}longestGlobalOptionTermLength(l,d){return d.visibleGlobalOptions(l).reduce((h,f)=>Math.max(h,this.displayWidth(d.styleOptionTerm(d.optionTerm(f)))),0)}longestArgumentTermLength(l,d){return d.visibleArguments(l).reduce((h,f)=>Math.max(h,this.displayWidth(d.styleArgumentTerm(d.argumentTerm(f)))),0)}commandUsage(l){let d=l._name;l._aliases[0]&&(d=d+"|"+l._aliases[0]);let h="";for(let f=l.parent;f;f=f.parent)h=f.name()+" "+h;return h+d+" "+l.usage()}commandDescription(l){return l.description()}subcommandDescription(l){return l.summary()||l.description()}optionDescription(l){let d=[];if(l.argChoices&&d.push(`choices: ${l.argChoices.map(h=>JSON.stringify(h)).join(", ")}`),l.defaultValue!==void 0&&(l.required||l.optional||l.isBoolean()&&typeof l.defaultValue=="boolean")&&d.push(`default: ${l.defaultValueDescription||JSON.stringify(l.defaultValue)}`),l.presetArg!==void 0&&l.optional&&d.push(`preset: ${JSON.stringify(l.presetArg)}`),l.envVar!==void 0&&d.push(`env: ${l.envVar}`),d.length>0){let h=`(${d.join(", ")})`;return l.description?`${l.description} ${h}`:h}return l.description}argumentDescription(l){let d=[];if(l.argChoices&&d.push(`choices: ${l.argChoices.map(h=>JSON.stringify(h)).join(", ")}`),l.defaultValue!==void 0&&d.push(`default: ${l.defaultValueDescription||JSON.stringify(l.defaultValue)}`),d.length>0){let h=`(${d.join(", ")})`;return l.description?`${l.description} ${h}`:h}return l.description}formatItemList(l,d,h){return d.length===0?[]:[h.styleTitle(l),...d,""]}groupItems(l,d,h){let f=new Map;return l.forEach(v=>{let D=h(v);f.has(D)||f.set(D,[])}),d.forEach(v=>{let D=h(v);f.has(D)||f.set(D,[]),f.get(D).push(v)}),f}formatHelp(l,d){let h=d.padWidth(l,d),f=d.helpWidth??80;function v(Pe,se){return d.formatItem(Pe,h,se,d)}let D=[`${d.styleTitle("Usage:")} ${d.styleUsage(d.commandUsage(l))}`,""],$=d.commandDescription(l);$.length>0&&(D=D.concat([d.boxWrap(d.styleCommandDescription($),f),""]));let ee=d.visibleArguments(l).map(Pe=>v(d.styleArgumentTerm(d.argumentTerm(Pe)),d.styleArgumentDescription(d.argumentDescription(Pe))));if(D=D.concat(this.formatItemList("Arguments:",ee,d)),this.groupItems(l.options,d.visibleOptions(l),Pe=>Pe.helpGroupHeading??"Options:").forEach((Pe,se)=>{let ft=Pe.map(Ze=>v(d.styleOptionTerm(d.optionTerm(Ze)),d.styleOptionDescription(d.optionDescription(Ze))));D=D.concat(this.formatItemList(se,ft,d))}),d.showGlobalOptions){let Pe=d.visibleGlobalOptions(l).map(se=>v(d.styleOptionTerm(d.optionTerm(se)),d.styleOptionDescription(d.optionDescription(se))));D=D.concat(this.formatItemList("Global Options:",Pe,d))}return this.groupItems(l.commands,d.visibleCommands(l),Pe=>Pe.helpGroup()||"Commands:").forEach((Pe,se)=>{let ft=Pe.map(Ze=>v(d.styleSubcommandTerm(d.subcommandTerm(Ze)),d.styleSubcommandDescription(d.subcommandDescription(Ze))));D=D.concat(this.formatItemList(se,ft,d))}),D.join(`
|
|
434
|
+
`+P.stack)}finally{this.performanceData=b}}parseMessage(t){return JSON.parse(t)}toStringMessage(t){return t}getFormatOptions(t){return this.projectService.getFormatCodeOptions(t)}getPreferences(t){return this.projectService.getPreferences(t)}getHostFormatOptions(){return this.projectService.getHostFormatCodeOptions()}getHostPreferences(){return this.projectService.getHostPreferences()}};function n$e(e){let t=e.diagnosticsDuration&&Es(e.diagnosticsDuration,([n,i])=>({...i,file:n}));return{...e,diagnosticsDuration:t}}function Tg(e,t){return{start:t.positionToLineOffset(e.start),end:t.positionToLineOffset(Pc(e))}}function kve(e,t,n){let i=Tg(e,n),s=t&&Tg(t,n);return s?{...i,contextStart:s.start,contextEnd:s.end}:i}function w1t(e,t){return{start:i$e(t,e.span.start),end:i$e(t,Pc(e.span)),newText:e.newText}}function i$e(e,t){return hve(e)?D1t(e.getLineAndCharacterOfPosition(t)):e.positionToLineOffset(t)}function E1t(e,t){let n=e.ranges.map(i=>({start:t.positionToLineOffset(i.start),end:t.positionToLineOffset(i.start+i.length)}));return e.wordPattern?{ranges:n,wordPattern:e.wordPattern}:{ranges:n}}function D1t(e){return{line:e.line+1,offset:e.character+1}}function P1t(e){O.assert(e.textChanges.length===1);let t=Za(e.textChanges);return O.assert(t.span.start===0&&t.span.length===0),{fileName:e.fileName,textChanges:[{start:{line:0,offset:0},end:{line:0,offset:0},newText:t.newText}]}}function Cve(e,t,n,i){let s=I1t(e,t,i),{line:o,character:u}=FE(aC(s),n);return{line:o+1,offset:u+1}}function I1t(e,t,n){for(let{fileName:i,textChanges:s}of n)if(i===t)for(let o=s.length-1;o>=0;o--){let{newText:u,span:{start:m,length:p}}=s[o];e=e.slice(0,m)+u+e.slice(m+p)}return e}function s$e(e,{fileName:t,textSpan:n,contextSpan:i,isWriteAccess:s,isDefinition:o},{disableLineTextInReferences:u}){let m=O.checkDefined(e.getScriptInfo(t)),p=kve(n,i,m),x=u?void 0:N1t(m,p);return{file:t,...p,lineText:x,isWriteAccess:s,isDefinition:o}}function N1t(e,t){let n=e.lineToTextSpan(t.start.line-1);return e.getSnapshot().getText(n.start,Pc(n)).replace(/\r|\n/g,"")}function A1t(e){return e===void 0||e&&typeof e=="object"&&typeof e.exportName=="string"&&(e.fileName===void 0||typeof e.fileName=="string")&&(e.ambientModuleName===void 0||typeof e.ambientModuleName=="string"&&(e.isPackageJsonImport===void 0||typeof e.isPackageJsonImport=="boolean"))}var b6=4,wve=(e=>(e[e.PreStart=0]="PreStart",e[e.Start=1]="Start",e[e.Entire=2]="Entire",e[e.Mid=3]="Mid",e[e.End=4]="End",e[e.PostEnd=5]="PostEnd",e))(wve||{}),O1t=class{constructor(){this.goSubtree=!0,this.lineIndex=new K7,this.endBranch=[],this.state=2,this.initialText="",this.trailingText="",this.lineIndex.root=new S6,this.startPath=[this.lineIndex.root],this.stack=[this.lineIndex.root]}get done(){return!1}insertLines(e,t){t&&(this.trailingText=""),e?e=this.initialText+e+this.trailingText:e=this.initialText+this.trailingText;let i=K7.linesFromText(e).lines;i.length>1&&i[i.length-1]===""&&i.pop();let s,o;for(let m=this.endBranch.length-1;m>=0;m--)this.endBranch[m].updateCounts(),this.endBranch[m].charCount()===0&&(o=this.endBranch[m],m>0?s=this.endBranch[m-1]:s=this.branchNode);o&&s.remove(o);let u=this.startPath[this.startPath.length-1];if(i.length>0)if(u.text=i[0],i.length>1){let m=new Array(i.length-1),p=u;for(let T=1;T<i.length;T++)m[T-1]=new Q$(i[T]);let x=this.startPath.length-2;for(;x>=0;){let T=this.startPath[x];m=T.insertAt(p,m),x--,p=T}let b=m.length;for(;b>0;){let T=new S6;T.add(this.lineIndex.root),m=T.insertAt(this.lineIndex.root,m),b=m.length,this.lineIndex.root=T}this.lineIndex.root.updateCounts()}else for(let m=this.startPath.length-2;m>=0;m--)this.startPath[m].updateCounts();else{this.startPath[this.startPath.length-2].remove(u);for(let p=this.startPath.length-2;p>=0;p--)this.startPath[p].updateCounts()}return this.lineIndex}post(e,t,n){n===this.lineCollectionAtBranch&&(this.state=4),this.stack.pop()}pre(e,t,n,i,s){let o=this.stack[this.stack.length-1];this.state===2&&s===1&&(this.state=1,this.branchNode=o,this.lineCollectionAtBranch=n);let u;function m(p){return p.isLeaf()?new Q$(""):new S6}switch(s){case 0:this.goSubtree=!1,this.state!==4&&o.add(n);break;case 1:this.state===4?this.goSubtree=!1:(u=m(n),o.add(u),this.startPath.push(u));break;case 2:this.state!==4?(u=m(n),o.add(u),this.startPath.push(u)):n.isLeaf()||(u=m(n),o.add(u),this.endBranch.push(u));break;case 3:this.goSubtree=!1;break;case 4:this.state!==4?this.goSubtree=!1:n.isLeaf()||(u=m(n),o.add(u),this.endBranch.push(u));break;case 5:this.goSubtree=!1,this.state!==1&&o.add(n);break}this.goSubtree&&this.stack.push(u)}leaf(e,t,n){this.state===1?this.initialText=n.text.substring(0,e):this.state===2?(this.initialText=n.text.substring(0,e),this.trailingText=n.text.substring(e+t)):this.trailingText=n.text.substring(e+t)}},F1t=class{constructor(e,t,n){this.pos=e,this.deleteLen=t,this.insertedText=n}getTextChangeRange(){return l3(Ou(this.pos,this.deleteLen),this.insertedText?this.insertedText.length:0)}},eY=class Hk{constructor(){this.changes=[],this.versions=new Array(Hk.maxVersions),this.minVersion=0,this.currentVersion=0}versionToIndex(t){if(!(t<this.minVersion||t>this.currentVersion))return t%Hk.maxVersions}currentVersionToIndex(){return this.currentVersion%Hk.maxVersions}edit(t,n,i){this.changes.push(new F1t(t,n,i)),(this.changes.length>Hk.changeNumberThreshold||n>Hk.changeLengthThreshold||i&&i.length>Hk.changeLengthThreshold)&&this.getSnapshot()}getSnapshot(){return this._getSnapshot()}_getSnapshot(){let t=this.versions[this.currentVersionToIndex()];if(this.changes.length>0){let n=t.index;for(let i of this.changes)n=n.edit(i.pos,i.deleteLen,i.insertedText);t=new a$e(this.currentVersion+1,this,n,this.changes),this.currentVersion=t.version,this.versions[this.currentVersionToIndex()]=t,this.changes=[],this.currentVersion-this.minVersion>=Hk.maxVersions&&(this.minVersion=this.currentVersion-Hk.maxVersions+1)}return t}getSnapshotVersion(){return this._getSnapshot().version}getAbsolutePositionAndLineText(t){return this._getSnapshot().index.lineNumberToInfo(t)}lineOffsetToPosition(t,n){return this._getSnapshot().index.absolutePositionOfStartOfLine(t)+(n-1)}positionToLineOffset(t){return this._getSnapshot().index.positionToLineOffset(t)}lineToTextSpan(t){let n=this._getSnapshot().index,{lineText:i,absolutePosition:s}=n.lineNumberToInfo(t+1),o=i!==void 0?i.length:n.absolutePositionOfStartOfLine(t+2)-s;return Ou(s,o)}getTextChangesBetweenVersions(t,n){if(t<n)if(t>=this.minVersion){let i=[];for(let s=t+1;s<=n;s++){let o=this.versions[this.versionToIndex(s)];for(let u of o.changesSincePreviousVersion)i.push(u.getTextChangeRange())}return lae(i)}else return;else return C9}getLineCount(){return this._getSnapshot().index.getLineCount()}static fromString(t){let n=new Hk,i=new a$e(0,n,new K7);n.versions[n.currentVersion]=i;let s=K7.linesFromText(t);return i.index.load(s.lines),n}};eY.changeNumberThreshold=8,eY.changeLengthThreshold=256,eY.maxVersions=8;var tY=eY,a$e=class kQe{constructor(t,n,i,s=Yl){this.version=t,this.cache=n,this.index=i,this.changesSincePreviousVersion=s}getText(t,n){return this.index.getText(t,n-t)}getLength(){return this.index.getLength()}getChangeRange(t){if(t instanceof kQe&&this.cache===t.cache)return this.version<=t.version?C9:this.cache.getTextChangesBetweenVersions(t.version,this.version)}},K7=class NEe{constructor(){this.checkEdits=!1}absolutePositionOfStartOfLine(t){return this.lineNumberToInfo(t).absolutePosition}positionToLineOffset(t){let{oneBasedLine:n,zeroBasedColumn:i}=this.root.charOffsetToLineInfo(1,t);return{line:n,offset:i+1}}positionToColumnAndLineText(t){return this.root.charOffsetToLineInfo(1,t)}getLineCount(){return this.root.lineCount()}lineNumberToInfo(t){let n=this.getLineCount();if(t<=n){let{position:i,leaf:s}=this.root.lineNumberToInfo(t,0);return{absolutePosition:i,lineText:s&&s.text}}else return{absolutePosition:this.root.charCount(),lineText:void 0}}load(t){if(t.length>0){let n=[];for(let i=0;i<t.length;i++)n[i]=new Q$(t[i]);this.root=NEe.buildTreeFromBottom(n)}else this.root=new S6}walk(t,n,i){this.root.walk(t,n,i)}getText(t,n){let i="";return n>0&&t<this.root.charCount()&&this.walk(t,n,{goSubtree:!0,done:!1,leaf:(s,o,u)=>{i=i.concat(u.text.substring(s,s+o))}}),i}getLength(){return this.root.charCount()}every(t,n,i){i||(i=this.root.charCount());let s={goSubtree:!0,done:!1,leaf(o,u,m){t(m,o,u)||(this.done=!0)}};return this.walk(n,i-n,s),!s.done}edit(t,n,i){if(this.root.charCount()===0)return O.assert(n===0),i!==void 0?(this.load(NEe.linesFromText(i).lines),this):void 0;{let s;if(this.checkEdits){let m=this.getText(0,this.root.charCount());s=m.slice(0,t)+i+m.slice(t+n)}let o=new O1t,u=!1;if(t>=this.root.charCount()){t=this.root.charCount()-1;let m=this.getText(t,1);i?i=m+i:i=m,n=0,u=!0}else if(n>0){let m=t+n,{zeroBasedColumn:p,lineText:x}=this.positionToColumnAndLineText(m);p===0&&(n+=x.length,i=i?i+x:x)}if(this.root.walk(t,n,o),o.insertLines(i,u),this.checkEdits){let m=o.lineIndex.getText(0,o.lineIndex.getLength());O.assert(s===m,"buffer edit mismatch")}return o.lineIndex}}static buildTreeFromBottom(t){if(t.length<b6)return new S6(t);let n=new Array(Math.ceil(t.length/b6)),i=0;for(let s=0;s<n.length;s++){let o=Math.min(i+b6,t.length);n[s]=new S6(t.slice(i,o)),i=o}return this.buildTreeFromBottom(n)}static linesFromText(t){let n=aC(t);if(n.length===0)return{lines:[],lineMap:n};let i=new Array(n.length),s=n.length-1;for(let u=0;u<s;u++)i[u]=t.substring(n[u],n[u+1]);let o=t.substring(n[s]);return o.length>0?i[s]=o:i.pop(),{lines:i,lineMap:n}}},S6=class AEe{constructor(t=[]){this.children=t,this.totalChars=0,this.totalLines=0,t.length&&this.updateCounts()}isLeaf(){return!1}updateCounts(){this.totalChars=0,this.totalLines=0;for(let t of this.children)this.totalChars+=t.charCount(),this.totalLines+=t.lineCount()}execWalk(t,n,i,s,o){return i.pre&&i.pre(t,n,this.children[s],this,o),i.goSubtree?(this.children[s].walk(t,n,i),i.post&&i.post(t,n,this.children[s],this,o)):i.goSubtree=!0,i.done}skipChild(t,n,i,s,o){s.pre&&!s.done&&(s.pre(t,n,this.children[i],this,o),s.goSubtree=!0)}walk(t,n,i){if(this.children.length===0)return;let s=0,o=this.children[s].charCount(),u=t;for(;u>=o;)this.skipChild(u,n,s,i,0),u-=o,s++,o=this.children[s].charCount();if(u+n<=o){if(this.execWalk(u,n,i,s,2))return}else{if(this.execWalk(u,o-u,i,s,1))return;let m=n-(o-u);for(s++,o=this.children[s].charCount();m>o;){if(this.execWalk(0,o,i,s,3))return;m-=o,s++,o=this.children[s].charCount()}if(m>0&&this.execWalk(0,m,i,s,4))return}if(i.pre){let m=this.children.length;if(s<m-1)for(let p=s+1;p<m;p++)this.skipChild(0,0,p,i,5)}}charOffsetToLineInfo(t,n){if(this.children.length===0)return{oneBasedLine:t,zeroBasedColumn:n,lineText:void 0};for(let o of this.children){if(o.charCount()>n)return o.isLeaf()?{oneBasedLine:t,zeroBasedColumn:n,lineText:o.text}:o.charOffsetToLineInfo(t,n);n-=o.charCount(),t+=o.lineCount()}let i=this.lineCount();if(i===0)return{oneBasedLine:1,zeroBasedColumn:0,lineText:void 0};let s=O.checkDefined(this.lineNumberToInfo(i,0).leaf);return{oneBasedLine:i,zeroBasedColumn:s.charCount(),lineText:void 0}}lineNumberToInfo(t,n){for(let i of this.children){let s=i.lineCount();if(s>=t)return i.isLeaf()?{position:n,leaf:i}:i.lineNumberToInfo(t,n);t-=s,n+=i.charCount()}return{position:n,leaf:void 0}}splitAfter(t){let n,i=this.children.length;t++;let s=t;if(t<i){for(n=new AEe;t<i;)n.add(this.children[t]),t++;n.updateCounts()}return this.children.length=s,n}remove(t){let n=this.findChildIndex(t),i=this.children.length;if(n<i-1)for(let s=n;s<i-1;s++)this.children[s]=this.children[s+1];this.children.pop()}findChildIndex(t){let n=this.children.indexOf(t);return O.assert(n!==-1),n}insertAt(t,n){let i=this.findChildIndex(t),s=this.children.length,o=n.length;if(s<b6&&i===s-1&&o===1)return this.add(n[0]),this.updateCounts(),[];{let u=this.splitAfter(i),m=0;for(i++;i<b6&&m<o;)this.children[i]=n[m],i++,m++;let p=[],x=0;if(m<o){x=Math.ceil((o-m)/b6),p=new Array(x);let b=0;for(let E=0;E<x;E++)p[E]=new AEe;let T=p[0];for(;m<o;)T.add(n[m]),m++,T.children.length===b6&&(b++,T=p[b]);for(let E=p.length-1;E>=0;E--)p[E].children.length===0&&p.pop()}u&&p.push(u),this.updateCounts();for(let b=0;b<x;b++)p[b].updateCounts();return p}}add(t){this.children.push(t),O.assert(this.children.length<=b6)}charCount(){return this.totalChars}lineCount(){return this.totalLines}},Q$=class{constructor(e){this.text=e}isLeaf(){return!0}walk(e,t,n){n.leaf(e,t,this)}charCount(){return this.text.length}lineCount(){return 1}},o$e=class CQe{constructor(t,n,i,s,o,u){this.telemetryEnabled=t,this.logger=n,this.host=i,this.globalTypingsCacheLocation=s,this.event=o,this.maxActiveRequestCount=u,this.activeRequestCount=0,this.requestQueue=GA(),this.requestMap=new Map,this.requestedRegistry=!1,this.packageInstallId=0}isKnownTypesPackageName(t){var n;return C1.validatePackageName(t)!==C1.NameValidationResult.Ok?!1:(this.requestedRegistry||(this.requestedRegistry=!0,this.installer.send({kind:"typesRegistry"})),!!((n=this.typesRegistryCache)!=null&&n.has(t)))}installPackage(t){this.packageInstallId++;let n={kind:"installPackage",...t,id:this.packageInstallId},i=new Promise((s,o)=>{(this.packageInstalledPromise??(this.packageInstalledPromise=new Map)).set(this.packageInstallId,{resolve:s,reject:o})});return this.installer.send(n),i}attach(t){this.projectService=t,this.installer=this.createInstallerProcess()}onProjectClosed(t){this.installer.send({projectName:t.getProjectName(),kind:"closeProject"})}enqueueInstallTypingsRequest(t,n,i){let s=O0e(t,n,i);this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Scheduling throttled operation:${Kb(s)}`),this.activeRequestCount<this.maxActiveRequestCount?this.scheduleRequest(s):(this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Deferring request for: ${s.projectName}`),this.requestQueue.enqueue(s),this.requestMap.set(s.projectName,s))}handleMessage(t){var n,i;switch(this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Received response:${Kb(t)}`),t.kind){case CZ:this.typesRegistryCache=new Map(Object.entries(t.typesRegistry));break;case hj:{let s=(n=this.packageInstalledPromise)==null?void 0:n.get(t.id);O.assertIsDefined(s,"Should find the promise for package install"),(i=this.packageInstalledPromise)==null||i.delete(t.id),t.success?s.resolve({successMessage:t.message}):s.reject(t.message),this.projectService.updateTypingsForProject(t),this.event(t,"setTypings");break}case $pe:{let s={message:t.message};this.event(s,"typesInstallerInitializationFailed");break}case wZ:{let s={eventId:t.eventId,packages:t.packagesToInstall};this.event(s,"beginInstallTypes");break}case EZ:{if(this.telemetryEnabled){let u={telemetryEventName:"typingsInstalled",payload:{installedPackages:t.packagesToInstall.join(","),installSuccess:t.installSuccess,typingsInstallerVersion:t.typingsInstallerVersion}};this.event(u,"telemetry")}let s={eventId:t.eventId,packages:t.packagesToInstall,success:t.installSuccess};this.event(s,"endInstallTypes");break}case gj:{this.projectService.updateTypingsForProject(t);break}case mj:{for(this.activeRequestCount>0?this.activeRequestCount--:O.fail("TIAdapter:: Received too many responses");!this.requestQueue.isEmpty();){let s=this.requestQueue.dequeue();if(this.requestMap.get(s.projectName)===s){this.requestMap.delete(s.projectName),this.scheduleRequest(s);break}this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Skipping defunct request for: ${s.projectName}`)}this.projectService.updateTypingsForProject(t),this.event(t,"setTypings");break}case VO:this.projectService.watchTypingLocations(t);break;default:}}scheduleRequest(t){this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Scheduling request for: ${t.projectName}`),this.activeRequestCount++,this.host.setTimeout(()=>{this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Sending request:${Kb(t)}`),this.installer.send(t)},CQe.requestDelayMillis,`${t.projectName}::${t.kind}`)}};o$e.requestDelayMillis=100;var c$e=o$e,l$e={};v(l$e,{ActionInvalidate:()=>gj,ActionPackageInstalled:()=>hj,ActionSet:()=>mj,ActionWatchTypingLocations:()=>VO,Arguments:()=>DZ,AutoImportProviderProject:()=>eve,AuxiliaryProject:()=>Q0e,CharRangeSection:()=>wve,CloseFileWatcherEvent:()=>UQ,CommandNames:()=>Hje,ConfigFileDiagEvent:()=>jQ,ConfiguredProject:()=>tve,ConfiguredProjectLoadKind:()=>ove,CreateDirectoryWatcherEvent:()=>JQ,CreateFileWatcherEvent:()=>BQ,Errors:()=>Wy,EventBeginInstallTypes:()=>wZ,EventEndInstallTypes:()=>EZ,EventInitializationFailed:()=>$pe,EventTypesRegistry:()=>CZ,ExternalProject:()=>AQ,GcTimer:()=>z0e,InferredProject:()=>X0e,LargeFileReferencedEvent:()=>RQ,LineIndex:()=>K7,LineLeaf:()=>Q$,LineNode:()=>S6,LogLevel:()=>N0e,Msg:()=>A0e,OpenFileInfoTelemetryEvent:()=>rve,Project:()=>Pw,ProjectInfoTelemetryEvent:()=>zQ,ProjectKind:()=>yN,ProjectLanguageServiceStateEvent:()=>$Q,ProjectLoadingFinishEvent:()=>MQ,ProjectLoadingStartEvent:()=>LQ,ProjectService:()=>gve,ProjectsUpdatedInBackgroundEvent:()=>Z$,ScriptInfo:()=>W0e,ScriptVersionCache:()=>tY,Session:()=>r$e,TextStorage:()=>U0e,ThrottledOperations:()=>$0e,TypingsInstallerAdapter:()=>c$e,allFilesAreJsOrDts:()=>H0e,allRootFilesAreJsOrDts:()=>G0e,asNormalizedPath:()=>bje,convertCompilerOptions:()=>K$,convertFormatOptions:()=>y6,convertScriptKindName:()=>VQ,convertTypeAcquisition:()=>ive,convertUserPreferences:()=>sve,convertWatchOptions:()=>H7,countEachFileTypes:()=>W7,createInstallTypingsRequest:()=>O0e,createModuleSpecifierCache:()=>vve,createNormalizedPathMap:()=>Sje,createPackageJsonCache:()=>bve,createSortedArray:()=>j0e,emptyArray:()=>Yl,findArgument:()=>SAe,formatDiagnosticToProtocol:()=>Z7,formatMessage:()=>Sve,getBaseConfigFileName:()=>NQ,getDetailWatchInfo:()=>ZQ,getLocationInNewDocument:()=>Cve,hasArgument:()=>bAe,hasNoTypeScriptSource:()=>Z0e,indent:()=>U4,isBackgroundProject:()=>q7,isConfigFile:()=>hve,isConfiguredProject:()=>Z0,isDynamicFileName:()=>hN,isExternalProject:()=>V7,isInferredProject:()=>h6,isInferredProjectName:()=>F0e,isProjectDeferredClose:()=>G7,makeAutoImportProviderProjectName:()=>M0e,makeAuxiliaryProjectName:()=>R0e,makeInferredProjectName:()=>L0e,maxFileSize:()=>FQ,maxProgramSizeForNonTsFiles:()=>OQ,normalizedPathToPath:()=>g6,nowString:()=>xAe,nullCancellationToken:()=>Vje,nullTypingsInstaller:()=>X$,protocol:()=>B0e,scriptInfoIsContainedByBackgroundProject:()=>V0e,scriptInfoIsContainedByDeferredClosedProject:()=>q0e,stringifyIndented:()=>Kb,toEvent:()=>xve,toNormalizedPath:()=>Po,tryConvertScriptKindName:()=>WQ,typingsInstaller:()=>I0e,updateProjectIfDirty:()=>$d}),typeof console<"u"&&(O.loggingHost={log(e,t){switch(e){case 1:return console.error(t);case 2:return console.warn(t);case 3:return console.log(t);case 4:return console.log(t)}}})})({get exports(){return yQe},set exports(c){yQe=c,typeof Zne<"u"&&Zne.exports&&(Zne.exports=c)}})});var cYe=dxe(($Jt,LLt)=>{LLt.exports={name:"@fabriziosalmi/slopless",version:"1.15.2",description:"",main:"dist/index.js",bin:{slopless:"dist/index.js"},files:["dist","rules"],scripts:{test:"vitest run","test:watch":"vitest","test:coverage":"vitest run --coverage",build:"tsup","docs:dev":"npm run docs:gen && vitepress dev docs","docs:gen":"ts-node scripts/generate-rule-docs.ts","docs:build":"npm run docs:gen && vitepress build docs","docs:preview":"vitepress preview docs","verify:bundle":"node scripts/verify-bundle.js","verify:action":"bash scripts/run-action-locally.sh . 'src/**/*.ts'","release:prep":"npm run docs:gen && npm run build && npm test && npm run verify:bundle",version:"node scripts/check-changelog.js && node scripts/sync-versions.js && npm run docs:gen && npm run build && git add dist docs README.md packages/*/package.json"},keywords:["linter","static-analysis","anti-vibecoding","sarif"],author:"Fabrizio Salmi",license:"MIT",repository:{type:"git",url:"git+https://github.com/fabriziosalmi/slopless.git"},homepage:"https://fabriziosalmi.github.io/slopless/",bugs:{url:"https://github.com/fabriziosalmi/slopless/issues"},type:"commonjs",devDependencies:{"@types/glob":"^9.0.0","@types/js-yaml":"^4.0.9","@types/node":"^26.4.0","@vitest/coverage-v8":"^4.0.18",commander:"^15.0.0",glob:"^13.0.6",ignore:"^7.0.5","js-yaml":"^5.4.1",minimatch:"^10.2.6","ts-node":"^10.9.2",tsup:"^8.5.1",typescript:"^5.9.3",vitepress:"^1.6.4",vitest:"^4.1.11",zod:"^4.3.6"},allowScripts:{esbuild:!0,fsevents:!0},publishConfig:{access:"public"}}});var ULt={};Mk(ULt,{NEVER_YOURS:()=>_Ye,UsageError:()=>$J,applyIgnoreRules:()=>BLt,partitionIgnored:()=>REe,selectRules:()=>fYe});module.exports=wIt(ULt);var sP=class extends Error{constructor(l,d,h){super(h),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=d,this.exitCode=l,this.nestedError=void 0}},fA=class extends sP{constructor(l){super(1,"commander.invalidArgument",l),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var DB=class{constructor(l,d){switch(this.description=d||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,l[0]){case"<":this.required=!0,this._name=l.slice(1,-1);break;case"[":this.required=!1,this._name=l.slice(1,-1);break;default:this.required=!0,this._name=l;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(l,d){return d===this.defaultValue||!Array.isArray(d)?[l]:(d.push(l),d)}default(l,d){return this.defaultValue=l,this.defaultValueDescription=d,this}argParser(l){return this.parseArg=l,this}choices(l){return this.argChoices=l.slice(),this.parseArg=(d,h)=>{if(!this.argChoices.includes(d))throw new fA(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(d,h):d},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function ute(c){let l=c.name()+(c.variadic===!0?"...":"");return c.required?"<"+l+">":"["+l+"]"}var aqe=require("events"),fte=wl(require("child_process"),1),Rk=wl(require("path"),1),IB=wl(require("fs"),1),Vu=wl(require("process"),1),oqe=require("util");var rqe=require("util"),PB=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(l){this.helpWidth=this.helpWidth??l.helpWidth??80}visibleCommands(l){let d=l.commands.filter(f=>!f._hidden),h=l._getHelpCommand();return h&&!h._hidden&&d.push(h),this.sortSubcommands&&d.sort((f,v)=>f.name().localeCompare(v.name())),d}compareOptions(l,d){let h=f=>f.short?f.short.replace(/^-/,""):f.long.replace(/^--/,"");return h(l).localeCompare(h(d))}visibleOptions(l){let d=l.options.filter(f=>!f.hidden),h=l._getHelpOption();if(h&&!h.hidden){let f=h.short&&l._findOption(h.short),v=h.long&&l._findOption(h.long);!f&&!v?d.push(h):h.long&&!v?d.push(l.createOption(h.long,h.description)):h.short&&!f&&d.push(l.createOption(h.short,h.description))}return this.sortOptions&&d.sort(this.compareOptions),d}visibleGlobalOptions(l){if(!this.showGlobalOptions)return[];let d=[];for(let h=l.parent;h;h=h.parent){let f=h.options.filter(v=>!v.hidden);d.push(...f)}return this.sortOptions&&d.sort(this.compareOptions),d}visibleArguments(l){return l._argsDescription&&l.registeredArguments.forEach(d=>{d.description=d.description||l._argsDescription[d.name()]||""}),l.registeredArguments.find(d=>d.description)?l.registeredArguments:[]}subcommandTerm(l){let d=l.registeredArguments.map(h=>ute(h)).join(" ");return l._name+(l._aliases[0]?"|"+l._aliases[0]:"")+(l.options.length?" [options]":"")+(d?" "+d:"")}optionTerm(l){return l.flags}argumentTerm(l){return l.name()}longestSubcommandTermLength(l,d){return d.visibleCommands(l).reduce((h,f)=>Math.max(h,this.displayWidth(d.styleSubcommandTerm(d.subcommandTerm(f)))),0)}longestOptionTermLength(l,d){return d.visibleOptions(l).reduce((h,f)=>Math.max(h,this.displayWidth(d.styleOptionTerm(d.optionTerm(f)))),0)}longestGlobalOptionTermLength(l,d){return d.visibleGlobalOptions(l).reduce((h,f)=>Math.max(h,this.displayWidth(d.styleOptionTerm(d.optionTerm(f)))),0)}longestArgumentTermLength(l,d){return d.visibleArguments(l).reduce((h,f)=>Math.max(h,this.displayWidth(d.styleArgumentTerm(d.argumentTerm(f)))),0)}commandUsage(l){let d=l._name;l._aliases[0]&&(d=d+"|"+l._aliases[0]);let h="";for(let f=l.parent;f;f=f.parent)h=f.name()+" "+h;return h+d+" "+l.usage()}commandDescription(l){return l.description()}subcommandDescription(l){return l.summary()||l.description()}optionDescription(l){let d=[];if(l.argChoices&&d.push(`choices: ${l.argChoices.map(h=>JSON.stringify(h)).join(", ")}`),l.defaultValue!==void 0&&(l.required||l.optional||l.isBoolean()&&typeof l.defaultValue=="boolean")&&d.push(`default: ${l.defaultValueDescription||JSON.stringify(l.defaultValue)}`),l.presetArg!==void 0&&l.optional&&d.push(`preset: ${JSON.stringify(l.presetArg)}`),l.envVar!==void 0&&d.push(`env: ${l.envVar}`),d.length>0){let h=`(${d.join(", ")})`;return l.description?`${l.description} ${h}`:h}return l.description}argumentDescription(l){let d=[];if(l.argChoices&&d.push(`choices: ${l.argChoices.map(h=>JSON.stringify(h)).join(", ")}`),l.defaultValue!==void 0&&d.push(`default: ${l.defaultValueDescription||JSON.stringify(l.defaultValue)}`),d.length>0){let h=`(${d.join(", ")})`;return l.description?`${l.description} ${h}`:h}return l.description}formatItemList(l,d,h){return d.length===0?[]:[h.styleTitle(l),...d,""]}groupItems(l,d,h){let f=new Map;return l.forEach(v=>{let D=h(v);f.has(D)||f.set(D,[])}),d.forEach(v=>{let D=h(v);f.has(D)||f.set(D,[]),f.get(D).push(v)}),f}formatHelp(l,d){let h=d.padWidth(l,d),f=d.helpWidth??80;function v(Pe,se){return d.formatItem(Pe,h,se,d)}let D=[`${d.styleTitle("Usage:")} ${d.styleUsage(d.commandUsage(l))}`,""],$=d.commandDescription(l);$.length>0&&(D=D.concat([d.boxWrap(d.styleCommandDescription($),f),""]));let ee=d.visibleArguments(l).map(Pe=>v(d.styleArgumentTerm(d.argumentTerm(Pe)),d.styleArgumentDescription(d.argumentDescription(Pe))));if(D=D.concat(this.formatItemList("Arguments:",ee,d)),this.groupItems(l.options,d.visibleOptions(l),Pe=>Pe.helpGroupHeading??"Options:").forEach((Pe,se)=>{let ft=Pe.map(Ze=>v(d.styleOptionTerm(d.optionTerm(Ze)),d.styleOptionDescription(d.optionDescription(Ze))));D=D.concat(this.formatItemList(se,ft,d))}),d.showGlobalOptions){let Pe=d.visibleGlobalOptions(l).map(se=>v(d.styleOptionTerm(d.optionTerm(se)),d.styleOptionDescription(d.optionDescription(se))));D=D.concat(this.formatItemList("Global Options:",Pe,d))}return this.groupItems(l.commands,d.visibleCommands(l),Pe=>Pe.helpGroup()||"Commands:").forEach((Pe,se)=>{let ft=Pe.map(Ze=>v(d.styleSubcommandTerm(d.subcommandTerm(Ze)),d.styleSubcommandDescription(d.subcommandDescription(Ze))));D=D.concat(this.formatItemList(se,ft,d))}),D.join(`
|
|
435
435
|
`)}displayWidth(l){return(0,rqe.stripVTControlCharacters)(l).length}styleTitle(l){return l}styleUsage(l){return l.split(" ").map(d=>d==="[options]"?this.styleOptionText(d):d==="[command]"?this.styleSubcommandText(d):d[0]==="["||d[0]==="<"?this.styleArgumentText(d):this.styleCommandText(d)).join(" ")}styleCommandDescription(l){return this.styleDescriptionText(l)}styleOptionDescription(l){return this.styleDescriptionText(l)}styleSubcommandDescription(l){return this.styleDescriptionText(l)}styleArgumentDescription(l){return this.styleDescriptionText(l)}styleDescriptionText(l){return l}styleOptionTerm(l){return this.styleOptionText(l)}styleSubcommandTerm(l){return l.split(" ").map(d=>d==="[options]"?this.styleOptionText(d):d[0]==="["||d[0]==="<"?this.styleArgumentText(d):this.styleSubcommandText(d)).join(" ")}styleArgumentTerm(l){return this.styleArgumentText(l)}styleOptionText(l){return l}styleArgumentText(l){return l}styleSubcommandText(l){return l}styleCommandText(l){return l}padWidth(l,d){return Math.max(d.longestOptionTermLength(l,d),d.longestGlobalOptionTermLength(l,d),d.longestSubcommandTermLength(l,d),d.longestArgumentTermLength(l,d))}preformatted(l){return/\n[^\S\r\n]/.test(l)}formatItem(l,d,h,f){let D=" ".repeat(2);if(!h)return D+l;let $=l.padEnd(d+l.length-f.displayWidth(l)),ee=2,ge=(this.helpWidth??80)-d-ee-2,Pe;return ge<this.minWidthToWrap||f.preformatted(h)?Pe=h:Pe=f.boxWrap(h,ge).replace(/\n/g,`
|
|
436
436
|
`+" ".repeat(d+ee)),D+$+" ".repeat(ee)+Pe.replace(/\n/g,`
|
|
437
437
|
${D}`)}boxWrap(l,d){if(d<this.minWidthToWrap)return l;let h=l.split(/\r\n|\n/),f=/[\s]*[^\s]+/g,v=[];return h.forEach(D=>{let $=D.match(f);if($===null){v.push("");return}let ee=[$.shift()],fe=this.displayWidth(ee[0]);$.forEach(ge=>{let Pe=this.displayWidth(ge);if(fe+Pe<=d){ee.push(ge),fe+=Pe;return}v.push(ee.join(""));let se=ge.trimStart();ee=[se],fe=this.displayWidth(se)}),v.push(ee.join(""))}),v.join(`
|
|
@@ -546,7 +546,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
546
546
|
`)?1:0),h=Qne(l,c);if(h.length===0)return d;let f=h.reduce((v,D)=>v+c.slice(D.start,D.end).split(`
|
|
547
547
|
`).length-1,0);return d-f}var tie=new Set(["empty-file","file-length-limit"]),nie=class{static check(l,d,h){var $,ee;let f=[],v=h!==void 0?h:BQe.readFileSync(l,"utf8");for(let fe of d){let ge=($=fe.match.ast_check)==null?void 0:$.type;!ge||!tie.has(ge)||O2(l,fe)||fe.match.file_types&&!fe.match.file_types.includes(zA(l))||f.push(...this.checkByCounting(ge,v,{rule:fe,file:l,threshold:fe.match.threshold??((ee=fe.match.ast_check)==null?void 0:ee.threshold)}))}if(!e9.has(zA(l)))return f;let D=Ss.createSourceFile(l,v,Ss.ScriptTarget.Latest,!0);for(let fe of d){if(!fe.match.ast_check||O2(l,fe))continue;let ge=fe.match.ast_check.type,Pe=fe.match.threshold??fe.match.ast_check.threshold,se={rule:fe,sourceFile:D,file:l,violations:f};tie.has(ge)||this.traverse(D,ft=>{ge==="function-params-limit"&&Pe&&this.checkFunctionParams(ft,Pe,se),ge==="function-length-limit"&&Pe&&this.checkFunctionLength(ft,Pe,se),ge==="empty-catch"&&this.checkEmptyCatch(ft,se),ge==="nested-blocks-limit"&&Pe&&this.checkNestedBlocks(ft,Pe,se),ge==="empty-block"&&this.checkEmptyBlock(ft,se),ge==="one-liner-limit"&&this.checkOneLiner(ft,se),ge==="redundant-if-true"&&this.checkRedundantIfTrue(ft,se),ge==="lying-function-names"&&this.checkLyingFunctionName(ft,se),ge==="empty-interface"&&this.checkEmptyInterface(ft,se),ge==="async-without-await"&&this.checkAsyncWithoutAwait(ft,se)})}return f}static checkFunctionParams(l,d,h){if(!Ss.isFunctionDeclaration(l)&&!Ss.isMethodDeclaration(l)&&!Ss.isArrowFunction(l)||l.parameters.length<=d)return;let{line:f}=h.sourceFile.getLineAndCharacterOfPosition(l.getStart());h.violations.push({ruleId:h.rule.id,name:h.rule.name,severity:h.rule.severity,message:this.formatMessage(h.rule.message,{threshold:d,count:l.parameters.length,line:f+1}),file:h.file,line:f+1})}static checkFunctionLength(l,d,h){if(!Ss.isFunctionDeclaration(l)&&!Ss.isMethodDeclaration(l)&&!Ss.isArrowFunction(l))return;let f=h.sourceFile.getLineAndCharacterOfPosition(l.getStart()).line,D=h.sourceFile.getLineAndCharacterOfPosition(l.getEnd()).line-f+1;D<=d||h.violations.push({ruleId:h.rule.id,name:h.rule.name,severity:h.rule.severity,message:this.formatMessage(h.rule.message,{threshold:d,count:D,line:f+1}),file:h.file,line:f+1})}static checkEmptyCatch(l,d){if(!Ss.isCatchClause(l)||l.block.statements.length>0||/\/\/|\/\*/.test(l.block.getText()))return;let{line:h}=d.sourceFile.getLineAndCharacterOfPosition(l.getStart());d.violations.push({ruleId:d.rule.id,name:d.rule.name,severity:d.rule.severity,message:this.formatMessage(d.rule.message,{line:h+1}),file:d.file,line:h+1})}static checkEmptyBlock(l,d){if(!Ss.isBlock(l)||l.statements.length>0||Ss.isCatchClause(l.parent)||Ss.isConstructorDeclaration(l.parent))return;let{line:h}=d.sourceFile.getLineAndCharacterOfPosition(l.getStart());d.violations.push({ruleId:d.rule.id,name:d.rule.name,severity:d.rule.severity,message:this.formatMessage(d.rule.message,{line:h+1}),file:d.file,line:h+1})}static checkOneLiner(l,d){if(!Ss.isBlock(l))return;let h=new Map;if(l.statements.forEach(D=>{let{line:$}=d.sourceFile.getLineAndCharacterOfPosition(D.getStart());h.set($,(h.get($)??0)+1)}),l.statements.length<=h.size)return;let v=[...h.entries()].filter(([,D])=>D>1).map(([D])=>D).sort((D,$)=>D-$)[0]??d.sourceFile.getLineAndCharacterOfPosition(l.getStart()).line;d.violations.push({ruleId:d.rule.id,name:d.rule.name,severity:d.rule.severity,message:this.formatMessage(d.rule.message,{line:v+1}),file:d.file,line:v+1})}static checkRedundantIfTrue(l,d){if(!Ss.isIfStatement(l))return;let h=l.expression;if(!(h.kind===Ss.SyntaxKind.TrueKeyword||Ss.isBinaryExpression(h)&&h.left.kind===Ss.SyntaxKind.TrueKeyword&&h.operatorToken.kind===Ss.SyntaxKind.EqualsEqualsEqualsToken))return;let{line:v}=d.sourceFile.getLineAndCharacterOfPosition(l.getStart());d.violations.push({ruleId:d.rule.id,name:d.rule.name,severity:d.rule.severity,message:this.formatMessage(d.rule.message,{line:v+1}),file:d.file,line:v+1})}static checkLyingFunctionName(l,d){var fe,ge;if(!Ss.isFunctionDeclaration(l)&&!Ss.isMethodDeclaration(l))return;let h=(fe=l.name)==null?void 0:fe.getText();if(!h||!new RegExp("^(get|is|has|retrieve)","i").test(h))return;let v=(ge=l.body)==null?void 0:ge.getText();if(!v)return;let D=/\bthis\.[\w.]*\.(?:set|delete|remove|update|write|modify|pop|push|shift|unshift|splice|clear|add|sort|reverse)\s*\(/,$=/\bObject\.assign\s*\(\s*this\b|\bdelete\s+this\./;if(!D.test(v)&&!vLt(l.body)&&!$.test(v))return;let{line:ee}=d.sourceFile.getLineAndCharacterOfPosition(l.getStart());d.violations.push({ruleId:d.rule.id,name:d.rule.name,severity:d.rule.severity,message:this.formatMessage(d.rule.message,{name:h,line:ee+1}),file:d.file,line:ee+1})}static checkByCounting(l,d,h){let{rule:f,file:v,threshold:D}=h;if(l==="empty-file"&&d.trim().length===0)return[{ruleId:f.id,name:f.name,severity:f.severity,message:this.formatMessage(f.message,{file:v,line:0}),file:v,line:0}];if(l==="file-length-limit"&&D){let $=TLt(d,zA(v));if($>D)return[{ruleId:f.id,name:f.name,severity:f.severity,message:this.formatMessage(f.message,{threshold:D,count:$}),file:v,line:0}]}return[]}static checkEmptyInterface(l,d){if(!Ss.isInterfaceDeclaration(l)||l.members.length>0||l.heritageClauses&&l.heritageClauses.length>0)return;let{line:h}=d.sourceFile.getLineAndCharacterOfPosition(l.getStart());d.violations.push({ruleId:d.rule.id,name:d.rule.name,severity:d.rule.severity,message:this.formatMessage(d.rule.message,{line:h+1}),file:d.file,line:h+1})}static checkAsyncWithoutAwait(l,d){let h=JQe(l);if(!h)return;let f=Ss.canHaveModifiers(l)?Ss.getModifiers(l):void 0;if(!((f==null?void 0:f.some($=>$.kind===Ss.SyntaxKind.AsyncKeyword))??!1)||Ss.isCallExpression(l.parent)&&l.parent.arguments.includes(l)||xLt(h))return;let{line:D}=d.sourceFile.getLineAndCharacterOfPosition(l.getStart());d.violations.push({ruleId:d.rule.id,name:d.rule.name,severity:d.rule.severity,message:this.formatMessage(d.rule.message,{line:D+1}),file:d.file,line:D+1})}static checkNestedBlocks(l,d,h){if(!rie(l))return;let f=0,v=($,ee)=>{f=Math.max(f,ee),Ss.forEachChild($,fe=>{if(rie(fe)){v(fe,0);return}let Pe=!(Ss.isIfStatement(fe)&&Ss.isIfStatement($)&&$.elseStatement===fe)&&(Ss.isIfStatement(fe)||Ss.isForStatement(fe)||Ss.isForOfStatement(fe)||Ss.isForInStatement(fe)||Ss.isWhileStatement(fe)||Ss.isDoStatement(fe)||Ss.isSwitchStatement(fe)||Ss.isTryStatement(fe));v(fe,Pe?ee+1:ee)})};if(v(l,0),f<=d)return;let{line:D}=h.sourceFile.getLineAndCharacterOfPosition(l.getStart());h.violations.push({ruleId:h.rule.id,name:h.rule.name,severity:h.rule.severity,message:this.formatMessage(h.rule.message,{threshold:d,count:f,line:D+1}),file:h.file,line:D+1})}static traverse(l,d){d(l),Ss.forEachChild(l,h=>this.traverse(h,d))}static formatMessage(l,d){let h=l;for(let[f,v]of Object.entries(d))h=h.replace(new RegExp(`\\{${f}\\}`,"g"),String(v));return h}};var qQe=wl(require("fs"));var UQe=wl(require("dns")),kLt=wl(require("http")),CLt=wl(require("https")),t9=wl(require("net")),jJ="ESLOPLESSBLOCKED";function WQe(c){return(c==null?void 0:c.code)===jJ}function LEe(c){let l=c.replace(/^\[|\]$/g,"");if(t9.isIPv4(l)){let[v,D]=l.split(".").map(Number);return v===0||v===10||v===127||v===169&&D===254||v===172&&D>=16&&D<=31||v===192&&D===168||v===100&&D>=64&&D<=127||v===192&&D===0||v===198&&(D===18||D===19)||v===198&&D===51||v===203&&D===0||v>=224}if(!t9.isIPv6(l))return!0;let d=wLt(l);if(!d||d.every(v=>v===0)||d.slice(0,7).every(v=>v===0)&&d[7]===1)return!0;let h=d.slice(0,5).every(v=>v===0)&&d[5]===65535,f=d[0]===100&&d[1]===65435&&d.slice(2,6).every(v=>v===0);if(h||f){let v=[d[6]>>8,d[6]&255,d[7]>>8,d[7]&255].join(".");return LEe(v)}return(d[0]&65472)===65152||(d[0]&65024)===64512||(d[0]&65280)===65280||d[0]===8193&&d[1]===3512}function wLt(c){let[l,d,...h]=c.toLowerCase().split("::");if(h.length)return null;let f=ee=>ee?ee.split(":").map(fe=>parseInt(fe,16)):[],v=f(l),D=d===void 0?[]:f(d),$=d===void 0?v:[...v,...new Array(8-v.length-D.length).fill(0),...D];return $.length===8&&$.every(ee=>Number.isInteger(ee)&&ee>=0&&ee<=65535)?$:null}var ELt=(c,l,d)=>{UQe.lookup(c,l,(h,f,v)=>{if(h)return d(h);let $=(Array.isArray(f)?f:[{address:f,family:v}]).find(ee=>LEe(ee.address));if($){let ee=new Error(`${c} resolves to ${$.address}, which is not a public address`);return ee.code=jJ,d(ee)}d(null,f,v)})};function VQe(c,l,d){return new Promise((h,f)=>{let v;try{v=new URL(c)}catch{let fe=new Error(`not a URL: ${c}`);return fe.code=jJ,f(fe)}if(v.protocol!=="http:"&&v.protocol!=="https:"){let fe=new Error(`refusing ${v.protocol}`);return fe.code=jJ,f(fe)}let D=v.hostname.replace(/^\[|\]$/g,"");if(t9.isIP(D)&&LEe(D)){let fe=new Error(`${D} is not a public address`);return fe.code=jJ,f(fe)}let ee=(v.protocol==="https:"?CLt:kLt).request(v,{method:l,lookup:ELt,timeout:d,headers:{"user-agent":"slopless (+https://github.com/fabriziosalmi/slopless)"}},fe=>{fe.resume(),h(fe.statusCode??0)});ee.on("timeout",()=>{let fe=new Error("timed out");fe.code="ETIMEDOUT",ee.destroy(fe)}),ee.on("error",f),ee.end()})}var iie=class{static async check(l,d,h){let f=[],v=h!==void 0?h:qQe.readFileSync(l,"utf8");for(let D of d)O2(l,D)||(D.match.heuristic_check==="link-checker"&&l.endsWith(".md")&&f.push(...await this.findBrokenLinks(l,v,D)),D.match.heuristic_check==="stale-copyright-year"&&f.push(...this.findStaleCopyright(l,v,D)));return f}static findStaleCopyright(l,d,h){let f=[],v=new Date().getFullYear(),D=/(?:©|\(c\)|copyright)\s*((?:19|20)\d{2})(?:\s*[-–—]\s*((?:19|20)?\d{2}|present|\$?\{|<%))?/gi;return d.split(`
|
|
548
548
|
`).forEach(($,ee)=>{for(let fe of $.matchAll(D)){let[,ge,Pe]=fe;Pe&&(/present/i.test(Pe)||/^(?:\$?\{|<%)/.test(Pe))||Number(Pe?Pe.length===2?ge.slice(0,2)+Pe:Pe:ge)>=v||f.push({ruleId:h.id,name:h.name,severity:h.severity,message:h.message.replace("{line}",String(ee+1)).replace("{match}",fe[0]).replace("{year}",String(v)),file:l,line:ee+1})}}),f}static async findBrokenLinks(l,d,h){let f=[];for(let v of this.extractLinks(d)){if(await this.checkLink(v)!=="broken")continue;let D=this.getLineNumber(d,v);f.push({ruleId:h.id,name:h.name,severity:h.severity,message:this.formatMessage(h.message,{url:v,match:v,line:D}),file:l,line:D})}return f}static extractLinks(l){let d=/\[.*?\]\((https?:\/\/.*?)\)/g,h=[],f;for(;(f=d.exec(l))!==null;)h.push(f[1]);return h}static async checkLink(l){for(let d of["HEAD","GET"])try{let h=await VQe(l,d,5e3);if(h>=200&&h<400)return"ok";if(d==="GET")return h===404||h===410?"broken":"unknown"}catch(h){if(WQe(h))return"unknown";if(this.isUnknownHost(h))return"broken"}return"unknown"}static isUnknownHost(l){var f;let d=l,h=(d==null?void 0:d.code)??((f=d==null?void 0:d.cause)==null?void 0:f.code);return h==="ENOTFOUND"||h==="EAI_AGAIN"}static getLineNumber(l,d){let h=l.indexOf(d);return h===-1?0:l.substring(0,h).split(`
|
|
549
|
-
`).length}static formatMessage(l,d){let h=l;for(let[f,v]of Object.entries(d))h=h.replace(new RegExp(`\\{${f}\\}`,"g"),String(v));return h}};var vp=wl($A()),GQe=wl(require("fs"));var sie=class{static check(l,d,h){let f=[];if(!e9.has(zA(l)))return[];let v=h!==void 0?h:GQe.readFileSync(l,"utf8"),D=vp.createSourceFile(l,v,vp.ScriptTarget.Latest,!0);for(let $ of d){if(!$.match.semantic_check||O2(l,$))continue;let ee=$.match.semantic_check;this.traverse(D,fe=>{if(ee==="boolean-naming"&&vp.isVariableDeclaration(fe)&&fe.initializer){let ge=fe.name.getText();if(this.isBooleanType(fe)&&!new RegExp("^(is|has|can|should|was|did|do|will)","i").test(ge)){let{line:se}=D.getLineAndCharacterOfPosition(fe.getStart());f.push({ruleId:$.id,name:$.name,severity:$.severity,message:this.formatMessage($.message,{name:ge,line:se+1}),file:l,line:se+1})}}if(ee==="boolean-redundancy"&&vp.isIfStatement(fe)){let ge=fe.thenStatement,Pe=fe.elseStatement;if(ge&&Pe&&this.isReturnBoolean(ge)&&this.isReturnBoolean(Pe)){let{line:se}=D.getLineAndCharacterOfPosition(fe.getStart());f.push({ruleId:$.id,name:$.name,severity:$.severity,message:this.formatMessage($.message,{line:se+1}),file:l,line:se+1})}}if(ee==="collection-suffix"&&vp.isVariableDeclaration(fe)&&fe.initializer){let ge=fe.name.getText(),Pe=this.isArrayType(fe),se
|
|
549
|
+
`).length}static formatMessage(l,d){let h=l;for(let[f,v]of Object.entries(d))h=h.replace(new RegExp(`\\{${f}\\}`,"g"),String(v));return h}};var vp=wl($A()),GQe=wl(require("fs"));var sie=class{static check(l,d,h){let f=[];if(!e9.has(zA(l)))return[];let v=h!==void 0?h:GQe.readFileSync(l,"utf8"),D=vp.createSourceFile(l,v,vp.ScriptTarget.Latest,!0);for(let $ of d){if(!$.match.semantic_check||O2(l,$))continue;let ee=$.match.semantic_check;this.traverse(D,fe=>{if(ee==="boolean-naming"&&vp.isVariableDeclaration(fe)&&fe.initializer){let ge=fe.name.getText();if(this.isBooleanType(fe)&&!new RegExp("^(is|has|can|should|was|did|do|will)","i").test(ge)){let{line:se}=D.getLineAndCharacterOfPosition(fe.getStart());f.push({ruleId:$.id,name:$.name,severity:$.severity,message:this.formatMessage($.message,{name:ge,line:se+1}),file:l,line:se+1})}}if(ee==="boolean-redundancy"&&vp.isIfStatement(fe)){let ge=fe.thenStatement,Pe=fe.elseStatement;if(ge&&Pe&&this.isReturnBoolean(ge)&&this.isReturnBoolean(Pe)){let{line:se}=D.getLineAndCharacterOfPosition(fe.getStart());f.push({ruleId:$.id,name:$.name,severity:$.severity,message:this.formatMessage($.message,{line:se+1}),file:l,line:se+1})}}if(ee==="collection-suffix"&&vp.isVariableDeclaration(fe)&&fe.initializer){let ge=fe.name.getText(),Pe=this.isArrayType(fe),se=!/s$/i.test(ge)&&!new RegExp("(List|Map|Set|Collection|Array)$","i").test(ge);if(Pe&&se){let{line:ft}=D.getLineAndCharacterOfPosition(fe.getStart());f.push({ruleId:$.id,name:$.name,severity:$.severity,message:this.formatMessage($.message,{name:ge,line:ft+1}),file:l,line:ft+1})}}if(ee==="semantic-shadowing"&&vp.isVariableDeclaration(fe)){let ge=fe.name.getText();if(["fs","path","crypto","http","https","express","os","child_process","cluster","dns"].includes(ge)){let{line:se}=D.getLineAndCharacterOfPosition(fe.getStart());f.push({ruleId:$.id,name:$.name,severity:$.severity,message:this.formatMessage($.message,{name:ge,line:se+1,match:ge}),file:l,line:se+1})}}})}return f}static traverse(l,d){d(l),vp.forEachChild(l,h=>this.traverse(h,d))}static formatMessage(l,d){let h=l;for(let[f,v]of Object.entries(d))h=h.replace(new RegExp(`\\{${f}\\}`,"g"),String(v));return h}static isBooleanType(l){var d,h,f;return((d=l.type)==null?void 0:d.kind)===vp.SyntaxKind.BooleanKeyword||((h=l.initializer)==null?void 0:h.kind)===vp.SyntaxKind.TrueKeyword||((f=l.initializer)==null?void 0:f.kind)===vp.SyntaxKind.FalseKeyword}static isArrayType(l){var d,h;return((d=l.type)==null?void 0:d.kind)===vp.SyntaxKind.ArrayType||((h=l.initializer)==null?void 0:h.kind)===vp.SyntaxKind.ArrayLiteralExpression}static isReturnBoolean(l){let d=l;return vp.isBlock(d)&&d.statements.length===1&&(d=d.statements[0]),vp.isReturnStatement(d)&&d.expression?d.expression.kind===vp.SyntaxKind.TrueKeyword||d.expression.kind===vp.SyntaxKind.FalseKeyword:!1}};var L2=wl($A());var aie=class{static check(l,d,h,f){let v=[],D=h.getSourceFile(l);if(!D)return v;let $=d.filter(fe=>fe.match.type_check&&!O2(l,fe));if($.length===0)return v;let ee=fe=>{for(let ge of $)ge.match.type_check==="floating-promise"&&this.checkFloatingPromise(fe,{checker:f,rule:ge,sourceFile:D,file:l,violations:v});L2.forEachChild(fe,ee)};return ee(D),v}static checkFloatingPromise(l,d){if(!L2.isCallExpression(l))return;let h=d.checker.getTypeAtLocation(l),f=d.checker.typeToString(h),v=f.includes("Promise")||f.includes("Thenable");if(!v){let D=d.checker.getResolvedSignature(l),$=D==null?void 0:D.declaration;$!=null&&$.modifiers&&(v=$.modifiers.some(ee=>ee.kind===L2.SyntaxKind.AsyncKeyword))}if(v&&L2.isExpressionStatement(l.parent)&&!this.isHandled(l)){let{line:D}=d.sourceFile.getLineAndCharacterOfPosition(l.getStart());d.violations.push({ruleId:d.rule.id,name:d.rule.name,severity:d.rule.severity,message:d.rule.message.replace("{match}",f),file:d.file,line:D+1})}}static isHandled(l){let d=l;for(;L2.isCallExpression(d);){let h=d.expression;if(!L2.isPropertyAccessExpression(h))return!1;let f=h.name.text;if(f==="catch"||f==="finally"||f==="then"&&d.arguments.length>=2)return!0;d=h.expression}return!1}};function HQe(c){return JSON.stringify(c,null,2)}function ZQe(c,l){let h=K5.loadRules(l).map(D=>({id:D.id,name:D.name,shortDescription:{text:D.name},fullDescription:{text:D.message},helpUri:D.docs_url||`https://github.com/fabriziosalmi/slopless/blob/main/docs/rules/${D.id}.md`,properties:{tags:D.tags||[],category:D.category}})),f=c.map(D=>({ruleId:D.ruleId,level:D.severity==="error"?"error":"warning",message:{text:D.message},locations:[{physicalLocation:{artifactLocation:{uri:D.file},region:{startLine:D.line>0?D.line:1,startColumn:1}}}]}));return JSON.stringify({version:"2.1.0",$schema:"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",runs:[{tool:{driver:{name:"Slopless",informationUri:"https://github.com/fabriziosalmi/slopless",version:"1.0.0",rules:h}},results:f}]},null,2)}var KQe=wl(require("crypto")),BA=wl(require("fs")),XQe=wl(require("path")),oie=class{constructor(l=!0){this.cacheMap={};this.cachePath=XQe.join(process.cwd(),".sloplesscache"),this.isEnabled=l,this.isEnabled&&this.loadCache()}loadCache(){if(BA.existsSync(this.cachePath))try{let l=BA.readFileSync(this.cachePath,"utf8");this.cacheMap=JSON.parse(l)}catch{this.cacheMap={}}}saveCache(){if(this.isEnabled)try{BA.writeFileSync(this.cachePath,JSON.stringify(this.cacheMap,null,2),"utf8")}catch(l){console.error("Failed to save Slopless cache:",l)}}calculateHash(l){try{let d=BA.readFileSync(l,"utf8");return KQe.createHash("sha256").update(d).digest("hex")}catch{return null}}getCachedViolations(l,d){if(!this.isEnabled)return null;let h=this.cacheMap[l];return h&&h.hash===d?h.violations:null}setCachedViolations(l,d,h){this.isEnabled&&(this.cacheMap[l]={hash:d,violations:h})}};var by=wl($A()),YQe=wl(require("vm")),DLt=/\.(?:m|c)?[jt]sx?$/;function QQe(c,l){let d=/\.(?:m|c)?ts$/.test(c)?by.ScriptKind.TS:by.ScriptKind.TSX,f=by.createSourceFile(c,l,by.ScriptTarget.Latest,!0,d).parseDiagnostics??[];if(f.length)return by.flattenDiagnosticMessageText(f[0].messageText," ");try{let v=by.transpileModule(l,{fileName:c,reportDiagnostics:!1,compilerOptions:{target:by.ScriptTarget.ESNext,module:by.ModuleKind.CommonJS,jsx:by.JsxEmit.React}}).outputText;new YQe.Script(v,{filename:c})}catch(v){return v.message}return null}function eYe(c,l,d){return!DLt.test(c)||QQe(c,l)!==null?null:QQe(c,d)}var tYe=wl(require("os"));async function rYe(c,l=tYe.cpus().length,d){let h=new Array(c.length),f=0,v=async()=>{for(;f<c.length;){let $=f++;h[$]=await d(c[$])}},D=Array.from({length:Math.min(l,c.length)},()=>v());return await Promise.all(D),h}function nYe(c,l){var f;let d=new Map;for(let v of l)(f=v.supersedes)!=null&&f.length&&d.set(v.id,v.supersedes);if(d.size===0)return c;let h=new Map;for(let v of c){let D=d.get(v.ruleId);if(!D)continue;let $=`${v.file}:${v.line}`,ee=h.get($);ee||(ee=new Set,h.set($,ee));for(let fe of D)ee.add(fe)}return h.size===0?c:c.filter(v=>{var D;return!((D=h.get(`${v.file}:${v.line}`))!=null&&D.has(v.ruleId))})}var iYe=wl(require("fs")),PLt=/slopless-disable-(next-line|line)\b([^\n]*)/,ILt=/\b(VBC-\d+)\b/g;function NLt(c){let l=[],d=c.split(`
|
|
550
550
|
`);for(let h=0;h<d.length;h++){let f=PLt.exec(d[h]);if(!f)continue;let D=f[2].split(/\s--\s|\s--$/)[0].match(ILt);l.push({line:f[1]==="next-line"?h+2:h+1,ruleIds:D&&D.length>0?D:null})}return l}function sYe(c,l=ALt){let d=new Map;return c.filter(h=>{if(!d.has(h.file)){let f=l(h.file);d.set(h.file,f===void 0?[]:NLt(f))}return!d.get(h.file).some(f=>f.line===h.line&&(f.ruleIds===null||f.ruleIds.includes(h.ruleId)))})}function ALt(c){try{return iYe.readFileSync(c,"utf8")}catch{return}}var r9=wl(require("fs")),OLt=500,FLt=2e3,aYe=64*1024;function oYe(c,l){let d=l;if(d===void 0)try{let D=r9.openSync(c,"r"),$=Buffer.alloc(aYe),ee=r9.readSync(D,$,0,aYe,0);r9.closeSync(D),d=$.subarray(0,ee).toString("utf8")}catch{return!1}if(d.length===0)return!1;let h=d.split(`
|
|
551
551
|
`);if(l===void 0&&h.length>1&&h.pop(),h.length===0)return!1;let f=h.reduce((D,$)=>Math.max(D,$.length),0);return d.length/h.length>OLt||f>FLt}var EP=wl($A()),MLt=QS.join(__dirname,"..","rules");function RLt(){try{return lYe.execSync("git diff --cached --name-only",{encoding:"utf8"}).split(`
|
|
552
552
|
`).filter(l=>l.trim().length>0)}catch{return[]}}function jLt(c,l,d){if(l.line<=0||l.line>c.length)return!1;let h=l.line-1,f=c[h];try{let v=new RegExp(l.fix.pattern,"g"),D=f.replace(v,l.fix.replacement);return f===D?!1:(c[h]=D,!0)}catch{return console.error(`Failed to apply fix for ${l.ruleId} on ${d}:${l.line}`),!1}}function $Lt(c,l){if(!T0.existsSync(c))return 0;let d=T0.readFileSync(c,"utf8"),h=d.split(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabriziosalmi/slopless",
|
|
3
|
-
"version": "1.15.
|
|
3
|
+
"version": "1.15.2",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"bin": {
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"verify:bundle": "node scripts/verify-bundle.js",
|
|
23
23
|
"verify:action": "bash scripts/run-action-locally.sh . 'src/**/*.ts'",
|
|
24
24
|
"release:prep": "npm run docs:gen && npm run build && npm test && npm run verify:bundle",
|
|
25
|
-
"version": "node scripts/check-changelog.js && npm run docs:gen && npm run build && git add dist docs README.md"
|
|
25
|
+
"version": "node scripts/check-changelog.js && node scripts/sync-versions.js && npm run docs:gen && npm run build && git add dist docs README.md packages/*/package.json"
|
|
26
26
|
},
|
|
27
27
|
"keywords": [
|
|
28
28
|
"linter",
|
package/rules/VBC-503.yaml
CHANGED
|
@@ -16,3 +16,7 @@ tests:
|
|
|
16
16
|
quiet:
|
|
17
17
|
- const users = [1, 2, 3];
|
|
18
18
|
- const userList = [1];
|
|
19
|
+
# The suffix check was case-insensitive and the plural was not, so a
|
|
20
|
+
# constant array shouting its own name was told to add the s it ends with.
|
|
21
|
+
- const LANGUAGES = ['ts', 'py'];
|
|
22
|
+
- const RULE_IDS = ['VBC-001'];
|