lcr.js
1#!/usr/bin/env node
2
3import { existsSync } from 'fs';
4import { resolve, join } from 'path';
5import { createServer } from 'http';
6import { fileURLToPath } from 'url';
7
8const args = process.argv.slice(2);
9const repoDir = resolve(args[0] || process.cwd());
10
11// Check if directory is a git or jj repo
12const isGit = existsSync(join(repoDir, '.git'));
13const isJj = existsSync(join(repoDir, '.jj'));
14if (!isGit && !isJj) {
15 console.error('Error: Not a git or jj repository. Run this command from within a git or jj repo.');
16 process.exit(1);
17}
18const vcs = isJj ? 'jj' : 'git';
19
20// Set repo dir for the server
21process.env.LCR_REPO_DIR = repoDir;
22
23// Find the build directory
24const __dirname = fileURLToPath(new URL('.', import.meta.url));
25const buildPath = join(__dirname, '..', 'build');
26
27if (!existsSync(join(buildPath, 'handler.js'))) {
28 console.error('Error: Build not found. Run `npm run build` first.');
29 process.exit(1);
30}
31
32// Import the SvelteKit handler
33const { handler } = await import(join(buildPath, 'handler.js'));
34
35const DEFAULT_PORT = 5678;
36const port = parseInt(process.env.PORT || String(DEFAULT_PORT), 10);
37
38const server = createServer(handler);
39
40// Attach WebSocket for terminal
41try {
42 const { attachWebSocket } = await import(join(buildPath, 'ws-handler.js'));
43 attachWebSocket(server);
44} catch (err) {
45 console.warn(' Warning: Terminal not available:', err.message);
46}
47
48server.listen(port, '127.0.0.1', async () => {
49 const url = `http://localhost:${port}`;
50 console.log(`\n Local Code Review`);
51 console.log(` Reviewing: ${repoDir} (${vcs})`);
52 console.log(` Server: ${url}\n`);
53
54 // Open browser
55 try {
56 const open = await import('open');
57 await open.default(url);
58 } catch {
59 console.log(` Open ${url} in your browser`);
60 }
61});
62
63server.on('error', (err) => {
64 if (err.code === 'EADDRINUSE') {
65 console.error(`Port ${port} is in use. Try: PORT=${port + 1} lcr`);
66 process.exit(1);
67 }
68 throw err;
69});
70
71// Graceful shutdown
72process.on('SIGINT', () => {
73 console.log('\n Shutting down...');
74 server.close();
75 process.exit(0);
76});
77
78process.on('SIGTERM', () => {
79 server.close();
80 process.exit(0);
81});