UNPKG

@regele/devtools

Version:

A collection of developer utilities for code processing and text analysis

1 lines 58.1 kB
"use strict";var e=require("commander"),t=require("fs"),n=require("path"),i=require("chalk"),s=require("ora"),r=require("fast-glob"),o=require("@babel/parser"),a=require("@babel/types"),l=require("@babel/traverse");function c(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var u,d,h=c(o),p=c(a);class m{constructor(e=!1,t=!1){this.silent=e,this.verboseMode=t,this.spinner=null}log(e){this.silent||console.log(e)}verbose(e){!this.silent&&this.verboseMode&&console.log(i.gray(`[verbose] ${e}`))}info(e){this.silent||console.log(i.blue("ℹ ")+e)}success(e){this.silent||console.log(i.green("✓ ")+e)}warn(e){this.silent||console.log(i.yellow("⚠ ")+e)}error(e){this.silent||console.log(i.red("✗ ")+e)}startSpinner(e){this.silent||(this.spinner=s({text:e,color:"cyan",spinner:"dots"}).start())}stopSpinnerSuccess(e){!this.silent&&this.spinner&&this.spinner.isSpinning&&(this.spinner.succeed(e),this.spinner=null)}stopSpinnerError(e){!this.silent&&this.spinner&&this.spinner.isSpinning&&(this.spinner.fail(e),this.spinner=null)}logResults(e,t){if(this.silent)return;const n=e.filter((e=>e.success)).length,s=e.length-n;this.log("\n"+i.bold("Results:")),this.log(`${i.green(`${n} files`)} processed successfully`),s>0&&(this.log(`${i.red(`${s} files`)} failed to process`),this.log("\n"+i.bold("Errors:")),e.filter((e=>!e.success)).forEach((e=>{this.log(` ${i.red("✗")} ${e.path}: ${e.error}`)})));const r=e.filter((e=>e.success));if(r.length>0){const e=r.reduce(((e,t)=>e+(t.originalSize||0)),0),t=r.reduce(((e,t)=>e+(t.newSize||0)),0),n=e-t,s=e>0?n/e*100:0;this.log("\n"+i.bold("Size Changes:")),this.log(` Original: ${g(e)}`),this.log(` New: ${g(t)}`),n>0?this.log(` Reduced by: ${i.green(g(n))} (${s.toFixed(2)}%)`):n<0?this.log(` Increased by: ${i.yellow(g(Math.abs(n)))} (${Math.abs(s).toFixed(2)}%)`):this.log(" No size change")}this.log("\n"+i.bold.green(`${t} completed.`))}}function g(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(2)} KB`:`${(e/1048576).toFixed(2)} MB`}function f(e,t){var n;if(t){const e=(null===(n=t.split(".").pop())||void 0===n?void 0:n.toLowerCase())||"";if(["js","cjs","mjs"].includes(e))return u.JavaScript;if(["jsx"].includes(e))return u.JSX;if(["ts"].includes(e))return u.TypeScript;if(["tsx"].includes(e))return u.TSX;if(["json"].includes(e))return u.JSON;if(["yaml","yml"].includes(e))return u.YAML;if(["css"].includes(e))return u.CSS;if(["scss","sass"].includes(e))return u.SCSS;if(["less"].includes(e))return u.LESS;if(["html","htm","xhtml","jsp","asp","aspx","cshtml","razor","ejs","hbs","handlebars","pug","jade"].includes(e))return u.HTML;if(["xml","xsd","xsl","xslt"].includes(e))return u.XML;if(["svg"].includes(e))return u.SVG;if(["py","pyw"].includes(e))return u.Python;if(["rb"].includes(e))return u.Ruby;if(["php","php5","phtml","inc"].includes(e))return u.PHP;if(["java"].includes(e))return u.Java;if(["cs"].includes(e))return u.CSharp;if(["c","h"].includes(e))return u.C;if(["cpp","hpp","cc","cxx","c++"].includes(e))return u.CPP;if(["go"].includes(e))return u.Go;if(["swift"].includes(e))return u.Swift;if(["kt"].includes(e))return u.Kotlin;if(["rs"].includes(e))return u.Rust;if(["sh","bash","zsh","fish","ksh"].includes(e))return u.Shell;if(["ps1"].includes(e))return u.PowerShell;if(["bat","cmd"].includes(e))return u.Batch;if(["sql","mysql","pgsql","sqlite","plsql"].includes(e))return u.SQL;if(["md","markdown"].includes(e))return u.Markdown;if(["txt"].includes(e))return u.Text}const i=e.slice(0,1e3).trim();return i.includes("import React")||i.includes('from "react"')||i.includes("from 'react'")||i.match(/<\w+(\s+\w+=".*?")*\s*\/?>/)||i.includes("</")?i.includes(": ")||i.includes("interface ")||i.includes("type ")||i.match(/:\s*[A-Za-z]+[<>]/)||i.includes("as ")?i.includes("JSX")||i.includes("<>")?u.TSX:u.TypeScript:i.includes("JSX")||i.includes("<>")?u.JSX:u.JavaScript:i.startsWith("{")&&i.includes('"')||i.startsWith("[")&&i.includes('"')?u.JSON:i.match(/^[a-zA-Z0-9_-]+:\s*[^\s]/)||i.match(/^\s+- [a-zA-Z0-9_-]+:/)?u.YAML:i.includes("{")&&i.includes("}")&&i.includes(":")&&(i.includes(";")||i.includes("px")||i.includes("em"))?u.CSS:i.match(/<html|<!DOCTYPE|<head|<body|<div/i)?u.HTML:i.match(/<\?xml|<[a-zA-Z0-9_-]+>[\s\S]*?<\/[a-zA-Z0-9_-]+>/)?u.XML:i.includes("<svg")||i.includes("xmlns:svg=")?u.SVG:i.match(/^(import|from|def|class)\s/m)||i.includes('if __name__ == "__main__"')||i.match(/^\s*#.*$/m)?u.Python:i.match(/^(require|class|def|module)\s/m)||i.includes("do |")||i.includes("end")?u.Ruby:i.includes("<?php")||i.match(/^\s*<\?/)?u.PHP:i.match(/public\s+(class|interface|enum)/)||i.match(/import\s+java\./)||i.match(/package\s+[a-z0-9_.]+;/)?u.Java:i.match(/using\s+System;/)||i.match(/namespace\s+[A-Za-z0-9_.]+/)||i.includes("public class ")?u.CSharp:i.match(/#include\s+[<"].*[>"]/)?i.includes("std::")||i.includes("namespace ")?u.CPP:u.C:i.match(/package\s+[a-z0-9_]+/)||i.match(/import\s+\(/)||i.match(/func\s+[A-Za-z0-9_]+\(/)?u.Go:i.match(/import\s+Foundation/)||i.match(/class\s+[A-Za-z0-9_]+\s*:/)||i.match(/func\s+[a-zA-Z0-9_]+\(/)?u.Swift:i.match(/fun\s+[a-zA-Z0-9_]+\(/)||i.match(/val\s+[a-zA-Z0-9_]+:/)||i.match(/var\s+[a-zA-Z0-9_]+:/)?u.Kotlin:i.match(/^#!/)||i.match(/^\s*#.*$/m)||i.match(/echo\s+["']/)||i.match(/export\s+[A-Z_]+=/)?u.Shell:i.includes("function ")&&i.includes("param(")?u.PowerShell:i.match(/^@echo off/i)||i.match(/^REM\s/i)||i.match(/^(set|echo|if|goto)\s/im)?u.Batch:i.match(/SELECT\s+.*\s+FROM/i)||i.match(/CREATE\s+TABLE/i)||i.match(/INSERT\s+INTO/i)||i.match(/UPDATE\s+.*\s+SET/i)?u.SQL:i.match(/^#\s+/)||i.match(/\n#{1,6}\s+/)||i.match(/\[.*\]\(.*\)/)||i.match(/\*\*.*\*\*/)?u.Markdown:i.split("\n").length>1||i.length>0?u.Text:u.Unknown}!function(e){e.JavaScript="javascript",e.TypeScript="typescript",e.JSX="jsx",e.TSX="tsx",e.HTML="html",e.CSS="css",e.SCSS="scss",e.LESS="less",e.JSON="json",e.XML="xml",e.SVG="svg",e.Python="python",e.Ruby="ruby",e.PHP="php",e.Java="java",e.CSharp="csharp",e.CPP="cpp",e.C="c",e.Go="go",e.Swift="swift",e.Kotlin="kotlin",e.Rust="rust",e.Shell="shell",e.PowerShell="powershell",e.Batch="batch",e.SQL="sql",e.Markdown="markdown",e.YAML="yaml",e.Text="text",e.Unknown="unknown"}(u||(u={})),function(e){e.JavaScript="js",e.HTML="html",e.CSS="css",e.JSON="json",e.XML="xml",e.Python="python",e.Ruby="ruby",e.PHP="php",e.CStyle="cstyle",e.Shell="shell",e.SQL="sql",e.Markdown="markdown",e.YAML="yaml",e.Text="text",e.Unknown="unknown"}(d||(d={}));const y=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/package-lock.json","**/yarn.lock","**/*.min.js","**/*.min.css","**/*.bundle.js"];async function S(e,t={}){const n=[...y,...t.ignore||[]],i=(Array.isArray(e)?e:[e]).map((e=>e.replace(/\\/g,"/")));return await r(i,{ignore:n,onlyFiles:!0,absolute:!0,followSymbolicLinks:!1})}function v(e){try{const n=t.readFileSync(e,"utf8");return{content:n,fileType:f(n,e)}}catch(t){throw new Error(`Failed to read file ${e}: ${t.message}`)}}async function w(e,n,i={}){try{const{content:s,fileType:r}=v(e),o=s.length;if(!s.trim())return{path:e,success:!0,fileType:r,originalSize:o,newSize:o,diffSize:0,diffPercentage:0};const a=await n(s,r),l=a.length,c=o-l,u=o>0?c/o*100:0;return i.write&&function(e,n){try{return t.writeFileSync(e,n,"utf8"),!0}catch(t){throw new Error(`Failed to write file ${e}: ${t.message}`)}}(e,a),{path:e,success:!0,fileType:r,originalSize:o,newSize:l,diffSize:c,diffPercentage:u}}catch(t){return{path:e,success:!1,error:t.message}}}async function C(e,t,n={}){const i=await S(e,n),s=[];for(const e of i){const i=await w(e,t,n);s.push(i)}return s}class b{constructor(e,t){this.options={semi:!0,singleQuote:!1,tabWidth:2,useTabs:!1,trailingComma:"es5",bracketSpacing:!0,arrowParens:"always",...e},this.prettier=t}async format(e,t){if(!e.trim())return"";const n="string"==typeof t&&t in u?t:f(e);try{return this.prettier?this.formatWithPrettier(e,n):"undefined"!=typeof window&&window.prettier?this.formatWithBrowserPrettier(e,n):this.formatWithSimpleFormatters(e)}catch(t){return console.warn("Formatting error:",t),e}}formatWithPrettier(e,t){const n=this.getPrettierParser(t);return this.prettier.format(e,{parser:n,...this.options})}formatWithBrowserPrettier(e,t){const n=this.getPrettierParser(t);return window.prettier.format(e,{parser:n,plugins:window.prettierPlugins?Object.values(window.prettierPlugins):void 0,...this.options})}getPrettierParser(e){switch(e){case u.JavaScript:case u.JSX:return"babel";case u.TypeScript:case u.TSX:return"typescript";case u.JSON:return"json";case u.CSS:return"css";case u.HTML:return"html";default:return"babel"}}formatWithSimpleFormatters(e){let t=e;return t=this.indentCode(t),t=this.formatQuotes(t),t=this.formatSemicolons(t),t}indentCode(e){const t=e.split("\n");let n=0;const i=this.options.useTabs?"\t":" ".repeat(this.options.tabWidth);return t.map((e=>{const t=e.trim();if(!t)return"";t.includes("}")&&n>0&&n--;const s=i.repeat(n)+t;return t.includes("{")&&n++,s})).join("\n")}formatQuotes(e){return this.options.singleQuote?e.replace(/"([^"\\]*(?:\\.[^"\\]*)*)"/g,((e,t)=>t.includes("'")?e:`'${t}'`)):e.replace(/'([^'\\]*(?:\\.[^'\\]*)*)'/g,((e,t)=>t.includes('"')?e:`"${t}"`))}formatSemicolons(e){return this.options.semi?e.replace(/(\w+|\)|\}|\])\s*(\n|$)/g,((e,t,n)=>t.endsWith(";")?e:`${t};${n}`)):e.replace(/;(\s*(\n|$))/g,"$1")}updateOptions(e){this.options={...this.options,...e}}getOptions(){return{...this.options}}setPrettier(e){this.prettier=e}async formatFiles(e,t={}){return C(e,(async(e,t)=>this.format(e,t)),t)}}class T{constructor(e){this.options={singleLine:!0,multiLine:!0,jsxComments:!0,emptyLines:!0,...e}}removeComments(e,t){if(!e.trim())return"";const n=function(e){return[u.JavaScript,u.TypeScript,u.JSX,u.TSX].includes(e)?d.JavaScript:[u.HTML,u.SVG].includes(e)?d.HTML:e===u.XML?d.XML:[u.CSS,u.SCSS,u.LESS].includes(e)?d.CSS:e===u.JSON?d.JSON:e===u.YAML?d.YAML:e===u.Python?d.Python:e===u.Ruby?d.Ruby:e===u.PHP?d.PHP:[u.Java,u.CSharp,u.C,u.CPP,u.Go,u.Swift,u.Kotlin,u.Rust].includes(e)?d.CStyle:[u.Shell,u.PowerShell,u.Batch].includes(e)?d.Shell:e===u.SQL?d.SQL:e===u.Markdown?d.Markdown:e===u.Text?d.Text:d.Unknown}("string"==typeof t&&t in u?t:f(e));try{switch(n){case d.JavaScript:return this.removeJavaScriptComments(e);case d.HTML:return this.removeHTMLComments(e);case d.CSS:return this.removeCSSComments(e);case d.JSON:return this.removeJavaScriptComments(e);case d.Text:return e;default:return this.removeJavaScriptComments(e)}}catch(e){throw new Error(`Failed during comment removal: ${e.message}`)}}removeJavaScriptComments(e){let t=e;try{const e=[];let n=0;t=t.replace(/(["'`])(?:\\[\s\S]|(?!\1)[^\\])*\1|\/(?![*+?])(?:[^\r\n\[/\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+\/(?:[gimuy]+\b)?/g,(t=>{const i=`__PRESERVED_ITEM_${n}__`;return e[n]=t,n++,i})),this.options.jsxComments&&(t=t.replace(/\{\/\*[\s\S]*?\*\/\}/g,"")),this.options.multiLine&&(t=t.replace(/\/\*[\s\S]*?\*\//g,"")),this.options.singleLine&&(t=t.replace(/^[ \t]*\/\/.*$/gm,""),t=t.replace(/([^:/])\/\/.*$/gm,"$1"));for(let i=0;i<n;i++){const n=`__PRESERVED_ITEM_${i}__`,s=new RegExp(n,"g");t=t.replace(s,(()=>e[i]))}return this.options.emptyLines&&(t=this.removeEmptyLines(t)),t.trim()}catch(e){throw new Error(`JavaScript comment removal failed: ${e.message}`)}}removeHTMLComments(e){let t=e;try{const e=[];let n=0;t=t.replace(/(["'`])(?:\\[\s\S]|(?!\1)[^\\])*\1/g,(t=>{const i=`__PRESERVED_ITEM_${n}__`;return e[n]=t,n++,i})),this.options.multiLine&&(t=t.replace(/<!--[\s\S]*?-->/g,""));for(let i=0;i<n;i++){const n=`__PRESERVED_ITEM_${i}__`,s=new RegExp(n,"g");t=t.replace(s,(()=>e[i]))}return this.options.emptyLines&&(t=this.removeEmptyLines(t)),t.trim()}catch(e){throw new Error(`HTML comment removal failed: ${e.message}`)}}removeCSSComments(e){let t=e;try{const e=[];let n=0;t=t.replace(/(["'`])(?:\\[\s\S]|(?!\1)[^\\])*\1/g,(t=>{const i=`__PRESERVED_ITEM_${n}__`;return e[n]=t,n++,i})),this.options.multiLine&&(t=t.replace(/\/\*[\s\S]*?\*\//g,""));for(let i=0;i<n;i++){const n=`__PRESERVED_ITEM_${i}__`,s=new RegExp(n,"g");t=t.replace(s,(()=>e[i]))}return this.options.emptyLines&&(t=this.removeEmptyLines(t)),t.trim()}catch(e){throw new Error(`CSS comment removal failed: ${e.message}`)}}removeEmptyLines(e){let t=e.replace(/^\s*[\r\n]/gm,"");return t=t.replace(/\n(\s*)\n(\s*)\n/g,"\n$2\n"),t=t.replace(/^(\s*\n)+/,""),t=t.replace(/(\n\s*)+$/,""),t}updateOptions(e){this.options={...this.options,...e}}getOptions(){return{...this.options}}async cleanFiles(e,t={}){return C(e,(async(e,t)=>this.removeComments(e,t)),t)}}class x{constructor(e){this.startTime=0,this.elapsedTime=0,this.isRunning=!1,this.intervalId=null,this.sessionHistory=[],this.currentSession=null,this.onTickCallback=null,this.onTickCallback=(null==e?void 0:e.onTick)||null,this.tickInterval=(null==e?void 0:e.tickInterval)||100}start(){this.isRunning||(this.startTime=Date.now()-this.elapsedTime,this.isRunning=!0,this.startInterval(),this.currentSession||(this.currentSession={id:Date.now(),startTime:new Date,duration:0,textSnapshots:[]}))}pause(){this.isRunning&&(this.clearInterval(),this.isRunning=!1,this.currentSession&&(this.currentSession.duration=this.elapsedTime))}stop(){this.clearInterval(),this.isRunning=!1,this.currentSession&&(this.currentSession.duration=this.elapsedTime,this.currentSession.endTime=new Date,this.sessionHistory.push(this.currentSession),this.currentSession=null),this.elapsedTime=0}reset(){this.clearInterval(),this.isRunning=!1,this.elapsedTime=0,this.currentSession=null}takeTextSnapshot(e){this.currentSession&&this.currentSession.textSnapshots.push({timestamp:new Date,text:e,elapsedTime:this.elapsedTime})}calculateWritingSpeed(){if(!this.currentSession||this.currentSession.textSnapshots.length<2)return{wordsPerMinute:0,charactersPerMinute:0,totalWords:0,totalCharacters:0,elapsedTimeMs:this.elapsedTime};const e=this.currentSession.textSnapshots,t=e[0],n=e[e.length-1],i=(n.elapsedTime-t.elapsedTime)/6e4;if(i<=0)return{wordsPerMinute:0,charactersPerMinute:0,totalWords:0,totalCharacters:0,elapsedTimeMs:this.elapsedTime};const s=""===t.text.trim()?0:t.text.trim().split(/\s+/).length,r=""===n.text.trim()?0:n.text.trim().split(/\s+/).length,o=Math.max(0,r-s),a=t.text.length,l=n.text.length,c=Math.max(0,l-a);return{wordsPerMinute:Math.round(o/i),charactersPerMinute:Math.round(c/i),totalWords:o,totalCharacters:c,elapsedTimeMs:this.elapsedTime}}get wpm(){const e=this.calculateWritingSpeed();return e?e.wordsPerMinute:0}get words(){const e=this.calculateWritingSpeed();return e?e.totalWords:0}getSessionHistory(){return[...this.sessionHistory]}getElapsedTime(){return this.elapsedTime}getFormattedTime(){return this.formatTime(this.elapsedTime)}isTimerRunning(){return this.isRunning}onTick(e){this.onTickCallback=e}formatTime(e){const t=Math.floor(e/1e3),n=Math.floor(t/3600),i=Math.floor(t%3600/60),s=t%60;return`${String(n).padStart(2,"0")}:${String(i).padStart(2,"0")}:${String(s).padStart(2,"0")}`}startInterval(){this.intervalId=setInterval((()=>{this.elapsedTime=Date.now()-this.startTime,this.onTickCallback&&this.onTickCallback(this.elapsedTime)}),this.tickInterval)}clearInterval(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}}class ${constructor(e="",t=200,n=25,i=60,s){this.text=e,this.wordsPerMinute=t,this.handwritingWpm=n,this.keyboardWpm=i,this.stats=this.calculateStats(),this.handwritingTimer=new x(s)}setText(e){this.text=e,this.stats=this.calculateStats()}getText(){return this.text}setReadingSpeed(e){this.wordsPerMinute=e,this.stats=this.calculateStats()}getReadingSpeed(){return this.wordsPerMinute}getStats(){return{...this.stats}}getCharacterCount(){return this.stats.characters}getCharacterCountNoSpaces(){return this.stats.charactersNoSpaces}getWordCount(){return this.stats.words}getSentenceCount(){return this.stats.sentences}getParagraphCount(){return this.stats.paragraphs}getReadingTime(){return this.stats.readingTime}getHandwritingTime(){return this.stats.handwritingTime||"~0 min"}getKeyboardTime(){return this.stats.keyboardTime||"~0 min"}setHandwritingSpeed(e){this.handwritingWpm=e,this.stats=this.calculateStats()}getHandwritingSpeed(){return this.handwritingWpm}setKeyboardSpeed(e){this.keyboardWpm=e,this.stats=this.calculateStats()}getKeyboardSpeed(){return this.keyboardWpm}calculateStats(){const e=this.text.length,t=this.text.replace(/\s/g,"").length,n=""===this.text.trim()?0:this.text.trim().split(/\s+/).length,i=(e,t)=>{if(0===e)return"~0 min";const n=e/t;return this.formatTimeValue(n)};return{characters:e,charactersNoSpaces:t,words:n,sentences:""===this.text?0:this.text.split(/[.!?]+/).filter((e=>e.trim().length>0)).length,paragraphs:""===this.text?0:this.text.split(/\n\s*\n/).filter((e=>e.trim().length>0)).length,readingTime:i(n,this.wordsPerMinute),handwritingTime:this.estimateHandwritingTime(n,e),keyboardTime:i(n,this.keyboardWpm)}}formatTimeValue(e){if(e<1)return"< 1 min";if(e<60)return`~${Math.ceil(e)} min`;return`~${Math.floor(e/60)}h ${Math.ceil(e%60)}m`}estimateHandwritingTime(e,t){const n=e>0?t/e:0,i=e/(this.handwritingWpm/(1*Math.min(1.5,Math.max(1,n/5))));return this.formatTimeValue(i)}getWordFrequency(){if(!this.text.trim())return{};const e={},t=this.text.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter((e=>e.length>0));for(const n of t)e[n]=(e[n]||0)+1;return e}getMostFrequentWords(e=10){const t=this.getWordFrequency();return Object.entries(t).sort(((e,t)=>t[1]-e[1])).slice(0,e)}getReadabilityScore(){if(!this.text.trim())return 100;const e=this.stats.words,t=this.stats.sentences;if(0===e||0===t)return 100;const n=206.835-e/t*1.015-this.countSyllables()/e*84.6;return Math.max(0,Math.min(100,n))}countSyllables(){var e;if(!this.text.trim())return 0;const t=this.text.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter((e=>e.length>0));let n=0;for(const i of t){let t=(null===(e=i.match(/[aeiouy]{1,2}/g))||void 0===e?void 0:e.length)||0;i.length>3&&i.endsWith("e")&&t--,n+=Math.max(1,t)}return n}startWritingSession(){this.handwritingTimer.start()}pauseWritingSession(){this.handwritingTimer.pause()}stopWritingSession(){this.handwritingTimer.stop()}resetWritingSession(){this.handwritingTimer.reset()}updateText(e){this.handwritingTimer.takeTextSnapshot(e),this.setText(e)}getWritingSpeed(){return this.handwritingTimer.calculateWritingSpeed()}getWritingSessionHistory(){return this.handwritingTimer.getSessionHistory()}getElapsedTime(){return this.handwritingTimer.getElapsedTime()}getFormattedElapsedTime(){return this.handwritingTimer.getFormattedTime()}isTimerRunning(){return this.handwritingTimer.isTimerRunning()}onTimerTick(e){this.handwritingTimer.onTick(e)}async analyzeFiles(e,t={}){const n=await S(e,t),i=[];for(const e of n)try{const{content:t,fileType:n}=v(e),s=t.length;if(!t.trim()){i.push({path:e,success:!0,fileType:n,originalSize:s,newSize:s,diffSize:0,diffPercentage:0,stats:{characters:0,charactersNoSpaces:0,words:0,sentences:0,paragraphs:0,readingTime:"0 min",handwritingTime:"0 min",keyboardTime:"0 min"},frequentWords:[],readabilityScore:100});continue}this.setText(t);const r=this.getStats(),o=this.getMostFrequentWords(10),a=this.getReadabilityScore();i.push({path:e,success:!0,fileType:n,originalSize:s,newSize:s,diffSize:0,diffPercentage:0,stats:r,frequentWords:o,readabilityScore:a})}catch(t){i.push({path:e,success:!1,error:t.message})}return i}}function E(e){return e.split(",").map((e=>e.trim()))}function P(e,t){const n=e.filter((e=>e.success&&e.stats&&e.stats[t]));if(0===n.length)return"~0 min";if("handwritingTime"===t){const e=n.reduce(((e,t)=>e+t.stats.words),0),t=n.reduce(((e,t)=>e+t.stats.characters),0),i=e>0?t/e:0;return F(e/(25/(Math.min(1.5,Math.max(1,i/5))*1)))}const i=n.map((e=>{const n=e.stats[t];if(n.includes("h")){return 60*(parseInt(n.split("h")[0].replace(/[^0-9]/g,""),10)||0)+(parseInt(n.split("h")[1].replace(/[^0-9]/g,""),10)||0)}return parseInt(n.replace(/[^0-9]/g,""),10)||0}));return F(i.reduce(((e,t)=>e+t),0)/i.length)}function F(e){if(e<1)return"< 1 min";if(e<60)return`~${Math.ceil(e)} min`;return`~${Math.floor(e/60)}h ${Math.ceil(e%60)}m`}class A{applyWithoutAST(e,t){return[]}getLineAndColumn(e,t){const n=e.slice(0,t).split("\n");return{line:n.length,column:n[n.length-1].length+1}}getCodeSnippet(e,t,n){return e.slice(t,n)}createFinding(e){return{id:this.id,message:e.message,severity:e.severity||this.defaultSeverity,category:this.category,filePath:e.filePath,line:e.line,column:e.column,endLine:e.endLine,endColumn:e.endColumn,code:e.code,suggestion:e.suggestion,explanation:e.explanation||this.description,functionName:e.functionName}}generateSuggestion(e,...t){return"// Consider refactoring this code to address the issue"}getFunctionName(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isFunctionExpression()||t.isArrowFunctionExpression()){if(t.node.id&&t.node.id.name)return t.node.id.name;const e=t.parentPath;return e&&e.isVariableDeclarator()&&e.node.id&&p.isIdentifier(e.node.id)?e.node.id.name:"anonymous function"}t=t.parentPath}}}var M,k;!function(e){e.Info="info",e.Warning="warning",e.Error="error",e.Critical="critical"}(M||(M={})),function(e){e.Performance="performance",e.Security="security",e.Maintainability="maintainability",e.Bugs="bugs",e.Style="style"}(k||(k={}));class L extends A{constructor(){super(...arguments),this.id="perf-nested-loops",this.name="Nested Loops",this.description="Detects nested loops that could be optimized for better performance",this.category=k.Performance,this.defaultSeverity=M.Warning,this.requiresAST=!0}apply(e,t,n){const i=[];return l(t,{ForStatement:t=>{var s,r;const o=t.parentPath;if(o.isForStatement()||o.isWhileStatement()||o.isDoWhileStatement()||o.isForInStatement()||o.isForOfStatement()){const a=o.node,l=t.node,c=null===(s=a.loc)||void 0===s?void 0:s.start,u=null===(r=l.loc)||void 0===r?void 0:r.end;if(c&&u){const s=e.slice(a.start||0,l.end||e.length);i.push(this.createFinding({message:"Nested loops detected - consider optimizing",filePath:n,line:c.line,column:c.column+1,endLine:u.line,endColumn:u.column+1,code:s,suggestion:this.generateSuggestion(s),explanation:"Nested loops have O(n²) time complexity. Consider using map/reduce/filter or restructuring the data to avoid nested iterations.",functionName:this.getFunctionName(t)}))}}}}),i}generateSuggestion(e){return"// Consider using Array methods instead of nested loops\nconst result = outerArray.flatMap(outerItem =>\n innerArray.map(innerItem => {\n // Your logic here\n return { outerItem, innerItem };\n })\n);"}}class R extends A{constructor(){super(...arguments),this.id="security-unsafe-eval",this.name="Unsafe Eval Usage",this.description="Detects potentially dangerous use of eval() and similar functions",this.category=k.Security,this.defaultSeverity=M.Critical,this.requiresAST=!0,this.dangerousFunctions=["eval","Function","setTimeout","setInterval","setImmediate","execScript","new Function"]}apply(e,t,n){const i=[];return l(t,{CallExpression:t=>{var s,r,o,a,l,c;const u=t.node.callee;if(p.isIdentifier(u)&&"eval"===u.name){const o=null===(s=t.node.loc)||void 0===s?void 0:s.start,a=null===(r=t.node.loc)||void 0===r?void 0:r.end;if(o&&a){const s=e.slice(t.node.start||0,t.node.end||e.length);i.push({id:this.id,message:"Unsafe use of eval() detected",severity:M.Critical,category:this.category,filePath:n,line:o.line,column:o.column+1,endLine:a.line,endColumn:a.column+1,code:s,suggestion:this.generateSuggestion(s),explanation:"Using eval() can introduce security vulnerabilities through code injection. It also makes your code slower and harder to debug.",functionName:this.getFunctionName(t)})}}if(p.isIdentifier(u)){const s=u.name;if(this.dangerousFunctions.includes(s)&&"eval"!==s){const r=t.node.arguments[0];if(p.isStringLiteral(r)&&r.value.includes("+")||p.isTemplateLiteral(r)||p.isBinaryExpression(r)){const r=null===(o=t.node.loc)||void 0===o?void 0:o.start,l=null===(a=t.node.loc)||void 0===a?void 0:a.end;if(r&&l){const o=e.slice(t.node.start||0,t.node.end||e.length);i.push(this.createFinding({message:`Potentially unsafe use of ${s}() with dynamic string`,severity:M.Error,filePath:n,line:r.line,column:r.column+1,endLine:l.line,endColumn:l.column+1,code:o,suggestion:this.generateAlternativeSuggestion(s,o),explanation:`Using ${s}() with dynamic strings can introduce security vulnerabilities through code injection.`,functionName:this.getFunctionName(t)}))}}}}if(p.isNewExpression(t.node)){const s=t.node;if(p.isIdentifier(s.callee)&&"Function"===s.callee.name){const r=null===(l=s.loc)||void 0===l?void 0:l.start,o=null===(c=s.loc)||void 0===c?void 0:c.end;if(r&&o){const a=e.slice(s.start||0,s.end||e.length);i.push({id:this.id,message:"Unsafe use of new Function() detected",severity:M.Critical,category:this.category,filePath:n,line:r.line,column:r.column+1,endLine:o.line,endColumn:o.column+1,code:a,suggestion:this.generateSuggestion(a),explanation:"Using new Function() can introduce security vulnerabilities through code injection. It also makes your code slower and harder to debug.",functionName:this.getFunctionName(t)})}}}}}),i}generateSuggestion(e){return"// Instead of using eval, consider:\n// 1. Using JSON.parse() for JSON data\n// 2. Using a predefined set of functions\n// 3. Restructuring your code to avoid dynamic execution\n\n// Example:\nconst data = JSON.parse(jsonString);\nconst result = predefinedFunctions[functionName](data);"}generateAlternativeSuggestion(e,t){return"setTimeout"===e||"setInterval"===e?`// Instead of passing a string to ${e}, use a function:\n${e}(() => {\n // Your code here\n}, delay);`:`// Avoid using ${e} with dynamic strings.\n// Consider using a safer alternative or restructuring your code.`}}class _ extends A{constructor(){super(...arguments),this.id="maint-complex-function",this.name="Complex Function",this.description="Detects functions with high cyclomatic complexity",this.category=k.Maintainability,this.defaultSeverity=M.Warning,this.requiresAST=!0,this.WARNING_THRESHOLD=10,this.ERROR_THRESHOLD=20,this.CRITICAL_THRESHOLD=30}apply(e,t,n){const i=[];return l(t,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression":t=>{var s,r;const o=t.node,a=this.getFunctionName(t),l=this.calculateComplexity(t);if(l>=this.WARNING_THRESHOLD){const t=null===(s=o.loc)||void 0===s?void 0:s.start,c=null===(r=o.loc)||void 0===r?void 0:r.end;if(t&&c){const s=e.slice(o.start||0,o.end||e.length);let r=M.Warning;l>=this.CRITICAL_THRESHOLD?r=M.Critical:l>=this.ERROR_THRESHOLD&&(r=M.Error),i.push(this.createFinding({message:`Function has high cyclomatic complexity (${l})`,severity:r,filePath:n,line:t.line,column:t.column+1,endLine:c.line,endColumn:c.column+1,code:s,suggestion:this.generateSuggestion(s,a||"function"),explanation:`Functions with high cyclomatic complexity (${l}) are difficult to understand, test, and maintain. Consider refactoring into smaller, more focused functions.`,functionName:a}))}}}}),i}calculateComplexity(e){let t=1;return l(e.node,{IfStatement:()=>{t++},ConditionalExpression:()=>{t++},SwitchCase:e=>{e.node.test&&t++},ForStatement:()=>{t++},ForInStatement:()=>{t++},ForOfStatement:()=>{t++},WhileStatement:()=>{t++},DoWhileStatement:()=>{t++},LogicalExpression:e=>{"&&"!==e.node.operator&&"||"!==e.node.operator||t++},CatchClause:()=>{t++},"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression":e=>{e.skip()}},e.scope),t}generateSuggestion(e,t){return`// Consider refactoring ${t} into smaller functions:\nfunction ${t}() {\n // Main logic with reduced complexity\n this.helperFunction1();\n this.helperFunction2();\n}\n\nfunction helperFunction1() {\n // Extract some of the logic here\n}\n\nfunction helperFunction2() {\n // Extract more logic here\n}`}getFunctionName(e){const t=e.node;if(p.isFunctionDeclaration(t)&&t.id)return t.id.name;if(p.isFunctionExpression(t)||p.isArrowFunctionExpression(t)){const n=e.parent;if(p.isVariableDeclarator(n)&&p.isIdentifier(n.id))return n.id.name;if(p.isObjectProperty(n)&&p.isIdentifier(n.key))return n.key.name;if(p.isClassMethod(n)&&p.isIdentifier(n.key))return n.key.name;if(p.isFunctionExpression(t)&&t.id)return t.id.name}}}class I extends A{constructor(){super(...arguments),this.id="maint-deep-nesting",this.name="Deep Nesting",this.description="Detects deeply nested code blocks that reduce readability",this.category=k.Maintainability,this.defaultSeverity=M.Warning,this.requiresAST=!0}apply(e,t,n){return[]}generateSuggestion(e,t){return"// Consider refactoring deeply nested code"}}class N extends A{constructor(){super(...arguments),this.id="bugs-unhandled-promise",this.name="Unhandled Promise",this.description="Detects promises without proper error handling",this.category=k.Bugs,this.defaultSeverity=M.Error,this.requiresAST=!0}apply(e,t,n){const i=[];return l(t,{CallExpression:t=>{var s,r;if(this.isPromiseReturningCall(t.node)&&!this.isPromiseHandled(t)){const o=null===(s=t.node.loc)||void 0===s?void 0:s.start,a=null===(r=t.node.loc)||void 0===r?void 0:r.end;if(o&&a){const s=e.slice(t.node.start||0,t.node.end||e.length);i.push(this.createFinding({message:"Unhandled promise rejection detected",filePath:n,line:o.line,column:o.column+1,endLine:a.line,endColumn:a.column+1,code:s,suggestion:this.generateSuggestion(s),explanation:"Unhandled promise rejections can lead to silent failures and make debugging difficult. Always handle potential errors in promises with .catch() or try/catch in async functions.",functionName:this.getFunctionName(t)}))}}}}),i}isPromiseReturningCall(e){if(p.isMemberExpression(e.callee)){const t=e.callee.property;if(p.isIdentifier(t)){const e=t.name;if(["fetch","then","catch","finally","request","get","post","put","delete","axios"].includes(e))return!0}}if(p.isIdentifier(e.callee)){const t=e.callee.name;if(["fetch","Promise","axios","request"].includes(t))return!0;if(t.startsWith("get")||t.startsWith("fetch")||t.startsWith("load")||t.startsWith("request")||t.includes("Async"))return!0}return!1}isPromiseHandled(e){const t=e.parentPath;if(t&&t.isMemberExpression()&&t.parentPath&&t.parentPath.isCallExpression()){const e=t.node.property;if(p.isIdentifier(e)&&("then"===e.name||"catch"===e.name))return!0}let n=e;for(;n;){if(n.isAwaitExpression()){let e=n;for(;e;){if(e.isTryStatement())return!0;e=e.parentPath}return!1}if(n.isVariableDeclarator()||n.isAssignmentExpression())return!1;n=n.parentPath}return!1}generateSuggestion(e){return`// Add error handling to your promise\n${e}\n .then(result => {\n // Handle successful result\n })\n .catch(error => {\n // Handle error properly\n console.error('Operation failed:', error);\n });\n\n// Or using async/await with try/catch:\ntry {\n const result = await ${e};\n // Handle successful result\n} catch (error) {\n // Handle error properly\n console.error('Operation failed:', error);\n}`}getFunctionName(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isFunctionExpression()||t.isArrowFunctionExpression()){if(t.node.id&&t.node.id.name)return t.node.id.name;const e=t.parentPath;return e&&e.isVariableDeclarator()&&e.node.id&&p.isIdentifier(e.node.id)?e.node.id.name:"anonymous function"}t=t.parentPath}}}class j extends A{constructor(){super(...arguments),this.id="bugs-inconsistent-return",this.name="Inconsistent Return",this.description="Detects functions with inconsistent return types or missing returns",this.category=k.Bugs,this.defaultSeverity=M.Warning,this.requiresAST=!0}apply(e,t,n){return[]}generateSuggestion(e,t){return"// Consider making return types consistent"}}class W extends A{constructor(){super(...arguments),this.id="style-naming-convention",this.name="Naming Convention",this.description="Enforces consistent naming conventions for variables, functions, and classes",this.category=k.Style,this.defaultSeverity=M.Info,this.requiresAST=!0,this.CONSTANT_PATTERN=/^[A-Z][A-Z0-9_]*$/,this.CAMEL_CASE_PATTERN=/^[a-z][a-zA-Z0-9]*$/,this.PASCAL_CASE_PATTERN=/^[A-Z][a-zA-Z0-9]*$/,this.PRIVATE_MEMBER_PATTERN=/^_[a-z][a-zA-Z0-9]*$/}apply(e,t,n){const i=[];return l(t,{VariableDeclarator:t=>{const s=t.node;if(p.isIdentifier(s.id)){const r=s.id.name;if(t.parentPath.isVariableDeclaration()){if("const"===t.parentPath.node.kind){const t=s.init;t&&(p.isStringLiteral(t)||p.isNumericLiteral(t)||p.isBooleanLiteral(t)||p.isNullLiteral(t))?this.CONSTANT_PATTERN.test(r)||r.toUpperCase()===r||this.addNamingFinding(i,s,e,n,r,"Constants should use UPPER_CASE",this.toUpperSnakeCase(r)):!t||p.isObjectExpression(t)||p.isArrayExpression(t)||p.isFunctionExpression(t)||p.isArrowFunctionExpression(t)||this.CAMEL_CASE_PATTERN.test(r)||this.addNamingFinding(i,s,e,n,r,"Variables should use camelCase",this.toCamelCase(r))}else this.CAMEL_CASE_PATTERN.test(r)||this.addNamingFinding(i,s,e,n,r,"Variables should use camelCase",this.toCamelCase(r))}}},FunctionDeclaration:t=>{const s=t.node;if(s.id){const t=s.id.name;this.CAMEL_CASE_PATTERN.test(t)||this.addNamingFinding(i,s,e,n,t,"Functions should use camelCase",this.toCamelCase(t))}},ClassDeclaration:t=>{const s=t.node;if(s.id){const t=s.id.name;this.PASCAL_CASE_PATTERN.test(t)||this.addNamingFinding(i,s,e,n,t,"Classes should use PascalCase",this.toPascalCase(t))}},ClassProperty:t=>{const s=t.node;if(p.isIdentifier(s.key)){const t=s.key.name;"private"!==s.accessibility||this.PRIVATE_MEMBER_PATTERN.test(t)?"private"===s.accessibility||this.CAMEL_CASE_PATTERN.test(t)||this.addNamingFinding(i,s,e,n,t,"Class members should use camelCase",this.toCamelCase(t)):this.addNamingFinding(i,s,e,n,t,"Private class members should start with underscore and use camelCase",`_${this.toCamelCase(t.startsWith("_")?t.slice(1):t)}`)}}}),i}addNamingFinding(e,t,n,i,s,r,o){var a,l;const c=null===(a=t.loc)||void 0===a?void 0:a.start,u=null===(l=t.loc)||void 0===l?void 0:l.end;if(c&&u){const a=n.slice(t.start||0,t.end||n.length);e.push(this.createFinding({message:`${r}: '${s}'`,filePath:i,line:c.line,column:c.column+1,endLine:u.line,endColumn:u.column+1,code:a,suggestion:a.replace(s,o),explanation:`Consistent naming conventions improve code readability and maintainability. Consider renaming '${s}' to '${o}'.`}))}}toCamelCase(e){return e.replace(/[^\w\s]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s_-]+/).map(((e,t)=>0===t?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())).join("")}toPascalCase(e){return e.replace(/[^\w\s]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s_-]+/).map((e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())).join("")}toUpperSnakeCase(e){return e.replace(/[^\w\s]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s_-]+/).map((e=>e.toUpperCase())).join("_")}}class z{constructor(e={}){this.options={minSeverity:M.Info,categories:Object.values(k),...e},this.rules=[new L,new R,new _,new I,new N,new j,new W]}async analyzeFile(e){try{const n=t.readFileSync(e,"utf8"),i=f(n,e);if(![u.JavaScript,u.TypeScript,u.JSX,u.TSX].includes(i))return{filePath:e,fileType:i,findings:[],success:!0};const s=this.parseCode(n,i),r=[];if(s)for(const t of this.rules){if(this.options.categories&&!this.options.categories.includes(t.category))continue;const i=t.apply(n,s,e).filter((e=>this.compareSeverity(e.severity,this.options.minSeverity||M.Info)>=0));r.push(...i)}for(const t of this.rules)if(!t.requiresAST&&(!this.options.categories||this.options.categories.includes(t.category))){const i=t.applyWithoutAST(n,e).filter((e=>this.compareSeverity(e.severity,this.options.minSeverity||M.Info)>=0));r.push(...i)}return{filePath:e,fileType:i,findings:r,success:!0}}catch(t){return{filePath:e,fileType:u.Unknown,findings:[],success:!1,error:t.message}}}async analyzeFiles(e){const t=await this.findFiles(e),n=[];for(const e of t){const t=await this.analyzeFile(e);n.push(t)}return n}async findFiles(e){const t=require("fast-glob"),n=require("ignore"),i=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/package-lock.json","**/yarn.lock","**/*.min.js","**/*.min.css","**/*.bundle.js"],s=this.options.ignore?[...i,...this.options.ignore]:i;n().add(s);const r=Array.isArray(e)?e.map((e=>e.replace(/\\/g,"/"))):e.replace(/\\/g,"/");return await t(r,{ignore:s,onlyFiles:!0,absolute:!0,followSymbolicLinks:!1})}parseCode(e,t){try{const n=[];return[u.TypeScript,u.TSX].includes(t)&&n.push("typescript"),[u.JSX,u.TSX].includes(t)&&n.push("jsx"),n.push("classProperties"),n.push("decorators-legacy"),n.push("objectRestSpread"),n.push("optionalChaining"),n.push("nullishCoalescingOperator"),h.parse(e,{sourceType:"module",plugins:n})}catch(e){return null}}compareSeverity(e,t){const n=[M.Info,M.Warning,M.Error,M.Critical];return n.indexOf(e)-n.indexOf(t)}}function O(){}function D(e,t,n,i,s){for(var r,o=[];t;)o.push(t),r=t.previousComponent,delete t.previousComponent,t=r;o.reverse();for(var a=0,l=o.length,c=0,u=0;a<l;a++){var d=o[a];if(d.removed){if(d.value=e.join(i.slice(u,u+d.count)),u+=d.count,a&&o[a-1].added){var h=o[a-1];o[a-1]=o[a],o[a]=h}}else{if(!d.added&&s){var p=n.slice(c,c+d.count);p=p.map((function(e,t){var n=i[u+t];return n.length>e.length?n:e})),d.value=e.join(p)}else d.value=e.join(n.slice(c,c+d.count));c+=d.count,d.added||(u+=d.count)}}var m=o[l-1];return l>1&&"string"==typeof m.value&&(m.added||m.removed)&&e.equals("",m.value)&&(o[l-2].value+=m.value,o.pop()),o}O.prototype={diff:function(e,t){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=i.callback;"function"==typeof i&&(s=i,i={}),this.options=i;var r=this;function o(e){return s?(setTimeout((function(){s(void 0,e)}),0),!0):e}e=this.castInput(e),t=this.castInput(t),e=this.removeEmpty(this.tokenize(e));var a=(t=this.removeEmpty(this.tokenize(t))).length,l=e.length,c=1,u=a+l;i.maxEditLength&&(u=Math.min(u,i.maxEditLength));var d=null!==(n=i.timeout)&&void 0!==n?n:1/0,h=Date.now()+d,p=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(p[0],t,e,0);if(p[0].oldPos+1>=l&&m+1>=a)return o([{value:this.join(t),count:t.length}]);var g=-1/0,f=1/0;function y(){for(var n=Math.max(g,-c);n<=Math.min(f,c);n+=2){var i=void 0,s=p[n-1],u=p[n+1];s&&(p[n-1]=void 0);var d=!1;if(u){var h=u.oldPos-n;d=u&&0<=h&&h<a}var y=s&&s.oldPos+1<l;if(d||y){if(i=!y||d&&s.oldPos+1<u.oldPos?r.addToPath(u,!0,void 0,0):r.addToPath(s,void 0,!0,1),m=r.extractCommon(i,t,e,n),i.oldPos+1>=l&&m+1>=a)return o(D(r,i.lastComponent,t,e,r.useLongestToken));p[n]=i,i.oldPos+1>=l&&(f=Math.min(f,n-1)),m+1>=a&&(g=Math.max(g,n+1))}else p[n]=void 0}c++}if(s)!function e(){setTimeout((function(){if(c>u||Date.now()>h)return s();y()||e()}),0)}();else for(;c<=u&&Date.now()<=h;){var S=y();if(S)return S}},addToPath:function(e,t,n,i){var s=e.lastComponent;return s&&s.added===t&&s.removed===n?{oldPos:e.oldPos+i,lastComponent:{count:s.count+1,added:t,removed:n,previousComponent:s.previousComponent}}:{oldPos:e.oldPos+i,lastComponent:{count:1,added:t,removed:n,previousComponent:s}}},extractCommon:function(e,t,n,i){for(var s=t.length,r=n.length,o=e.oldPos,a=o-i,l=0;a+1<s&&o+1<r&&this.equals(t[a+1],n[o+1]);)a++,o++,l++;return l&&(e.lastComponent={count:l,previousComponent:e.lastComponent}),e.oldPos=o,a},equals:function(e,t){return this.options.comparator?this.options.comparator(e,t):e===t||this.options.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};var q=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,H=/\S/,J=new O;J.equals=function(e,t){return this.options.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||this.options.ignoreWhitespace&&!H.test(e)&&!H.test(t)},J.tokenize=function(e){for(var t=e.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),n=0;n<t.length-1;n++)!t[n+1]&&t[n+2]&&q.test(t[n])&&q.test(t[n+2])&&(t[n]+=t[n+2],t.splice(n+1,2),n--);return t};var B=new O;function U(e){return U="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},U(e)}B.tokenize=function(e){this.options.stripTrailingCr&&(e=e.replace(/\r\n/g,"\n"));var t=[],n=e.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var i=0;i<n.length;i++){var s=n[i];i%2&&!this.options.newlineIsToken?t[t.length-1]+=s:(this.options.ignoreWhitespace&&(s=s.trim()),t.push(s))}return t},(new O).tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)},(new O).tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};var X=Object.prototype.toString,V=new O;function Z(e,t,n,i,s){var r,o;for(t=t||[],n=n||[],i&&(e=i(s,e)),r=0;r<t.length;r+=1)if(t[r]===e)return n[r];if("[object Array]"===X.call(e)){for(t.push(e),o=new Array(e.length),n.push(o),r=0;r<e.length;r+=1)o[r]=Z(e[r],t,n,i,s);return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),"object"===U(e)&&null!==e){t.push(e),o={},n.push(o);var a,l=[];for(a in e)e.hasOwnProperty(a)&&l.push(a);for(l.sort(),r=0;r<l.length;r+=1)o[a=l[r]]=Z(e[a],t,n,i,a);t.pop(),n.pop()}else o=e;return o}V.useLongestToken=!0,V.tokenize=B.tokenize,V.castInput=function(e){var t=this.options,n=t.undefinedReplacement,i=t.stringifyReplacer,s=void 0===i?function(e,t){return void 0===t?n:t}:i;return"string"==typeof e?e:JSON.stringify(Z(e,null,null,s),s," ")},V.equals=function(e,t){return O.prototype.equals.call(V,e.replace(/,([\r\n])/g,"$1"),t.replace(/,([\r\n])/g,"$1"))};var Q=new O;function G(){const s=new e.Command("analyze-code");return s.description("Analyze code for potential issues, bugs, and improvements").argument("<patterns...>",'File patterns to analyze (e.g., "src/**/*.js")').option("--severity <level>","Minimum severity level to report (info, warning, error, critical)","info").option("--category <categories>","Categories to include (comma-separated: performance, security, maintainability, bugs, style)",Y).option("--ignore <pattern>","Files to ignore (comma-separated)",K).option("--max-depth <depth>","Maximum depth for recursive analysis",parseInt).option("--root-dir <path>","Root directory for analysis").option("--output <path>","Write report to file (json or html)").option("--format <format>","Output format (text, json, html)","text").option("--silent","Suppress output",!1).action((async(e,s)=>{const r=new m(s.silent);try{const o=function(e){switch(e.toLowerCase()){case"info":return M.Info;case"warning":return M.Warning;case"error":return M.Error;case"critical":return M.Critical;default:throw new Error(`Invalid severity level: ${e}`)}}(s.severity),a=new z({minSeverity:o,categories:s.category,ignore:s.ignore,maxDepth:s.maxDepth,rootDir:s.rootDir,dryRun:s.dryRun});r.startSpinner("Analyzing code...");const l=await a.analyzeFiles(e),c=l.reduce(((e,t)=>e+t.findings.length),0);if(r.stopSpinnerSuccess(`Analyzed ${l.length} files, found ${c} issues`),!s.silent){const e=l.filter((e=>e.success)),o=l.filter((e=>!e.success));if(o.length>0&&(r.log("\n"+i.bold("Errors:")),o.forEach((e=>{r.error(`Failed to analyze ${e.filePath}: ${e.error}`)}))),c>0){r.log("\n"+i.bold("Findings:"));const t={};e.forEach((e=>{e.findings.length>0&&(t[e.filePath]=e.findings)})),Object.entries(t).forEach((([e,t])=>{r.log(`\n${i.underline(e)}`),t.sort(((e,t)=>e.line-t.line)),t.forEach((e=>{let t,n;switch(e.severity){case M.Critical:t=i.bgRed.white;break;case M.Error:t=i.red;break;case M.Warning:t=i.yellow;break;default:t=i.blue}switch(e.category){case k.Performance:n=i.magenta;break;case k.Security:n=i.red;break;case k.Maintainability:n=i.cyan;break;case k.Bugs:n=i.yellow;break;default:n=i.gray}if(r.log(` ${t(e.severity.toUpperCase())} ${n(`[${e.category}]`)} Line ${e.line}${e.column?`:${e.column}`:""}: ${e.message}`),r.log(""),r.log(i.gray(" │ "+e.code.replace(/\n/g,"\n │ "))),r.log(""),e.suggestion){if(r.log(i.green(" Suggestion:")),e.code&&e.suggestion){(s=e.code,o=e.suggestion,B.diff(s,o,a)).forEach((e=>{const t=e.added?i.green:e.removed?i.red:i.gray,n=e.added?"+ ":e.removed?"- ":" ";e.value.trim()&&e.value.split("\n").forEach((e=>{e.trim()&&r.log(t(` ${n}${e}`))}))}))}else r.log(i.green(" "+e.suggestion.replace(/\n/g,"\n ")));r.log("")}var s,o,a;r.log(i.gray(" "+e.explanation)),r.log("")}))}))}r.log("\n"+i.bold("Summary:"));const a={[M.Info]:0,[M.Warning]:0,[M.Error]:0,[M.Critical]:0},u={[k.Performance]:0,[k.Security]:0,[k.Maintainability]:0,[k.Bugs]:0,[k.Style]:0};e.forEach((e=>{e.findings.forEach((e=>{a[e.severity]++,u[e.category]++}))})),r.log(" Severity:"),r.log(` ${i.red("Critical")}: ${a[M.Critical]}`),r.log(` ${i.red("Error")}: ${a[M.Error]}`),r.log(` ${i.yellow("Warning")}: ${a[M.Warning]}`),r.log(` ${i.blue("Info")}: ${a[M.Info]}`),r.log(" Category:"),r.log(` ${i.magenta("Performance")}: ${u[k.Performance]}`),r.log(` ${i.red("Security")}: ${u[k.Security]}`),r.log(` ${i.cyan("Maintainability")}: ${u[k.Maintainability]}`),r.log(` ${i.yellow("Bugs")}: ${u[k.Bugs]}`),r.log(` ${i.gray("Style")}: ${u[k.Style]}`);const d=function(e,t,n){let i=100;i-=10*e[M.Critical],i-=5*e[M.Error],i-=2*e[M.Warning],i-=.5*e[M.Info];const s=2*Math.log10(Math.max(1,n));return i=Math.min(100,i+s),Math.max(0,Math.min(100,i))}(a,0,l.length);if(r.log(` Quality Score: ${function(e){let t,n;e>=90?(t="A+",n=i.green):e>=85?(t="A",n=i.green):e>=80?(t="A-",n=i.green):e>=75?(t="B+",n=i.greenBright):e>=70?(t="B",n=i.greenBright):e>=65?(t="B-",n=i.greenBright):e>=60?(t="C+",n=i.yellow):e>=55?(t="C",n=i.yellow):e>=50?(t="C-",n=i.yellow):e>=45?(t="D+",n=i.red):e>=40?(t="D",n=i.red):(t="F",n=i.redBright);return n(`${t} (${Math.round(e)})`)}(d)}`),s.output){"html"===(".html"===n.extname(s.output).toLowerCase()?"html":"json")?(!function(e,n,i){const s=`<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n <title>Code Analysis Report</title>\n <style>\n body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; line-height: 1.6; color: #333; max-width: 1200px; margin: 0 auto; padding: 20px; }\n h1, h2, h3 { margin-top: 24px; }\n .summary { display: flex; flex-wrap: wrap; gap: 20px; margin-bottom: 30px; }\n .summary-card { background: #f5f5f5; border-radius: 8px; padding: 16px; flex: 1; min-width: 200px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }\n .file { margin-bottom: 30px; border: 1px solid #ddd; border-radius: 8px; overflow: hidden; }\n .file-header { background: #f0f0f0; padding: 10px 16px; font-weight: bold; border-bottom: 1px solid #ddd; }\n .finding { padding: 16px; border-bottom: 1px solid #eee; }\n .finding:last-child { border-bottom: none; }\n .severity { display: inline-block; padding: 3px 8px; border-radius: 4px; font-size: 12px; font-weight: bold; margin-right: 8px; }\n .severity.critical { background: #ffebee; color: #d32f2f; }\n .severity.error { background: #ffebee; color: #f44336; }\n .severity.warning { background: #fff8e1; color: #ff8f00; }\n .severity.info { background: #e3f2fd; color: #1976d2; }\n .category { display: inline-block; padding: 3px 8px; border-radius: 4px; font-size: 12px; margin-right: 8px; background: #f5f5f5; }\n .location { font-family: monospace; color: #666; }\n .code { background: #f8f8f8; padding: 12px; border-radius: 4px; overflow-x: auto; margin: 12px 0; font-family: monospace; white-space: pre; }\n .suggestion { background: #e8f5e9; padding: 12px; border-radius: 4px; margin: 12px 0; }\n .explanation { color: #666; font-style: italic; }\n .diff-added { background: #e6ffed; color: #22863a; }\n .diff-removed { background: #ffeef0; color: #cb2431; }\n </style>\n</head>\n<body>\n <h1>Code Analysis Report</h1>\n <p>Generated on ${(new Date).toLocaleString()}</p>\n\n <div class="summary">\n <div class="summary-card">\n <h3>Overview</h3>\n <p>Files analyzed: ${n.length}</p>\n <p>Quality score: ${function(e){let t,n;e>=90?(t="A+",n="#4caf50"):e>=85?(t="A",n="#4caf50"):e>=80?(t="A-",n="#4caf50"):e>=75?(t="B+",n="#8bc34a"):e>=70?(t="B",n="#8bc34a"):e>=65?(t="B-",n="#8bc34a"):e>=60?(t="C+",n="#ffc107"):e>=55?(t="C",n="#ffc107"):e>=50?(t="C-",n="#ffc107"):e>=45?(t="D+",n="#ff5722"):e>=40?(t="D",n="#ff5722"):(t="F",n="#f44336");return`<span style="color: ${n}; font-weight: bold;">${t}</span> (${Math.round(e)})`}(i.qualityScore)}</p>\n </div>\n\n <div class="summary-card">\n <h3>Severity</h3>\n <p>Critical: ${i.severityCounts.critical||0}</p>\n <p>Error: ${i.severityCounts.error||0}</p>\n <p>Warning: ${i.severityCounts.warning||0}</p>\n <p>Info: ${i.severityCounts.info||0}</p>\n </div>\n\n <div class="summary-card">\n <h3>Category</h3>\n <p>Performance: ${i.categoryCounts.performance||0}</p>\n <p>Security: ${i.categoryCounts.security||0}</p>\n <p>Maintainability: ${i.categoryCounts.maintainability||0}</p>\n <p>Bugs: ${i.categoryCounts.bugs||0}</p>\n <p>Style: ${i.categoryCounts.style||0}</p>\n </div>\n </div>\n\n <h2>Findings</h2>\n\n ${function(e){let t="";const n={};return e.forEach((e=>{e.success&&e.findings.length>0&&(n[e.filePath]=e.findings)})),Object.entries(n).forEach((([e,n])=>{t+=`<div class="file">\n <div class="file-header">${e}</div>\n ${n.map((e=>`\n <div class="finding">\n <div>\n <span class="severity ${e.severity}">${e.severity.toUpperCase()}</span>\n <span class="category">${e.category}</span>\n <span class="location">Line ${e.line}${e.column?`:${e.column}`:""}</span>\n </div>\n <h3>${ee(e.message)}</h3>\n <div class="code">${ee(e.code)}</div>\n ${e.suggestion?`\n <div class="suggestion">\n <strong>Suggestion:</strong>\n <div class="code">${ee(e.suggestion)}</div>\n </div>\n `:""}\n <div class="explanation">${ee(e.explanation)}</div>\n </div>\n `)).join("")}\n </div>`}