Comparar commits

..

9 Commits

Autor SHA1 Mensaje Fecha
ale
511b545ffb 1.1.0 2025-08-19 23:13:15 +02:00
ale
76e9c939e2 v1.1.0
Signed-off-by: ale <ale@manalejandro.com>
2025-08-19 23:11:19 +02:00
ale
6c575750ff 1.0.7 2025-08-19 06:57:59 +02:00
ale
9eb10395ad v1.0.7
Signed-off-by: ale <ale@manalejandro.com>
2025-08-19 06:57:52 +02:00
ale
e46dd6a16a temporizador
Signed-off-by: ale <ale@manalejandro.com>
2025-08-19 06:51:59 +02:00
ale
30d2b35bda v1.0.6
Signed-off-by: ale <ale@manalejandro.com>
2025-08-19 06:35:06 +02:00
ale
2fccf3fd48 1.0.6 2025-08-19 06:28:19 +02:00
ale
fdeb3b2a2c some fixes
Signed-off-by: ale <ale@manalejandro.com>
2025-08-19 06:28:08 +02:00
ale
a92b2496e1 1.0.5 2025-08-19 06:17:00 +02:00
Se han modificado 3 ficheros con 219 adiciones y 86 borrados

Ver fichero

@@ -1,6 +1,6 @@
{
"name": "alepm",
"version": "1.0.4",
"version": "1.1.0",
"description": "Advanced and secure Node.js package manager with binary storage, intelligent caching, and comprehensive security features",
"main": "src/index.js",
"bin": {
@@ -51,21 +51,14 @@
"IMPLEMENTATION.md"
],
"dependencies": {
"body-parser": "^2.2.0",
"chalk": "^4.1.2",
"commander": "^11.1.0",
"crypto": "^1.0.1",
"debug": "^4.4.1",
"express": "^5.1.0",
"fs-extra": "^11.3.1",
"inquirer": "^8.2.6",
"listr2": "^6.6.1",
"lodash": "^4.17.21",
"node-fetch": "^2.6.12",
"ora": "^5.4.1",
"semver": "^7.7.2",
"tar": "^6.2.1",
"lodash.debounce": "^4.0.8"
"tar": "^6.2.1"
},
"devDependencies": {
"eslint": "^8.45.0",

Ver fichero

@@ -11,13 +11,15 @@ class CacheManager {
constructor() {
this.cacheDir = path.join(require('os').homedir(), '.alepm', 'cache');
this.metadataFile = path.join(this.cacheDir, 'metadata.json');
this.init();
this._initialized = false;
}
async init() {
if (this._initialized) return;
await fs.ensureDir(this.cacheDir);
if (!fs.existsSync(this.metadataFile)) {
if (!await fs.pathExists(this.metadataFile)) {
await this.saveMetadata({
version: '1.0.0',
entries: {},
@@ -25,9 +27,12 @@ class CacheManager {
lastCleanup: Date.now()
});
}
this._initialized = true;
}
async get(packageName, version) {
await this.init();
const key = this.generateKey(packageName, version);
const metadata = await this.loadMetadata();
@@ -38,7 +43,7 @@ class CacheManager {
const entry = metadata.entries[key];
const filePath = path.join(this.cacheDir, entry.file);
if (!fs.existsSync(filePath)) {
if (!await fs.pathExists(filePath)) {
// Remove stale entry
delete metadata.entries[key];
await this.saveMetadata(metadata);
@@ -67,6 +72,7 @@ class CacheManager {
}
async has(packageName, version) {
await this.init();
const key = this.generateKey(packageName, version);
const metadata = await this.loadMetadata();
@@ -78,7 +84,7 @@ class CacheManager {
const filePath = path.join(this.cacheDir, entry.file);
// Check if file exists
if (!fs.existsSync(filePath)) {
if (!await fs.pathExists(filePath)) {
// Remove stale entry
delete metadata.entries[key];
await this.saveMetadata(metadata);
@@ -89,6 +95,7 @@ class CacheManager {
}
async store(packageName, version, data) {
await this.init();
const key = this.generateKey(packageName, version);
const metadata = await this.loadMetadata();
@@ -117,7 +124,7 @@ class CacheManager {
if (metadata.entries[key]) {
const oldEntry = metadata.entries[key];
const oldFilePath = path.join(this.cacheDir, oldEntry.file);
if (fs.existsSync(oldFilePath)) {
if (await fs.pathExists(oldFilePath)) {
await fs.remove(oldFilePath);
metadata.totalSize -= oldEntry.size;
}
@@ -135,6 +142,7 @@ class CacheManager {
}
async remove(packageName, version) {
await this.init();
const key = this.generateKey(packageName, version);
const metadata = await this.loadMetadata();
@@ -145,7 +153,7 @@ class CacheManager {
const entry = metadata.entries[key];
const filePath = path.join(this.cacheDir, entry.file);
if (fs.existsSync(filePath)) {
if (await fs.pathExists(filePath)) {
await fs.remove(filePath);
}
@@ -157,13 +165,14 @@ class CacheManager {
}
async clean() {
await this.init();
const metadata = await this.loadMetadata();
let cleanedSize = 0;
for (const [, entry] of Object.entries(metadata.entries)) {
const filePath = path.join(this.cacheDir, entry.file);
if (fs.existsSync(filePath)) {
if (await fs.pathExists(filePath)) {
await fs.remove(filePath);
cleanedSize += entry.size;
}
@@ -182,6 +191,7 @@ class CacheManager {
}
async verify() {
await this.init();
const metadata = await this.loadMetadata();
const corrupted = [];
const missing = [];
@@ -189,7 +199,7 @@ class CacheManager {
for (const [key, entry] of Object.entries(metadata.entries)) {
const filePath = path.join(this.cacheDir, entry.file);
if (!fs.existsSync(filePath)) {
if (!await fs.pathExists(filePath)) {
missing.push(key);
continue;
}
@@ -220,6 +230,7 @@ class CacheManager {
}
async getStats() {
await this.init();
const metadata = await this.loadMetadata();
const entries = Object.values(metadata.entries);

Ver fichero

@@ -115,7 +115,7 @@ class PackageManager {
const packageJson = await fs.readJson(packageJsonPath);
const dependencies = {
...packageJson.dependencies,
...(options.includeDev ? packageJson.devDependencies : {})
...(options.includeDev || options.saveDev ? packageJson.devDependencies : {})
};
if (Object.keys(dependencies).length === 0) {
@@ -125,8 +125,8 @@ class PackageManager {
const packages = Object.entries(dependencies).map(([name, version]) => `${name}@${version}`);
// Call the main installation logic directly, bypassing the package.json check
return await this.installPackages(packages, { ...options, fromPackageJson: true });
// Call the main installation logic with special flag for package.json installs
return await this.installPackages(packages, { ...options, fromPackageJsonMain: true });
}
async installPackages(packages, options = {}) {
@@ -134,6 +134,13 @@ class PackageManager {
return;
}
// Start timer for installation (for main installations only)
const isMainInstall = !options.fromPackageJson && !options._depth;
const isPackageJsonMain = options.fromPackageJsonMain;
const isRecursiveInstall = options._depth > 0;
const shouldShowSummary = (isMainInstall || isPackageJsonMain) && !isRecursiveInstall;
const startTime = shouldShowSummary ? Date.now() : null;
console.log(chalk.blue(`Installing ${packages.length} package(s)...`));
const results = [];
@@ -216,7 +223,9 @@ class PackageManager {
try {
// Write buffer to temporary file and extract from there
const tempFile = path.join(os.tmpdir(), `${name}-${Date.now()}.tgz`);
// Sanitize package name for file system
const sanitizedName = name.replace(/[@/]/g, '-');
const tempFile = path.join(os.tmpdir(), `${sanitizedName}-${Date.now()}.tgz`);
await fs.writeFile(tempFile, packageData);
// Extract the tarball directly to the target directory
@@ -279,6 +288,47 @@ class PackageManager {
// Update lock file
await this.lock.update(results.filter(r => !r.error));
// Show installation summary for main installations (including package.json main installs)
if (shouldShowSummary) {
const successfulInstalls = results.filter(r => !r.error);
const failedInstalls = results.filter(r => r.error);
// Calculate elapsed time
const endTime = Date.now();
const elapsedTime = startTime ? endTime - startTime : 0;
const elapsedSeconds = (elapsedTime / 1000).toFixed(2);
console.log('');
console.log(chalk.green('📦 Installation Summary:'));
console.log('');
if (successfulInstalls.length > 0) {
if (successfulInstalls.length === 1 && !isPackageJsonMain) {
const result = successfulInstalls[0];
const sourceLabel = result.source === 'cache' ? '(cached)' : `(${result.source})`;
console.log(chalk.green(`✓ Successfully installed ${result.name}@${result.version} ${chalk.gray(sourceLabel)}`));
} else {
console.log(chalk.green(`✓ Successfully installed ${successfulInstalls.length} package(s):`));
successfulInstalls.forEach(result => {
const sourceLabel = result.source === 'cache' ? '(cached)' : `(${result.source})`;
console.log(chalk.green(`${result.name}@${result.version} ${chalk.gray(sourceLabel)}`));
});
}
}
if (failedInstalls.length > 0) {
console.log('');
console.log(chalk.red(`✗ Failed to install ${failedInstalls.length} package(s):`));
failedInstalls.forEach(result => {
console.log(chalk.red(`${result.packageSpec}: ${result.error}`));
});
}
console.log('');
console.log(chalk.gray(`⏱️ Total time: ${elapsedSeconds}s`));
console.log('');
}
console.log(chalk.green(`Installation completed. ${results.filter(r => !r.error).length} packages installed.`));
return results;
}
@@ -299,9 +349,13 @@ class PackageManager {
...(options.includeDev ? packageJson.devDependencies : {})
};
const optionalDependencies = packageJson.optionalDependencies || {};
if (!dependencies || Object.keys(dependencies).length === 0) {
// No dependencies to install
return;
// If no regular dependencies, check if there are optional dependencies to install
if (Object.keys(optionalDependencies).length === 0) {
return;
}
}
// Initialize installed packages tracking if not exists
@@ -318,6 +372,14 @@ class PackageManager {
console.log(chalk.blue(`Installing dependencies for ${packageName}...`));
// Install dependencies recursively by calling installPackages
const depOptions = {
...options,
fromPackageJson: true, // Prevent updating package.json
_depth: currentDepth + 1, // Increment depth
_installedPackages: options._installedPackages // Pass along installed packages set
};
// Filter out already installed packages to avoid duplicates
const dependenciesToInstall = Object.entries(dependencies).filter(([name, version]) => {
const packageKey = `${name}@${version}`;
@@ -334,37 +396,74 @@ class PackageManager {
});
if (dependenciesToInstall.length === 0) {
return;
// No regular dependencies to install, but continue to check optional dependencies
} else {
// Prepare dependency specs for installation
const dependencySpecs = dependenciesToInstall.map(([name, version]) => {
// Mark as installed to prevent duplicates
options._installedPackages.add(`${name}@${version}`);
// Handle various version formats
if (version.startsWith('^') || version.startsWith('~') || version.startsWith('>=') || version.startsWith('<=')) {
return `${name}@${version}`;
} else if (version === '*' || version === 'latest') {
return `${name}@latest`;
} else if (semver.validRange(version)) {
return `${name}@${version}`;
} else {
// For non-semver versions (git urls, file paths, etc.), use as-is
return `${name}@${version}`;
}
});
// Install dependencies
await this.installPackages(dependencySpecs, depOptions);
}
// Prepare dependency specs for installation
const dependencySpecs = dependenciesToInstall.map(([name, version]) => {
// Mark as installed to prevent duplicates
options._installedPackages.add(`${name}@${version}`);
// Install optional dependencies (ignore failures)
if (Object.keys(optionalDependencies).length > 0) {
const optionalDependenciesToInstall = Object.entries(optionalDependencies).filter(([name, version]) => {
const packageKey = `${name}@${version}`;
if (options._installedPackages && options._installedPackages.has(packageKey)) {
return false; // Skip already installed package
}
// Handle various version formats
if (version.startsWith('^') || version.startsWith('~') || version.startsWith('>=') || version.startsWith('<=')) {
return `${name}@${version}`;
} else if (version === '*' || version === 'latest') {
return `${name}@latest`;
} else if (semver.validRange(version)) {
return `${name}@${version}`;
} else {
// For non-semver versions (git urls, file paths, etc.), use as-is
return `${name}@${version}`;
// Check if package already exists in node_modules
const targetDir = options.global
? path.join(this.globalRoot, 'node_modules', name)
: path.join(this.projectRoot, 'node_modules', name);
const exists = fs.existsSync(targetDir);
return !exists;
});
if (optionalDependenciesToInstall.length > 0) {
const optionalSpecs = optionalDependenciesToInstall.map(([name, version]) => {
// Mark as installed to prevent duplicates
if (options._installedPackages) {
options._installedPackages.add(`${name}@${version}`);
}
// Handle various version formats
if (version.startsWith('^') || version.startsWith('~') || version.startsWith('>=') || version.startsWith('<=')) {
return `${name}@${version}`;
} else if (version === '*' || version === 'latest') {
return `${name}@latest`;
} else if (semver.validRange(version)) {
return `${name}@${version}`;
} else {
return `${name}@${version}`;
}
});
// Install optional dependencies (ignore failures)
try {
await this.installPackages(optionalSpecs, depOptions);
} catch (error) {
console.warn(chalk.yellow(`Some optional dependencies for ${packageName} could not be installed (this is usually safe to ignore)`));
}
}
});
// Install dependencies recursively by calling installPackages
const depOptions = {
...options,
fromPackageJson: true, // Prevent updating package.json
_depth: currentDepth + 1, // Increment depth
_installedPackages: options._installedPackages // Pass along installed packages set
};
// Install dependencies
await this.installPackages(dependencySpecs, depOptions);
}
} catch (error) {
console.warn(chalk.yellow(`Failed to install dependencies for ${packageName}: ${error.message}`));
@@ -658,12 +757,8 @@ class PackageManager {
const { spawn } = require('child_process');
return new Promise((resolve, reject) => {
// Determine shell based on OS
const isWindows = process.platform === 'win32';
const shell = isWindows ? 'cmd' : 'sh';
const shellFlag = isWindows ? '/c' : '-c';
const childProcess = spawn(shell, [shellFlag, script], {
// Use cross-platform approach
const childProcess = spawn(script, [], {
cwd: this.projectRoot,
stdio: options.silent ? 'pipe' : 'inherit',
shell: true,
@@ -674,11 +769,12 @@ class PackageManager {
}
});
// Initialize output variables for silent mode
let stdout = '';
let stderr = '';
// Handle silent mode
if (options.silent) {
let stdout = '';
let stderr = '';
if (childProcess.stdout) {
childProcess.stdout.on('data', (data) => {
stdout += data.toString();
@@ -690,34 +786,60 @@ class PackageManager {
stderr += data.toString();
});
}
childProcess.on('close', (code) => {
if (code === 0) {
if (stdout.trim()) {
console.log(stdout.trim());
}
resolve();
} else {
if (stderr.trim()) {
console.error(stderr.trim());
}
reject(new Error(`Script "${scriptName}" exited with code ${code}`));
}
});
} else {
childProcess.on('close', (code) => {
if (code === 0) {
console.log(chalk.green(`✓ Script "${scriptName}" completed successfully`));
resolve();
} else {
reject(new Error(`Script "${scriptName}" exited with code ${code}`));
}
});
}
// Handle process completion
let completed = false;
const handleCompletion = (code, signal) => {
if (completed) return;
completed = true;
if (options.silent) {
if (stdout && stdout.trim()) {
console.log(stdout.trim());
}
if (stderr && stderr.trim()) {
console.error(stderr.trim());
}
}
if (code === 0) {
if (!options.silent) {
console.log(chalk.green(`✓ Script "${scriptName}" completed successfully`));
}
resolve();
} else {
const errorMsg = signal
? `Script "${scriptName}" was terminated by signal ${signal}`
: `Script "${scriptName}" exited with code ${code}`;
reject(new Error(errorMsg));
}
};
childProcess.on('close', handleCompletion);
childProcess.on('exit', handleCompletion);
childProcess.on('error', (error) => {
if (completed) return;
completed = true;
reject(new Error(`Failed to run script "${scriptName}": ${error.message}`));
});
// Handle process termination signals
const cleanup = () => {
if (!completed && !childProcess.killed) {
childProcess.kill('SIGTERM');
setTimeout(() => {
if (!childProcess.killed) {
childProcess.kill('SIGKILL');
}
}, 5000);
}
};
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
});
}
@@ -799,7 +921,12 @@ class PackageManager {
}
// Handle standard npm packages
const match = spec.match(/^(@?[^@]+)(?:@(.+))?$/);
// Improved regex to handle scoped packages like @scope/package@version
const match = spec.match(/^(@[^/]+\/[^@]+|[^@]+)(?:@(.+))?$/);
if (!match) {
throw new Error(`Invalid package specification: ${spec}`);
}
return {
name: match[1],
version: match[2] || 'latest',
@@ -1201,7 +1328,8 @@ class PackageManager {
// Create tarball from cloned directory
const tar = require('tar');
const tarballPath = path.join(os.tmpdir(), `${gitSpec.name}-${Date.now()}.tgz`);
const sanitizedName = gitSpec.name.replace(/[@/]/g, '-');
const tarballPath = path.join(os.tmpdir(), `${sanitizedName}-${Date.now()}.tgz`);
await tar.create({
gzip: true,
@@ -1242,7 +1370,8 @@ class PackageManager {
// Handle directory - create tarball
const tar = require('tar');
const os = require('os');
const tarballPath = path.join(os.tmpdir(), `${fileSpec.name}-${Date.now()}.tgz`);
const sanitizedName = fileSpec.name.replace(/[@/]/g, '-');
const tarballPath = path.join(os.tmpdir(), `${sanitizedName}-${Date.now()}.tgz`);
await tar.create({
gzip: true,