@seflless/ghosttown 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/ghosttown.js CHANGED
@@ -1,849 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * ghosttown CLI - Web-based terminal emulator
4
+ * ghosttown CLI - Primary command
5
5
  *
6
- * Starts a local HTTP server with WebSocket PTY support,
7
- * or runs a command in a new tmux session.
8
- *
9
- * Usage:
10
- * ghosttown [options] [command]
11
- *
12
- * Options:
13
- * -p, --port <port> Port to listen on (default: 8080, or PORT env var)
14
- * -h, --help Show this help message
15
- *
16
- * Examples:
17
- * ghosttown Start the web terminal server
18
- * ghosttown -p 3000 Start the server on port 3000
19
- * ghosttown vim Run vim in a new tmux session
20
- * ghosttown "npm run dev" Run npm in a new tmux session
21
- */
22
-
23
- import { execSync, spawn } from 'child_process';
24
- import fs from 'fs';
25
- import http from 'http';
26
- import { homedir, networkInterfaces } from 'os';
27
- import path from 'path';
28
- import { fileURLToPath } from 'url';
29
-
30
- // Node-pty for cross-platform PTY support
31
- import pty from '@lydell/node-pty';
32
- // WebSocket server
33
- import { WebSocketServer } from 'ws';
34
- // ASCII art generator
35
- import { asciiArt } from './ascii.js';
36
-
37
- const __filename = fileURLToPath(import.meta.url);
38
- const __dirname = path.dirname(__filename);
39
-
40
- // ============================================================================
41
- // Tmux Session Management
42
- // ============================================================================
43
-
44
- /**
45
- * Check if tmux is installed
46
- */
47
- function checkTmuxInstalled() {
48
- try {
49
- execSync('which tmux', { stdio: 'pipe' });
50
- return true;
51
- } catch (err) {
52
- return false;
53
- }
54
- }
55
-
56
- /**
57
- * Print tmux installation instructions and exit
58
- */
59
- function printTmuxInstallHelp() {
60
- console.error('\x1b[31mError: tmux is not installed.\x1b[0m\n');
61
- console.error('tmux is required to run commands in ghosttown sessions.\n');
62
- console.error('To install tmux:\n');
63
-
64
- if (process.platform === 'darwin') {
65
- console.error(' \x1b[36mmacOS (Homebrew):\x1b[0m brew install tmux');
66
- console.error(' \x1b[36mmacOS (MacPorts):\x1b[0m sudo port install tmux');
67
- } else if (process.platform === 'linux') {
68
- console.error(' \x1b[36mDebian/Ubuntu:\x1b[0m sudo apt install tmux');
69
- console.error(' \x1b[36mFedora:\x1b[0m sudo dnf install tmux');
70
- console.error(' \x1b[36mArch:\x1b[0m sudo pacman -S tmux');
71
- } else {
72
- console.error(' Please install tmux using your system package manager.');
73
- }
74
-
75
- console.error('');
76
- process.exit(1);
77
- }
78
-
79
- /**
80
- * Get the next available ghosttown session ID
81
- * Scans existing tmux sessions named ghosttown-<N> and returns max(N) + 1
6
+ * This is a thin wrapper that delegates to the shared CLI implementation.
7
+ * Aliases: gt, ght
82
8
  */
