@re-shell/cli
Version:
Full-stack development platform uniting microservices and microfrontends. Build complete applications with .NET (ASP.NET Core Web API, Minimal API), Java (Spring Boot, Quarkus, Micronaut, Vert.x), Rust (Actix-Web, Warp, Rocket, Axum), Python (FastAPI, Dja
233 lines (230 loc) • 7.77 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.commandTreeShaker = exports.CommandTreeShaker = void 0;
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
class CommandTreeShaker {
constructor() {
this.registry = {
commands: new Map(),
dependencies: new Map(),
usage: new Map()
};
this.loadUsageStats();
}
static getInstance() {
if (!CommandTreeShaker.instance) {
CommandTreeShaker.instance = new CommandTreeShaker();
}
return CommandTreeShaker.instance;
}
/**
* Register a command with its metadata
*/
registerCommand(metadata) {
this.registry.commands.set(metadata.name, metadata);
// Track dependencies
if (metadata.dependencies) {
this.registry.dependencies.set(metadata.name, new Set(metadata.dependencies));
}
}
/**
* Get commands that should be loaded immediately
*/
getCriticalCommands() {
const criticalCommands = [
'init',
'add',
'serve',
'build',
'help',
'--version'
];
// Add frequently used commands based on usage stats
const frequentCommands = Array.from(this.registry.usage.entries())
.filter(([_, count]) => count > 10)
.sort(([_, a], [__, b]) => b - a)
.slice(0, 5)
.map(([cmd]) => cmd);
return [...new Set([...criticalCommands, ...frequentCommands])];
}
/**
* Get commands that can be lazy loaded
*/
getLazyCommands() {
const critical = new Set(this.getCriticalCommands());
return Array.from(this.registry.commands.keys())
.filter(cmd => !critical.has(cmd));
}
/**
* Track command usage
*/
trackUsage(command) {
const count = this.registry.usage.get(command) || 0;
this.registry.usage.set(command, count + 1);
this.saveUsageStats();
}
/**
* Analyze command dependencies
*/
analyzeDependencies(command) {
const visited = new Set();
const queue = [command];
while (queue.length > 0) {
const current = queue.shift();
if (visited.has(current))
continue;
visited.add(current);
const deps = this.registry.dependencies.get(current);
if (deps) {
deps.forEach(dep => {
if (!visited.has(dep)) {
queue.push(dep);
}
});
}
}
return visited;
}
/**
* Generate optimized command loader
*/
generateOptimizedLoader() {
const critical = this.getCriticalCommands();
const lazy = this.getLazyCommands();
return `
// Auto-generated optimized command loader
// Critical commands loaded immediately
const criticalCommands = {
${critical.map(cmd => ` '${cmd}': () => require('./commands/${cmd}')`).join(',\n')}
};
// Lazy-loaded commands
const lazyCommands = {
${lazy.map(cmd => ` '${cmd}': () => import('./commands/${cmd}')`).join(',\n')}
};
export function loadCommand(name: string): any {
if (criticalCommands[name]) {
return criticalCommands[name]();
}
if (lazyCommands[name]) {
return lazyCommands[name]();
}
throw new Error(\`Unknown command: \${name}\`);
}
`;
}
/**
* Optimize command imports
*/
optimizeImports(filePath) {
const content = fs.readFileSync(filePath, 'utf-8');
// Replace static imports with dynamic imports for non-critical modules
const optimized = content
// Convert heavy library imports to dynamic
.replace(/import\s+(\w+)\s+from\s+['"](?:chalk|ora|inquirer|globby|fs-extra)['"]/g, 'const $1 = await import(\'$2\').then(m => m.default || m)')
// Convert unused imports to comments
.replace(/import\s+{\s*([^}]+)\s*}\s+from\s+['"][^'"]+['"]\s*;?\s*\/\/\s*unused/gi, '// $&');
return optimized;
}
/**
* Analyze command size
*/
async analyzeCommandSize(commandPath) {
try {
const stats = await fs.promises.stat(commandPath);
return stats.size;
}
catch {
return 0;
}
}
/**
* Generate command manifest
*/
async generateManifest() {
const manifest = {};
for (const [name, metadata] of this.registry.commands) {
const commandPath = path.join(__dirname, '..', 'commands', `${name}.ts`);
const size = await this.analyzeCommandSize(commandPath);
manifest[name] = {
...metadata,
size,
usage: this.registry.usage.get(name) || 0
};
}
const manifestPath = path.join(__dirname, '..', '..', 'command-manifest.json');
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
}
/**
* Load usage statistics
*/
loadUsageStats() {
try {
const statsPath = path.join(process.env.HOME || process.env.USERPROFILE || '', '.re-shell', 'usage-stats.json');
if (fs.existsSync(statsPath)) {
const stats = JSON.parse(fs.readFileSync(statsPath, 'utf-8'));
Object.entries(stats).forEach(([cmd, count]) => {
this.registry.usage.set(cmd, count);
});
}
}
catch {
// Ignore errors
}
}
/**
* Save usage statistics
*/
saveUsageStats() {
try {
const statsDir = path.join(process.env.HOME || process.env.USERPROFILE || '', '.re-shell');
if (!fs.existsSync(statsDir)) {
fs.mkdirSync(statsDir, { recursive: true });
}
const statsPath = path.join(statsDir, 'usage-stats.json');
const stats = {};
this.registry.usage.forEach((count, cmd) => {
stats[cmd] = count;
});
fs.writeFileSync(statsPath, JSON.stringify(stats, null, 2));
}
catch {
// Ignore errors
}
}
}
exports.CommandTreeShaker = CommandTreeShaker;
exports.commandTreeShaker = CommandTreeShaker.getInstance();