UNPKG

devboot

Version:

Zero-config dev environment setup for modern web projects

27 lines 155 kB
#!/usr/bin/env node import{Command as cs}from"commander";import j from"chalk";var yt="0.2.3";import P from"chalk";import{intro as ss,outro as Ke,note as ut,cancel as xt,confirm as jt,isCancel as _t}from"@clack/prompts";import it from"fs-extra";import At from"path";var C=class extends Error{constructor(t,s,i){super(t,{cause:i});this.context=s;this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}};var b=class extends C{get solution(){}},h=class extends b{constructor(t,s,i=!0,r,o){super(s,r);this.code=t;this.isRecoverable=i;this._solution=o}get solution(){return this._solution}};var me={COMMAND_NOT_FOUND:"COMMAND_NOT_FOUND",INVALID_ARGUMENT:"INVALID_ARGUMENT",MISSING_ARGUMENT:"MISSING_ARGUMENT",USER_CANCELLED:"USER_CANCELLED",PROMPT_FAILED:"PROMPT_FAILED",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_IN_PROJECT:"NOT_IN_PROJECT"},u={PROJECT_NOT_FOUND:"PROJECT_NOT_FOUND",PROJECT_INVALID:"PROJECT_INVALID",PROJECT_ANALYSIS_FAILED:"PROJECT_ANALYSIS_FAILED",PKG_MANAGER_NOT_FOUND:"PKG_MANAGER_NOT_FOUND",PKG_INSTALL_FAILED:"PKG_INSTALL_FAILED",PKG_MANAGER_MISMATCH:"PKG_MANAGER_MISMATCH",CONFIG_PARSE_ERROR:"CONFIG_PARSE_ERROR",CONFIG_CONFLICT:"CONFIG_CONFLICT",CONFIG_MERGE_FAILED:"CONFIG_MERGE_FAILED",CONFIG_INVALID_FORMAT:"CONFIG_INVALID_FORMAT",CONFIG_GENERATION_FAILED:"CONFIG_GENERATION_FAILED",CONFIG_READ_ERROR:"CONFIG_READ_ERROR",CONFIG_NOT_FOUND:"CONFIG_NOT_FOUND",CONFIG_VALIDATION_ERROR:"CONFIG_VALIDATION_ERROR",PROJECT_NOT_VALID:"PROJECT_NOT_VALID",MODULE_NOT_FOUND:"MODULE_NOT_FOUND",MODULE_ALREADY_EXISTS:"MODULE_ALREADY_EXISTS",MODULE_INSTALL_FAILED:"MODULE_INSTALL_FAILED",MODULE_CONFIG_INVALID:"MODULE_CONFIG_INVALID",FILE_NOT_FOUND:"FILE_NOT_FOUND",FILE_READ_ERROR:"FILE_READ_ERROR",FILE_WRITE_ERROR:"FILE_WRITE_ERROR",FILE_ALREADY_EXISTS:"FILE_ALREADY_EXISTS",FILE_OPERATION_ERROR:"FILE_OPERATION_ERROR",FILE_PERMISSION_ERROR:"FILE_PERMISSION_ERROR",FILE_MODIFICATION_FAILED:"FILE_MODIFICATION_FAILED",PKG_UNINSTALL_FAILED:"PKG_UNINSTALL_FAILED",PKG_MANAGER_EXECUTION_ERROR:"PKG_MANAGER_EXECUTION_ERROR",INVALID_PACKAGE_MANAGER:"INVALID_PACKAGE_MANAGER",PERMISSION_DENIED:"PERMISSION_DENIED",NETWORK_ERROR:"NETWORK_ERROR",USER_CANCELLED:"USER_CANCELLED",DISK_FULL:"DISK_FULL",ROLLBACK_FAILED:"ROLLBACK_FAILED",MODULE_UNINSTALL_FAILED:"MODULE_UNINSTALL_FAILED"},hs={...me,...u};function M(c){return c instanceof Error&&"code"in c}function Et(c){return M(c)&&["ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETUNREACH","ENOTFOUND"].includes(c.code||"")}function vt(c){return{ENOENT:u.FILE_NOT_FOUND,EACCES:u.FILE_PERMISSION_ERROR,EPERM:u.PERMISSION_DENIED,ENOSPC:u.DISK_FULL,ECONNREFUSED:u.NETWORK_ERROR,ECONNRESET:u.NETWORK_ERROR,ETIMEDOUT:u.NETWORK_ERROR,ENETUNREACH:u.NETWORK_ERROR}[c.code||""]||null}var Pe=class extends b{code=u.PROJECT_NOT_FOUND;isRecoverable=!1;get solution(){let{suggestion:e}=this.context||{};return e?`Run '${e}' to initialize a new project.`:"Please run this command from a project root with a package.json file."}},ne=class extends b{code=u.PROJECT_INVALID;isRecoverable=!1;get solution(){let{parseError:e}=this.context||{};return e?`Fix JSON syntax error: ${e}`:"Please ensure package.json is valid JSON format."}};async function B(c){let e=At.join(c,"package.json");if(!await y(e))throw new Pe("No package.json found in project directory",{projectPath:c,searchedPath:e,hasPackageJson:!1,suggestion:"npm init"});try{let t=await it.readFile(e,"utf-8"),s=JSON.parse(t);if(typeof s!="object"||s===null)throw new Error("package.json must be an object");return s}catch(t){if(t instanceof SyntaxError)throw new ne("Invalid package.json format",{projectPath:c,hasPackageJson:!0,parseError:t.message},t);if(M(t)){let s=t;throw new h(u.FILE_READ_ERROR,`Failed to read package.json: ${t.message}`,!1,{packageJsonPath:e,errorCode:s.code,syscall:s.syscall},"Check file permissions and try again.")}throw new h(u.FILE_READ_ERROR,t instanceof Error?`Failed to read package.json: ${t.message}`:"Failed to read package.json",!1,{packageJsonPath:e},"Check file permissions and try again.")}}async function y(c){try{return await it.pathExists(c)}catch{return!1}}async function wt(c){try{return await it.readFile(c,"utf-8")}catch(e){if(M(e)){let t=e;if(t.code==="ENOENT")throw new h(u.FILE_NOT_FOUND,`File not found: ${c}`,!1,{filePath:c});if(t.code==="EACCES"||t.code==="EPERM")throw new h(u.FILE_PERMISSION_ERROR,`Permission denied reading file: ${c}`,!1,{filePath:c,errorCode:t.code},"Check file permissions")}throw new h(u.FILE_READ_ERROR,e instanceof Error?`Failed to read file: ${e.message}`:"Failed to read file",!1,{filePath:c})}}import $ from"path";var ae=class{async analyze(e){if(!await y(e))throw new h(u.PROJECT_NOT_FOUND,`Project path does not exist: ${e}`,!1,{projectPath:e,currentDir:process.cwd()},"Please check the project path and try again.");let t;try{t=await B(e)}catch(s){throw s instanceof Error?new ne(s.message,{projectPath:e,hasPackageJson:await y($.join(e,"package.json"))},s):s}return{projectPath:e,name:t.name||"unnamed-project",version:t.version||"0.0.0",packageJson:t,projectType:await this.detectProjectType(t),packageManager:await this.detectPackageManager(e,t),hasTypeScript:await this.detectTypeScript(e),hasSrcDirectory:await y($.join(e,"src")),hasTestDirectory:await y($.join(e,"test"))||await y($.join(e,"tests"))||await y($.join(e,"__tests__"))}}async detectProjectType(e){let t={...e.dependencies,...e.devDependencies};return t.next?"next":t.vite&&t.react?"vite":t.react?"react":"node"}async detectPackageManager(e,t){if(await y($.join(e,"bun.lockb")))return"bun";if(await y($.join(e,"pnpm-lock.yaml")))return"pnpm";if(await y($.join(e,"yarn.lock")))return"yarn";if(await y($.join(e,"package-lock.json")))return"npm";if(t.packageManager&&typeof t.packageManager=="string"){let s=t.packageManager.match(/^(npm|pnpm|yarn|bun)@/);if(s&&s[1])return s[1]}return"npm"}async detectTypeScript(e){return await y($.join(e,"tsconfig.json"))?!0:await y($.join(e,"src"))?await this.hasFilesWithExtension($.join(e,"src"),".ts")||await this.hasFilesWithExtension($.join(e,"src"),".tsx"):!1}async hasFilesWithExtension(e,t){try{let{readdir:s}=await import("fs/promises");return(await s(e)).some(r=>r.endsWith(t))}catch{return!1}}};import{writeFile as ot,unlink as Ut,readFile as Jt,mkdir as Vt}from"fs/promises";import te from"path";import G from"chalk";import $t from"ora";var rt=class{verboseMode;constructor(e=!1){this.verboseMode=e}info(e){console.log(G.blue("\u2139"),e)}success(e){console.log(G.green("\u2713"),e)}error(e){console.log(G.red("\u2717"),e)}warn(e){console.log(G.yellow("\u26A0"),e)}debug(e){this.verboseMode&&console.log(G.gray("\u25CB"),e)}log(e){console.log(e)}plain(e){console.log(e)}gray(e){console.log(G.gray(e))}cyan(e){console.log(G.cyan(e))}bold(e){console.log(G.bold(e))}yellow(e){console.log(G.yellow(e))}red(e){console.log(G.red(e))}newline(){console.log("")}spinner(e){return $t({text:e,spinner:"dots",color:"blue"})}},f=new rt;var he=class extends b{code=u.FILE_OPERATION_ERROR;isRecoverable=!1;get solution(){let{operation:e,path:t,errorCode:s}=this.context||{},i=t?.split("/").pop(),r=t?.substring(0,t.lastIndexOf("/"));switch(e){case"write":case"create":return s==="ENOSPC"?"Not enough disk space. Free up some space and try again":r?`Ensure directory '${r}' exists and you have write permissions`:"Check if the parent directory exists and you have write permissions";case"read":return i?`Ensure file '${i}' exists in '${r||"current directory"}' and you have read permissions`:"Check if the file exists and you have read permissions";case"mkdir":return t?`Check if you have permission to create directory '${t}'`:"Check if you have permission to create directories";case"modify":return i?`Ensure '${i}' is not locked by another process and you have write permissions`:"Check if the file is not locked and you have write permissions";case"delete":return t?`Ensure '${t}' exists and you have delete permissions`:"Check if the file exists and you have delete permissions";default:return t?`Check permissions for '${t}'`:"Check file permissions and path"}}},W=class extends b{code=u.FILE_NOT_FOUND;isRecoverable=!1;get solution(){return"Ensure the file exists at the specified path"}},ee=class extends b{code=u.FILE_PERMISSION_ERROR;isRecoverable=!1;get solution(){let{operation:e}=this.context||{};return e==="write"||e==="create"?"Try running with elevated permissions (sudo) or check directory ownership":"Check file permissions or run with elevated privileges"}};import F from"chalk";var I=class{static ERROR_PREFIX={error:F.red("\u2717"),warning:F.yellow("\u26A0"),info:F.blue("\u2139")};static logError(e,t={}){let{verbose:s=!1,prefix:i=!0,showSolution:r=!0,showContext:o=!1}=t;e instanceof C?this.logBaseError(e,{verbose:s,prefix:i,showSolution:r,showContext:o}):e instanceof Error?this.logGenericError(e,{verbose:s,prefix:i}):this.logUnknownError(e,{prefix:i})}static logBaseError(e,t){let s=t.prefix?`${this.ERROR_PREFIX.error} `:"";console.error(`${s}${e.message}`),t.showSolution&&e instanceof b&&e.solution&&console.log(F.yellow(` \u{1F4A1} ${e.solution}`)),t.showContext&&e.context&&(t.verbose||process.env.DEBUG)&&(console.log(F.gray(` Debug info:`)),console.log(F.gray(JSON.stringify(e.context,null,2)))),t.verbose&&e.stack&&(console.log(F.gray(` Stack trace:`)),console.log(F.gray(e.stack)))}static logGenericError(e,t){let s=t.prefix?`${this.ERROR_PREFIX.error} `:"";console.error(`${s}${e.message}`),t.verbose&&e.stack&&(console.log(F.gray(` Stack trace:`)),console.log(F.gray(e.stack)))}static logUnknownError(e,t){let s=t.prefix?`${this.ERROR_PREFIX.error} `:"";console.error(`${s}An unexpected error occurred`),console.error(F.gray(String(e)))}static logWarning(e){console.warn(`${this.ERROR_PREFIX.warning} ${e}`)}static logInfo(e){console.log(`${this.ERROR_PREFIX.info} ${e}`)}static logErrorSummary(e){if(e.length===0)return;let t=`${e.length} error${e.length===1?"":"s"} occurred:`;console.error(F.red(` \u26A0\uFE0F ${t}`)),e.forEach((s,i)=>{console.error(F.red(` ${i+1}. ${s.message}`)),s instanceof b&&s.solution&&console.log(F.yellow(` \u{1F4A1} ${s.solution}`))})}static logErrorWithProgress(e,t){let s=F.gray(`[${t.current}/${t.total}] ${t.item}`);console.error(`${this.ERROR_PREFIX.error} ${s}`),this.logError(e,{prefix:!1})}};var z=class{constructor(e){this.config=e}get name(){return this.config.name}get displayName(){return this.config.displayName}get description(){return this.config.description}get version(){return this.config.version}async install(e){let t={success:!1,installedFiles:[],installedPackages:[],modifiedFiles:[],errors:[],hints:[],rollbackActions:[]};try{let s=await this.validate(e);if(!s.valid)return t.errors=s.errors.map(n=>new h(u.MODULE_CONFIG_INVALID,n,!1,{module:this.name,validationErrors:s.errors,conflictingModules:s.conflictingModules},s.conflictingModules?.length?"Use --force to override existing configurations":void 0)),s.conflictingModules?.length&&t.hints?.push("Use --force to override existing configurations"),t;if(s.warnings.length>0&&e.verbose&&s.warnings.forEach(n=>f.warn(n)),e.dryRun)return await this.previewChanges(e),t.success=!0,t.message="Dry run completed successfully",t;let i=await this.getFilesToCreate(e);for(let[n,l]of i)await this.createFile(te.join(e.projectPath,n),l,t,e);let r=await this.getFilesToModify(e);for(let[n,l]of r)await this.modifyFile(te.join(e.projectPath,n),l,t,e);let o=await this.getDependencies(e);return(o.dependencies||o.devDependencies)&&e.verbose&&f.info("Dependencies to be installed by package manager"),t.success=!0,t.message=`${this.displayName} configured successfully`,t}catch(s){if(t.rollbackActions?.length){e.verbose&&f.info("Rolling back changes...");try{await this.rollback(t.rollbackActions)}catch(i){let r=new h(u.ROLLBACK_FAILED,"Failed to rollback changes",!1,{module:this.name,originalError:s instanceof Error?s.message:String(s),rollbackError:i instanceof Error?i.message:String(i)});t.errors?.push(r)}}if(s instanceof C)t.errors?.push(s);else{let i=s instanceof Error?s.message:String(s);t.errors?.push(new h(u.MODULE_INSTALL_FAILED,`Module installation failed: ${i}`,!1,{module:this.name,originalError:i}))}return t.success=!1,t}}async previewChanges(e){f.info(`\u{1F4CB} Preview of changes: `);let t=await this.getFilesToCreate(e);if(t.size>0){f.info("Files to create:");for(let[r]of t)f.info(` \u2728 ${r}`);f.info("")}let s=await this.getFilesToModify(e);if(s.size>0){f.info("Files to modify:");for(let[r]of s)f.info(` \u270F\uFE0F ${r}`);f.info("")}let i=await this.getDependencies(e);(i.dependencies||i.devDependencies)&&(f.info("Packages to install:"),Object.entries(i.dependencies||{}).forEach(([r,o])=>{f.info(` \u{1F4E6} ${r}@${o}`)}),Object.entries(i.devDependencies||{}).forEach(([r,o])=>{f.info(` \u{1F4E6} ${r}@${o} (dev)`)}))}async createFile(e,t,s,i){try{let r=te.dirname(e);try{await Vt(r,{recursive:!0})}catch(o){if(M(o)){let n=o;if(n.code==="EACCES"||n.code==="EPERM")throw new ee(`Permission denied creating directory: ${r}`,{path:r,operation:"mkdir",errorCode:n.code})}throw o}try{await ot(e,t,"utf-8")}catch(o){if(M(o)){let n=o;if(n.code==="EACCES"||n.code==="EPERM")throw new ee(`Permission denied writing file: ${e}`,{path:e,operation:"write",errorCode:n.code});if(n.code==="ENOSPC")throw new h(u.DISK_FULL,"Not enough disk space",!1,{path:e})}throw o}s.installedFiles?.push(te.relative(i.projectPath,e)),i.verbose&&I.logInfo(`Created: ${te.relative(i.projectPath,e)}`),s.rollbackActions?.push(async()=>{try{await Ut(e)}catch{f.debug(`Rollback: File already removed: ${e}`)}})}catch(r){throw r instanceof C?r:new he(`Failed to create file: ${e}`,{path:e,operation:"create",originalError:r instanceof Error?r.message:String(r)},r)}}async modifyFile(e,t,s,i){let r;try{try{r=await Jt(e,"utf-8")}catch(n){if(M(n)){let l=n;if(l.code==="ENOENT")throw new W(`File not found: ${e}`,{path:e,operation:"read"});if(l.code==="EACCES"||l.code==="EPERM")throw new ee(`Permission denied reading file: ${e}`,{path:e,operation:"read",errorCode:l.code})}throw n}let o;try{o=await t(r)}catch(n){throw new h(u.FILE_MODIFICATION_FAILED,`Failed to modify file content: ${e}`,!1,{path:e,modifierError:n instanceof Error?n.message:String(n)})}try{await ot(e,o,"utf-8")}catch(n){if(M(n)){let l=n;if(l.code==="EACCES"||l.code==="EPERM")throw new ee(`Permission denied writing file: ${e}`,{path:e,operation:"write",errorCode:l.code})}throw n}s.modifiedFiles?.push(te.relative(i.projectPath,e)),i.verbose&&I.logInfo(`Modified: ${te.relative(i.projectPath,e)}`),s.rollbackActions?.push(async()=>{await ot(e,r,"utf-8")})}catch(o){throw o instanceof C?o:new he(`Failed to modify file: ${e}`,{path:e,operation:"modify",originalError:o instanceof Error?o.message:String(o)},o)}}async rollback(e){for(let t of e.reverse())try{await t()}catch(s){I.logError(s,{verbose:!1})}}checkNodeVersion(e){try{let t=process.version.slice(1).split(".").map(Number),s=e.split(".").map(Number);for(let i=0;i<Math.max(t.length,s.length);i++){let r=t[i]||0,o=s[i]||0;if(isNaN(r)||isNaN(o))return f.warn(`Invalid version number at position ${i}`),!1;if(r>o)return!0;if(r<o)return!1}return!0}catch(t){return f.error(`Version check failed: ${t}`),!1}}};import Ct from"path";import{unlink as Gt}from"fs/promises";import*as g from"@clack/prompts";import le from"chalk";var H={charset:[{value:"utf-8",label:"UTF-8",hint:"Recommended for most projects"},{value:"latin1",label:"Latin-1",hint:"Legacy encoding"}],end_of_line:[{value:"lf",label:"LF (Unix)",hint:"Recommended for Git compatibility"},{value:"crlf",label:"CRLF (Windows)",hint:"Windows native"},{value:"cr",label:"CR (Classic Mac)",hint:"Rarely used"}],indent_style:[{value:"space",label:"Spaces",hint:"More consistent across editors"},{value:"tab",label:"Tabs",hint:"Allows personal width preference"}],indent_size:[{value:"2",label:"2",hint:"Common in JS/TS projects"},{value:"4",label:"4",hint:"Common in Python/Java"},{value:"8",label:"8",hint:"Traditional tab width"},{value:"custom",label:"Custom",hint:"Enter your own value"}],max_line_length:[{value:"80",label:"80",hint:"Traditional terminal width"},{value:"100",label:"100",hint:"Common in modern projects"},{value:"120",label:"120",hint:"Comfortable for wide screens"},{value:"off",label:"No limit",hint:"Let formatter decide"},{value:"custom",label:"Custom",hint:"Enter your own value"}]},D={charset:{utf8:{key:"charset",value:"utf-8",description:"UTF-8 encoding"},latin1:{key:"charset",value:"latin1",description:"Latin-1 encoding"}},endOfLine:{lf:{key:"end_of_line",value:"lf",description:"Unix-style (LF)"},crlf:{key:"end_of_line",value:"crlf",description:"Windows-style (CRLF)"},cr:{key:"end_of_line",value:"cr",description:"Old Mac-style (CR)"}},indentStyle:{space:{key:"indent_style",value:"space",description:"Use spaces"},tab:{key:"indent_style",value:"tab",description:"Use tabs"}},indentSize:{two:{key:"indent_size",value:2,description:"2 spaces"},four:{key:"indent_size",value:4,description:"4 spaces"},eight:{key:"indent_size",value:8,description:"8 spaces"}},trimTrailingWhitespace:{yes:{key:"trim_trailing_whitespace",value:!0,description:"Remove trailing spaces"},no:{key:"trim_trailing_whitespace",value:!1,description:"Keep trailing spaces"}},insertFinalNewline:{yes:{key:"insert_final_newline",value:!0,description:"Add newline at EOF"},no:{key:"insert_final_newline",value:!1,description:"No newline at EOF"}}},nt={javascript:{pattern:"*.{js,jsx,mjs,cjs}",description:"JavaScript files",recommendedRules:[D.indentStyle.space,D.indentSize.two],optionalRules:[{key:"max_line_length",value:100,description:"Line length limit"}]},typescript:{pattern:"*.{ts,tsx}",description:"TypeScript files",recommendedRules:[D.indentStyle.space,D.indentSize.two],optionalRules:[{key:"max_line_length",value:100,description:"Line length limit"}]},python:{pattern:"*.py",description:"Python files",recommendedRules:[D.indentStyle.space,D.indentSize.four,{key:"max_line_length",value:88,description:"Black formatter default"}],optionalRules:[]},markdown:{pattern:"*.md",description:"Markdown files",recommendedRules:[D.trimTrailingWhitespace.no],optionalRules:[{key:"max_line_length",value:80,description:"Readable line length"}]},makefile:{pattern:"Makefile",description:"Makefiles",recommendedRules:[D.indentStyle.tab],optionalRules:[]},yaml:{pattern:"*.{yml,yaml}",description:"YAML files",recommendedRules:[D.indentStyle.space,D.indentSize.two],optionalRules:[]},json:{pattern:"*.json",description:"JSON files",recommendedRules:[D.indentStyle.space,D.indentSize.two],optionalRules:[]},css:{pattern:"*.{css,scss,sass,less}",description:"Style files",recommendedRules:[D.indentStyle.space,D.indentSize.two],optionalRules:[{key:"max_line_length",value:80,description:"Line length limit"}]}};var Ie=class{sections=[];globalRules=[];async build(e){g.intro(le.blue("\u{1F527} EditorConfig Interactive Setup")),await this.setupGlobalRules(),await this.setupFileTypeRules(e),await this.setupCustomRules();let t=this.generatePreview();g.log.message(""),g.log.info("\u{1F4C4} Generated Configuration Preview:"),g.log.message(le.gray(t));let s=await g.confirm({message:"Apply this configuration?",initialValue:!0});if(!s||g.isCancel(s))throw g.cancel("Configuration cancelled"),new Error("Configuration cancelled");return g.outro(le.green("\u2705 EditorConfig setup complete!")),this.generate()}async setupGlobalRules(){g.log.step(le.cyan("Global Rules Configuration")),g.log.message(`These rules will apply to all files by default `);let e=await g.select({message:"Character encoding",options:H.charset});if(g.isCancel(e))throw g.cancel("Setup cancelled"),new Error("Cancelled");this.globalRules.push({key:"charset",value:e});let t=await g.select({message:"Line ending style",options:H.end_of_line});if(g.isCancel(t))throw g.cancel("Setup cancelled"),new Error("Cancelled");this.globalRules.push({key:"end_of_line",value:t});let s=await g.select({message:"Indentation style",options:H.indent_style});if(g.isCancel(s))throw g.cancel("Setup cancelled"),new Error("Cancelled");if(this.globalRules.push({key:"indent_style",value:s}),s==="space"){let r=await g.select({message:"Indentation size",options:H.indent_size});if(g.isCancel(r))throw g.cancel("Setup cancelled"),new Error("Cancelled");if(r==="custom"){let o=await g.text({message:"Enter custom indent size (1-16)",validate:n=>{let l=parseInt(n);if(isNaN(l)||l<1||l>16)return"Please enter a number between 1 and 16"}});if(g.isCancel(o))throw g.cancel("Setup cancelled"),new Error("Cancelled");this.globalRules.push({key:"indent_size",value:parseInt(o)})}else this.globalRules.push({key:"indent_size",value:r})}let i=await g.multiselect({message:"Additional global rules",options:[{value:"trim_trailing_whitespace",label:"Trim trailing whitespace",hint:"Remove spaces at line endings"},{value:"insert_final_newline",label:"Insert final newline",hint:"Ensure files end with newline"}],initialValues:["trim_trailing_whitespace","insert_final_newline"],required:!1});if(!g.isCancel(i))for(let r of i)this.globalRules.push({key:r,value:!0});g.log.success(`Global rules configured `)}async setupFileTypeRules(e){g.log.step(le.cyan("File Type Specific Rules"));let t=this.detectFileTypes(e);if(t.length===0){g.log.warning("No specific file types detected");return}g.log.message(`Detected file types in your project: `);let s=await g.multiselect({message:"Select file types to configure",options:t.map(i=>({value:i.key,label:i.label,hint:i.hint})),initialValues:t.map(i=>i.key),required:!1});if(!(g.isCancel(s)||s.length===0)){for(let i of s){let r=nt[i];if(!r)continue;g.log.info(` Configuring ${r.description}`);let o=await g.select({message:`How would you like to configure ${r.description}?`,options:[{value:"recommended",label:"Use recommended settings",hint:"Quick setup"},{value:"customize",label:"Customize settings",hint:"Fine-tune rules"},{value:"skip",label:"Skip",hint:"Use global rules only"}]});g.isCancel(o)||o==="skip"||(o==="recommended"?this.sections.push({pattern:r.pattern,rules:[...r.recommendedRules],description:r.description}):await this.customizeFileType(r))}this.sections.length>0&&g.log.success(` File type rules configured for ${this.sections.length} patterns`)}}async customizeFileType(e){let t=[],s=await g.confirm({message:"Override global indentation settings?",initialValue:!1});if(!g.isCancel(s)&&s){let r=await g.select({message:`Indentation style for ${e.description}`,options:H.indent_style});if(!g.isCancel(r)&&(t.push({key:"indent_style",value:r}),r==="space")){let o=await g.select({message:`Indentation size for ${e.description}`,options:H.indent_size.filter(n=>n.value!=="custom")});g.isCancel(o)||t.push({key:"indent_size",value:o})}}let i=await g.confirm({message:"Set maximum line length?",initialValue:!1});if(!g.isCancel(i)&&i){let r=await g.select({message:"Maximum line length",options:H.max_line_length});if(!g.isCancel(r))if(r==="custom"){let o=await g.text({message:"Enter custom max line length",validate:n=>{let l=parseInt(n);if(isNaN(l)||l<1)return"Please enter a positive number"}});g.isCancel(o)||t.push({key:"max_line_length",value:parseInt(o)})}else r!=="off"&&t.push({key:"max_line_length",value:r})}if(e.optionalRules&&e.optionalRules.length>0){let r=await g.multiselect({message:`Additional rules for ${e.description}`,options:e.optionalRules.map(o=>({value:o.key,label:`${o.key} = ${o.value}`,hint:o.description})),required:!1});if(!g.isCancel(r))for(let o of r){let n=e.optionalRules.find(l=>l.key===o);n&&t.push(n)}}this.sections.push({pattern:e.pattern,rules:t,description:e.description})}async setupCustomRules(){let e=await g.confirm({message:` Add custom file patterns?`,initialValue:!1});if(!e||g.isCancel(e))return;g.log.step(le.cyan("Custom Pattern Configuration"));let t=!0;for(;t;){let s=await g.text({message:"File pattern (e.g., *.{css,scss} or src/**/*.js)",placeholder:"*.{css,scss}"});if(g.isCancel(s))break;let i=[],r=await g.confirm({message:`Add specific rules for ${s}?`,initialValue:!0});if(!g.isCancel(r)&&r){let n=await g.confirm({message:"Set custom indentation?",initialValue:!1});if(!g.isCancel(n)&&n){let l=await g.text({message:"Indent size",placeholder:"2",validate:m=>{let N=parseInt(m);if(isNaN(N)||N<1||N>16)return"Please enter a number between 1 and 16"}});g.isCancel(l)||i.push({key:"indent_size",value:parseInt(l)})}}this.sections.push({pattern:s,rules:i,description:"Custom pattern"});let o=await g.confirm({message:"Add another custom pattern?",initialValue:!1});(g.isCancel(o)||!o)&&(t=!1)}}detectFileTypes(e){let t=[],s={...e.packageJson.dependencies,...e.packageJson.devDependencies},i=["json","yaml","markdown"];t.push({key:"javascript",label:"JavaScript (.js, .jsx)",hint:"Essential for Node.js projects"}),e.hasTypeScript&&t.push({key:"typescript",label:"TypeScript (.ts, .tsx)",hint:"TypeScript configuration detected"}),(s.sass||s.less||s["styled-components"]||s.emotion||e.projectType==="next"||e.projectType==="vite")&&t.push({key:"css",label:"Styles (.css, .scss, .sass, .less)",hint:"Style files detected"}),(s.python||s.django||s.flask)&&t.push({key:"python",label:"Python (.py)",hint:"Python dependencies detected"}),(s["node-gyp"]||s["cmake-js"])&&t.push({key:"makefile",label:"Makefile",hint:"Native build system detected"});for(let r of i){let o=nt[r];o&&t.push({key:r,label:o.description,hint:"Commonly used"})}return t}generatePreview(){let e=this.generate().split(` `),t=20;return e.length<=t?e.join(` `):e.slice(0,t).join(` `)+` ...`}generate(){let e=["# EditorConfig is awesome: https://EditorConfig.org","","root = true",""];if(this.globalRules.length>0){e.push("[*]");for(let t of this.globalRules)e.push(`${t.key} = ${t.value}`);e.push("")}for(let t of this.sections){if(t.description&&e.push(`# ${t.description}`),e.push(`[${t.pattern}]`),t.rules.length>0)for(let s of t.rules)e.push(`${s.key} = ${s.value}`);e.push("")}for(;e[e.length-1]==="";)e.pop();return e.join(` `)}};var ke=class extends z{generatedContent;constructor(){super({name:"editorconfig",displayName:"EditorConfig",description:"Consistent coding styles across different editors",detectFiles:[".editorconfig"],conflicts:[],version:"1.0.0"})}async isInstalled(e){try{return await y(Ct.join(e,".editorconfig"))}catch{return!1}}async validate(e){let t={valid:!0,errors:[],warnings:[]};try{let s=await this.isInstalled(e.projectPath);return s&&!e.force?(t.valid=!1,t.errors.push(".editorconfig already exists. Use --force to overwrite."),t):(s&&e.force&&t.warnings.push("Existing .editorconfig will be overwritten"),t)}catch(s){t.valid=!1;let i=s instanceof Error?s.message:String(s);return t.errors.push(`Validation failed: ${i}`),t}}async getDependencies(){return{}}async getFilesToCreate(e){let t=new Map;try{let s;if(!e.dryRun&&!this.generatedContent){let i=new Ie;try{this.generatedContent=await i.build(e),s=this.generatedContent}catch(r){throw r instanceof Error&&r.message==="Configuration cancelled"?new h(u.USER_CANCELLED,"EditorConfig setup cancelled by user",!1):r}}else this.generatedContent?s=this.generatedContent:(s=this.generateDefaultConfig(e),e.verbose&&f.info("Using default EditorConfig configuration"));return t.set(".editorconfig",s),t}catch(s){throw s instanceof C?s:new h(u.CONFIG_GENERATION_FAILED,"Failed to generate .editorconfig content",!1,{module:this.name,error:s instanceof Error?s.message:String(s)})}}async getFilesToModify(){return new Map}async uninstall(e){let t={success:!1,errors:[],hints:[]};try{let s=Ct.join(e.projectPath,".editorconfig");if(!await y(s))throw new W(".editorconfig file not found",{path:s,operation:"delete"});try{await Gt(s),t.success=!0,t.message=".editorconfig removed successfully",e.verbose&&f.success("EditorConfig configuration removed")}catch(i){throw i.code==="EACCES"?new h(u.FILE_PERMISSION_ERROR,"Permission denied while removing .editorconfig",!1,{path:s,errorCode:i.code},"Try running with elevated permissions (sudo)"):i}}catch(s){if(s instanceof C)t.errors?.push(s);else{let i=s instanceof Error?s.message:String(s);t.errors?.push(new h(u.MODULE_UNINSTALL_FAILED,`Failed to uninstall EditorConfig: ${i}`,!1,{module:this.name,originalError:i}))}}return t}generateDefaultConfig(e){let t=["# EditorConfig is awesome: https://EditorConfig.org","","root = true","","[*]","charset = utf-8","end_of_line = lf","insert_final_newline = true","trim_trailing_whitespace = true","indent_style = space","indent_size = 2",""];t.push("[*.md]","trim_trailing_whitespace = false",""),t.push("[*.{json,yml,yaml}]","indent_size = 2",""),["next","vite","react","node"].includes(e.projectType)&&(t.push("[*.{js,jsx,mjs,cjs}]","indent_size = 2",""),e.hasTypeScript&&t.push("[*.{ts,tsx}]","indent_size = 2","")),t.push("[Makefile]","indent_style = tab","");let s=e.packageJson.prettier;if(s&&typeof s=="object"){if("tabWidth"in s&&typeof s.tabWidth=="number")return t.join(` `).replace(/indent_size = \d+/g,`indent_size = ${s.tabWidth}`);if("useTabs"in s&&s.useTabs===!0)return t.join(` `).replace(/indent_style = space/g,"indent_style = tab")}return t.join(` `)}};import de from"path";import*as a from"@clack/prompts";import S from"chalk";var ce={targets:[{value:"ES2022",label:"ES2022",hint:"Node 16+ and modern browsers"},{value:"ES2020",label:"ES2020",hint:"Node 14+ and 2020+ browsers"},{value:"ES2017",label:"ES2017",hint:"Wider compatibility"},{value:"ES2015",label:"ES2015",hint:"Maximum compatibility"},{value:"ESNext",label:"ESNext",hint:"Latest features (unstable)"}],modules:[{value:"NodeNext",label:"NodeNext",hint:"Modern Node.js with ESM"},{value:"ESNext",label:"ESNext",hint:"Latest ES modules"},{value:"ES2022",label:"ES2022",hint:"ES2022 modules"},{value:"CommonJS",label:"CommonJS",hint:"Traditional Node.js"},{value:"AMD",label:"AMD",hint:"Asynchronous Module Definition"},{value:"UMD",label:"UMD",hint:"Universal Module Definition"},{value:"System",label:"System",hint:"SystemJS loader"}],moduleResolution:[{value:"bundler",label:"Bundler",hint:"For modern bundlers (recommended)"},{value:"node",label:"Node",hint:"Node.js style resolution"},{value:"node16",label:"Node16",hint:"Node.js 16+ with ESM"},{value:"nodenext",label:"NodeNext",hint:"Latest Node.js resolution"},{value:"classic",label:"Classic",hint:"Legacy TypeScript resolution"}],strictness:[{value:"strict",label:"Strict",hint:"Maximum type safety (recommended)"},{value:"moderate",label:"Moderate",hint:"Balanced for migration"},{value:"loose",label:"Loose",hint:"Minimal checks"},{value:"custom",label:"Custom",hint:"Choose individual options"}],jsx:[{value:"preserve",label:"Preserve",hint:"Keep JSX for bundler"},{value:"react-jsx",label:"React 17+",hint:"New JSX transform"},{value:"react-jsxdev",label:"React Dev",hint:"Development mode"},{value:"react",label:"React Classic",hint:"React.createElement"},{value:"react-native",label:"React Native",hint:"For RN projects"}],libs:[{value:"default",label:"Default",hint:"Based on target"},{value:"dom",label:"DOM",hint:"Browser APIs"},{value:"webworker",label:"WebWorker",hint:"Worker APIs"},{value:"esnext",label:"ESNext",hint:"Latest ES features"},{value:"node",label:"Node",hint:"Node.js globals"},{value:"custom",label:"Custom",hint:"Select individually"}]},k={"next-app":{name:"Next.js App Router",description:"Next.js 13+ with App Router",config:{compilerOptions:{target:"ES2022",lib:["dom","dom.iterable","esnext"],allowJs:!0,skipLibCheck:!0,strict:!0,noEmit:!0,esModuleInterop:!0,module:"esnext",moduleResolution:"bundler",resolveJsonModule:!0,isolatedModules:!0,jsx:"preserve",incremental:!0,plugins:[{name:"next"}],paths:{"@/*":["./src/*"]}},include:["next-env.d.ts","**/*.ts","**/*.tsx",".next/types/**/*.ts"],exclude:["node_modules"]}},"next-pages":{name:"Next.js Pages Router",description:"Next.js with Pages Router",config:{compilerOptions:{target:"ES2022",lib:["dom","dom.iterable","esnext"],allowJs:!0,skipLibCheck:!0,strict:!0,forceConsistentCasingInFileNames:!0,noEmit:!0,esModuleInterop:!0,module:"esnext",moduleResolution:"node",resolveJsonModule:!0,isolatedModules:!0,jsx:"preserve",incremental:!0,paths:{"@/*":["./src/*"]}},include:["next-env.d.ts","**/*.ts","**/*.tsx"],exclude:["node_modules"]}},"vite-react":{name:"Vite + React",description:"Vite with React and HMR",config:{compilerOptions:{target:"ES2022",useDefineForClassFields:!0,lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",skipLibCheck:!0,moduleResolution:"bundler",allowImportingTsExtensions:!0,isolatedModules:!0,moduleDetection:"force",noEmit:!0,jsx:"react-jsx",strict:!0,noUnusedLocals:!0,noUnusedParameters:!0,noFallthroughCasesInSwitch:!0,paths:{"@/*":["./src/*"]}},include:["src"],references:[{path:"./tsconfig.node.json"}]},additionalFiles:{"tsconfig.node.json":JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2023"],module:"ESNext",skipLibCheck:!0,moduleResolution:"bundler",allowSyntheticDefaultImports:!0,strict:!0,types:["vite/client"]},include:["vite.config.ts"]},null,2)}},"vite-vue":{name:"Vite + Vue",description:"Vite with Vue 3",config:{compilerOptions:{target:"ES2022",module:"ESNext",moduleResolution:"bundler",lib:["ES2022","DOM","DOM.Iterable"],skipLibCheck:!0,noEmit:!0,isolatedModules:!0,moduleDetection:"force",jsx:"preserve",strict:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,types:["vite/client","@types/node"],paths:{"@/*":["./src/*"]}},include:["src/**/*.ts","src/**/*.tsx","src/**/*.vue"],references:[{path:"./tsconfig.node.json"}]}},"node-esm":{name:"Node.js ESM",description:"Modern Node.js with ES Modules",config:{compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",lib:["ES2022"],outDir:"./dist",rootDir:"./src",strict:!0,esModuleInterop:!0,skipLibCheck:!0,forceConsistentCasingInFileNames:!0,resolveJsonModule:!0,declaration:!0,declarationMap:!0,sourceMap:!0,allowSyntheticDefaultImports:!0,types:["node"]},include:["src/**/*"],exclude:["node_modules","dist"],"ts-node":{esm:!0,experimentalSpecifierResolution:"node"}}},"node-commonjs":{name:"Node.js CommonJS",description:"Traditional Node.js with CommonJS",config:{compilerOptions:{target:"ES2022",module:"CommonJS",moduleResolution:"node",lib:["ES2022"],outDir:"./dist",rootDir:"./src",strict:!0,esModuleInterop:!0,skipLibCheck:!0,forceConsistentCasingInFileNames:!0,resolveJsonModule:!0,declaration:!0,sourceMap:!0},include:["src/**/*"],exclude:["node_modules","dist"]}},"express-api":{name:"Express API",description:"Express.js REST API server",config:{compilerOptions:{target:"ES2022",module:"CommonJS",moduleResolution:"node",lib:["ES2022"],outDir:"./dist",rootDir:"./src",strict:!0,esModuleInterop:!0,skipLibCheck:!0,forceConsistentCasingInFileNames:!0,resolveJsonModule:!0,types:["node","express"],typeRoots:["./node_modules/@types","./src/types"]},include:["src/**/*"],exclude:["node_modules","dist","**/*.spec.ts"]}},"react-library":{name:"React Component Library",description:"Publishable React component library",config:{compilerOptions:{target:"ES2020",module:"ESNext",moduleResolution:"bundler",lib:["ES2020","DOM","DOM.Iterable"],jsx:"react-jsx",declaration:!0,declarationMap:!0,outDir:"./dist",rootDir:"./src",strict:!0,esModuleInterop:!0,skipLibCheck:!0,forceConsistentCasingInFileNames:!0,resolveJsonModule:!1,isolatedModules:!0,types:["react","react-dom"]},include:["src/**/*"],exclude:["node_modules","dist","**/*.test.ts","**/*.test.tsx","**/*.stories.tsx"]}},"node-library":{name:"Node.js Library",description:"Publishable Node.js package",config:{compilerOptions:{target:"ES2020",module:"CommonJS",moduleResolution:"node",lib:["ES2020"],declaration:!0,declarationMap:!0,outDir:"./dist",rootDir:"./src",strict:!0,esModuleInterop:!0,skipLibCheck:!0,forceConsistentCasingInFileNames:!0,resolveJsonModule:!0,types:["node"]},include:["src/**/*"],exclude:["node_modules","dist","**/*.test.ts"]}},"monorepo-root":{name:"Monorepo Root",description:"Root configuration for monorepo",config:{compilerOptions:{target:"ES2022",module:"ESNext",moduleResolution:"node",composite:!0,declaration:!0,declarationMap:!0,strict:!0,esModuleInterop:!0,skipLibCheck:!0,forceConsistentCasingInFileNames:!0},files:[],references:[{path:"./packages/*/tsconfig.json"}]}},"monorepo-package":{name:"Monorepo Package",description:"Package within a monorepo",config:{extends:"../../tsconfig.json",compilerOptions:{outDir:"./dist",rootDir:"./src",composite:!0,declaration:!0,declarationMap:!0},include:["src/**/*"],exclude:["node_modules","dist"]}},"react-native":{name:"React Native",description:"React Native with TypeScript",config:{compilerOptions:{target:"ESNext",module:"CommonJS",lib:["ES2022"],jsx:"react-native",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node",resolveJsonModule:!0,allowSyntheticDefaultImports:!0,types:["react-native","jest"]},exclude:["node_modules","babel.config.js","metro.config.js","jest.config.js"]}},electron:{name:"Electron",description:"Electron desktop application",config:{compilerOptions:{target:"ES2022",module:"CommonJS",lib:["ES2022","DOM"],outDir:"./dist",rootDir:"./src",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node",resolveJsonModule:!0,types:["node","electron"]},include:["src/**/*"],exclude:["node_modules","dist"]}}},ye={experimental:[{value:"experimentalDecorators",label:"Decorators",hint:"Enable decorators"},{value:"emitDecoratorMetadata",label:"Decorator Metadata",hint:"For reflection"},{value:"useDefineForClassFields",label:"Class Fields",hint:"Standard behavior"}],output:[{value:"declaration",label:"Type Declarations",hint:"Generate .d.ts files"},{value:"declarationMap",label:"Declaration Maps",hint:"Source maps for .d.ts"},{value:"sourceMap",label:"Source Maps",hint:"For debugging"},{value:"inlineSourceMap",label:"Inline Source Maps",hint:"Embed in output"},{value:"removeComments",label:"Remove Comments",hint:"Strip comments"},{value:"preserveConstEnums",label:"Preserve Const Enums",hint:"Keep enums"}],imports:[{value:"allowSyntheticDefaultImports",label:"Synthetic Default Imports",hint:"import React"},{value:"allowImportingTsExtensions",label:"TS Extensions",hint:"import './file.ts'"},{value:"allowArbitraryExtensions",label:"Arbitrary Extensions",hint:"Any file type"},{value:"resolvePackageJsonExports",label:"Package Exports",hint:"Use exports field"},{value:"resolvePackageJsonImports",label:"Package Imports",hint:"Use imports field"}],checks:[{value:"noUnusedLocals",label:"No Unused Locals",hint:"Error on unused vars"},{value:"noUnusedParameters",label:"No Unused Parameters",hint:"Error on unused params"},{value:"noImplicitReturns",label:"No Implicit Returns",hint:"All paths return"},{value:"noFallthroughCasesInSwitch",label:"No Fallthrough",hint:"Explicit breaks"},{value:"noUncheckedIndexedAccess",label:"Checked Index Access",hint:"Safer arrays"},{value:"noPropertyAccessFromIndexSignature",label:"No Index Access",hint:"Use bracket notation"},{value:"exactOptionalPropertyTypes",label:"Exact Optional",hint:"No undefined assignment"}]};function Ee(c){let e={...c.packageJson.dependencies,...c.packageJson.devDependencies};return e.next?c.hasSrcDirectory&&c.packageJson.scripts?.dev?.includes("next dev")?"next-app":"next-pages":e.vite?e.vue?"vite-vue":(e.react,"vite-react"):e["react-native"]?"react-native":e.electron?"electron":e.express||e.fastify||e.koa?"express-api":c.packageJson.main||c.packageJson.exports?e.react?"react-library":"node-library":c.packageJson.workspaces?"monorepo-root":e.react?"react":"node-esm"}function bt(){return{typeChecking:[{value:"noImplicitAny",label:"No Implicit Any",default:!0},{value:"strictNullChecks",label:"Strict Null Checks",default:!0},{value:"strictFunctionTypes",label:"Strict Function Types",default:!0},{value:"strictBindCallApply",label:"Strict Bind/Call/Apply",default:!0},{value:"strictPropertyInitialization",label:"Strict Property Init",default:!0},{value:"noImplicitThis",label:"No Implicit This",default:!0},{value:"alwaysStrict",label:"Always Strict Mode",default:!0}],codeQuality:[{value:"noUnusedLocals",label:"No Unused Locals",default:!1},{value:"noUnusedParameters",label:"No Unused Parameters",default:!1},{value:"noImplicitReturns",label:"No Implicit Returns",default:!1},{value:"noFallthroughCasesInSwitch",label:"No Switch Fallthrough",default:!1},{value:"noUncheckedIndexedAccess",label:"Checked Array Access",default:!1}]}}import St from"path";import Wt from"path";var pe=class{async analyze(e){let t={isValid:!1,config:null,errors:[],warnings:[],suggestions:[]};try{let s=await wt(Wt.join(e,"tsconfig.json"));try{t.config=JSON.parse(s),t.isValid=!0}catch{return t.errors.push("Invalid JSON format"),t}return this.analyzeCompilerOptions(t),this.analyzeIncludes(t),this.checkCommonIssues(t),t}catch(s){return t.errors.push(`Failed to read tsconfig.json: ${s}`),t}}analyzeCompilerOptions(e){let{compilerOptions:t}=e.config;if(!t){e.warnings.push("No compilerOptions found");return}t.target||e.warnings.push("No target specified, defaulting to ES3"),t.module||e.warnings.push("No module system specified"),!t.strict&&!t.strictNullChecks&&e.suggestions.push("Consider enabling strict mode for better type safety"),(t.target==="ES5"||t.target==="ES6")&&e.suggestions.push("Consider upgrading target to ES2022 for modern JavaScript features")}analyzeIncludes(e){!e.config.include&&!e.config.files&&e.warnings.push("No 'include' or 'files' specified. All TypeScript files will be included.")}checkCommonIssues(e){let{compilerOptions:t}=e.config;t?.jsx&&!t.target?.includes("ES")&&e.warnings.push("JSX requires ES target for proper support"),t?.paths&&!t.baseUrl&&e.errors.push("'paths' requires 'baseUrl' to be specified")}};var xe=class{config={};selectedPreset=null;presetKey=null;async build(e){a.intro(S.blue("\u{1F527} TypeScript Configuration Setup")),await this.checkExistingConfig(e);let t=await a.select({message:"How would you like to set it up?",options:[{value:"quick",label:"\u{1F680} Quick setup",hint:"Automatically choose an optimized preset for your project"},{value:"custom",label:"\u{1F6E0}\uFE0F Custom setup",hint:"Configure step-by-step with fine-grained options"}]});if(a.isCancel(t))throw a.cancel("Setup canceled"),new Error("Cancelled");return t==="quick"?await this.quickSetup(e):await this.customSetup(e)}async quickSetup(e){let t=Ee(e);if(t){let s=k[t];if(!s)return a.log.warning("Could not find the detected preset"),await this.selectPresetManually(e);a.log.info(` \u{1F3AF} Detected project type: ${S.cyan(s.name)}`),a.log.message(S.gray(` ${s.description}`));let i=await a.confirm({message:"Would you like to review the configuration details?",initialValue:!1});!a.isCancel(i)&&i&&(a.log.message(` \u{1F4CB} Configuration to be applied:`),this.displayPresetDetails(s));let r=await a.confirm({message:`Apply ${s.name} configuration?`,initialValue:!0});if(a.isCancel(r))throw a.cancel("Setup canceled"),new Error("Cancelled");if(!r)return a.log.info("Please select a different preset"),await this.selectPresetManually(e);this.selectedPreset=s,this.presetKey=t,this.config=JSON.parse(JSON.stringify(s.config));let o=await a.confirm({message:"Would you like to add customizations?",initialValue:!1});!a.isCancel(o)&&o&&await this.quickCustomize(e)}else return a.log.warning("Could not automatically detect the project type"),await this.selectPresetManually(e);return this.finalizeConfiguration()}async customSetup(e){this.selectedPreset=await this.selectFramework(e),this.config=JSON.parse(JSON.stringify(this.selectedPreset.config));let t=[{name:"Target",fn:()=>this.configureTarget()},{name:"Module system",fn:()=>this.configureModuleSystem()},{name:"Type-checking strictness",fn:()=>this.configureStrictness()},{name:"Path aliases",fn:()=>this.configurePathAliases(e)},{name:"Type libraries",fn:()=>this.configureLibraries()},{name:"Additional options",fn:()=>this.configureAdditionalOptions(e)},{name:"File patterns",fn:()=>this.configureFilePatterns(e)}];a.log.info(S.cyan(` Setup steps:`)),t.forEach((s,i)=>{a.log.message(S.gray(` ${i+1}. ${s.name}`))});for(let s of t){let i=await a.confirm({message:`Skip "${s.name}"?`,initialValue:!1});if(a.isCancel(i))throw a.cancel("Setup canceled"),new Error("Cancelled");i||await s.fn()}return this.finalizeConfiguration()}async selectPresetManually(e){let t=Object.entries(k).map(([r,o])=>({value:r,label:o.name,hint:o.description})),s=await a.select({message:"Select a preset",options:t});if(a.isCancel(s))throw a.cancel("Setup canceled"),new Error("Cancelled");this.selectedPreset=k[s],this.presetKey=s,this.config=JSON.parse(JSON.stringify(this.selectedPreset.config));let i=await a.confirm({message:"Would you like to customize the configuration?",initialValue:!1});return!a.isCancel(i)&&i&&await this.quickCustomize(e),this.finalizeConfiguration()}async quickCustomize(e){let t=await a.multiselect({message:"Select items to customize",options:[{value:"paths",label:"Path aliases (@/*, etc.)"},{value:"strict",label:"Type-checking strictness"},{value:"target",label:"Compilation target (ES2022, ES2020, etc.)"},{value:"output",label:"Output options (source maps, declarations, etc.)"}],required:!1});if(!a.isCancel(t))for(let s of t)switch(s){case"paths":await this.configurePathAliases(e);break;case"strict":await this.configureStrictness();break;case"target":await this.configureTarget();break;case"output":await this.configureOutputOptions();break}}async configureOutputOptions(){let e=await a.multiselect({message:"Choose output options",options:[{value:"sourceMap",label:"Generate source maps"},{value:"declaration",label:"Emit declaration files (.d.ts)"},{value:"declarationMap",label:"Emit declaration source maps"},{value:"removeComments",label:"Remove comments"}],initialValues:["sourceMap"]});a.isCancel(e)||e.forEach(t=>{this.config.compilerOptions[t]=!0})}displayPresetDetails(e){let{compilerOptions:t}=e.config;a.log.message(S.gray(` \u2022 Target: ${t.target}`)),a.log.message(S.gray(` \u2022 Module: ${t.module}`)),a.log.message(S.gray(` \u2022 Strict mode: ${t.strict?"Enabled":"Disabled"}`)),t.jsx&&a.log.message(S.gray(` \u2022 JSX: ${t.jsx}`)),t.paths&&a.log.message(S.gray(` \u2022 Path aliases: ${Object.keys(t.paths).join(", ")}`)),e.additionalFiles&&a.log.message(S.gray(` \u2022 Additional files: ${Object.keys(e.additionalFiles).join(", ")}`))}async finalizeConfiguration(){let e=this.generatePreview();a.log.message(""),a.log.info("\u{1F4C4} Final configuration preview:"),a.log.message(S.gray(e));let t=await a.confirm({message:"Apply this configuration?",initialValue:!0});if(!t||a.isCancel(t))throw a.cancel("Setup canceled"),new Error("Configuration cancelled");return this.selectedPreset.additionalFiles&&(a.log.info(S.yellow(` \u{1F4DD} Additional files to be created:`)),Object.keys(this.selectedPreset.additionalFiles).forEach(s=>{a.log.message(S.gray(` \u2022 ${s}`))})),a.outro(S.green("\u2705 TypeScript configuration completed!")),{config:JSON.stringify(this.config,null,2),additionalFiles:this.selectedPreset?.additionalFiles,presetKey:this.presetKey}}async checkExistingConfig(e){let t=St.join(e.projectPath,"tsconfig.json");if(await y(t)){let i=await new pe().analyze(e.projectPath);if(i.isValid){a.log.warning("Found existing tsconfig.json"),i.warnings.length>0&&(a.log.message(S.yellow(` \u26A0\uFE0F Issues found:`)),i.warnings.forEach(o=>{a.log.message(S.gray(` \u2022 ${o}`))}));let r=await a.select({message:"How would you like to proceed?",options:[{value:"merge",label:"Merge with existing",hint:"Keep custom settings and update defaults"},{value:"replace",label:"Replace entirely",hint:"Start with fresh configuration"},{value:"cancel",label:"Cancel",hint:"Keep existing configuration"}]});if(a.isCancel(r)||r==="cancel")throw a.cancel("Keeping existing configuration"),new Error("Cancelled");this.config._action=r}}}async selectFramework(e){let t=Ee(e);if(t){let n=k[t];a.log.info(`Detected project type: ${S.cyan(n?.name)}`);let l=await a.confirm({message:`Use ${n?.name} optimized settings?"`,initialValue:!0});if(a.isCancel(l))throw a.cancel("Setup cancelled"),new Error("Cancelled");if(l)return n}let s=await a.select({message:"What type of project is this?",options:[{value:"frontend",label:"Frontend Application",hint:"React, Vue, Angular"},{value:"backend",label:"Backend Application",hint:"Node.js, Express, NestJS"},{value:"fullstack",label:"Full-stack Framework",hint:"Next.js, Remix, Nuxt"},{value:"library",label:"Library/Package",hint:"NPM package to publish"},{value:"mobile",label:"Mobile Application",hint:"React Native, Ionic"},{value:"desktop",label:"Desktop Application",hint:"Electron, Tauri"},{value:"monorepo",label:"Monorepo",hint:"Multi-package repository"},{value:"custom",label:"Custom",hint:"Configure from scratch"}]});if(a.isCancel(s))throw a.cancel("Setup cancelled"),new Error("Cancelled");let i={frontend:[{key:"vite-react",preset:k["vite-react"]},{key:"vite-vue",preset:k["vite-vue"]},{key:"react",preset:k.react}],backend:[{key:"node-esm",preset:k["node-esm"]},{key:"node-commonjs",preset:k["node-commonjs"]},{key:"express-api",preset:k["express-api"]}],fullstack:[{key:"next-app",preset:k["next-app"]},{key:"next-pages",preset:k["next-pages"]}],library:[{key:"react-library",preset:k["react-library"]},{key:"node-library",preset:k["node-library"]}],mobile:[{key:"react-native",preset:k["react-native"]}],desktop:[{key:"electron",preset:k.electron}],monorepo:[{key:"monorepo-root",preset:k["monorepo-root"]},{key:"monorepo-package",preset:k["monorepo-package"]}],custom:[]};if(s==="custom")return k["node-commonjs"];let r=i[s]||[],o=await a.select({message:"Select specific configuration",options:r.map(({key:n,preset:l})=>({value:n,label:l.name,hint:l.description}))});if(a.isCancel(o))throw a.cancel("Setup cancelled"),new Error("Cancelled");return this.presetKey=o,k[o]}async configureTarget(){let e=await a.confirm({message:"Customize the compilation target?",initialValue:!1});if(a.isCancel(e)||!e)return;a.log.step(S.cyan("\u{1F3AF} Set compilation target")),a.log.info("Target versions & typical environments:"),a.log.message(S.gray(" \u2022 ES2022: Node 16+, modern browsers (recommended)")),a.log.message(S.gray(" \u2022 ES2020