brsh 2.4.1 → 2.5.0

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/index.js CHANGED
@@ -5,6 +5,7 @@ const LocalCommand = require('./lib/local/LocalCommand');
5
5
  const ScriptCommand = require('./lib/ScriptCommand');
6
6
  const WasmCommand = require('./lib/WasmCommand');
7
7
  const Command = require('./lib/Command');
8
+ const InteractiveCommand = require('./lib/InteractiveCommand');
8
9
 
9
10
  const builtins = require('./lib/builtins');
10
11
  const localCommands = require('./lib/local');
@@ -79,6 +80,17 @@ class Shell extends EventEmitter {
79
80
  }
80
81
  }
81
82
 
83
+ setTerminalSize(cols, rows) {
84
+ this._terminalSize = { cols, rows };
85
+ this.context.setVar('COLUMNS', String(cols));
86
+ this.context.setVar('LINES', String(rows));
87
+ this.emit('resize', { cols, rows });
88
+ }
89
+
90
+ get terminalSize() {
91
+ return this._terminalSize || { cols: 80, rows: 24 };
92
+ }
93
+
82
94
  _loadDefaultCommands() {
83
95
  localCommands.forEach(command => {
84
96
  this.context.setCommand(command);
@@ -233,6 +245,9 @@ class Shell extends EventEmitter {
233
245
  this._emitOutput(lines);
234
246
  });
235
247
  }
248
+ if (instance.interactive) {
249
+ this.emit('interactive');
250
+ }
236
251
 
237
252
  return instance.runCommand().then(result => {
238
253
  const stdOutput = result.getStdOutput();
@@ -611,6 +626,7 @@ Shell.STATUS_WORKING = 'WORKING';
611
626
  Shell.STATUS_DESTROYED = 'DESTROYED';
612
627
 
613
628
  Shell.Command = Command;
629
+ Shell.InteractiveCommand = InteractiveCommand;
614
630
  Shell.FS = BaseFileSystem;
615
631
 
616
632
  global.shell = Shell;
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ const LocalCommand = require('./local/LocalCommand');
4
+
5
+ /**
6
+ * Base class for interactive full-screen terminal applications (e.g. text editors).
7
+ *
8
+ * Subclasses:
9
+ * - Must implement `run()` — return a Promise that resolves when the app exits.
10
+ * - Must implement `onInput(key)` — receives keystroke strings:
11
+ * - Printable characters: 'a', 'B', '1', ' ', etc.
12
+ * - Special keys: 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight',
13
+ * 'Enter', 'Backspace', 'Delete', 'Escape',
14
+ * 'Home', 'End', 'PageUp', 'PageDown', 'Tab'
15
+ * - Ctrl combos: '^A' through '^Z' (caret + uppercase letter)
16
+ * - Should render by setting `this.stdOut = screenString` then calling `this.flush()`.
17
+ * Start the screen string with '\x1b[2J\x1b[H' to signal a full-screen replace.
18
+ * Send the entire screen as ONE stdOut assignment (multi-line string) for efficiency.
19
+ *
20
+ * Terminal size is available via `this.terminalSize` → `{ cols, rows }`.
21
+ */
22
+ class InteractiveCommand extends LocalCommand {
23
+ /**
24
+ * Tells Shell to route all keystrokes here via onInput().
25
+ */
26
+ get captureInput() {
27
+ return true;
28
+ }
29
+
30
+ /**
31
+ * Tells Shell/Terminal that this command owns the full screen.
32
+ * Terminal will hide the normal <ul> output list and show a <pre>
33
+ * rendering surface for the duration of this command.
34
+ */
35
+ get interactive() {
36
+ return true;
37
+ }
38
+
39
+ /**
40
+ * Current terminal dimensions reported by the host Terminal, or 80×24 fallback.
41
+ * @returns {{ cols: number, rows: number }}
42
+ */
43
+ get terminalSize() {
44
+ const cols = parseInt(this.context.getVar('COLUMNS'), 10) || 80;
45
+ const rows = parseInt(this.context.getVar('LINES'), 10) || 24;
46
+ return { cols, rows };
47
+ }
48
+ }
49
+
50
+ module.exports = InteractiveCommand;
package/lib/Terminal.js CHANGED
@@ -142,6 +142,25 @@ class Terminal {
142
142
  this._cmdList.classList.add('terminal--wrap');
143
143
  }
144
144
  parent.appendChild(this._cmdList);
145
+
146
+ // Full-screen surface for interactive commands (pico, etc.)
147
+ this._screen = document.createElement('pre');
148
+ this._screen.className = 'terminal__screen';
149
+ this._screen.style.fontFamily = `'${font}', monospace`;
150
+ parent.appendChild(this._screen);
151
+
152
+ // Hidden single-character span for measuring character cell dimensions
153
+ this._charMeasure = document.createElement('span');
154
+ this._charMeasure.className = 'terminal__char-measure';
155
+ this._charMeasure.textContent = 'X';
156
+ this._charMeasure.setAttribute('aria-hidden', 'true');
157
+ parent.appendChild(this._charMeasure);
158
+
159
+ // Measure on first paint, then track container resizes
160
+ setTimeout(() => this._measureAndSetSize(), 0);
161
+ if (typeof ResizeObserver !== 'undefined') {
162
+ new ResizeObserver(() => this._measureAndSetSize()).observe(parent);
163
+ }
145
164
  }
146
165
 
147
166
  _newPrompt(callback) {
@@ -272,6 +291,9 @@ class Terminal {
272
291
 
273
292
  _statusCheck(status) {
274
293
  if(status === Shell.STATUS_READY) {
294
+ if (this._interactive) {
295
+ this._exitInteractiveMode();
296
+ }
275
297
  this._working = false;
276
298
  if (!this._historyLoaded) {
277
299
  this._loadHistory();
@@ -339,17 +361,27 @@ class Terminal {
339
361
  this.cli.on('status', this._statusCheck.bind(this));
340
362
 
341
363
  this.cli.on('stdOut', line => {
342
- this._print(line, 'out');
364
+ if (this._interactive) {
365
+ this._renderInteractiveScreen(line);
366
+ } else {
367
+ this._print(line, 'out');
368
+ }
343
369
  });
344
370
 
345
371
  this.cli.on('stdErr', line => {
346
- this._print(line, 'err');
372
+ if (!this._interactive) {
373
+ this._print(line, 'err');
374
+ }
347
375
  });
348
376
 
349
377
  this.cli.on('clear', () => {
350
378
  this._clearOutput();
351
379
  });
352
380
 
381
+ this.cli.on('interactive', () => {
382
+ this._enterInteractiveMode();
383
+ });
384
+
353
385
  this.cli.on('exit', code => {
354
386
  delete this.cli;
355
387
  if(typeof this._exitFn === 'function') {
@@ -362,6 +394,14 @@ class Terminal {
362
394
 
363
395
  _listenForKeyEvents(onUpdate, el) {
364
396
  window.addEventListener('keydown', e => {
397
+ // Interactive mode: route ALL keystrokes to the running command
398
+ if (this._interactive) {
399
+ e.preventDefault();
400
+ const key = this._buildInteractiveKey(e);
401
+ if (key) this.cli.onInput(key);
402
+ return;
403
+ }
404
+
365
405
  if (e.keyCode === 9) {
366
406
  e.preventDefault();
367
407
  }
@@ -379,22 +419,23 @@ class Terminal {
379
419
  }
380
420
  });
381
421
 
382
- el.addEventListener('keyup', (e) => this._keyEvent(onUpdate, e.key));
422
+ el.addEventListener('keyup', (e) => {
423
+ if (this._interactive) return;
424
+ this._keyEvent(onUpdate, e.key);
425
+ });
383
426
 
384
427
  window.addEventListener('paste', (e) => {
385
428
  e.preventDefault();
429
+ if (this._interactive) return;
386
430
  const text = (e.clipboardData || window.clipboardData).getData('text');
387
431
  if (!text) return;
388
432
 
389
- // Split on newlines; each newline acts as Enter (submits a command)
390
433
  const segments = text.split(/\r?\n/);
391
434
  segments.forEach((segment, idx) => {
392
- // Bulk-insert characters for this segment
393
435
  const chars = segment.split('');
394
436
  this._buffer.splice(this._cursorPos, 0, ...chars);
395
437
  this._cursorPos += chars.length;
396
438
 
397
- // Newline between segments → submit as Enter
398
439
  if (idx < segments.length - 1) {
399
440
  this._keyEvent(onUpdate, 'Enter');
400
441
  }
@@ -404,6 +445,18 @@ class Terminal {
404
445
  });
405
446
  }
406
447
 
448
+ _buildInteractiveKey(e) {
449
+ const key = e.key;
450
+ // Skip bare modifier keys
451
+ if (['Control', 'Alt', 'Shift', 'Meta'].includes(key)) return null;
452
+ // Ctrl+letter → caret notation '^X'
453
+ if (e.ctrlKey && key.length === 1) {
454
+ return '^' + key.toUpperCase();
455
+ }
456
+ // All other keys passed as e.key strings ('ArrowUp', 'Enter', 'a', etc.)
457
+ return key;
458
+ }
459
+
407
460
  _wordLeft() {
408
461
  let pos = this._cursorPos;
409
462
  while (pos > 0 && this._buffer[pos - 1] === ' ') pos--;
@@ -520,6 +573,48 @@ class Terminal {
520
573
  }
521
574
  }
522
575
  }
576
+ _enterInteractiveMode() {
577
+ this._interactive = true;
578
+ this._cmdList.style.display = 'none';
579
+ this._screen.style.display = 'block';
580
+ this._clearCursor();
581
+ }
582
+
583
+ _exitInteractiveMode() {
584
+ this._interactive = false;
585
+ this._screen.style.display = 'none';
586
+ this._screen.innerHTML = '';
587
+ this._cmdList.style.display = '';
588
+ }
589
+
590
+ _renderInteractiveScreen(text) {
591
+ // Strip ANSI clear-screen and cursor-home/position sequences used as
592
+ // full-screen replace signal. AnsiUp handles colours; we just drop the
593
+ // cursor-control codes before passing to it.
594
+ const cleaned = text
595
+ .replace(/\x1b\[\d*J/g, '') // erase in display (\x1b[2J etc.)
596
+ .replace(/\x1b\[\d+;\d+H/g, '') // cursor position row;col
597
+ .replace(/\x1b\[H/g, ''); // cursor home (no args)
598
+ try {
599
+ this._screen.innerHTML = this._ansi.ansi_to_html(cleaned);
600
+ } catch(e) {
601
+ this._screen.textContent = cleaned;
602
+ }
603
+ }
604
+
605
+ _measureAndSetSize() {
606
+ if (!this._charMeasure || !this.cli) return;
607
+ const charRect = this._charMeasure.getBoundingClientRect();
608
+ const containerRect = this._el.getBoundingClientRect();
609
+ if (!charRect.width || !charRect.height || !containerRect.width) return;
610
+ const cols = Math.max(1, Math.floor(containerRect.width / charRect.width));
611
+ const rows = Math.max(1, Math.floor(containerRect.height / charRect.height));
612
+ if (cols !== this._lastCols || rows !== this._lastRows) {
613
+ this._lastCols = cols;
614
+ this._lastRows = rows;
615
+ this.cli.setTerminalSize(cols, rows);
616
+ }
617
+ }
523
618
  }
524
619
 
525
620
  module.exports = Terminal;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "2.4.1",
3
+ "version": "2.5.0",
4
4
  "description": "A unix like shell written in javascript",
5
5
  "main": "./dist/shell.min.js",
6
6
  "module": "./dist/shell.es.js",
@@ -1,11 +1,41 @@
1
+ :root {
2
+ --terminal-cursor-bg: #000;
3
+ --terminal-cursor-color: #fff;
4
+ }
5
+
1
6
  .terminal__cursor {
2
7
  display: inline-block;
3
8
  }
4
9
 
10
+ /* Full-screen rendering surface for interactive commands */
11
+ .terminal__screen {
12
+ display: none;
13
+ margin: 0;
14
+ padding: 0;
15
+ white-space: pre;
16
+ overflow: hidden;
17
+ flex: 1;
18
+ line-height: 1.15em;
19
+ }
20
+
21
+ /* Hidden span used to measure character cell dimensions */
22
+ .terminal__char-measure {
23
+ position: absolute;
24
+ visibility: hidden;
25
+ pointer-events: none;
26
+ white-space: pre;
27
+ line-height: 1.15em;
28
+ }
29
+
5
30
  .terminal__cursor.blink {
6
31
  animation: 1s blink 500ms step-end infinite;
7
32
  }
8
33
 
34
+ .terminal__cursor.block {
35
+ background-color: var(--terminal-cursor-bg);
36
+ color: var(--terminal-cursor-color);
37
+ }
38
+
9
39
  .terminal__line {
10
40
  white-space: pre;
11
41
  overflow: hidden;
@@ -21,10 +51,12 @@
21
51
 
22
52
  @keyframes blink {
23
53
  from, to {
24
- opacity: 0;
54
+ background-color: var(--terminal-cursor-bg);
55
+ color: var(--terminal-cursor-color);
25
56
  }
26
57
  50% {
27
- opacity: 1;
58
+ background-color: transparent;
59
+ color: inherit;
28
60
  }
29
61
  }
30
62
 
@@ -1,10 +1,11 @@
1
1
  import { createRequire } from 'module';
2
2
  import { describe, it, expect, beforeEach, afterEach } from 'vitest';
3
3
  import { spawnSync } from 'child_process';
4
- import { mkdtempSync, writeFileSync, mkdirSync, chmodSync, readFileSync, rmSync } from 'fs';
4
+ import { mkdtempSync, writeFileSync, mkdirSync, chmodSync, readFileSync, rmSync, statSync } from 'fs';
5
5
  import { tmpdir } from 'os';
6
6
  import { join, resolve } from 'path';
7
7
  import { fileURLToPath } from 'url';
8
+ import { createContext, runInContext } from 'vm';
8
9
 
9
10
  const require = createRequire(import.meta.url);
10
11
  const { buildStructure } = require('../lib/buildFilesystemStructure.js');
@@ -244,3 +245,96 @@ describe('exportFileSystem CLI', () => {
244
245
  expect(() => new Function(content)).not.toThrow();
245
246
  });
246
247
  });
248
+
249
+ // ---------------------------------------------------------------------------
250
+ // CLI integration tests – --compress (-c) flag
251
+ // ---------------------------------------------------------------------------
252
+
253
+ describe('exportFileSystem CLI --compress', () => {
254
+ let root;
255
+ let outDir;
256
+
257
+ beforeEach(() => {
258
+ root = tmpDir();
259
+ outDir = tmpDir();
260
+ writeFileSync(join(root, 'hello.txt'), 'Hello World');
261
+ writeFileSync(join(root, 'app.js'), 'module.exports = function() {}');
262
+ });
263
+
264
+ afterEach(() => {
265
+ rmSync(root, { recursive: true, force: true });
266
+ rmSync(outDir, { recursive: true, force: true });
267
+ });
268
+
269
+ it('builds successfully with --compress flag', () => {
270
+ const outFile = join(outDir, 'fs.js');
271
+ const r = runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
272
+ expect(r.status).toBe(0);
273
+ expect(r.stdout).toContain('Build succeeded');
274
+ });
275
+
276
+ it('compressed output is valid JavaScript', () => {
277
+ const outFile = join(outDir, 'fs.js');
278
+ runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
279
+ const content = readFileSync(outFile, 'utf8');
280
+ expect(() => new Function(content)).not.toThrow();
281
+ });
282
+
283
+ it('compressed output contains DecompressionStream reference', () => {
284
+ const outFile = join(outDir, 'fs.js');
285
+ runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
286
+ const content = readFileSync(outFile, 'utf8');
287
+ expect(content).toContain('DecompressionStream');
288
+ });
289
+
290
+ it('compressed output does not contain plain text file content', () => {
291
+ const outFile = join(outDir, 'fs.js');
292
+ runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
293
+ const content = readFileSync(outFile, 'utf8');
294
+ expect(content).not.toContain('Hello World');
295
+ });
296
+
297
+ it('compressed output is smaller than uncompressed for text-heavy filesystem', () => {
298
+ const textRoot = tmpDir();
299
+ try {
300
+ for (let i = 0; i < 20; i++) {
301
+ writeFileSync(join(textRoot, `doc${i}.txt`), `${'Content line repeated many times.\n'.repeat(200)} document ${i}`);
302
+ }
303
+ const compressedOut = join(outDir, 'compressed.js');
304
+ const uncompressedOut = join(outDir, 'uncompressed.js');
305
+ runCLI([textRoot, '-v', 'FS', '-o', compressedOut, '--compress']);
306
+ runCLI([textRoot, '-v', 'FS', '-o', uncompressedOut]);
307
+ expect(statSync(compressedOut).size).toBeLessThan(statSync(uncompressedOut).size);
308
+ } finally {
309
+ rmSync(textRoot, { recursive: true, force: true });
310
+ }
311
+ });
312
+
313
+ it('compressed output resolves to an object with filesystem and permissions', async () => {
314
+ const outFile = join(outDir, 'fs.js');
315
+ runCLI([root, '-v', 'TestFS', '-o', outFile, '--compress']);
316
+ const content = readFileSync(outFile, 'utf8');
317
+ const ctx = createContext({
318
+ atob: globalThis.atob,
319
+ DecompressionStream: globalThis.DecompressionStream,
320
+ Response: globalThis.Response,
321
+ TextDecoder: globalThis.TextDecoder,
322
+ Uint8Array,
323
+ Set,
324
+ Object,
325
+ });
326
+ runInContext(content, ctx);
327
+ const result = await ctx.TestFS;
328
+ expect(result).toHaveProperty('filesystem');
329
+ expect(result).toHaveProperty('permissions');
330
+ expect(result.filesystem['hello.txt']).toBe('Hello World');
331
+ });
332
+
333
+ it('compressed output with JS command files still bundles the command code', () => {
334
+ const outFile = join(outDir, 'fs.js');
335
+ runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
336
+ const content = readFileSync(outFile, 'utf8');
337
+ // app.js exports a function – its compiled form should appear in the bundle
338
+ expect(content.length).toBeGreaterThan(0);
339
+ });
340
+ });