83
- function getNextSessionId() {
84
- try {
85
- // List all tmux sessions
86
- const output = execSync('tmux list-sessions -F "#{session_name}"', {
87
- encoding: 'utf8',
88
- stdio: ['pipe', 'pipe', 'pipe'],
89
- });
90
-
91
- // Find all ghosttown-<N> sessions and extract IDs
92
- const sessionIds = output
93
- .split('\n')
94
- .filter((name) => name.startsWith('ghosttown-'))
95
- .map((name) => {
96
- const id = parseInt(name.replace('ghosttown-', ''), 10);
97
- return isNaN(id) ? 0 : id;
98
- });
99
-
100
- // Return max + 1, or 1 if no sessions exist
101
- return sessionIds.length > 0 ? Math.max(...sessionIds) + 1 : 1;
102
- } catch (err) {
103
- // tmux not running or no sessions - start with 1
104
- return 1;
105
- }
106
- }
107
-
108
- /**
109
- * Create a new tmux session and run the command
110
- */
111
- function createTmuxSession(command) {
112
- // Check if tmux is installed
113
- if (!checkTmuxInstalled()) {
114
- printTmuxInstallHelp();
115
- }
116
-
117
- const sessionId = getNextSessionId();
118
- const sessionName = `ghosttown-${sessionId}`;
119
-
120
- try {
121
- // Create tmux session and attach directly (not detached)
122
- // Use -x and -y to set initial size, avoiding "terminal too small" issues
123
- // The command runs in the session, and we attach immediately
124
- const attach = spawn(
125
- 'tmux',
126
- [
127
- 'new-session',
128
- '-s',
129
- sessionName,
130
- '-x',
131
- '200',
132
- '-y',
133
- '50',
134
- // Set status off (no HUD), run the command, then start a shell
135
- // so the session stays open and interactive after command completes
136
- 'tmux set-option status off; ' + command + '; exec $SHELL',
137
- ],
138
- {
139
- stdio: 'inherit',
140
- }
141
- );
142
-
143
- attach.on('exit', (code) => {
144
- process.exit(code || 0);
145
- });
146
- } catch (err) {
147
- console.error(`Error creating tmux session: ${err.message}`);
148
- process.exit(1);
149
- }
150
- }
151
-
152
- // ============================================================================
153
- // Parse CLI arguments
154
- // ============================================================================
155
-
156
- function parseArgs() {
157
- const args = process.argv.slice(2);
158
- let port = null;
159
- let command = null;
160
-
161
- for (let i = 0; i < args.length; i++) {
162
- const arg = args[i];
163
-
164
- if (arg === '-h' || arg === '--help') {
165
- console.log(`
166
- Usage: ghosttown [options] [command]
167
-
168
- Options:
169
- -p, --port <port> Port to listen on (default: 8080, or PORT env var)
170
- -h, --help Show this help message
171
-
172
- Commands:
173
- If a command is provided, ghosttown creates a new tmux session
174
- named ghosttown-<id> (with status bar disabled) and runs the command.
175
-
176
- Examples:
177
- ghosttown Start the web terminal server
178
- ghosttown -p 3000 Start the server on port 3000
179
- ghosttown vim Run vim in a new tmux session
180
- ghosttown "npm run dev" Run npm in a new tmux session
181
- `);
182
- process.exit(0);
183
- }
184
-
185
- if (arg === '-p' || arg === '--port') {
186
- const nextArg = args[i + 1];
187
- if (!nextArg || nextArg.startsWith('-')) {
188
- console.error(`Error: ${arg} requires a port number`);
189
- process.exit(1);
190
- }
191
- port = parseInt(nextArg, 10);
192
- if (isNaN(port) || port < 1 || port > 65535) {
193
- console.error(`Error: Invalid port number: ${nextArg}`);
194
- process.exit(1);
195
- }
196
- i++; // Skip the next argument since we consumed it
197
- continue;
198
- }
199
-
200
- // Any non-flag argument is treated as the command
201
- if (!arg.startsWith('-')) {
202
- command = arg;
203
- }
204
- }
205
-
206
- return { port, command };
207
- }
208
-
209
- const cliArgs = parseArgs();
210
-
211
- // If a command is provided, create a tmux session instead of starting server
212
- if (cliArgs.command) {
213
- createTmuxSession(cliArgs.command);
214
- // createTmuxSession spawns tmux attach and waits for it to exit
215
- // The script will exit when tmux attach exits (via the exit handler)
216
- // We must not continue to server code, so we stop here
217
- } else {
218
- // Server mode (no command provided)
219
- startWebServer();
220
- }
221
-
222
- function startWebServer() {
223
- const HTTP_PORT = cliArgs.port || process.env.PORT || 8080;
224
-
225
- // ============================================================================
226
- // Locate ghosttown assets
227
- // ============================================================================
228
-
229
- function findAssets() {
230
- // Assets are in the package root (one level up from bin/)
231
- const packageRoot = path.join(__dirname, '..');
232
- const distPath = path.join(packageRoot, 'dist');
233
- const wasmPath = path.join(packageRoot, 'ghostty-vt.wasm');
234
-
235
- if (!fs.existsSync(path.join(distPath, 'ghostty-web.js'))) {
236
- console.error('Error: dist/ghostty-web.js not found.');
237
- console.error('The package may not have been built correctly.');
238
- process.exit(1);
239
- }
240
-
241
- if (!fs.existsSync(wasmPath)) {
242
- console.error('Error: ghostty-vt.wasm not found.');
243
- console.error('The package may not have been built correctly.');
244
- process.exit(1);
245
- }
246
-
247
- return { distPath, wasmPath };
248
- }
249
-
250
- const { distPath, wasmPath } = findAssets();
251
-
252
- // ============================================================================
253
- // HTML Template
254
- // ============================================================================
255
-
256
- const HTML_TEMPLATE = `<!doctype html>
257
- <html lang="en">
258
- <head>
259
- <meta charset="UTF-8" />
260
- <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
261
- <title>ghosttown</title>
262
- <style>
263
- :root {
264
- --vvh: 100vh;
265
- --vv-offset-top: 0px;
266
- }
267
-
268
- * {
269
- margin: 0;
270
- padding: 0;
271
- box-sizing: border-box;
272
- }
273
-
274
- html, body {
275
- margin: 0;
276
- padding: 0;
277
- height: var(--vvh);
278
- overflow: hidden;
279
- overscroll-behavior: none;
280
- touch-action: none;
281
- transition: none;
282
- }
283
-
284
- body {
285
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
286
- background: #292c34;
287
- padding: 8px 8px 14px 8px;
288
- box-sizing: border-box;
289
- position: fixed;
290
- inset: 0;
291
- height: var(--vvh);
292
- }
293
-
294
- .terminal-window {
295
- width: 100%;
296
- height: 100%;
297
- background: #ededed;
298
- display: flex;
299
- flex-direction: column;
300
- overflow: hidden;
301
- box-shadow:
302
- 0 0 0 0.5px #65686e,
303
- 0 0 0 1px #74777c,
304
- 0 0 0 1.5px #020203,
305
- 0px 4px 10px 0px rgba(0, 0, 0, 0.5);
306
- border-radius: 8px;
307
- box-sizing: border-box;
308
- transform: translateY(calc(var(--vv-offset-top) * -1));
309
- transition: none;
310
- }
311
-
312
- .title-bar {
313
- background: #292c34;
314
- padding: 8px 16px 6px 10px;
315
- display: flex;
316
- align-items: center;
317
- gap: 12px;
318
- }
319
-
320
- .traffic-lights {
321
- display: flex;
322
- gap: 8px;
323
- }
324
-
325
- .light {
326
- width: 12px;
327
- height: 12px;
328
- border-radius: 50%;
329
- }
330
-
331
- .light.red { background: #ff5f56; }
332
- .light.yellow { background: #ffbd2e; }
333
- .light.green { background: #27c93f; }
334
-
335
- .title {
336
- color: #e5e5e5;
337
- font-size: 13px;
338
- font-weight: 500;
339
- letter-spacing: 0.3px;
340
- display: flex;
341
- align-items: center;
342
- gap: 8px;
343
- }
344
-
345
- .title-separator { color: #666; }
346
- .current-directory {
347
- color: #888;
348
- font-size: 12px;
349
- font-weight: 400;
350
- max-width: 400px;
351
- overflow: hidden;
352
- text-overflow: ellipsis;
353
- white-space: nowrap;
354
- }
355
-
356
- .connection-status {
357
- margin-left: auto;
358
- font-size: 11px;
359
- color: #888;
360
- display: flex;
361
- align-items: center;
362
- gap: 6px;
363
- }
364
-
365
- .connection-dot {
366
- width: 6px;
367
- height: 6px;
368
- border-radius: 50%;
369
- background: #666;
370
- }
371
-
372
- .connection-dot.connected { background: #27c93f; }
373
-
374
- #terminal-container {
375
- flex: 1;
376
- padding: 2px 0 2px 2px;
377
- background: #292c34;
378
- position: relative;
379
- overflow: hidden;
380
- min-height: 0;
381
- touch-action: none;
382
- }
383
-
384
- #terminal-container canvas {
385
- display: block;
386
- touch-action: none;
387
- }
388
- </style>
389
- </head>
390
- <body>
391
- <div class="terminal-window">
392
- <div class="title-bar">
393
- <div class="traffic-lights">
394
- <span class="light red"></span>
395
- <span class="light yellow"></span>
396
- <span class="light green"></span>
397
- </div>
398
- <div class="title">
399
- <span>ghosttown</span>
400
- <span class="title-separator" id="title-separator" style="display: none">•</span>
401
- <span class="current-directory" id="current-directory"></span>
402
- </div>
403
- <div class="connection-status">
404
- <span class="connection-dot" id="connection-dot"></span>
405
- <span id="connection-text">Disconnected</span>
406
- </div>
407
- </div>
408
- <div id="terminal-container"></div>
409
- </div>
410
-
411
- <script type="module">
412
- import { init, Terminal, FitAddon } from '/dist/ghostty-web.js';
413
-
414
- let term;
415
- let ws;
416
- let fitAddon;
417
-
418
- async function initTerminal() {
419
- await init();
420
-
421
- term = new Terminal({
422
- cursorBlink: true,
423
- fontSize: 12,
424
- fontFamily: 'Monaco, Menlo, "Courier New", monospace',
425
- theme: {
426
- background: '#292c34',
427
- foreground: '#d4d4d4',
428
- },
429
- smoothScrollDuration: 0,
430
- scrollback: 10000,
431
- scrollbarVisible: false,
432
- });
433
-
434
- fitAddon = new FitAddon();
435
- term.loadAddon(fitAddon);
436
-
437
- term.open(document.getElementById('terminal-container'));
438
- fitAddon.fit();
439
- fitAddon.observeResize();
440
-
441
- // Desktop: auto-focus. Mobile: focus only on tap.
442
- const isCoarsePointer = window.matchMedia && window.matchMedia('(pointer: coarse)').matches;
443
- if (!isCoarsePointer) {
444
- term.focus();
445
- }
446
-
447
- // Prevent page scroll on iOS
448
- document.addEventListener('touchmove', (e) => {
449
- const container = document.getElementById('terminal-container');
450
- if (container && !container.contains(e.target)) {
451
- e.preventDefault();
452
- }
453
- }, { passive: false });
454
-
455
- // Mobile keyboard handling via visualViewport
456
- {
457
- const root = document.documentElement;
458
- let watchRafId = null;
459
- let vvhCurrent = 0;
460
- let vvhTarget = 0;
461
- let offsetCurrent = 0;
462
- let offsetTarget = 0;
463
- let lastTick = 0;
464
-
465
- const readViewport = () => ({
466
- height: window.visualViewport?.height ?? window.innerHeight,
467
- offsetTop: window.visualViewport?.offsetTop ?? 0,
468
- });
469
-
470
- const applyVars = () => {
471
- root.style.setProperty('--vvh', vvhCurrent + 'px');
472
- root.style.setProperty('--vv-offset-top', offsetCurrent + 'px');
473
- };
474
-
475
- const startKeyboardWatch = () => {
476
- if (watchRafId !== null) return;
477
- lastTick = performance.now();
478
-
479
- const tick = () => {
480
- const now = performance.now();
481
- const dtMs = Math.max(1, now - lastTick);
482
- lastTick = now;
483
-
484
- const { height, offsetTop } = readViewport();
485
- vvhTarget = height;
486
- offsetTarget = offsetTop;
487
-
488
- if (vvhCurrent === 0) vvhCurrent = vvhTarget;
489
-
490
- const tauMs = 100;
491
- const alpha = 1 - Math.exp(-dtMs / tauMs);
492
- const deltaH = vvhTarget - vvhCurrent;
493
- const deltaO = offsetTarget - offsetCurrent;
494
-
495
- if (Math.abs(deltaH) > 1) vvhCurrent += deltaH * alpha;
496
- else vvhCurrent = vvhTarget;
497
-
498
- if (Math.abs(deltaO) > 0.5) offsetCurrent += deltaO * alpha;
499
- else offsetCurrent = offsetTarget;
500
-
501
- applyVars();
502
- fitAddon.fit();
503
-
504
- const stillAnimating = Math.abs(vvhTarget - vvhCurrent) > 0.5 || Math.abs(offsetTarget - offsetCurrent) > 0.5;
505
- if (stillAnimating) {
506
- watchRafId = requestAnimationFrame(tick);
507
- } else {
508
- watchRafId = null;
509
- }
510
- };
511
-
512
- watchRafId = requestAnimationFrame(tick);
513
- };
514
-
515
- // Initial setup
516
- const { height, offsetTop } = readViewport();
517
- vvhCurrent = height;
518
- vvhTarget = height;
519
- offsetCurrent = offsetTop;
520
- offsetTarget = offsetTop;
521
- applyVars();
522
-
523
- window.addEventListener('resize', startKeyboardWatch);
524
- window.addEventListener('focusin', startKeyboardWatch);
525
- window.addEventListener('focusout', startKeyboardWatch);
526
- window.visualViewport?.addEventListener('resize', startKeyboardWatch);
527
- }
528
-
529
- // Handle terminal resize
530
- term.onResize((size) => {
531
- if (ws && ws.readyState === WebSocket.OPEN) {
532
- ws.send(JSON.stringify({ type: 'resize', cols: size.cols, rows: size.rows }));
533
- }
534
- });
535
-
536
- // Handle user input
537
- term.onData((data) => {
538
- if (ws && ws.readyState === WebSocket.OPEN) {
539
- ws.send(data);
540
- }
541
- });
542
-
543
- // Handle directory changes
544
- const directoryElement = document.getElementById('current-directory');
545
- const separatorElement = document.getElementById('title-separator');
546
- term.onDirectoryChange((directory) => {
547
- if (directoryElement && separatorElement) {
548
- if (directory) {
549
- directoryElement.textContent = directory;
550
- separatorElement.style.display = 'inline';
551
- } else {
552
- directoryElement.textContent = '';
553
- separatorElement.style.display = 'none';
554
- }
555
- }
556
- });
557
-
558
- connectWebSocket();
559
- }
560
-
561
- function connectWebSocket() {
562
- const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
563
- const wsUrl = protocol + '//' + window.location.host + '/ws?cols=' + term.cols + '&rows=' + term.rows;
564
-
565
- ws = new WebSocket(wsUrl);
566
-
567
- ws.onopen = () => {
568
- updateConnectionStatus(true);
569
- };
570
-
571
- ws.onmessage = (event) => {
572
- term.write(event.data);
573
- };
574
-
575
- ws.onerror = () => {
576
- updateConnectionStatus(false);
577
- };
578
-
579
- ws.onclose = () => {
580
- updateConnectionStatus(false);
581
- setTimeout(() => {
582
- if (!ws || ws.readyState === WebSocket.CLOSED) {
583
- connectWebSocket();
584
- }
585
- }, 3000);
586
- };
587
- }
588
-
589
- function updateConnectionStatus(connected) {
590
- const dot = document.getElementById('connection-dot');
591
- const text = document.getElementById('connection-text');
592
- if (connected) {
593
- dot.classList.add('connected');
594
- text.textContent = 'Connected';
595
- } else {
596
- dot.classList.remove('connected');
597
- text.textContent = 'Disconnected';
598
- }
599
- }
600
-
601
- initTerminal();
602
- </script>
603
- </body>
604
- </html>`;
605
-
606
- // ============================================================================
607
- // MIME Types
608
- // ============================================================================
609
-
610
- const MIME_TYPES = {
611
- '.html': 'text/html',
612
- '.js': 'application/javascript',
613
- '.mjs': 'application/javascript',
614
- '.css': 'text/css',
615
- '.json': 'application/json',
616
- '.wasm': 'application/wasm',
617
- '.png': 'image/png',
618
- '.svg': 'image/svg+xml',
619
- '.ico': 'image/x-icon',
620
- };
621
-
622
- // ============================================================================
623
- // HTTP Server
624
- // ============================================================================
625
-
626
- const httpServer = http.createServer((req, res) => {
627
- const url = new URL(req.url, `http://${req.headers.host}`);
628
- const pathname = url.pathname;
629
-
630
- // Serve index page
631
- if (pathname === '/' || pathname === '/index.html') {
632
- res.writeHead(200, { 'Content-Type': 'text/html' });
633
- res.end(HTML_TEMPLATE);
634
- return;
635
- }
636
-
637
- // Serve dist files
638
- if (pathname.startsWith('/dist/')) {
639
- const filePath = path.join(distPath, pathname.slice(6));
640
- serveFile(filePath, res);
641
- return;
642
- }
643
-
644
- // Serve WASM file
645
- if (pathname === '/ghostty-vt.wasm') {
646
- serveFile(wasmPath, res);
647
- return;
648
- }
649
-
650
- // 404
651
- res.writeHead(404);
652
- res.end('Not Found');
653
- });
654
-
655
- function serveFile(filePath, res) {
656
- const ext = path.extname(filePath);
657
- const contentType = MIME_TYPES[ext] || 'application/octet-stream';
658
-
659
- fs.readFile(filePath, (err, data) => {
660
- if (err) {
661
- res.writeHead(404);
662
- res.end('Not Found');
663
- return;
664
- }
665
- res.writeHead(200, { 'Content-Type': contentType });
666
- res.end(data);
667
- });
668
- }
669
-
670
- // ============================================================================
671
- // WebSocket Server
672
- // ============================================================================
673
-
674
- const sessions = new Map();
675
-
676
- function getShell() {
677
- if (process.platform === 'win32') {
678
- return process.env.COMSPEC || 'cmd.exe';
679
- }
680
- return process.env.SHELL || '/bin/bash';
681
- }
682
-
683
- function createPtySession(cols, rows) {
684
- const shell = getShell();
685
-
686
- const ptyProcess = pty.spawn(shell, [], {
687
- name: 'xterm-256color',
688
- cols: cols,
689
- rows: rows,
690
- cwd: homedir(),
691
- env: {
692
- ...process.env,
693
- TERM: 'xterm-256color',
694
- COLORTERM: 'truecolor',
695
- },
696
- });
697
-
698
- return ptyProcess;
699
- }
700
-
701
- const wss = new WebSocketServer({ noServer: true });
702
-
703
- httpServer.on('upgrade', (req, socket, head) => {
704
- const url = new URL(req.url, `http://${req.headers.host}`);
705
-
706
- if (url.pathname === '/ws') {
707
- wss.handleUpgrade(req, socket, head, (ws) => {
708
- wss.emit('connection', ws, req);
709
- });
710
- } else {
711
- socket.destroy();
712
- }
713
- });
714
-
715
- wss.on('connection', (ws, req) => {
716
- const url = new URL(req.url, `http://${req.headers.host}`);
717
- const cols = Number.parseInt(url.searchParams.get('cols') || '80');
718
- const rows = Number.parseInt(url.searchParams.get('rows') || '24');
719
-
720
- const ptyProcess = createPtySession(cols, rows);
721
- sessions.set(ws, { pty: ptyProcess });
722
-
723
- ptyProcess.onData((data) => {
724
- if (ws.readyState === ws.OPEN) {
725
- ws.send(data);
726
- }
727
- });
728
-
729
- ptyProcess.onExit(({ exitCode }) => {
730
- if (ws.readyState === ws.OPEN) {
731
- ws.send(`\r\n\x1b[33mShell exited (code: ${exitCode})\x1b[0m\r\n`);
732
- ws.close();
733
- }
734
- });
735
-
736
- ws.on('message', (data) => {
737
- const message = data.toString('utf8');
738
-
739
- if (message.startsWith('{')) {
740
- try {
741
- const msg = JSON.parse(message);
742
- if (msg.type === 'resize') {
743
- ptyProcess.resize(msg.cols, msg.rows);
744
- return;
745
- }
746
- } catch (e) {
747
- // Not JSON, treat as input
748
- }
749
- }
750
-
751
- ptyProcess.write(message);
752
- });
753
-
754
- ws.on('close', () => {
755
- const session = sessions.get(ws);
756
- if (session) {
757
- session.pty.kill();
758
- sessions.delete(ws);
759
- }
760
- });
761
-
762
- ws.on('error', () => {
763
- // Ignore socket errors
764
- });
765
- });
766
-
767
- // ============================================================================
768
- // Startup
769
- // ============================================================================
770
-
771
- function getLocalIPs() {
772
- const interfaces = networkInterfaces();
773
- const ips = [];
774
- for (const name of Object.keys(interfaces)) {
775
- for (const iface of interfaces[name] || []) {
776
- if (iface.family === 'IPv4' && !iface.internal) {
777
- ips.push(iface.address);
778
- }
779
- }
780
- }
781
- return ips;
782
- }
783
-
784
- function printBanner(url) {
785
- const localIPs = getLocalIPs();
786
- // ANSI color codes
787
- const RESET = '\x1b[0m';
788
- const CYAN = '\x1b[36m'; // Labels
789
- const BEIGE = '\x1b[38;2;255;220;150m'; // Warm yellow/beige for values (RGB: 255,220,150)
790
- const DIM = '\x1b[2m'; // Dimmed text
791
-
792
- // console.log('');
793
-
794
- // Open: URL
795
- console.log(` ${CYAN}Open:${RESET} ${BEIGE}${url}${RESET}`);
796
-
797
- // Network: URLs
798
- const network = [` ${CYAN}Network: ${RESET}`];
799
- if (localIPs.length > 0) {
800
- let networkCount = 0;
801
- for (const ip of localIPs) {
802
- networkCount++;
803
- const spaces = networkCount !== 1 ? ' ' : '';
804
- network.push(`${spaces}${BEIGE}http://${ip}:${HTTP_PORT}${RESET}\n`);
805
- }
806
- }
807
- console.log(`\n${network.join('')} `);
808
-
809
- // Shell: path
810
- console.log(` ${CYAN}Shell:${RESET} ${BEIGE}${getShell()}${RESET}`);
811
-
812
- console.log('');
813
-
814
- // Home: path
815
- console.log(` ${CYAN}Home:${RESET} ${BEIGE}${homedir()}${RESET}`);
816
-
817
- console.log('');
818
- console.log(` ${DIM}Press Ctrl+C to stop.${RESET}\n`);
819
- }
820
-
821
- process.on('SIGINT', () => {
822
- console.log('\n\nShutting down...');
823
- for (const [ws, session] of sessions.entries()) {
824
- session.pty.kill();
825
- ws.close();
826
- }
827
- wss.close();
828
- process.exit(0);
829
- });
830
9
 
831
- httpServer.listen(HTTP_PORT, '0.0.0.0', async () => {
832
- // Display ASCII art banner
833
- try {
834
- const imagePath = path.join(__dirname, 'assets', 'ghosts.png');
835
- if (fs.existsSync(imagePath)) {
836
- // Welcome text with orange/yellow color (bright yellow, bold)
837
- console.log('\n \x1b[1;93mWelcome to Ghosttown!\x1b[0m\n');
838
- const art = await asciiArt(imagePath, { maxWidth: 80, maxHeight: 20 });
839
- console.log(art);
840
- console.log('');
841
- }
842
- } catch (err) {
843
- // Silently fail if ASCII art can't be displayed
844
- // This allows the server to start even if the image is missing
845
- }
10
+ import { run } from '../src/cli.js';
846
11
 
847
- printBanner(`http://localhost:${HTTP_PORT}`);
848
- });
849
- } // end startWebServer
12
+ run(process.argv);