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 | 1x 1x 1x 1x 1x 1x 2x | /**
* Dev command - Starts development server with hot reload
*/
import { Command } from 'commander';
import ora from 'ora';
import picocolors from 'picocolors';
import { spawn } from 'child_process';
import { existsSync, readFileSync } from 'fs';
import { join } from 'path';
import { startDevServer } from '../dev-server/index.js';
/**
* Open `url` in the default browser via the optional `open` package, which
* this CLI does not depend on. Never throws: prints how to enable it instead.
*/
export async function openBrowser(url, importOpen = () => import('open')) {
try {
const { default: open } = await importOpen();
await open(url);
return true;
} catch (error) {
if (error?.code === 'ERR_MODULE_NOT_FOUND') {
console.log(picocolors.yellow('⚠️ --open needs the optional "open" package: npm install --save-dev open'));
} else E{
console.log(picocolors.yellow(`⚠️ Could not open a browser: ${error?.message ?? error}`));
}
console.log(picocolors.gray(` Open ${url} manually.`));
return false;
}
}
/**
* True when the current project should use the built-in Coherent dev
* server instead of delegating to vite/webpack/nodemon. Either the
* `--coherent` flag is set, or a `coherent.config.js`/`.mjs` file
* exists in the project root.
*/
function shouldUseCoherentDevServer(cwd, options) {
if (options.coherent) return true;
return existsSync(join(cwd, 'coherent.config.js')) || existsSync(join(cwd, 'coherent.config.mjs'));
}
/** Split a comma-separated option value into its trimmed, non-empty entries. */
function splitList(value) {
return String(value).split(',').map((entry) => entry.trim()).filter(Boolean);
}
/** Commander parser for a comma-separated option that may also be repeated. */
function collectList(value, previous = []) {
return [...previous, ...splitList(value)];
}
export const devCommand = new Command('dev')
.description('Start development server with hot reload')
.option('-p, --port <port>', 'port number', '3000')
.option('-H, --host <host>', 'host address', 'localhost')
.option('--open', 'open browser automatically')
.option('--no-hmr', 'disable hot module replacement')
.option('--coherent', 'use the built-in Coherent HMR dev server (HTTP + WebSocket + chokidar)')
.option('--allowed-hosts <hosts>', 'built-in server: comma-separated extra Host names to answer (besides localhost, IPs and --host)')
.option('--fs-allow <dirs>', 'built-in server: comma-separated extra directories files may be served from, relative to the project root (repeatable)', collectList)
.action(async (options) => {
console.log(picocolors.cyan('🚀 Starting Coherent.js development server...'));
console.log();
const cwd = process.cwd();
const packageJsonPath = join(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);
}
// --- Built-in Coherent dev server (opt-in via --coherent or coherent.config.js) ---
if (shouldUseCoherentDevServer(cwd, options)) {
try {
const server = await startDevServer({
root: cwd,
port: Number(options.port),
host: options.host,
open: false,
log: true,
hmr: options.hmr !== false,
allowedHosts: options.allowedHosts ? splitList(options.allowedHosts) : [],
fsAllow: options.fsAllow ?? [],
});
const cleanup = async () => {
console.log();
console.log(picocolors.yellow('👋 Stopping Coherent dev server...'));
try { await server.close(); } catch { /* ignore */ }
process.exit(0);
};
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
if (options.open) {
await openBrowser(`http://${server.host}:${server.port}`);
}
} catch (error) {
console.error(picocolors.red('❌ Failed to start Coherent dev server:'), error.message);
process.exit(1);
}
return;
}
// --- Fallback: existing delegation behavior ---
const spinner = ora('Starting development server...').start();
let devProcess;
try {
if (packageJson.scripts && packageJson.scripts.dev) {
spinner.text = 'Running dev script...';
devProcess = spawn('npm', ['run', 'dev'], {
stdio: 'inherit',
cwd,
shell: true,
env: {
...process.env,
PORT: options.port,
HOST: options.host,
},
});
} else if (existsSync('vite.config.js') || existsSync('vite.config.ts')) {
spinner.text = 'Starting default dev server...';
devProcess = spawn('npx', ['vite', '--port', options.port, '--host', options.host], {
stdio: 'inherit',
cwd,
shell: true,
});
} else if (existsSync('webpack.config.js')) {
spinner.text = 'Starting default dev server...';
devProcess = spawn('npx', ['webpack', 'serve', '--port', options.port, '--host', options.host], {
stdio: 'inherit',
cwd,
shell: true,
});
} else if (packageJson.type === 'module' || existsSync('src/index.js')) {
spinner.text = 'Starting default dev server...';
devProcess = spawn('npx', ['nodemon', 'src/index.js'], {
stdio: 'inherit',
cwd,
shell: true,
env: {
...process.env,
PORT: options.port,
HOST: options.host,
},
});
} else {
throw new Error('No development server configuration found. Run with --coherent to use the built-in Coherent HMR dev server.');
}
spinner.stop();
console.log(picocolors.green('✅ Development server started!'));
console.log();
console.log(picocolors.cyan('🌐 Local:'), `http://${options.host}:${options.port}`);
if (options.host !== 'localhost') {
console.log(picocolors.cyan('🔗 Network:'), `http://${options.host}:${options.port}`);
}
console.log();
console.log(picocolors.gray('Press Ctrl+C to stop the server'));
console.log();
const cleanup = () => {
console.log();
console.log(picocolors.yellow('👋 Stopping development server...'));
if (devProcess) {
devProcess.kill();
}
process.exit(0);
};
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
devProcess.on('exit', (code) => {
if (code !== 0) {
console.error(picocolors.red(`❌ Development server exited with code ${code}`));
process.exit(code);
}
});
devProcess.on('error', (_error) => {
console.error(picocolors.red('❌ Failed to start development server:'), _error.message);
process.exit(1);
});
if (options.open) {
await openBrowser(`http://${options.host}:${options.port}`);
}
} catch (error) {
// Never leave a server running behind a command that reports failure
if (devProcess && devProcess.exitCode === null) {
devProcess.kill();
}
spinner.fail('Failed to start development server');
console.error(picocolors.red('❌ Error:'), error.message);
console.log();
console.log(picocolors.yellow('💡 Suggestions:'));
console.log(picocolors.gray(' • Run with --coherent to use the built-in Coherent HMR dev server'));
console.log(picocolors.gray(' • Make sure you have a dev script in package.json'));
console.log(picocolors.gray(' • Install development dependencies: npm install'));
console.log(picocolors.gray(' • Check if port', options.port, 'is available'));
process.exit(1);
}
});
|