Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | 2x 2x 2x 30x 30x 23x 23x 20x 20x 20x 20x 66x 66x 46x 46x 46x 20x 5x 11x 11x 7x 20x 20x 15x 1x 1x 2x 15x 19x 19x 19x 9x 9x 17x 14x 7x 6x 1x 9x 2x | /**
* Build command - Builds the project for production
*/
import { Command } from 'commander';
import ora from 'ora';
import picocolors from 'picocolors';
import { execSync } from 'child_process';
import { existsSync, readFileSync } from 'fs';
import { dirname, join, parse } from 'path';
const COHERENT_PACKAGES = ['@coherent.js/core', 'coherentjs'];
/**
* esbuild fallback command.
*
* --packages=external keeps dependencies out of the bundle: server deps like
* express pull in CJS packages that call require() dynamically (debug ->
* require('tty')), which an ESM bundle cannot satisfy. Without it the build
* exits 0 but the artifact dies at startup.
*/
export const ESBUILD_FALLBACK_COMMAND =
'npx esbuild src/index.js --bundle --minify --outfile=dist/index.js --platform=node --format=esm --packages=external';
const DEPENDENCY_FIELDS = [
'dependencies',
'devDependencies',
'peerDependencies',
'optionalDependencies'
];
/** Read and parse a package.json, or null when absent/unreadable. */
function readPackageJson(dir) {
const path = join(dir, 'package.json');
if (!existsSync(path)) return null;
try {
return JSON.parse(readFileSync(path, 'utf-8'));
} catch {
return null;
}
}
/** Every directory from `start` up to the filesystem root. */
function ancestorDirectories(start) {
const dirs = [];
const { root } = parse(start);
let current = start;
while (true) {
dirs.push(current);
if (current === root) break;
const parent = dirname(current);
Iif (parent === current) break;
current = parent;
}
return dirs;
}
/**
* Detect a Coherent.js dependency.
*
* Workspace setups (pnpm/yarn/npm workspaces) hoist dependencies to the
* repository root, so the package manifest next to the build may not list
* @coherent.js/core at all. Walk up the tree and check every dependency
* field, and accept an installed copy under any ancestor's node_modules.
*/
export function hasCoherentDependency(startDir) {
for (const dir of ancestorDirectories(startDir)) {
const manifest = readPackageJson(dir);
if (manifest) {
for (const field of DEPENDENCY_FIELDS) {
const deps = manifest[field];
if (deps && COHERENT_PACKAGES.some(name => deps[name])) return true;
}
}
if (COHERENT_PACKAGES.some(name => existsSync(join(dir, 'node_modules', name)))) {
return true;
}
}
return false;
}
/**
* detectPackageManager() must only return a member of this set: the result is
* interpolated into a shell command and `packageManager` comes from a
* package.json that may be hostile.
*/
const SUPPORTED_PACKAGE_MANAGERS = new Set(['npm', 'pnpm', 'yarn', 'bun']);
/** Detect the package manager in use, falling back to npm. */
export function detectPackageManager(startDir) {
for (const dir of ancestorDirectories(startDir)) {
const manifest = readPackageJson(dir);
const declared = manifest?.packageManager;
if (typeof declared === 'string') {
// corepack format: "<name>@<version>[+hash]"
const name = declared.split('@')[0].trim().toLowerCase();
if (SUPPORTED_PACKAGE_MANAGERS.has(name)) return name;
}
if (existsSync(join(dir, 'pnpm-lock.yaml'))) return 'pnpm';
if (existsSync(join(dir, 'yarn.lock'))) return 'yarn';
if (existsSync(join(dir, 'bun.lockb'))) return 'bun';
if (existsSync(join(dir, 'package-lock.json'))) return 'npm';
}
return 'npm';
}
/** True when a build script would re-enter this command. */
export function isSelfReferential(script) {
return typeof script === 'string' && /(^|[\s&|;])coherent\s+build\b/.test(script);
}
export const buildCommand = new Command('build')
.description('Build the project for production')
.option('-w, --watch', 'watch for changes')
.option('--analyze', 'analyze bundle size')
.option('--no-minify', 'disable minification')
.option('--no-optimize', 'disable optimizations')
.action(async (options) => {
console.log(picocolors.cyan('🏗️ Building Coherent.js project...'));
console.log();
// Check if we're in a Coherent.js project
const packageJsonPath = join(process.cwd(), 'package.json');
if (!existsSync(packageJsonPath)) {
console.error(picocolors.red('❌ No package.json found. Are you in a project directory?'));
process.exit(1);
}
let packageJson;
try {
packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
} catch {
console.error(picocolors.red('❌ Failed to read package.json'));
process.exit(1);
}
// Check for Coherent.js dependencies (including hoisted workspace deps)
if (!hasCoherentDependency(process.cwd())) {
console.error(picocolors.red('❌ This doesn\'t appear to be a Coherent.js project'));
console.error(picocolors.gray(' Missing @coherent.js/core dependency'));
process.exit(1);
}
const packageManager = detectPackageManager(process.cwd());
const spinner = ora('Building project...').start();
try {
// Check for existing build script. A script of `coherent build` (which
// `coherent create` generates) would re-enter this command forever, so
// fall through to the default pipeline instead.
const buildScript = packageJson.scripts?.build;
if (buildScript && !isSelfReferential(buildScript)) {
spinner.text = `Running build script with ${packageManager}...`;
// shell:true is safe here: packageManager is allowlisted, and the
// binaries are .cmd shims on Windows.
execSync(`${packageManager} run build`, {
stdio: options.watch ? 'inherit' : 'pipe',
cwd: process.cwd(),
shell: true
});
} else {
if (buildScript) {
spinner.warn('Build script runs "coherent build" — using the default pipeline to avoid recursion.');
spinner.start();
}
// Default build process for Coherent.js projects
spinner.text = 'Building with default configuration...';
// Check for different build tools
if (existsSync('vite.config.js') || existsSync('vite.config.ts')) {
execSync('npx vite build', {
stdio: options.watch ? 'inherit' : 'pipe',
cwd: process.cwd(),
shell: true
});
} else if (existsSync('webpack.config.js')) {
execSync('npx webpack --mode production', {
stdio: options.watch ? 'inherit' : 'pipe',
cwd: process.cwd(),
shell: true
});
} else if (existsSync('rollup.config.js')) {
execSync('npx rollup -c', {
stdio: options.watch ? 'inherit' : 'pipe',
cwd: process.cwd(),
shell: true
});
} else {
// Use esbuild as fallback
spinner.text = 'Building with esbuild (fallback)...';
execSync(ESBUILD_FALLBACK_COMMAND, {
stdio: options.watch ? 'inherit' : 'pipe',
cwd: process.cwd(),
shell: true
});
}
}
// Bundle analysis
if (options.analyze) {
spinner.text = 'Analyzing bundle...';
try {
// Try to run bundle analyzer if available
execSync('npx webpack-bundle-analyzer dist/stats.json', {
stdio: 'inherit',
cwd: process.cwd(),
shell: true
});
} catch {
console.log(picocolors.yellow('⚠️ Bundle analyzer not available'));
console.log(picocolors.gray(' Install webpack-bundle-analyzer for detailed analysis'));
}
}
spinner.succeed('Build completed successfully!');
// Show build info
console.log();
console.log(picocolors.green('✅ Build completed!'));
// Check if dist directory exists and show size info
if (existsSync('dist')) {
try {
const distSize = execSync('du -sh dist', { encoding: 'utf-8' }).trim().split('\t')[0];
console.log(picocolors.gray('📦 Output size:'), distSize);
} catch {
// Ignore size calculation errors
}
}
console.log();
console.log(picocolors.cyan('Next steps:'));
console.log(picocolors.gray(' Deploy your dist/ directory to your hosting provider'));
console.log(picocolors.gray(` Or run: ${packageManager} run start (if available)`));
console.log();
} catch (error) {
spinner.fail('Build failed');
console.error(picocolors.red('❌ Build error:'));
console.error(error.message);
// Show helpful error messages
if (error.message.includes('command not found')) {
console.log();
console.log(picocolors.yellow('💡 Try installing dependencies:'));
console.log(picocolors.gray(` ${packageManager} install`));
}
process.exit(1);
}
}); |